{"version":3,"sources":["../../node_modules/citty/dist/_chunks/libs/scule.mjs","../../node_modules/citty/dist/index.mjs","../../node_modules/chalk/source/vendor/ansi-styles/index.js","../../node_modules/chalk/source/vendor/supports-color/index.js","../../node_modules/chalk/source/utilities.js","../../node_modules/chalk/source/index.js","../../src/shared/terminal.ts","../../src/cli/ui/theme.ts","../../src/cli/ui/symbols.ts","../../src/cli/ui/output.ts","../../src/cli/ui/format.ts","../../src/cli/commands/version.ts","../../src/cli/utils/file-spec.ts","../../src/cli/utils/entrypoint-bootstrap.ts","../../node_modules/@modelcontextprotocol/client/dist/chunk-DYPzFuB5.mjs","../../node_modules/@modelcontextprotocol/core-internal/src/validators/dialects.ts","../../node_modules/zod/v4/core/util.js","../../node_modules/zod/v4/core/core.js","../../node_modules/zod/v4/core/errors.js","../../node_modules/zod/v4/core/parse.js","../../node_modules/zod/v4/core/regexes.js","../../node_modules/zod/v4/core/checks.js","../../node_modules/zod/v4/core/doc.js","../../node_modules/zod/v4/core/versions.js","../../node_modules/zod/v4/core/schemas.js","../../node_modules/zod/v4/core/memoizer.js","../../node_modules/zod/v4/locales/en.js","../../node_modules/zod/v4/locales/index.js","../../node_modules/zod/v4/core/registries.js","../../node_modules/zod/v4/core/compile.js","../../node_modules/zod/v4/core/api.js","../../node_modules/zod/v4/core/to-json-schema.js","../../node_modules/zod/v4/core/json-schema-processors.js","../../node_modules/zod/v4/core/json-schema.js","../../node_modules/zod/v4/core/index.js","../../node_modules/zod/v4/classic/checks.js","../../node_modules/zod/v4/classic/errors.js","../../node_modules/zod/v4/classic/parse.js","../../node_modules/zod/v4/classic/schemas.js","../../node_modules/zod/v4/classic/compat.js","../../node_modules/zod/v4/classic/iso.js","../../node_modules/zod/v4/classic/coerce.js","../../node_modules/zod/v4/classic/external.js","../../node_modules/zod/v4/classic/index.js","../../node_modules/zod/v4/index.js","../../node_modules/@modelcontextprotocol/core/src/constants.ts","../../node_modules/@modelcontextprotocol/core/src/schemas.ts","../../node_modules/@modelcontextprotocol/core/src/auth.ts","../../node_modules/@modelcontextprotocol/core/dist/internal.mjs","../../node_modules/@modelcontextprotocol/core-internal/src/errors/crossBundleBrand.ts","../../node_modules/@modelcontextprotocol/core-internal/src/auth/errors.ts","../../node_modules/@modelcontextprotocol/core-internal/src/errors/sdkErrors.ts","../../node_modules/@modelcontextprotocol/core-internal/src/shared/authUtils.ts","../../node_modules/@modelcontextprotocol/core-internal/src/shared/protocolEras.ts","../../node_modules/@modelcontextprotocol/core-internal/src/wire/textFallback.ts","../../node_modules/@modelcontextprotocol/core-internal/src/wire/resultFamilies.ts","../../node_modules/@modelcontextprotocol/core-internal/src/wire/rev2025-11-25/buildSchemas.ts","../../node_modules/@modelcontextprotocol/core-internal/src/wire/rev2025-11-25/legacyWrap.ts","../../node_modules/@modelcontextprotocol/core-internal/src/wire/rev2025-11-25/registry.ts","../../node_modules/@modelcontextprotocol/core-internal/src/wire/rev2025-11-25/codec.ts","../../node_modules/@modelcontextprotocol/core-internal/src/wire/rev2026-07-28/buildSchemas.ts","../../node_modules/@modelcontextprotocol/core-internal/src/shared/resultCacheHints.ts","../../node_modules/@modelcontextprotocol/core-internal/src/types/enums.ts","../../node_modules/@modelcontextprotocol/core-internal/src/types/errors.ts","../../node_modules/@modelcontextprotocol/core-internal/src/wire/rev2026-07-28/encodeContract.ts","../../node_modules/@modelcontextprotocol/core-internal/src/wire/rev2026-07-28/inputRequired.ts","../../node_modules/@modelcontextprotocol/core-internal/src/wire/rev2026-07-28/registry.ts","../../node_modules/@modelcontextprotocol/core-internal/src/wire/rev2026-07-28/codec.ts","../../node_modules/@modelcontextprotocol/core-internal/src/wire/codec.ts","../../node_modules/@modelcontextprotocol/core-internal/src/types/schemas.ts","../../node_modules/@modelcontextprotocol/core-internal/src/types/guards.ts","../../node_modules/@modelcontextprotocol/core-internal/src/shared/mcpParamHeaders.ts","../../node_modules/@modelcontextprotocol/core-internal/src/shared/inboundClassification.ts","../../node_modules/@modelcontextprotocol/core-internal/src/util/schema.ts","../../node_modules/@modelcontextprotocol/core-internal/src/util/standardSchema.ts","../../node_modules/@modelcontextprotocol/core-internal/src/shared/elicitation.ts","../../node_modules/@modelcontextprotocol/core-internal/src/shared/inputRequired.ts","../../node_modules/@modelcontextprotocol/core-internal/src/shared/inputRequiredDriver.ts","../../node_modules/@modelcontextprotocol/core-internal/src/types/specTypeSchema.ts","../../node_modules/@modelcontextprotocol/core-internal/src/wire/bootstrap.ts","../../node_modules/@modelcontextprotocol/core-internal/src/shared/protocol.ts","../../node_modules/@modelcontextprotocol/core-internal/src/shared/inputRequiredEngine.ts","../../node_modules/node_modules/.pnpm/content-type@1.0.5/node_modules/content-type/index.js","../../node_modules/@modelcontextprotocol/core-internal/src/shared/mediaType.ts","../../node_modules/@modelcontextprotocol/core-internal/src/shared/metadataUtils.ts","../../node_modules/@modelcontextprotocol/core-internal/src/shared/stdio.ts","../../node_modules/@modelcontextprotocol/core-internal/src/shared/transport.ts","../../node_modules/@modelcontextprotocol/core-internal/src/shared/uriTemplate.ts","../../node_modules/@modelcontextprotocol/core-internal/src/util/inMemory.ts","../../node_modules/@modelcontextprotocol/core-internal/src/wire/preload.ts","../../node_modules/@modelcontextprotocol/core-internal/src/validators/fromJsonSchema.ts","../../node_modules/node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/compile/codegen/code.js","../../node_modules/node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/compile/codegen/scope.js","../../node_modules/node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/compile/codegen/index.js","../../node_modules/node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/compile/util.js","../../node_modules/node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/compile/names.js","../../node_modules/node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/compile/errors.js","../../node_modules/node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/compile/validate/boolSchema.js","../../node_modules/node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/compile/rules.js","../../node_modules/node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/compile/validate/applicability.js","../../node_modules/node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/compile/validate/dataType.js","../../node_modules/node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/compile/validate/defaults.js","../../node_modules/node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/vocabularies/code.js","../../node_modules/node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/compile/validate/keyword.js","../../node_modules/node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/compile/validate/subschema.js","../../node_modules/node_modules/.pnpm/fast-deep-equal@3.1.3/node_modules/fast-deep-equal/index.js","../../node_modules/node_modules/.pnpm/json-schema-traverse@1.0.0/node_modules/json-schema-traverse/index.js","../../node_modules/node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/compile/resolve.js","../../node_modules/node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/compile/validate/index.js","../../node_modules/node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/runtime/validation_error.js","../../node_modules/node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/compile/ref_error.js","../../node_modules/node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/compile/index.js","../../node_modules/node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/refs/data.json","../../node_modules/node_modules/.pnpm/fast-uri@3.1.8/node_modules/fast-uri/lib/utils.js","../../node_modules/node_modules/.pnpm/fast-uri@3.1.8/node_modules/fast-uri/lib/schemes.js","../../node_modules/node_modules/.pnpm/fast-uri@3.1.8/node_modules/fast-uri/index.js","../../node_modules/node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/runtime/uri.js","../../node_modules/node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/core.js","../../node_modules/node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/vocabularies/core/id.js","../../node_modules/node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/vocabularies/core/ref.js","../../node_modules/node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/vocabularies/core/index.js","../../node_modules/node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/vocabularies/validation/limitNumber.js","../../node_modules/node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/vocabularies/validation/multipleOf.js","../../node_modules/node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/runtime/ucs2length.js","../../node_modules/node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/vocabularies/validation/limitLength.js","../../node_modules/node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/vocabularies/validation/pattern.js","../../node_modules/node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/vocabularies/validation/limitProperties.js","../../node_modules/node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/vocabularies/validation/required.js","../../node_modules/node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/vocabularies/validation/limitItems.js","../../node_modules/node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/runtime/equal.js","../../node_modules/node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/vocabularies/validation/uniqueItems.js","../../node_modules/node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/vocabularies/validation/const.js","../../node_modules/node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/vocabularies/validation/enum.js","../../node_modules/node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/vocabularies/validation/index.js","../../node_modules/node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/vocabularies/applicator/additionalItems.js","../../node_modules/node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/vocabularies/applicator/items.js","../../node_modules/node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/vocabularies/applicator/prefixItems.js","../../node_modules/node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/vocabularies/applicator/items2020.js","../../node_modules/node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/vocabularies/applicator/contains.js","../../node_modules/node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/vocabularies/applicator/dependencies.js","../../node_modules/node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/vocabularies/applicator/propertyNames.js","../../node_modules/node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/vocabularies/applicator/additionalProperties.js","../../node_modules/node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/vocabularies/applicator/properties.js","../../node_modules/node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/vocabularies/applicator/patternProperties.js","../../node_modules/node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/vocabularies/applicator/not.js","../../node_modules/node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/vocabularies/applicator/anyOf.js","../../node_modules/node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/vocabularies/applicator/oneOf.js","../../node_modules/node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/vocabularies/applicator/allOf.js","../../node_modules/node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/vocabularies/applicator/if.js","../../node_modules/node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/vocabularies/applicator/thenElse.js","../../node_modules/node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/vocabularies/applicator/index.js","../../node_modules/node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/vocabularies/format/format.js","../../node_modules/node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/vocabularies/format/index.js","../../node_modules/node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/vocabularies/metadata.js","../../node_modules/node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/vocabularies/draft7.js","../../node_modules/node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/vocabularies/discriminator/types.js","../../node_modules/node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/vocabularies/discriminator/index.js","../../node_modules/node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/refs/json-schema-draft-07.json","../../node_modules/node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/ajv.js","../../node_modules/node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/vocabularies/dynamic/dynamicAnchor.js","../../node_modules/node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/vocabularies/dynamic/dynamicRef.js","../../node_modules/node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/vocabularies/dynamic/recursiveAnchor.js","../../node_modules/node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/vocabularies/dynamic/recursiveRef.js","../../node_modules/node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/vocabularies/dynamic/index.js","../../node_modules/node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/vocabularies/validation/dependentRequired.js","../../node_modules/node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/vocabularies/applicator/dependentSchemas.js","../../node_modules/node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/vocabularies/validation/limitContains.js","../../node_modules/node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/vocabularies/next.js","../../node_modules/node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/vocabularies/unevaluated/unevaluatedProperties.js","../../node_modules/node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/vocabularies/unevaluated/unevaluatedItems.js","../../node_modules/node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/vocabularies/unevaluated/index.js","../../node_modules/node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/refs/json-schema-2019-09/schema.json","../../node_modules/node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/refs/json-schema-2019-09/meta/applicator.json","../../node_modules/node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/refs/json-schema-2019-09/meta/content.json","../../node_modules/node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/refs/json-schema-2019-09/meta/core.json","../../node_modules/node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/refs/json-schema-2019-09/meta/format.json","../../node_modules/node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/refs/json-schema-2019-09/meta/meta-data.json","../../node_modules/node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/refs/json-schema-2019-09/meta/validation.json","../../node_modules/node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/refs/json-schema-2019-09/index.js","../../node_modules/node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/2019.js","../../node_modules/node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/vocabularies/draft2020.js","../../node_modules/node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/refs/json-schema-2020-12/schema.json","../../node_modules/node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/refs/json-schema-2020-12/meta/applicator.json","../../node_modules/node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/refs/json-schema-2020-12/meta/unevaluated.json","../../node_modules/node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/refs/json-schema-2020-12/meta/content.json","../../node_modules/node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/refs/json-schema-2020-12/meta/core.json","../../node_modules/node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/refs/json-schema-2020-12/meta/format-annotation.json","../../node_modules/node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/refs/json-schema-2020-12/meta/meta-data.json","../../node_modules/node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/refs/json-schema-2020-12/meta/validation.json","../../node_modules/node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/refs/json-schema-2020-12/index.js","../../node_modules/node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/2020.js","../../node_modules/node_modules/.pnpm/ajv-formats@3.0.1_ajv@8.18.0/node_modules/ajv-formats/dist/formats.js","../../node_modules/node_modules/.pnpm/ajv-formats@3.0.1_ajv@8.18.0/node_modules/ajv-formats/dist/limit.js","../../node_modules/node_modules/.pnpm/ajv-formats@3.0.1_ajv@8.18.0/node_modules/ajv-formats/dist/index.js","../../node_modules/@modelcontextprotocol/core-internal/src/validators/ajvProvider.ts","../../node_modules/@modelcontextprotocol/client/src/shimsNode.ts","../../node_modules/pkce-challenge/dist/index.node.js","../../node_modules/@modelcontextprotocol/client/src/client/authErrors.ts","../../node_modules/@modelcontextprotocol/client/src/client/auth.ts","../../node_modules/@modelcontextprotocol/client/src/client/responseCache.ts","../../node_modules/@modelcontextprotocol/client/src/client/authSeam.ts","../../node_modules/@modelcontextprotocol/client/src/client/probeClassifier.ts","../../node_modules/@modelcontextprotocol/client/src/client/versionNegotiation.ts","../../node_modules/@modelcontextprotocol/client/src/client/client.ts","../../node_modules/eventsource-parser/src/errors.ts","../../node_modules/eventsource-parser/src/parse.ts","../../node_modules/eventsource/src/errors.ts","../../node_modules/eventsource/src/EventSource.ts","../../node_modules/eventsource-parser/src/stream.ts","../../node_modules/@modelcontextprotocol/client/src/client/authExtensions.ts","../../node_modules/@modelcontextprotocol/client/src/client/crossAppAccess.ts","../../node_modules/@modelcontextprotocol/client/src/client/dpop.ts","../../node_modules/@modelcontextprotocol/client/src/client/middleware.ts","../../node_modules/@modelcontextprotocol/client/src/client/sse.ts","../../node_modules/@modelcontextprotocol/client/src/client/streamableHttp.ts","../../node_modules/@modelcontextprotocol/client/src/fromJsonSchema.ts","../../src/cli/utils/error.ts","../../node_modules/fast-string-truncated-width/dist/utils.js","../../node_modules/fast-string-truncated-width/dist/index.js","../../node_modules/fast-string-width/dist/index.js","../../node_modules/fast-wrap-ansi/lib/main.js","../../node_modules/sisteransi/src/index.js","../../node_modules/@clack/core/dist/index.mjs","../../node_modules/@clack/prompts/dist/index.mjs","../../src/cli/ui/startup.ts","../../node_modules/readdirp/index.js","../../node_modules/chokidar/handler.js","../../node_modules/chokidar/index.js","../../src/cli/commands/run.ts","../../src/client/auth.ts","../../src/client/capabilities.ts","../../src/client/handlers.ts","../../package.json","../../src/client/options.ts","../../src/client/results.ts","../../node_modules/@modelcontextprotocol/core/src/ext/skills/constants.ts","../../node_modules/@modelcontextprotocol/core/src/ext/skills/schemas.ts","../../node_modules/@modelcontextprotocol/core/src/ext/skills/capability.ts","../../node_modules/@modelcontextprotocol/client/src/ext/skills/errors.ts","../../node_modules/@modelcontextprotocol/core-internal/src/ext/skills/bytes.ts","../../node_modules/@modelcontextprotocol/core-internal/src/ext/skills/frontmatter.ts","../../node_modules/@modelcontextprotocol/core-internal/src/ext/skills/uri.ts","../../node_modules/@modelcontextprotocol/core-internal/src/ext/skills/entry.ts","../../node_modules/@modelcontextprotocol/client/src/ext/skills/entries.ts","../../node_modules/@modelcontextprotocol/client/src/ext/skills/pageSchemas.ts","../../node_modules/@modelcontextprotocol/client/src/ext/skills/verify.ts","../../node_modules/@modelcontextprotocol/client/src/ext/skills/skillsClient.ts","../../node_modules/isexe/windows.js","../../node_modules/isexe/mode.js","../../node_modules/isexe/index.js","../../node_modules/which/which.js","../../node_modules/path-key/index.js","../../node_modules/cross-spawn/lib/util/resolveCommand.js","../../node_modules/cross-spawn/lib/util/escape.js","../../node_modules/shebang-regex/index.js","../../node_modules/shebang-command/index.js","../../node_modules/cross-spawn/lib/util/readShebang.js","../../node_modules/cross-spawn/lib/parse.js","../../node_modules/cross-spawn/lib/enoent.js","../../node_modules/cross-spawn/index.js","../../node_modules/@modelcontextprotocol/client/src/client/stdio.ts","../../src/client/transports.ts","../../src/client/multi-server.ts","../../src/client/client.ts","../../src/cli/utils/connect.ts","../../src/cli/utils/auth.ts","../../src/cli/utils/manifest.ts","../../src/cli/ui/spinner.ts","../../node_modules/cli-table3/src/debug.js","../../node_modules/cli-table3/node_modules/ansi-regex/index.js","../../node_modules/cli-table3/node_modules/strip-ansi/index.js","../../node_modules/is-fullwidth-code-point/index.js","../../node_modules/cli-table3/node_modules/emoji-regex/index.js","../../node_modules/cli-table3/node_modules/string-width/index.js","../../node_modules/cli-table3/src/utils.js","../../node_modules/@colors/colors/lib/styles.js","../../node_modules/@colors/colors/lib/system/has-flag.js","../../node_modules/@colors/colors/lib/system/supports-colors.js","../../node_modules/@colors/colors/lib/custom/trap.js","../../node_modules/@colors/colors/lib/custom/zalgo.js","../../node_modules/@colors/colors/lib/maps/america.js","../../node_modules/@colors/colors/lib/maps/zebra.js","../../node_modules/@colors/colors/lib/maps/rainbow.js","../../node_modules/@colors/colors/lib/maps/random.js","../../node_modules/@colors/colors/lib/colors.js","../../node_modules/@colors/colors/safe.js","../../node_modules/cli-table3/src/cell.js","../../node_modules/cli-table3/src/layout-manager.js","../../node_modules/cli-table3/src/table.js","../../node_modules/cli-table3/index.js","../../src/cli/ui/table.ts","../../src/cli/commands/inspect.ts","../../src/cli/ui/schema.ts","../../src/cli/commands/list.ts","../../node_modules/fastest-levenshtein/esm/mod.js","../../src/cli/utils/fuzzy.ts","../../src/cli/commands/call.ts","../../node_modules/yaml/dist/nodes/identity.js","../../node_modules/yaml/dist/visit.js","../../node_modules/yaml/dist/doc/directives.js","../../node_modules/yaml/dist/doc/anchors.js","../../node_modules/yaml/dist/doc/applyReviver.js","../../node_modules/yaml/dist/nodes/toJS.js","../../node_modules/yaml/dist/nodes/Node.js","../../node_modules/yaml/dist/nodes/Alias.js","../../node_modules/yaml/dist/nodes/Scalar.js","../../node_modules/yaml/dist/doc/createNode.js","../../node_modules/yaml/dist/nodes/Collection.js","../../node_modules/yaml/dist/stringify/stringifyComment.js","../../node_modules/yaml/dist/stringify/foldFlowLines.js","../../node_modules/yaml/dist/stringify/stringifyString.js","../../node_modules/yaml/dist/stringify/stringify.js","../../node_modules/yaml/dist/stringify/stringifyPair.js","../../node_modules/yaml/dist/log.js","../../node_modules/yaml/dist/schema/yaml-1.1/merge.js","../../node_modules/yaml/dist/nodes/addPairToJSMap.js","../../node_modules/yaml/dist/nodes/Pair.js","../../node_modules/yaml/dist/stringify/stringifyCollection.js","../../node_modules/yaml/dist/nodes/YAMLMap.js","../../node_modules/yaml/dist/schema/common/map.js","../../node_modules/yaml/dist/nodes/YAMLSeq.js","../../node_modules/yaml/dist/schema/common/seq.js","../../node_modules/yaml/dist/schema/common/string.js","../../node_modules/yaml/dist/schema/common/null.js","../../node_modules/yaml/dist/schema/core/bool.js","../../node_modules/yaml/dist/stringify/stringifyNumber.js","../../node_modules/yaml/dist/schema/core/float.js","../../node_modules/yaml/dist/schema/core/int.js","../../node_modules/yaml/dist/schema/core/schema.js","../../node_modules/yaml/dist/schema/json/schema.js","../../node_modules/yaml/dist/schema/yaml-1.1/binary.js","../../node_modules/yaml/dist/schema/yaml-1.1/pairs.js","../../node_modules/yaml/dist/schema/yaml-1.1/omap.js","../../node_modules/yaml/dist/schema/yaml-1.1/bool.js","../../node_modules/yaml/dist/schema/yaml-1.1/float.js","../../node_modules/yaml/dist/schema/yaml-1.1/int.js","../../node_modules/yaml/dist/schema/yaml-1.1/set.js","../../node_modules/yaml/dist/schema/yaml-1.1/timestamp.js","../../node_modules/yaml/dist/schema/yaml-1.1/schema.js","../../node_modules/yaml/dist/schema/tags.js","../../node_modules/yaml/dist/schema/Schema.js","../../node_modules/yaml/dist/stringify/stringifyDocument.js","../../node_modules/yaml/dist/doc/Document.js","../../node_modules/yaml/dist/errors.js","../../node_modules/yaml/dist/compose/resolve-props.js","../../node_modules/yaml/dist/compose/util-contains-newline.js","../../node_modules/yaml/dist/compose/util-flow-indent-check.js","../../node_modules/yaml/dist/compose/util-map-includes.js","../../node_modules/yaml/dist/compose/resolve-block-map.js","../../node_modules/yaml/dist/compose/resolve-block-seq.js","../../node_modules/yaml/dist/compose/resolve-end.js","../../node_modules/yaml/dist/compose/resolve-flow-collection.js","../../node_modules/yaml/dist/compose/compose-collection.js","../../node_modules/yaml/dist/compose/resolve-block-scalar.js","../../node_modules/yaml/dist/compose/resolve-flow-scalar.js","../../node_modules/yaml/dist/compose/compose-scalar.js","../../node_modules/yaml/dist/compose/util-empty-scalar-position.js","../../node_modules/yaml/dist/compose/compose-node.js","../../node_modules/yaml/dist/compose/compose-doc.js","../../node_modules/yaml/dist/compose/composer.js","../../node_modules/yaml/dist/parse/cst-scalar.js","../../node_modules/yaml/dist/parse/cst-stringify.js","../../node_modules/yaml/dist/parse/cst-visit.js","../../node_modules/yaml/dist/parse/cst.js","../../node_modules/yaml/dist/parse/lexer.js","../../node_modules/yaml/dist/parse/line-counter.js","../../node_modules/yaml/dist/parse/parser.js","../../node_modules/yaml/dist/public-api.js","../../node_modules/yaml/dist/index.js","../../src/cli/utils/config-paths.ts","../../src/cli/commands/discover.ts","../../node_modules/eventemitter3/index.js","../../node_modules/eventemitter3/index.mjs","../../node_modules/rfdc/index.js","../../node_modules/environment/index.js","../../node_modules/ansi-escapes/base.js","../../node_modules/ansi-escapes/index.js","../../node_modules/mimic-function/index.js","../../node_modules/onetime/index.js","../../node_modules/signal-exit/src/signals.ts","../../node_modules/signal-exit/src/index.ts","../../node_modules/restore-cursor/index.js","../../node_modules/cli-cursor/index.js","../../node_modules/ansi-regex/index.js","../../node_modules/strip-ansi/index.js","../../node_modules/get-east-asian-width/lookup-data.js","../../node_modules/get-east-asian-width/utilities.js","../../node_modules/get-east-asian-width/lookup.js","../../node_modules/get-east-asian-width/index.js","../../node_modules/emoji-regex/index.mjs","../../node_modules/string-width/index.js","../../node_modules/ansi-styles/index.js","../../node_modules/wrap-ansi/index.js","../../node_modules/log-update/node_modules/is-fullwidth-code-point/index.js","../../node_modules/log-update/node_modules/slice-ansi/index.js","../../node_modules/log-update/index.js","../../node_modules/slice-ansi/node_modules/is-fullwidth-code-point/index.js","../../node_modules/slice-ansi/tokenize-ansi.js","../../node_modules/slice-ansi/index.js","../../node_modules/cli-truncate/node_modules/string-width/index.js","../../node_modules/cli-truncate/index.js","../../node_modules/listr2/node_modules/string-width/index.js","../../node_modules/listr2/node_modules/wrap-ansi/index.js","../../node_modules/listr2/dist/index.mjs","../../src/cli/commands/install/shared.ts","../../src/cli/commands/install/claude-code.ts","../../src/cli/commands/install/claude-desktop.ts","../../src/cli/commands/install/cursor.ts","../../src/cli/commands/install/gemini.ts","../../src/cli/commands/install/goose.ts","../../src/cli/commands/install/mcp-json.ts","../../src/cli/commands/install/index.ts","../../src/cli/commands/dev/inspector.ts","../../src/cli/commands/dev/index.ts","../../src/cli/index.ts"],"sourcesContent":["//#region node_modules/.pnpm/scule@1.3.0/node_modules/scule/dist/index.mjs\nconst NUMBER_CHAR_RE = /\\d/;\nconst STR_SPLITTERS = [\n\t\"-\",\n\t\"_\",\n\t\"/\",\n\t\".\"\n];\nfunction isUppercase(char = \"\") {\n\tif (NUMBER_CHAR_RE.test(char)) return;\n\treturn char !== char.toLowerCase();\n}\nfunction splitByCase(str, separators) {\n\tconst splitters = separators ?? STR_SPLITTERS;\n\tconst parts = [];\n\tif (!str || typeof str !== \"string\") return parts;\n\tlet buff = \"\";\n\tlet previousUpper;\n\tlet previousSplitter;\n\tfor (const char of str) {\n\t\tconst isSplitter = splitters.includes(char);\n\t\tif (isSplitter === true) {\n\t\t\tparts.push(buff);\n\t\t\tbuff = \"\";\n\t\t\tpreviousUpper = void 0;\n\t\t\tcontinue;\n\t\t}\n\t\tconst isUpper = isUppercase(char);\n\t\tif (previousSplitter === false) {\n\t\t\tif (previousUpper === false && isUpper === true) {\n\t\t\t\tparts.push(buff);\n\t\t\t\tbuff = char;\n\t\t\t\tpreviousUpper = isUpper;\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tif (previousUpper === true && isUpper === false && buff.length > 1) {\n\t\t\t\tconst lastChar = buff.at(-1);\n\t\t\t\tparts.push(buff.slice(0, Math.max(0, buff.length - 1)));\n\t\t\t\tbuff = lastChar + char;\n\t\t\t\tpreviousUpper = isUpper;\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t}\n\t\tbuff += char;\n\t\tpreviousUpper = isUpper;\n\t\tpreviousSplitter = isSplitter;\n\t}\n\tparts.push(buff);\n\treturn parts;\n}\nfunction upperFirst(str) {\n\treturn str ? str[0].toUpperCase() + str.slice(1) : \"\";\n}\nfunction lowerFirst(str) {\n\treturn str ? str[0].toLowerCase() + str.slice(1) : \"\";\n}\nfunction pascalCase(str, opts) {\n\treturn str ? (Array.isArray(str) ? str : splitByCase(str)).map((p) => upperFirst(opts?.normalize ? p.toLowerCase() : p)).join(\"\") : \"\";\n}\nfunction camelCase(str, opts) {\n\treturn lowerFirst(pascalCase(str || \"\", opts));\n}\nfunction kebabCase(str, joiner) {\n\treturn str ? (Array.isArray(str) ? str : splitByCase(str)).map((p) => p.toLowerCase()).join(joiner ?? \"-\") : \"\";\n}\nfunction snakeCase(str) {\n\treturn kebabCase(str || \"\", \"_\");\n}\n//#endregion\nexport { kebabCase as n, snakeCase as r, camelCase as t };\n","import { n as kebabCase, r as snakeCase, t as camelCase } from \"./_chunks/libs/scule.mjs\";\nimport { parseArgs as parseArgs$1 } from \"node:util\";\n//#region src/_utils.ts\nfunction toArray(val) {\n\tif (Array.isArray(val)) return val;\n\treturn val === void 0 ? [] : [val];\n}\nfunction formatLineColumns(lines, linePrefix = \"\") {\n\tconst maxLength = [];\n\tfor (const line of lines) for (const [i, element] of line.entries()) maxLength[i] = Math.max(maxLength[i] || 0, element.length);\n\treturn lines.map((l) => l.map((c, i) => linePrefix + c[i === 0 ? \"padStart\" : \"padEnd\"](maxLength[i])).join(\"  \")).join(\"\\n\");\n}\nfunction resolveValue(input) {\n\treturn typeof input === \"function\" ? input() : input;\n}\nvar CLIError = class extends Error {\n\tcode;\n\tconstructor(message, code) {\n\t\tsuper(message);\n\t\tthis.name = \"CLIError\";\n\t\tthis.code = code;\n\t}\n};\n//#endregion\n//#region src/_parser.ts\nfunction parseRawArgs(args = [], opts = {}) {\n\tconst booleans = new Set(opts.boolean || []);\n\tconst strings = new Set(opts.string || []);\n\tconst aliasMap = opts.alias || {};\n\tconst defaults = opts.default || {};\n\tconst aliasToMain = /* @__PURE__ */ new Map();\n\tconst mainToAliases = /* @__PURE__ */ new Map();\n\tfor (const [key, value] of Object.entries(aliasMap)) {\n\t\tconst targets = value;\n\t\tfor (const target of targets) {\n\t\t\taliasToMain.set(key, target);\n\t\t\tif (!mainToAliases.has(target)) mainToAliases.set(target, []);\n\t\t\tmainToAliases.get(target).push(key);\n\t\t\taliasToMain.set(target, key);\n\t\t\tif (!mainToAliases.has(key)) mainToAliases.set(key, []);\n\t\t\tmainToAliases.get(key).push(target);\n\t\t}\n\t}\n\tconst options = {};\n\tfunction getType(name) {\n\t\tif (booleans.has(name)) return \"boolean\";\n\t\tconst aliases = mainToAliases.get(name) || [];\n\t\tfor (const alias of aliases) if (booleans.has(alias)) return \"boolean\";\n\t\treturn \"string\";\n\t}\n\tfunction isStringType(name) {\n\t\tif (strings.has(name)) return true;\n\t\tconst aliases = mainToAliases.get(name) || [];\n\t\tfor (const alias of aliases) if (strings.has(alias)) return true;\n\t\treturn false;\n\t}\n\tconst allOptions = new Set([\n\t\t...booleans,\n\t\t...strings,\n\t\t...Object.keys(aliasMap),\n\t\t...Object.values(aliasMap).flat(),\n\t\t...Object.keys(defaults)\n\t]);\n\tfor (const name of allOptions) if (!options[name]) options[name] = {\n\t\ttype: getType(name),\n\t\tdefault: defaults[name]\n\t};\n\tfor (const [alias, main] of aliasToMain.entries()) if (alias.length === 1 && options[main] && !options[main].short) options[main].short = alias;\n\tconst processedArgs = [];\n\tconst negatedFlags = {};\n\tfor (let i = 0; i < args.length; i++) {\n\t\tconst arg = args[i];\n\t\tif (arg === \"--\") {\n\t\t\tprocessedArgs.push(...args.slice(i));\n\t\t\tbreak;\n\t\t}\n\t\tif (arg.startsWith(\"--no-\")) {\n\t\t\tconst flagName = arg.slice(5);\n\t\t\tnegatedFlags[flagName] = true;\n\t\t\tcontinue;\n\t\t}\n\t\tprocessedArgs.push(arg);\n\t}\n\tlet parsed;\n\ttry {\n\t\tparsed = parseArgs$1({\n\t\t\targs: processedArgs,\n\t\t\toptions: Object.keys(options).length > 0 ? options : void 0,\n\t\t\tallowPositionals: true,\n\t\t\tstrict: false\n\t\t});\n\t} catch {\n\t\tparsed = {\n\t\t\tvalues: {},\n\t\t\tpositionals: processedArgs\n\t\t};\n\t}\n\tconst out = { _: [] };\n\tout._ = parsed.positionals;\n\tfor (const [key, value] of Object.entries(parsed.values)) {\n\t\tlet coerced = value;\n\t\tif (getType(key) === \"boolean\" && typeof value === \"string\") coerced = value !== \"false\";\n\t\telse if (isStringType(key) && typeof value === \"boolean\") coerced = \"\";\n\t\tout[key] = coerced;\n\t}\n\tfor (const [name] of Object.entries(negatedFlags)) {\n\t\tout[name] = false;\n\t\tconst mainName = aliasToMain.get(name);\n\t\tif (mainName) out[mainName] = false;\n\t\tconst aliases = mainToAliases.get(name);\n\t\tif (aliases) for (const alias of aliases) out[alias] = false;\n\t}\n\tfor (const [alias, main] of aliasToMain.entries()) {\n\t\tif (out[alias] !== void 0 && out[main] === void 0) out[main] = out[alias];\n\t\tif (out[main] !== void 0 && out[alias] === void 0) out[alias] = out[main];\n\t\tif (out[alias] !== out[main] && defaults[main] === out[main]) out[main] = out[alias];\n\t}\n\treturn out;\n}\n//#endregion\n//#region src/_color.ts\nconst noColor = /* @__PURE__ */ (() => {\n\tconst env = globalThis.process?.env ?? {};\n\treturn env.NO_COLOR === \"1\" || env.TERM === \"dumb\" || env.TEST || env.CI;\n})();\nconst _c = (c, r = 39) => (t) => noColor ? t : `\\u001B[${c}m${t}\\u001B[${r}m`;\nconst bold = /* @__PURE__ */ _c(1, 22);\nconst cyan = /* @__PURE__ */ _c(36);\nconst gray = /* @__PURE__ */ _c(90);\nconst underline = /* @__PURE__ */ _c(4, 24);\n//#endregion\n//#region src/args.ts\nfunction parseArgs(rawArgs, argsDef) {\n\tconst parseOptions = {\n\t\tboolean: [],\n\t\tstring: [],\n\t\talias: {},\n\t\tdefault: {}\n\t};\n\tconst args = resolveArgs(argsDef);\n\tfor (const arg of args) {\n\t\tif (arg.type === \"positional\") continue;\n\t\tif (arg.type === \"string\" || arg.type === \"enum\") parseOptions.string.push(arg.name);\n\t\telse if (arg.type === \"boolean\") parseOptions.boolean.push(arg.name);\n\t\tif (arg.default !== void 0) parseOptions.default[arg.name] = arg.default;\n\t\tif (arg.alias) parseOptions.alias[arg.name] = arg.alias;\n\t\tconst camelName = camelCase(arg.name);\n\t\tconst kebabName = kebabCase(arg.name);\n\t\tif (camelName !== arg.name || kebabName !== arg.name) {\n\t\t\tconst existingAliases = toArray(parseOptions.alias[arg.name] || []);\n\t\t\tif (camelName !== arg.name && !existingAliases.includes(camelName)) existingAliases.push(camelName);\n\t\t\tif (kebabName !== arg.name && !existingAliases.includes(kebabName)) existingAliases.push(kebabName);\n\t\t\tif (existingAliases.length > 0) parseOptions.alias[arg.name] = existingAliases;\n\t\t}\n\t}\n\tconst parsed = parseRawArgs(rawArgs, parseOptions);\n\tconst [ ...positionalArguments] = parsed._;\n\tconst parsedArgsProxy = new Proxy(parsed, { get(target, prop) {\n\t\treturn target[prop] ?? target[camelCase(prop)] ?? target[kebabCase(prop)];\n\t} });\n\tfor (const [, arg] of args.entries()) if (arg.type === \"positional\") {\n\t\tconst nextPositionalArgument = positionalArguments.shift();\n\t\tif (nextPositionalArgument !== void 0) parsedArgsProxy[arg.name] = nextPositionalArgument;\n\t\telse if (arg.default === void 0 && arg.required !== false) throw new CLIError(`Missing required positional argument: ${arg.name.toUpperCase()}`, \"EARG\");\n\t\telse parsedArgsProxy[arg.name] = arg.default;\n\t} else if (arg.type === \"enum\") {\n\t\tconst argument = parsedArgsProxy[arg.name];\n\t\tconst options = arg.options || [];\n\t\tif (argument !== void 0 && options.length > 0 && !options.includes(argument)) throw new CLIError(`Invalid value for argument: ${cyan(`--${arg.name}`)} (${cyan(argument)}). Expected one of: ${options.map((o) => cyan(o)).join(\", \")}.`, \"EARG\");\n\t} else if (arg.required && parsedArgsProxy[arg.name] === void 0) throw new CLIError(`Missing required argument: --${arg.name}`, \"EARG\");\n\treturn parsedArgsProxy;\n}\nfunction resolveArgs(argsDef) {\n\tconst args = [];\n\tfor (const [name, argDef] of Object.entries(argsDef || {})) args.push({\n\t\t...argDef,\n\t\tname,\n\t\talias: toArray(argDef.alias)\n\t});\n\treturn args;\n}\n//#endregion\n//#region src/plugin.ts\nfunction defineCittyPlugin(plugin) {\n\treturn plugin;\n}\nasync function resolvePlugins(plugins) {\n\treturn Promise.all(plugins.map((p) => resolveValue(p)));\n}\n//#endregion\n//#region src/command.ts\nfunction defineCommand(def) {\n\treturn def;\n}\nasync function runCommand(cmd, opts) {\n\tconst cmdArgs = await resolveValue(cmd.args || {});\n\tconst parsedArgs = parseArgs(opts.rawArgs, cmdArgs);\n\tconst context = {\n\t\trawArgs: opts.rawArgs,\n\t\targs: parsedArgs,\n\t\tdata: opts.data,\n\t\tcmd\n\t};\n\tconst plugins = await resolvePlugins(cmd.plugins ?? []);\n\tlet result;\n\tlet runError;\n\ttry {\n\t\tfor (const plugin of plugins) await plugin.setup?.(context);\n\t\tif (typeof cmd.setup === \"function\") await cmd.setup(context);\n\t\tconst subCommands = await resolveValue(cmd.subCommands);\n\t\tif (subCommands && Object.keys(subCommands).length > 0) {\n\t\t\tconst subCommandArgIndex = findSubCommandIndex(opts.rawArgs, cmdArgs);\n\t\t\tconst explicitName = opts.rawArgs[subCommandArgIndex];\n\t\t\tif (explicitName) {\n\t\t\t\tconst subCommand = await _findSubCommand(subCommands, explicitName);\n\t\t\t\tif (!subCommand) throw new CLIError(`Unknown command ${cyan(explicitName)}`, \"E_UNKNOWN_COMMAND\");\n\t\t\t\tawait runCommand(subCommand, { rawArgs: opts.rawArgs.slice(subCommandArgIndex + 1) });\n\t\t\t} else {\n\t\t\t\tconst defaultSubCommand = await resolveValue(cmd.default);\n\t\t\t\tif (defaultSubCommand) {\n\t\t\t\t\tif (cmd.run) throw new CLIError(`Cannot specify both 'run' and 'default' on the same command.`, \"E_DEFAULT_CONFLICT\");\n\t\t\t\t\tconst subCommand = await _findSubCommand(subCommands, defaultSubCommand);\n\t\t\t\t\tif (!subCommand) throw new CLIError(`Default sub command ${cyan(defaultSubCommand)} not found in subCommands.`, \"E_UNKNOWN_COMMAND\");\n\t\t\t\t\tawait runCommand(subCommand, { rawArgs: opts.rawArgs });\n\t\t\t\t} else if (!cmd.run) throw new CLIError(`No command specified.`, \"E_NO_COMMAND\");\n\t\t\t}\n\t\t}\n\t\tif (typeof cmd.run === \"function\") result = await cmd.run(context);\n\t} catch (error) {\n\t\trunError = error;\n\t}\n\tconst cleanupErrors = [];\n\tif (typeof cmd.cleanup === \"function\") try {\n\t\tawait cmd.cleanup(context);\n\t} catch (error) {\n\t\tcleanupErrors.push(error);\n\t}\n\tfor (const plugin of [...plugins].reverse()) try {\n\t\tawait plugin.cleanup?.(context);\n\t} catch (error) {\n\t\tcleanupErrors.push(error);\n\t}\n\tif (runError) throw runError;\n\tif (cleanupErrors.length === 1) throw cleanupErrors[0];\n\tif (cleanupErrors.length > 1) throw new Error(\"Multiple cleanup errors\", { cause: cleanupErrors });\n\treturn { result };\n}\nasync function resolveSubCommand(cmd, rawArgs, parent) {\n\tconst subCommands = await resolveValue(cmd.subCommands);\n\tif (subCommands && Object.keys(subCommands).length > 0) {\n\t\tconst subCommandArgIndex = findSubCommandIndex(rawArgs, await resolveValue(cmd.args || {}));\n\t\tconst subCommandName = rawArgs[subCommandArgIndex];\n\t\tconst subCommand = await _findSubCommand(subCommands, subCommandName);\n\t\tif (subCommand) return resolveSubCommand(subCommand, rawArgs.slice(subCommandArgIndex + 1), cmd);\n\t}\n\treturn [cmd, parent];\n}\nasync function _findSubCommand(subCommands, name) {\n\tif (name in subCommands) return resolveValue(subCommands[name]);\n\tfor (const sub of Object.values(subCommands)) {\n\t\tconst resolved = await resolveValue(sub);\n\t\tconst meta = await resolveValue(resolved?.meta);\n\t\tif (meta?.alias) {\n\t\t\tif (toArray(meta.alias).includes(name)) return resolved;\n\t\t}\n\t}\n}\nfunction findSubCommandIndex(rawArgs, argsDef) {\n\tfor (let i = 0; i < rawArgs.length; i++) {\n\t\tconst arg = rawArgs[i];\n\t\tif (arg === \"--\") return -1;\n\t\tif (arg.startsWith(\"-\")) {\n\t\t\tif (!arg.includes(\"=\") && _isValueFlag(arg, argsDef)) i++;\n\t\t\tcontinue;\n\t\t}\n\t\treturn i;\n\t}\n\treturn -1;\n}\nfunction _isValueFlag(flag, argsDef) {\n\tconst name = flag.replace(/^-{1,2}/, \"\");\n\tconst normalized = camelCase(name);\n\tfor (const [key, def] of Object.entries(argsDef)) {\n\t\tif (def.type !== \"string\" && def.type !== \"enum\") continue;\n\t\tif (normalized === camelCase(key)) return true;\n\t\tif ((Array.isArray(def.alias) ? def.alias : def.alias ? [def.alias] : []).includes(name)) return true;\n\t}\n\treturn false;\n}\n//#endregion\n//#region src/usage.ts\nasync function showUsage(cmd, parent) {\n\ttry {\n\t\tconsole.log(await renderUsage(cmd, parent) + \"\\n\");\n\t} catch (error) {\n\t\tconsole.error(error);\n\t}\n}\nconst negativePrefixRe = /^no[-A-Z]/;\nasync function renderUsage(cmd, parent) {\n\tconst cmdMeta = await resolveValue(cmd.meta || {});\n\tconst cmdArgs = resolveArgs(await resolveValue(cmd.args || {}));\n\tconst parentMeta = await resolveValue(parent?.meta || {});\n\tconst commandName = `${parentMeta.name ? `${parentMeta.name} ` : \"\"}` + (cmdMeta.name || process.argv[1]);\n\tconst argLines = [];\n\tconst posLines = [];\n\tconst commandsLines = [];\n\tconst usageLine = [];\n\tfor (const arg of cmdArgs) if (arg.type === \"positional\") {\n\t\tconst name = arg.name.toUpperCase();\n\t\tconst isRequired = arg.required !== false && arg.default === void 0;\n\t\tposLines.push([cyan(name + renderValueHint(arg)), renderDescription(arg, isRequired)]);\n\t\tusageLine.push(isRequired ? `<${name}>` : `[${name}]`);\n\t} else {\n\t\tconst isRequired = arg.required === true && arg.default === void 0;\n\t\tconst argStr = [...(arg.alias || []).map((a) => `-${a}`), `--${arg.name}`].join(\", \") + renderValueHint(arg);\n\t\targLines.push([cyan(argStr), renderDescription(arg, isRequired)]);\n\t\t/**\n\t\t* print negative boolean arg variant usage when\n\t\t* - enabled by default or has `negativeDescription`\n\t\t* - not prefixed with `no-` or `no[A-Z]`\n\t\t*/\n\t\tif (arg.type === \"boolean\" && (arg.default === true || arg.negativeDescription) && !negativePrefixRe.test(arg.name)) {\n\t\t\tconst negativeArgStr = [...(arg.alias || []).map((a) => `--no-${a}`), `--no-${arg.name}`].join(\", \");\n\t\t\targLines.push([cyan(negativeArgStr), [arg.negativeDescription, isRequired ? gray(\"(Required)\") : \"\"].filter(Boolean).join(\" \")]);\n\t\t}\n\t\tif (isRequired) usageLine.push(`--${arg.name}` + renderValueHint(arg));\n\t}\n\tif (cmd.subCommands) {\n\t\tconst commandNames = [];\n\t\tconst subCommands = await resolveValue(cmd.subCommands);\n\t\tfor (const [name, sub] of Object.entries(subCommands)) {\n\t\t\tconst meta = await resolveValue((await resolveValue(sub))?.meta);\n\t\t\tif (meta?.hidden) continue;\n\t\t\tconst aliases = toArray(meta?.alias);\n\t\t\tconst label = [name, ...aliases].join(\", \");\n\t\t\tcommandsLines.push([cyan(label), meta?.description || \"\"]);\n\t\t\tcommandNames.push(name, ...aliases);\n\t\t}\n\t\tusageLine.push(commandNames.join(\"|\"));\n\t}\n\tconst usageLines = [];\n\tconst version = cmdMeta.version || parentMeta.version;\n\tusageLines.push(gray(`${cmdMeta.description} (${commandName + (version ? ` v${version}` : \"\")})`), \"\");\n\tconst hasOptions = argLines.length > 0 || posLines.length > 0;\n\tusageLines.push(`${underline(bold(\"USAGE\"))} ${cyan(`${commandName}${hasOptions ? \" [OPTIONS]\" : \"\"} ${usageLine.join(\" \")}`)}`, \"\");\n\tif (posLines.length > 0) {\n\t\tusageLines.push(underline(bold(\"ARGUMENTS\")), \"\");\n\t\tusageLines.push(formatLineColumns(posLines, \"  \"));\n\t\tusageLines.push(\"\");\n\t}\n\tif (argLines.length > 0) {\n\t\tusageLines.push(underline(bold(\"OPTIONS\")), \"\");\n\t\tusageLines.push(formatLineColumns(argLines, \"  \"));\n\t\tusageLines.push(\"\");\n\t}\n\tif (commandsLines.length > 0) {\n\t\tusageLines.push(underline(bold(\"COMMANDS\")), \"\");\n\t\tusageLines.push(formatLineColumns(commandsLines, \"  \"));\n\t\tusageLines.push(\"\", `Use ${cyan(`${commandName} <command> --help`)} for more information about a command.`);\n\t}\n\treturn usageLines.filter((l) => typeof l === \"string\").join(\"\\n\");\n}\nfunction renderValueHint(arg) {\n\tconst valueHint = arg.valueHint ? `=<${arg.valueHint}>` : \"\";\n\tconst fallbackValueHint = valueHint || `=<${snakeCase(arg.name)}>`;\n\tif (!arg.type || arg.type === \"positional\" || arg.type === \"boolean\") return valueHint;\n\tif (arg.type === \"enum\" && arg.options?.length) return `=<${arg.options.join(\"|\")}>`;\n\treturn fallbackValueHint;\n}\nfunction renderDescription(arg, required) {\n\tconst requiredHint = required ? gray(\"(Required)\") : \"\";\n\tconst defaultHint = arg.default === void 0 ? \"\" : gray(`(Default: ${arg.default})`);\n\treturn [\n\t\targ.description,\n\t\trequiredHint,\n\t\tdefaultHint\n\t].filter(Boolean).join(\" \");\n}\n//#endregion\n//#region src/main.ts\nasync function runMain(cmd, opts = {}) {\n\tconst rawArgs = opts.rawArgs || process.argv.slice(2);\n\tconst showUsage$1 = opts.showUsage || showUsage;\n\ttry {\n\t\tconst builtinFlags = await _resolveBuiltinFlags(cmd);\n\t\tif (builtinFlags.help.length > 0 && rawArgs.some((arg) => builtinFlags.help.includes(arg))) {\n\t\t\tawait showUsage$1(...await resolveSubCommand(cmd, rawArgs));\n\t\t\tprocess.exit(0);\n\t\t} else if (rawArgs.length === 1 && builtinFlags.version.includes(rawArgs[0])) {\n\t\t\tconst meta = typeof cmd.meta === \"function\" ? await cmd.meta() : await cmd.meta;\n\t\t\tif (!meta?.version) throw new CLIError(\"No version specified\", \"E_NO_VERSION\");\n\t\t\tconsole.log(meta.version);\n\t\t} else await runCommand(cmd, { rawArgs });\n\t} catch (error) {\n\t\tif (error instanceof CLIError) {\n\t\t\tawait showUsage$1(...await resolveSubCommand(cmd, rawArgs));\n\t\t\tconsole.error(error.message);\n\t\t} else console.error(error, \"\\n\");\n\t\tprocess.exit(1);\n\t}\n}\nfunction createMain(cmd) {\n\treturn (opts = {}) => runMain(cmd, opts);\n}\nasync function _resolveBuiltinFlags(cmd) {\n\tconst argsDef = await resolveValue(cmd.args || {});\n\tconst userNames = /* @__PURE__ */ new Set();\n\tconst userAliases = /* @__PURE__ */ new Set();\n\tfor (const [name, def] of Object.entries(argsDef)) {\n\t\tuserNames.add(name);\n\t\tfor (const alias of toArray(def.alias)) userAliases.add(alias);\n\t}\n\treturn {\n\t\thelp: _getBuiltinFlags(\"help\", \"h\", userNames, userAliases),\n\t\tversion: _getBuiltinFlags(\"version\", \"v\", userNames, userAliases)\n\t};\n}\nfunction _getBuiltinFlags(long, short, userNames, userAliases) {\n\tif (userNames.has(long) || userAliases.has(long)) return [];\n\tif (userNames.has(short) || userAliases.has(short)) return [`--${long}`];\n\treturn [`--${long}`, `-${short}`];\n}\n//#endregion\nexport { createMain, defineCittyPlugin, defineCommand, parseArgs, renderUsage, runCommand, runMain, showUsage };\n","const ANSI_BACKGROUND_OFFSET = 10;\n\nconst wrapAnsi16 = (offset = 0) => code => `\\u001B[${code + offset}m`;\n\nconst wrapAnsi256 = (offset = 0) => code => `\\u001B[${38 + offset};5;${code}m`;\n\nconst wrapAnsi16m = (offset = 0) => (red, green, blue) => `\\u001B[${38 + offset};2;${red};${green};${blue}m`;\n\nconst styles = {\n\tmodifier: {\n\t\treset: [0, 0],\n\t\t// 21 isn't widely supported and 22 does the same thing\n\t\tbold: [1, 22],\n\t\tdim: [2, 22],\n\t\titalic: [3, 23],\n\t\tunderline: [4, 24],\n\t\toverline: [53, 55],\n\t\tinverse: [7, 27],\n\t\thidden: [8, 28],\n\t\tstrikethrough: [9, 29],\n\t},\n\tcolor: {\n\t\tblack: [30, 39],\n\t\tred: [31, 39],\n\t\tgreen: [32, 39],\n\t\tyellow: [33, 39],\n\t\tblue: [34, 39],\n\t\tmagenta: [35, 39],\n\t\tcyan: [36, 39],\n\t\twhite: [37, 39],\n\n\t\t// Bright color\n\t\tblackBright: [90, 39],\n\t\tgray: [90, 39], // Alias of `blackBright`\n\t\tgrey: [90, 39], // Alias of `blackBright`\n\t\tredBright: [91, 39],\n\t\tgreenBright: [92, 39],\n\t\tyellowBright: [93, 39],\n\t\tblueBright: [94, 39],\n\t\tmagentaBright: [95, 39],\n\t\tcyanBright: [96, 39],\n\t\twhiteBright: [97, 39],\n\t},\n\tbgColor: {\n\t\tbgBlack: [40, 49],\n\t\tbgRed: [41, 49],\n\t\tbgGreen: [42, 49],\n\t\tbgYellow: [43, 49],\n\t\tbgBlue: [44, 49],\n\t\tbgMagenta: [45, 49],\n\t\tbgCyan: [46, 49],\n\t\tbgWhite: [47, 49],\n\n\t\t// Bright color\n\t\tbgBlackBright: [100, 49],\n\t\tbgGray: [100, 49], // Alias of `bgBlackBright`\n\t\tbgGrey: [100, 49], // Alias of `bgBlackBright`\n\t\tbgRedBright: [101, 49],\n\t\tbgGreenBright: [102, 49],\n\t\tbgYellowBright: [103, 49],\n\t\tbgBlueBright: [104, 49],\n\t\tbgMagentaBright: [105, 49],\n\t\tbgCyanBright: [106, 49],\n\t\tbgWhiteBright: [107, 49],\n\t},\n};\n\nexport const modifierNames = Object.keys(styles.modifier);\nexport const foregroundColorNames = Object.keys(styles.color);\nexport const backgroundColorNames = Object.keys(styles.bgColor);\nexport const colorNames = [...foregroundColorNames, ...backgroundColorNames];\n\nfunction assembleStyles() {\n\tconst codes = new Map();\n\n\tfor (const [groupName, group] of Object.entries(styles)) {\n\t\tfor (const [styleName, style] of Object.entries(group)) {\n\t\t\tstyles[styleName] = {\n\t\t\t\topen: `\\u001B[${style[0]}m`,\n\t\t\t\tclose: `\\u001B[${style[1]}m`,\n\t\t\t};\n\n\t\t\tgroup[styleName] = styles[styleName];\n\n\t\t\tcodes.set(style[0], style[1]);\n\t\t}\n\n\t\tObject.defineProperty(styles, groupName, {\n\t\t\tvalue: group,\n\t\t\tenumerable: false,\n\t\t});\n\t}\n\n\tObject.defineProperty(styles, 'codes', {\n\t\tvalue: codes,\n\t\tenumerable: false,\n\t});\n\n\tstyles.color.close = '\\u001B[39m';\n\tstyles.bgColor.close = '\\u001B[49m';\n\n\tstyles.color.ansi = wrapAnsi16();\n\tstyles.color.ansi256 = wrapAnsi256();\n\tstyles.color.ansi16m = wrapAnsi16m();\n\tstyles.bgColor.ansi = wrapAnsi16(ANSI_BACKGROUND_OFFSET);\n\tstyles.bgColor.ansi256 = wrapAnsi256(ANSI_BACKGROUND_OFFSET);\n\tstyles.bgColor.ansi16m = wrapAnsi16m(ANSI_BACKGROUND_OFFSET);\n\n\t// From https://github.com/Qix-/color-convert/blob/3f0e0d4e92e235796ccb17f6e85c72094a651f49/conversions.js\n\tObject.defineProperties(styles, {\n\t\trgbToAnsi256: {\n\t\t\tvalue(red, green, blue) {\n\t\t\t\t// We use the extended greyscale palette here, with the exception of\n\t\t\t\t// black and white. normal palette only has 4 greyscale shades.\n\t\t\t\tif (red === green && green === blue) {\n\t\t\t\t\tif (red < 8) {\n\t\t\t\t\t\treturn 16;\n\t\t\t\t\t}\n\n\t\t\t\t\tif (red > 248) {\n\t\t\t\t\t\treturn 231;\n\t\t\t\t\t}\n\n\t\t\t\t\treturn Math.round(((red - 8) / 247) * 24) + 232;\n\t\t\t\t}\n\n\t\t\t\treturn 16\n\t\t\t\t\t+ (36 * Math.round(red / 255 * 5))\n\t\t\t\t\t+ (6 * Math.round(green / 255 * 5))\n\t\t\t\t\t+ Math.round(blue / 255 * 5);\n\t\t\t},\n\t\t\tenumerable: false,\n\t\t},\n\t\thexToRgb: {\n\t\t\tvalue(hex) {\n\t\t\t\tconst matches = /[a-f\\d]{6}|[a-f\\d]{3}/i.exec(hex.toString(16));\n\t\t\t\tif (!matches) {\n\t\t\t\t\treturn [0, 0, 0];\n\t\t\t\t}\n\n\t\t\t\tlet [colorString] = matches;\n\n\t\t\t\tif (colorString.length === 3) {\n\t\t\t\t\tcolorString = [...colorString].map(character => character + character).join('');\n\t\t\t\t}\n\n\t\t\t\tconst integer = Number.parseInt(colorString, 16);\n\n\t\t\t\treturn [\n\t\t\t\t\t/* eslint-disable no-bitwise */\n\t\t\t\t\t(integer >> 16) & 0xFF,\n\t\t\t\t\t(integer >> 8) & 0xFF,\n\t\t\t\t\tinteger & 0xFF,\n\t\t\t\t\t/* eslint-enable no-bitwise */\n\t\t\t\t];\n\t\t\t},\n\t\t\tenumerable: false,\n\t\t},\n\t\thexToAnsi256: {\n\t\t\tvalue: hex => styles.rgbToAnsi256(...styles.hexToRgb(hex)),\n\t\t\tenumerable: false,\n\t\t},\n\t\tansi256ToAnsi: {\n\t\t\tvalue(code) {\n\t\t\t\tif (code < 8) {\n\t\t\t\t\treturn 30 + code;\n\t\t\t\t}\n\n\t\t\t\tif (code < 16) {\n\t\t\t\t\treturn 90 + (code - 8);\n\t\t\t\t}\n\n\t\t\t\tlet red;\n\t\t\t\tlet green;\n\t\t\t\tlet blue;\n\n\t\t\t\tif (code >= 232) {\n\t\t\t\t\tred = (((code - 232) * 10) + 8) / 255;\n\t\t\t\t\tgreen = red;\n\t\t\t\t\tblue = red;\n\t\t\t\t} else {\n\t\t\t\t\tcode -= 16;\n\n\t\t\t\t\tconst remainder = code % 36;\n\n\t\t\t\t\tred = Math.floor(code / 36) / 5;\n\t\t\t\t\tgreen = Math.floor(remainder / 6) / 5;\n\t\t\t\t\tblue = (remainder % 6) / 5;\n\t\t\t\t}\n\n\t\t\t\tconst value = Math.max(red, green, blue) * 2;\n\n\t\t\t\tif (value === 0) {\n\t\t\t\t\treturn 30;\n\t\t\t\t}\n\n\t\t\t\t// eslint-disable-next-line no-bitwise\n\t\t\t\tlet result = 30 + ((Math.round(blue) << 2) | (Math.round(green) << 1) | Math.round(red));\n\n\t\t\t\tif (value === 2) {\n\t\t\t\t\tresult += 60;\n\t\t\t\t}\n\n\t\t\t\treturn result;\n\t\t\t},\n\t\t\tenumerable: false,\n\t\t},\n\t\trgbToAnsi: {\n\t\t\tvalue: (red, green, blue) => styles.ansi256ToAnsi(styles.rgbToAnsi256(red, green, blue)),\n\t\t\tenumerable: false,\n\t\t},\n\t\thexToAnsi: {\n\t\t\tvalue: hex => styles.ansi256ToAnsi(styles.hexToAnsi256(hex)),\n\t\t\tenumerable: false,\n\t\t},\n\t});\n\n\treturn styles;\n}\n\nconst ansiStyles = assembleStyles();\n\nexport default ansiStyles;\n","import process from 'node:process';\nimport os from 'node:os';\nimport tty from 'node:tty';\n\n// From: https://github.com/sindresorhus/has-flag/blob/main/index.js\n/// function hasFlag(flag, argv = globalThis.Deno?.args ?? process.argv) {\nfunction hasFlag(flag, argv = globalThis.Deno ? globalThis.Deno.args : process.argv) {\n\tconst prefix = flag.startsWith('-') ? '' : (flag.length === 1 ? '-' : '--');\n\tconst position = argv.indexOf(prefix + flag);\n\tconst terminatorPosition = argv.indexOf('--');\n\treturn position !== -1 && (terminatorPosition === -1 || position < terminatorPosition);\n}\n\nconst {env} = process;\n\nlet flagForceColor;\nif (\n\thasFlag('no-color')\n\t|| hasFlag('no-colors')\n\t|| hasFlag('color=false')\n\t|| hasFlag('color=never')\n) {\n\tflagForceColor = 0;\n} else if (\n\thasFlag('color')\n\t|| hasFlag('colors')\n\t|| hasFlag('color=true')\n\t|| hasFlag('color=always')\n) {\n\tflagForceColor = 1;\n}\n\nfunction envForceColor() {\n\tif ('FORCE_COLOR' in env) {\n\t\tif (env.FORCE_COLOR === 'true') {\n\t\t\treturn 1;\n\t\t}\n\n\t\tif (env.FORCE_COLOR === 'false') {\n\t\t\treturn 0;\n\t\t}\n\n\t\treturn env.FORCE_COLOR.length === 0 ? 1 : Math.min(Number.parseInt(env.FORCE_COLOR, 10), 3);\n\t}\n}\n\nfunction translateLevel(level) {\n\tif (level === 0) {\n\t\treturn false;\n\t}\n\n\treturn {\n\t\tlevel,\n\t\thasBasic: true,\n\t\thas256: level >= 2,\n\t\thas16m: level >= 3,\n\t};\n}\n\nfunction _supportsColor(haveStream, {streamIsTTY, sniffFlags = true} = {}) {\n\tconst noFlagForceColor = envForceColor();\n\tif (noFlagForceColor !== undefined) {\n\t\tflagForceColor = noFlagForceColor;\n\t}\n\n\tconst forceColor = sniffFlags ? flagForceColor : noFlagForceColor;\n\n\tif (forceColor === 0) {\n\t\treturn 0;\n\t}\n\n\tif (sniffFlags) {\n\t\tif (hasFlag('color=16m')\n\t\t\t|| hasFlag('color=full')\n\t\t\t|| hasFlag('color=truecolor')) {\n\t\t\treturn 3;\n\t\t}\n\n\t\tif (hasFlag('color=256')) {\n\t\t\treturn 2;\n\t\t}\n\t}\n\n\t// Check for Azure DevOps pipelines.\n\t// Has to be above the `!streamIsTTY` check.\n\tif ('TF_BUILD' in env && 'AGENT_NAME' in env) {\n\t\treturn 1;\n\t}\n\n\tif (haveStream && !streamIsTTY && forceColor === undefined) {\n\t\treturn 0;\n\t}\n\n\tconst min = forceColor || 0;\n\n\tif (env.TERM === 'dumb') {\n\t\treturn min;\n\t}\n\n\tif (process.platform === 'win32') {\n\t\t// Windows 10 build 10586 is the first Windows release that supports 256 colors.\n\t\t// Windows 10 build 14931 is the first release that supports 16m/TrueColor.\n\t\tconst osRelease = os.release().split('.');\n\t\tif (\n\t\t\tNumber(osRelease[0]) >= 10\n\t\t\t&& Number(osRelease[2]) >= 10_586\n\t\t) {\n\t\t\treturn Number(osRelease[2]) >= 14_931 ? 3 : 2;\n\t\t}\n\n\t\treturn 1;\n\t}\n\n\tif ('CI' in env) {\n\t\tif (['GITHUB_ACTIONS', 'GITEA_ACTIONS', 'CIRCLECI'].some(key => key in env)) {\n\t\t\treturn 3;\n\t\t}\n\n\t\tif (['TRAVIS', 'APPVEYOR', 'GITLAB_CI', 'BUILDKITE', 'DRONE'].some(sign => sign in env) || env.CI_NAME === 'codeship') {\n\t\t\treturn 1;\n\t\t}\n\n\t\treturn min;\n\t}\n\n\tif ('TEAMCITY_VERSION' in env) {\n\t\treturn /^(9\\.(0*[1-9]\\d*)\\.|\\d{2,}\\.)/.test(env.TEAMCITY_VERSION) ? 1 : 0;\n\t}\n\n\tif (env.COLORTERM === 'truecolor') {\n\t\treturn 3;\n\t}\n\n\tif (env.TERM === 'xterm-kitty') {\n\t\treturn 3;\n\t}\n\n\tif (env.TERM === 'xterm-ghostty') {\n\t\treturn 3;\n\t}\n\n\tif (env.TERM === 'wezterm') {\n\t\treturn 3;\n\t}\n\n\tif ('TERM_PROGRAM' in env) {\n\t\tconst version = Number.parseInt((env.TERM_PROGRAM_VERSION || '').split('.')[0], 10);\n\n\t\tswitch (env.TERM_PROGRAM) {\n\t\t\tcase 'iTerm.app': {\n\t\t\t\treturn version >= 3 ? 3 : 2;\n\t\t\t}\n\n\t\t\tcase 'Apple_Terminal': {\n\t\t\t\treturn 2;\n\t\t\t}\n\t\t\t// No default\n\t\t}\n\t}\n\n\tif (/-256(color)?$/i.test(env.TERM)) {\n\t\treturn 2;\n\t}\n\n\tif (/^screen|^xterm|^vt100|^vt220|^rxvt|color|ansi|cygwin|linux/i.test(env.TERM)) {\n\t\treturn 1;\n\t}\n\n\tif ('COLORTERM' in env) {\n\t\treturn 1;\n\t}\n\n\treturn min;\n}\n\nexport function createSupportsColor(stream, options = {}) {\n\tconst level = _supportsColor(stream, {\n\t\tstreamIsTTY: stream && stream.isTTY,\n\t\t...options,\n\t});\n\n\treturn translateLevel(level);\n}\n\nconst supportsColor = {\n\tstdout: createSupportsColor({isTTY: tty.isatty(1)}),\n\tstderr: createSupportsColor({isTTY: tty.isatty(2)}),\n};\n\nexport default supportsColor;\n","// TODO: When targeting Node.js 16, use `String.prototype.replaceAll`.\nexport function stringReplaceAll(string, substring, replacer) {\n\tlet index = string.indexOf(substring);\n\tif (index === -1) {\n\t\treturn string;\n\t}\n\n\tconst substringLength = substring.length;\n\tlet endIndex = 0;\n\tlet returnValue = '';\n\tdo {\n\t\treturnValue += string.slice(endIndex, index) + substring + replacer;\n\t\tendIndex = index + substringLength;\n\t\tindex = string.indexOf(substring, endIndex);\n\t} while (index !== -1);\n\n\treturnValue += string.slice(endIndex);\n\treturn returnValue;\n}\n\nexport function stringEncaseCRLFWithFirstIndex(string, prefix, postfix, index) {\n\tlet endIndex = 0;\n\tlet returnValue = '';\n\tdo {\n\t\tconst gotCR = string[index - 1] === '\\r';\n\t\treturnValue += string.slice(endIndex, (gotCR ? index - 1 : index)) + prefix + (gotCR ? '\\r\\n' : '\\n') + postfix;\n\t\tendIndex = index + 1;\n\t\tindex = string.indexOf('\\n', endIndex);\n\t} while (index !== -1);\n\n\treturnValue += string.slice(endIndex);\n\treturn returnValue;\n}\n","import ansiStyles from '#ansi-styles';\nimport supportsColor from '#supports-color';\nimport { // eslint-disable-line import/order\n\tstringReplaceAll,\n\tstringEncaseCRLFWithFirstIndex,\n} from './utilities.js';\n\nconst {stdout: stdoutColor, stderr: stderrColor} = supportsColor;\n\nconst GENERATOR = Symbol('GENERATOR');\nconst STYLER = Symbol('STYLER');\nconst IS_EMPTY = Symbol('IS_EMPTY');\n\n// `supportsColor.level` → `ansiStyles.color[name]` mapping\nconst levelMapping = [\n\t'ansi',\n\t'ansi',\n\t'ansi256',\n\t'ansi16m',\n];\n\nconst styles = Object.create(null);\n\nconst applyOptions = (object, options = {}) => {\n\tif (options.level && !(Number.isInteger(options.level) && options.level >= 0 && options.level <= 3)) {\n\t\tthrow new Error('The `level` option should be an integer from 0 to 3');\n\t}\n\n\t// Detect level if not set manually\n\tconst colorLevel = stdoutColor ? stdoutColor.level : 0;\n\tobject.level = options.level === undefined ? colorLevel : options.level;\n};\n\nexport class Chalk {\n\tconstructor(options) {\n\t\t// eslint-disable-next-line no-constructor-return\n\t\treturn chalkFactory(options);\n\t}\n}\n\nconst chalkFactory = options => {\n\tconst chalk = (...strings) => strings.join(' ');\n\tapplyOptions(chalk, options);\n\n\tObject.setPrototypeOf(chalk, createChalk.prototype);\n\n\treturn chalk;\n};\n\nfunction createChalk(options) {\n\treturn chalkFactory(options);\n}\n\nObject.setPrototypeOf(createChalk.prototype, Function.prototype);\n\nfor (const [styleName, style] of Object.entries(ansiStyles)) {\n\tstyles[styleName] = {\n\t\tget() {\n\t\t\tconst builder = createBuilder(this, createStyler(style.open, style.close, this[STYLER]), this[IS_EMPTY]);\n\t\t\tObject.defineProperty(this, styleName, {value: builder});\n\t\t\treturn builder;\n\t\t},\n\t};\n}\n\nstyles.visible = {\n\tget() {\n\t\tconst builder = createBuilder(this, this[STYLER], true);\n\t\tObject.defineProperty(this, 'visible', {value: builder});\n\t\treturn builder;\n\t},\n};\n\nconst getModelAnsi = (model, level, type, ...arguments_) => {\n\tif (model === 'rgb') {\n\t\tif (level === 'ansi16m') {\n\t\t\treturn ansiStyles[type].ansi16m(...arguments_);\n\t\t}\n\n\t\tif (level === 'ansi256') {\n\t\t\treturn ansiStyles[type].ansi256(ansiStyles.rgbToAnsi256(...arguments_));\n\t\t}\n\n\t\treturn ansiStyles[type].ansi(ansiStyles.rgbToAnsi(...arguments_));\n\t}\n\n\tif (model === 'hex') {\n\t\treturn getModelAnsi('rgb', level, type, ...ansiStyles.hexToRgb(...arguments_));\n\t}\n\n\treturn ansiStyles[type][model](...arguments_);\n};\n\nconst usedModels = ['rgb', 'hex', 'ansi256'];\n\nfor (const model of usedModels) {\n\tstyles[model] = {\n\t\tget() {\n\t\t\tconst {level} = this;\n\t\t\treturn function (...arguments_) {\n\t\t\t\tconst styler = createStyler(getModelAnsi(model, levelMapping[level], 'color', ...arguments_), ansiStyles.color.close, this[STYLER]);\n\t\t\t\treturn createBuilder(this, styler, this[IS_EMPTY]);\n\t\t\t};\n\t\t},\n\t};\n\n\tconst bgModel = 'bg' + model[0].toUpperCase() + model.slice(1);\n\tstyles[bgModel] = {\n\t\tget() {\n\t\t\tconst {level} = this;\n\t\t\treturn function (...arguments_) {\n\t\t\t\tconst styler = createStyler(getModelAnsi(model, levelMapping[level], 'bgColor', ...arguments_), ansiStyles.bgColor.close, this[STYLER]);\n\t\t\t\treturn createBuilder(this, styler, this[IS_EMPTY]);\n\t\t\t};\n\t\t},\n\t};\n}\n\nconst proto = Object.defineProperties(() => {}, {\n\t...styles,\n\tlevel: {\n\t\tenumerable: true,\n\t\tget() {\n\t\t\treturn this[GENERATOR].level;\n\t\t},\n\t\tset(level) {\n\t\t\tthis[GENERATOR].level = level;\n\t\t},\n\t},\n});\n\nconst createStyler = (open, close, parent) => {\n\tlet openAll;\n\tlet closeAll;\n\tif (parent === undefined) {\n\t\topenAll = open;\n\t\tcloseAll = close;\n\t} else {\n\t\topenAll = parent.openAll + open;\n\t\tcloseAll = close + parent.closeAll;\n\t}\n\n\treturn {\n\t\topen,\n\t\tclose,\n\t\topenAll,\n\t\tcloseAll,\n\t\tparent,\n\t};\n};\n\nconst createBuilder = (self, _styler, _isEmpty) => {\n\t// Single argument is hot path, implicit coercion is faster than anything\n\t// eslint-disable-next-line no-implicit-coercion\n\tconst builder = (...arguments_) => applyStyle(builder, (arguments_.length === 1) ? ('' + arguments_[0]) : arguments_.join(' '));\n\n\t// We alter the prototype because we must return a function, but there is\n\t// no way to create a function with a different prototype\n\tObject.setPrototypeOf(builder, proto);\n\n\tbuilder[GENERATOR] = self;\n\tbuilder[STYLER] = _styler;\n\tbuilder[IS_EMPTY] = _isEmpty;\n\n\treturn builder;\n};\n\nconst applyStyle = (self, string) => {\n\tif (self.level <= 0 || !string) {\n\t\treturn self[IS_EMPTY] ? '' : string;\n\t}\n\n\tlet styler = self[STYLER];\n\n\tif (styler === undefined) {\n\t\treturn string;\n\t}\n\n\tconst {openAll, closeAll} = styler;\n\tif (string.includes('\\u001B')) {\n\t\twhile (styler !== undefined) {\n\t\t\t// Replace any instances already present with a re-opening code\n\t\t\t// otherwise only the part of the string until said closing code\n\t\t\t// will be colored, and the rest will simply be 'plain'.\n\t\t\tstring = stringReplaceAll(string, styler.close, styler.open);\n\n\t\t\tstyler = styler.parent;\n\t\t}\n\t}\n\n\t// We can move both next actions out of loop, because remaining actions in loop won't have\n\t// any/visible effect on parts we add here. Close the styling before a linebreak and reopen\n\t// after next line to fix a bleed issue on macOS: https://github.com/chalk/chalk/pull/92\n\tconst lfIndex = string.indexOf('\\n');\n\tif (lfIndex !== -1) {\n\t\tstring = stringEncaseCRLFWithFirstIndex(string, closeAll, openAll, lfIndex);\n\t}\n\n\treturn openAll + string + closeAll;\n};\n\nObject.defineProperties(createChalk.prototype, styles);\n\nconst chalk = createChalk();\nexport const chalkStderr = createChalk({level: stderrColor ? stderrColor.level : 0});\n\nexport {\n\tmodifierNames,\n\tforegroundColorNames,\n\tbackgroundColorNames,\n\tcolorNames,\n\n\t// TODO: Remove these aliases in the next major version\n\tmodifierNames as modifiers,\n\tforegroundColorNames as foregroundColors,\n\tbackgroundColorNames as backgroundColors,\n\tcolorNames as colors,\n} from './vendor/ansi-styles/index.js';\n\nexport {\n\tstdoutColor as supportsColor,\n\tstderrColor as supportsColorStderr,\n};\n\nexport default chalk;\n","// Shared terminal presentation: one visual language for CLI output and\n// framework logs. Imported by src/cli/ui/* (re-export) and src/server/logger.ts.\n\nimport chalk from 'chalk'\n\nexport const theme = {\n  primary: chalk.bold.cyan,\n  success: chalk.green,\n  warning: chalk.yellow,\n  error: chalk.red,\n  muted: chalk.dim.gray,\n  value: chalk.white,\n  label: chalk.bold,\n  url: chalk.cyan.underline,\n  code: chalk.dim.white,\n} as const\n\nconst isUnicode = process.env['TERM'] !== 'dumb' && !process.env['CI']\n\nexport const symbols = {\n  success: isUnicode ? '✓' : '√',\n  failure: isUnicode ? '✗' : 'x',\n  info: isUnicode ? '◆' : '*',\n  pointer: isUnicode ? '→' : '>',\n  warning: isUnicode ? '⚠' : '!',\n  pending: isUnicode ? '○' : '-',\n  active: isUnicode ? '●' : '*',\n  ellipsis: isUnicode ? '…' : '...',\n  reload: isUnicode ? '↺' : '~',\n  separator: isUnicode ? '──────────────────────────────────' : '----------------------------------',\n} as const\n","export { theme } from '../../shared/terminal.js'\n","export { symbols } from '../../shared/terminal.js'\n","import { theme } from './theme.js'\nimport { symbols } from './symbols.js'\n\nlet quiet = false\n\nexport function setQuiet(value: boolean): void {\n  quiet = value\n}\n\nexport function isQuiet(): boolean {\n  return quiet\n}\n\nexport const log = {\n  info(message: string): void {\n    if (quiet) return\n    process.stderr.write(`${theme.muted(symbols.info)} ${message}\\n`)\n  },\n\n  success(message: string): void {\n    if (quiet) return\n    process.stderr.write(`${theme.success(symbols.success)} ${message}\\n`)\n  },\n\n  warn(message: string): void {\n    if (quiet) return\n    process.stderr.write(`${theme.warning(symbols.warning)} ${theme.warning(message)}\\n`)\n  },\n\n  error(message: string): void {\n    process.stderr.write(`${theme.error(symbols.failure)} ${theme.error(message)}\\n`)\n  },\n\n  muted(message: string): void {\n    if (quiet) return\n    process.stderr.write(`${theme.muted(message)}\\n`)\n  },\n\n  section(title: string): void {\n    if (quiet) return\n    process.stderr.write(`\\n${theme.primary(title)}\\n${theme.muted(symbols.separator)}\\n`)\n  },\n\n  kv(key: string, value: string): void {\n    if (quiet) return\n    process.stderr.write(`${theme.label(key.padEnd(12))} ${theme.value(value)}\\n`)\n  },\n\n  raw(message: string): void {\n    process.stdout.write(`${message}\\n`)\n  },\n}\n","let jsonMode = false\n\nexport function setJsonMode(value: boolean): void {\n  jsonMode = value\n}\n\nexport function isJsonMode(): boolean {\n  return jsonMode\n}\n\nexport function output<T>(data: T, renderFn: (data: T) => void): void {\n  if (jsonMode) {\n    process.stdout.write(JSON.stringify(data, null, 2) + '\\n')\n  } else {\n    renderFn(data)\n  }\n}\n","import { defineCommand } from 'citty'\nimport { output, setJsonMode } from '../ui/format.js'\nimport { log } from '../ui/output.js'\n\ndeclare const __FASTMCP_VERSION__: string\ndeclare const __MCP_SDK_VERSION__: string\n\nexport default defineCommand({\n  meta: { name: 'version', description: 'Print version information' },\n  args: {\n    json: { type: 'boolean', description: 'Output JSON', default: false },\n  },\n  async run({ args }) {\n    if (args.json) setJsonMode(true)\n    const data = {\n      fastmcp: __FASTMCP_VERSION__,\n      'mcp-sdk': __MCP_SDK_VERSION__,\n      node: process.version,\n      platform: `${process.platform} ${process.arch}`,\n    }\n\n    output(data, (d) => {\n      for (const [key, value] of Object.entries(d)) {\n        log.kv(key, value)\n      }\n    })\n  },\n})\n","import { existsSync } from 'node:fs'\nimport { resolve, extname } from 'node:path'\n\nexport interface FileSpec {\n  filePath: string\n  /** Export name to resolve. Meaningless when `explicitExport` is false — the\n   *  loader auto-detects a conventional export name in that case. */\n  exportName: string\n  /** True when the user specified an export name via `file:export` colon syntax\n   *  or an explicit `--export` flag. False when only a file path was given, in\n   *  which case the entrypoint loader falls back to auto-detection. */\n  explicitExport: boolean\n  isTypeScript: boolean\n}\n\nexport function parseFileSpec(spec: string, exportOverride?: string): FileSpec {\n  const colonIdx = spec.lastIndexOf(':')\n  let filePart: string\n  let exportName: string\n  let explicitExport: boolean\n\n  if (colonIdx > 1) {\n    filePart = spec.slice(0, colonIdx)\n    exportName = spec.slice(colonIdx + 1)\n    explicitExport = exportName.length > 0\n    if (!explicitExport) exportName = 'default'\n  } else {\n    filePart = spec\n    exportName = 'default'\n    explicitExport = false\n  }\n\n  // An explicit --export flag takes precedence over the colon syntax.\n  if (exportOverride) {\n    exportName = exportOverride\n    explicitExport = true\n  }\n\n  const filePath = resolve(process.cwd(), filePart)\n\n  if (!existsSync(filePath)) {\n    throw new Error(`File not found: ${filePath}`)\n  }\n\n  const ext = extname(filePath).toLowerCase()\n  const isTypeScript = ext === '.ts' || ext === '.tsx' || ext === '.mts'\n\n  return { filePath, exportName, explicitExport, isTypeScript }\n}\n","import { join } from 'node:path'\n\n// The CLI is bundled to CJS (see tsup.config.ts), so `__dirname` refers to the\n// bundle's own output directory (dist/cli/) at runtime — `import.meta.url`\n// isn't usable here since esbuild leaves it empty for cjs output.\ndeclare const __dirname: string\n\n/**\n * Absolute path to the bundled entrypoint bootstrap script that `run`,\n * `inspect`, `list`, `call`, and `dev inspector` spawn instead of the user's\n * server file directly (see `src/cli/entrypoint-runtime.ts`). tsup emits it as\n * `entrypoint-runtime.cjs`, a sibling of this bundle's own output file\n * (`dist/cli/index.cjs`), so it's resolved relative to that directory rather\n * than hardcoded.\n */\nexport function resolveEntrypointBootstrapPath(): string {\n  return join(__dirname, 'entrypoint-runtime.cjs')\n}\n\n/** Environment variables consumed by the entrypoint bootstrap. */\nexport function buildEntrypointEnv(spec: {\n  filePath: string\n  exportName: string\n  explicitExport: boolean\n}): Record<string, string> {\n  const env: Record<string, string> = {\n    FASTMCP_ENTRYPOINT_FILE: spec.filePath,\n  }\n  if (spec.explicitExport) {\n    env['FASTMCP_ENTRYPOINT_EXPORT'] = spec.exportName\n  }\n  return env\n}\n","//#region rolldown:runtime\nvar __create = Object.create;\nvar __defProp = Object.defineProperty;\nvar __getOwnPropDesc = Object.getOwnPropertyDescriptor;\nvar __getOwnPropNames = Object.getOwnPropertyNames;\nvar __getProtoOf = Object.getPrototypeOf;\nvar __hasOwnProp = Object.prototype.hasOwnProperty;\nvar __commonJSMin = (cb, mod) => () => (mod || cb((mod = { exports: {} }).exports, mod), mod.exports);\nvar __exportAll = (all, symbols) => {\n\tlet target = {};\n\tfor (var name in all) {\n\t\t__defProp(target, name, {\n\t\t\tget: all[name],\n\t\t\tenumerable: true\n\t\t});\n\t}\n\tif (symbols) {\n\t\t__defProp(target, Symbol.toStringTag, { value: \"Module\" });\n\t}\n\treturn target;\n};\nvar __copyProps = (to, from, except, desc) => {\n\tif (from && typeof from === \"object\" || typeof from === \"function\") {\n\t\tfor (var keys = __getOwnPropNames(from), i = 0, n = keys.length, key; i < n; i++) {\n\t\t\tkey = keys[i];\n\t\t\tif (!__hasOwnProp.call(to, key) && key !== except) {\n\t\t\t\t__defProp(to, key, {\n\t\t\t\t\tget: ((k) => from[k]).bind(null, key),\n\t\t\t\t\tenumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable\n\t\t\t\t});\n\t\t\t}\n\t\t}\n\t}\n\treturn to;\n};\nvar __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(isNodeMode || !mod || !mod.__esModule ? __defProp(target, \"default\", {\n\tvalue: mod,\n\tenumerable: true\n}) : target, mod));\n\n//#endregion\nexport { __exportAll as n, __toESM as r, __commonJSMin as t };","/**\n * Declared-dialect classification shared by the default validator providers.\n */\n\nimport type { JsonSchemaType } from './types';\n\n/**\n * Canonical `$schema` URIs per supported dialect (http + https variants, trailing-`#` stripped).\n */\nconst DRAFT_2020_12_URIS: ReadonlySet<string> = new Set([\n    'https://json-schema.org/draft/2020-12/schema',\n    'http://json-schema.org/draft/2020-12/schema'\n]);\nconst DRAFT_2019_09_URIS: ReadonlySet<string> = new Set([\n    'https://json-schema.org/draft/2019-09/schema',\n    'http://json-schema.org/draft/2019-09/schema'\n]);\nconst DRAFT_07_URIS: ReadonlySet<string> = new Set(['https://json-schema.org/draft-07/schema', 'http://json-schema.org/draft-07/schema']);\nconst DRAFT_06_URIS: ReadonlySet<string> = new Set(['https://json-schema.org/draft-06/schema', 'http://json-schema.org/draft-06/schema']);\n\n/**\n * Dialects the default providers dispatch on. draft-06 maps to `'draft-7'`: draft-07 only adds\n * keywords over draft-06 (`if`/`then`/`else`), and enforcing them on a draft-06 schema is the\n * accepted downlevel.\n */\nexport type DeclaredDialect = '2020-12' | '2019-09' | 'draft-7';\n\n/**\n * Whether a `$schema` value declares the 2019-09 dialect — the only supported dialect with\n * `$recursiveRef`/`$recursiveAnchor`. Non-throwing (unlike {@linkcode declaredDialect}) so\n * wire-layer callers can consult it for documents whose dialect may be unsupported.\n */\nexport function declares2019Dialect($schema: unknown): boolean {\n    return typeof $schema === 'string' && DRAFT_2019_09_URIS.has($schema.replace(/#$/, ''));\n}\n\n/**\n * Classify a schema's declared `$schema` dialect. No `$schema` (or a non-string one) means\n * 2020-12. Any other dialect throws a plain `Error` with a clear message rather than letting the\n * engine crash on an opaque internal error or silently mis-validate; `remedy` names the calling\n * provider's escape hatch in that message.\n */\nexport function declaredDialect(schema: JsonSchemaType, remedy: string): DeclaredDialect {\n    if (!('$schema' in schema) || typeof schema.$schema !== 'string') {\n        return '2020-12';\n    }\n    const declared = schema.$schema.replace(/#$/, '');\n    if (DRAFT_2020_12_URIS.has(declared)) {\n        return '2020-12';\n    }\n    if (DRAFT_2019_09_URIS.has(declared)) {\n        return '2019-09';\n    }\n    if (DRAFT_07_URIS.has(declared) || DRAFT_06_URIS.has(declared)) {\n        return 'draft-7';\n    }\n    throw new Error(\n        `JSON Schema declares an unsupported dialect (\"$schema\": \"${schema.$schema.slice(0, 200)}\"). ` +\n            `The default validator supports JSON Schema 2020-12, 2019-09, draft-07, and draft-06; ${remedy}`\n    );\n}\n","import { globalConfig } from \"./core.js\";\n// functions\nexport function assertEqual(val) {\n    return val;\n}\nexport function assertNotEqual(val) {\n    return val;\n}\nexport function toZod() {\n    return (schema) => schema;\n}\nexport function assertIs(_arg) { }\nexport function assertNever(_x) {\n    throw new Error(\"Unexpected value in exhaustive check\");\n}\nexport function assert(_) { }\nexport function getEnumValues(entries) {\n    const numericValues = Object.values(entries).filter((v) => typeof v === \"number\");\n    const values = Object.entries(entries)\n        .filter(([k, _]) => numericValues.indexOf(+k) === -1)\n        .map(([_, v]) => v);\n    return values;\n}\nexport function joinValues(array, separator = \"|\") {\n    return array.map((val) => stringifyPrimitive(val)).join(separator);\n}\nexport function jsonStringifyReplacer(_, value) {\n    if (typeof value === \"bigint\")\n        return value.toString();\n    return value;\n}\n// the accessor lives on a shared prototype: an own accessor makes every box a dictionary-mode object (~360 B and a slow load per read against ~100 B and an inlined getter here)\nclass Cached {\n    constructor(getter) {\n        this._getter = getter;\n        this._value = undefined;\n    }\n    get value() {\n        const getter = this._getter;\n        if (getter !== undefined) {\n            this._value = getter();\n            this._getter = undefined;\n        }\n        return this._value;\n    }\n}\nexport function cached(getter) {\n    return new Cached(getter);\n}\nexport function nullish(input) {\n    return input === null || input === undefined;\n}\nexport function cleanRegex(source) {\n    const start = source.startsWith(\"^\") ? 1 : 0;\n    const end = source.endsWith(\"$\") ? source.length - 1 : source.length;\n    return source.slice(start, end);\n}\nexport function floatSafeRemainder(val, step) {\n    const ratio = val / step;\n    const roundedRatio = Math.round(ratio);\n    // `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.\n    const tolerance = 4 * Number.EPSILON * Math.max(Math.abs(ratio), 1);\n    if (Math.abs(ratio - roundedRatio) < tolerance)\n        return 0;\n    return ratio - roundedRatio;\n}\nconst EVALUATING = /* @__PURE__*/ Symbol(\"evaluating\");\nexport function defineLazy(object, key, getter) {\n    let value = undefined;\n    Object.defineProperty(object, key, {\n        get() {\n            if (value === EVALUATING) {\n                // Circular reference detected, return undefined to break the cycle\n                return undefined;\n            }\n            if (value === undefined) {\n                value = EVALUATING;\n                value = getter();\n            }\n            return value;\n        },\n        set(v) {\n            Object.defineProperty(object, key, {\n                value: v,\n                // configurable: true,\n            });\n            // object[key] = v;\n        },\n        configurable: true,\n    });\n}\nexport function objectClone(obj) {\n    return Object.create(Object.getPrototypeOf(obj), Object.getOwnPropertyDescriptors(obj));\n}\nexport function assignProp(target, prop, value) {\n    Object.defineProperty(target, prop, {\n        value,\n        writable: true,\n        enumerable: true,\n        configurable: true,\n    });\n}\n/**\n * Whichever object a def's `shape` currently answers from: the one the caller passed until the first read, the frozen copy after it.\n *\n * Its keys and descriptors read without invoking anything, which is what lets a discriminated union check its discriminator, and the cycle walk read a shape, without resolving a getter that references the schema being constructed. A def that answers `shape` from an accessor of its own has none.\n */\nexport function rawShape(def) {\n    const desc = Object.getOwnPropertyDescriptor(def, \"shape\");\n    return desc?.get ? desc.get.raw : desc?.value;\n}\n// where a builder reads its source's keys and descriptors, resolving only a shape a def answers for itself. A shape resolves by object spread, so only its enumerable keys are ever part of it.\nfunction sourceShape(schema) {\n    return rawShape(schema._zod.def) ?? schema._zod.def.shape;\n}\n// a key whose value is not settled yet, self-caching so every read after the first gets the same one\nfunction deferProp(target, key, getter) {\n    Object.defineProperty(target, key, {\n        get() {\n            const value = getter();\n            assignProp(this, key, value);\n            return value;\n        },\n        enumerable: true,\n        configurable: true,\n    });\n}\n// Writes a settled key. A plain assignment is much cheaper than `defineProperty` and produces the same descriptor, but it runs whatever setter already answers to the key — an accessor this shape deferred, or an inherited one, which `__proto__` has on every object and prototype pollution can add for any name.\nfunction putProp(target, key, value) {\n    if (key in target)\n        assignProp(target, key, value);\n    else\n        target[key] = value;\n}\n/**\n * Copies `keys` of `source`'s shape onto `target`, each value passed through `wrap`.\n *\n * A key the source has resolved is copied through now, so the derived shape states it outright and nothing has to resolve it to learn what it holds. A key the source still defers stays deferred, and reads back through the source's own `shape`, so it resolves once and both shapes get that one schema.\n */\nfunction mirrorShape(target, source, keys, wrap) {\n    const raw = sourceShape(source);\n    for (const key of keys) {\n        const desc = Object.getOwnPropertyDescriptor(raw, key);\n        if (!desc.enumerable)\n            continue;\n        if (desc.get) {\n            deferProp(target, key, () => {\n                const value = source._zod.def.shape[key];\n                return wrap ? wrap(value, key) : value;\n            });\n        }\n        else\n            putProp(target, key, wrap ? wrap(desc.value, key) : desc.value);\n    }\n}\n// same, for a plain shape a caller passed rather than a schema's\nfunction mirrorProps(target, source) {\n    for (const key of Reflect.ownKeys(source)) {\n        const desc = Object.getOwnPropertyDescriptor(source, key);\n        if (!desc.enumerable)\n            continue;\n        if (desc.get)\n            deferProp(target, key, () => source[key]);\n        else\n            putProp(target, key, desc.value);\n    }\n}\nexport function mergeDefs(...defs) {\n    const mergedDescriptors = {};\n    for (const def of defs) {\n        const descriptors = Object.getOwnPropertyDescriptors(def);\n        Object.assign(mergedDescriptors, descriptors);\n    }\n    return Object.defineProperties({}, mergedDescriptors);\n}\nexport function cloneDef(schema) {\n    return mergeDefs(schema._zod.def);\n}\nexport function getElementAtPath(obj, path) {\n    if (!path)\n        return obj;\n    return path.reduce((acc, key) => acc?.[key], obj);\n}\nexport function promiseAllObject(promisesObj) {\n    const keys = Object.keys(promisesObj);\n    const promises = keys.map((key) => promisesObj[key]);\n    return Promise.all(promises).then((results) => {\n        const resolvedObj = {};\n        for (let i = 0; i < keys.length; i++) {\n            resolvedObj[keys[i]] = results[i];\n        }\n        return resolvedObj;\n    });\n}\nexport function randomString(length = 10) {\n    const chars = \"abcdefghijklmnopqrstuvwxyz\";\n    let str = \"\";\n    for (let i = 0; i < length; i++) {\n        str += chars[Math.floor(Math.random() * chars.length)];\n    }\n    return str;\n}\nexport function esc(str) {\n    return JSON.stringify(str);\n}\nexport function slugify(input) {\n    return input\n        .toLowerCase()\n        .trim()\n        .replace(/[^\\w\\s-]/g, \"\")\n        .replace(/[\\s_-]+/g, \"-\")\n        .replace(/^-+|-+$/g, \"\");\n}\nexport const captureStackTrace = (\"captureStackTrace\" in Error ? Error.captureStackTrace : (..._args) => { });\nexport function isObject(data) {\n    return typeof data === \"object\" && data !== null && !Array.isArray(data);\n}\nexport const allowsEval = /* @__PURE__*/ cached(() => {\n    // Skip the probe under `jitless`: strict CSPs report the caught `new Function` as a `securitypolicyviolation` even though the throw is swallowed.\n    if (globalConfig.jitless) {\n        return false;\n    }\n    // @ts-ignore\n    if (typeof navigator !== \"undefined\" && navigator?.userAgent?.includes(\"Cloudflare\")) {\n        return false;\n    }\n    try {\n        const F = Function;\n        new F(\"\");\n        return true;\n    }\n    catch (_) {\n        return false;\n    }\n});\nexport function isPlainObject(o) {\n    if (isObject(o) === false)\n        return false;\n    // modified constructor\n    const ctor = o.constructor;\n    if (ctor === undefined)\n        return true;\n    if (typeof ctor !== \"function\")\n        return true;\n    // modified prototype\n    const prot = ctor.prototype;\n    if (isObject(prot) === false)\n        return false;\n    // ctor doesn't have static `isPrototypeOf`\n    if (Object.prototype.hasOwnProperty.call(prot, \"isPrototypeOf\") === false) {\n        return false;\n    }\n    return true;\n}\nexport function shallowClone(o) {\n    if (isPlainObject(o))\n        return { ...o };\n    if (Array.isArray(o))\n        return [...o];\n    if (o instanceof Map)\n        return new Map(o);\n    if (o instanceof Set)\n        return new Set(o);\n    return o;\n}\nexport function numKeys(data) {\n    let keyCount = 0;\n    for (const key in data) {\n        if (Object.prototype.hasOwnProperty.call(data, key)) {\n            keyCount++;\n        }\n    }\n    return keyCount;\n}\nexport const getParsedType = (data) => {\n    const t = typeof data;\n    switch (t) {\n        case \"undefined\":\n            return \"undefined\";\n        case \"string\":\n            return \"string\";\n        case \"number\":\n            return Number.isNaN(data) ? \"nan\" : \"number\";\n        case \"boolean\":\n            return \"boolean\";\n        case \"function\":\n            return \"function\";\n        case \"bigint\":\n            return \"bigint\";\n        case \"symbol\":\n            return \"symbol\";\n        case \"object\":\n            if (Array.isArray(data)) {\n                return \"array\";\n            }\n            if (data === null) {\n                return \"null\";\n            }\n            if (data.then && typeof data.then === \"function\" && data.catch && typeof data.catch === \"function\") {\n                return \"promise\";\n            }\n            if (typeof Map !== \"undefined\" && data instanceof Map) {\n                return \"map\";\n            }\n            if (typeof Set !== \"undefined\" && data instanceof Set) {\n                return \"set\";\n            }\n            if (typeof Date !== \"undefined\" && data instanceof Date) {\n                return \"date\";\n            }\n            // @ts-ignore\n            if (typeof File !== \"undefined\" && data instanceof File) {\n                return \"file\";\n            }\n            return \"object\";\n        default:\n            throw new Error(`Unknown data type: ${t}`);\n    }\n};\nexport const propertyKeyTypes = /* @__PURE__*/ new Set([\"string\", \"number\", \"symbol\"]);\nexport const primitiveTypes = /* @__PURE__*/ new Set([\n    \"string\",\n    \"number\",\n    \"bigint\",\n    \"boolean\",\n    \"symbol\",\n    \"undefined\",\n]);\nexport function escapeRegex(str) {\n    return str.replace(/[.*+?^${}()|[\\]\\\\]/g, \"\\\\$&\");\n}\n// zod-specific utils\nexport function clone(inst, def, params) {\n    const cl = new inst._zod.constr(def ?? inst._zod.def);\n    if (!def || params?.parent)\n        cl._zod.parent = inst;\n    return cl;\n}\nexport function normalizeParams(_params) {\n    const params = _params;\n    if (!params)\n        return {};\n    if (typeof params === \"string\")\n        return { error: () => params };\n    if (params?.message !== undefined) {\n        if (params?.error !== undefined)\n            throw new Error(\"Cannot specify both `message` and `error` params\");\n        params.error = params.message;\n    }\n    delete params.message;\n    if (typeof params.error === \"string\")\n        return { ...params, error: () => params.error };\n    return params;\n}\nexport function createTransparentProxy(getter) {\n    let target;\n    return new Proxy({}, {\n        get(_, prop, receiver) {\n            target ?? (target = getter());\n            return Reflect.get(target, prop, receiver);\n        },\n        set(_, prop, value, receiver) {\n            target ?? (target = getter());\n            return Reflect.set(target, prop, value, receiver);\n        },\n        has(_, prop) {\n            target ?? (target = getter());\n            return Reflect.has(target, prop);\n        },\n        deleteProperty(_, prop) {\n            target ?? (target = getter());\n            return Reflect.deleteProperty(target, prop);\n        },\n        ownKeys(_) {\n            target ?? (target = getter());\n            return Reflect.ownKeys(target);\n        },\n        getOwnPropertyDescriptor(_, prop) {\n            target ?? (target = getter());\n            return Reflect.getOwnPropertyDescriptor(target, prop);\n        },\n        defineProperty(_, prop, descriptor) {\n            target ?? (target = getter());\n            return Reflect.defineProperty(target, prop, descriptor);\n        },\n    });\n}\nexport function stringifyPrimitive(value) {\n    if (typeof value === \"bigint\")\n        return value.toString() + \"n\";\n    if (typeof value === \"string\")\n        return `\"${value}\"`;\n    return `${value}`;\n}\nexport function optionalKeys(shape) {\n    return Object.keys(shape).filter((k) => {\n        return shape[k]._zod.optin !== undefined && shape[k]._zod.optout === \"optional\";\n    });\n}\n// 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.\nexport const NUMBER_FORMAT_RANGES = /*@__PURE__*/ (() => ({\n    safeint: [Number.MIN_SAFE_INTEGER, Number.MAX_SAFE_INTEGER],\n    int32: [-2147483648, 2147483647],\n    uint32: [0, 4294967295],\n    float32: [-3.4028234663852886e38, 3.4028234663852886e38],\n    float64: [-Number.MAX_VALUE, Number.MAX_VALUE],\n}))();\nexport const BIGINT_FORMAT_RANGES = {\n    int64: [/* @__PURE__*/ BigInt(\"-9223372036854775808\"), /* @__PURE__*/ BigInt(\"9223372036854775807\")],\n    uint64: [/* @__PURE__*/ BigInt(0), /* @__PURE__*/ BigInt(\"18446744073709551615\")],\n};\nexport function pick(schema, mask) {\n    const currDef = schema._zod.def;\n    const checks = currDef.checks;\n    const hasChecks = checks && checks.length > 0;\n    if (hasChecks) {\n        throw new Error(\".pick() cannot be used on object schemas containing refinements\");\n    }\n    const newShape = {};\n    mirrorShape(newShape, schema, maskedKeys(schema, mask));\n    return clone(schema, mergeDefs(currDef, { shape: newShape, checks: [] }));\n}\n// the mask keys that select something, checked against the source's shape without resolving it\nfunction maskedKeys(schema, mask) {\n    const raw = sourceShape(schema);\n    const keys = [];\n    // `for...in` skips symbols, so a symbol in the mask would select nothing\n    for (const key of Reflect.ownKeys(mask)) {\n        if (!Object.getOwnPropertyDescriptor(raw, key)?.enumerable) {\n            throw new Error(`Unrecognized key: \"${String(key)}\"`);\n        }\n        if (mask[key])\n            keys.push(key);\n    }\n    return keys;\n}\nexport function omit(schema, mask) {\n    const currDef = schema._zod.def;\n    const checks = currDef.checks;\n    const hasChecks = checks && checks.length > 0;\n    if (hasChecks) {\n        throw new Error(\".omit() cannot be used on object schemas containing refinements\");\n    }\n    const omitted = new Set(maskedKeys(schema, mask));\n    const newShape = {};\n    mirrorShape(newShape, schema, Reflect.ownKeys(sourceShape(schema)).filter((key) => !omitted.has(key)));\n    return clone(schema, mergeDefs(currDef, { shape: newShape, checks: [] }));\n}\nexport function extend(schema, shape) {\n    if (!isPlainObject(shape)) {\n        throw new Error(\"Invalid input to extend: expected a plain object\");\n    }\n    const checks = schema._zod.def.checks;\n    const hasChecks = checks && checks.length > 0;\n    if (hasChecks) {\n        // Only throw if new shape overlaps with existing shape. Use getOwnPropertyDescriptor to check key existence without accessing values\n        const existingShape = sourceShape(schema);\n        for (const key of Reflect.ownKeys(shape)) {\n            if (Object.getOwnPropertyDescriptor(existingShape, key) !== undefined) {\n                throw new Error(\"Cannot overwrite keys on object schemas containing refinements. Use `.safeExtend()` instead.\");\n            }\n        }\n    }\n    return clone(schema, mergeDefs(schema._zod.def, { shape: extended(schema, shape) }));\n}\n// the source's keys, then the caller's overlaid on top\nfunction extended(schema, shape) {\n    const newShape = {};\n    mirrorShape(newShape, schema, Reflect.ownKeys(sourceShape(schema)));\n    mirrorProps(newShape, shape);\n    return newShape;\n}\nexport function safeExtend(schema, shape) {\n    if (!isPlainObject(shape)) {\n        throw new Error(\"Invalid input to safeExtend: expected a plain object\");\n    }\n    return clone(schema, mergeDefs(schema._zod.def, { shape: extended(schema, shape) }));\n}\nexport function merge(a, b) {\n    if (!b?._zod?.def) {\n        throw new Error(\"Invalid input to merge: expected an object schema. To merge a plain shape, use `.extend()`.\");\n    }\n    if (a._zod.def.checks?.length) {\n        throw new Error(\".merge() cannot be used on object schemas containing refinements. Use .safeExtend() instead.\");\n    }\n    const newShape = {};\n    mirrorShape(newShape, a, Reflect.ownKeys(sourceShape(a)));\n    mirrorShape(newShape, b, Reflect.ownKeys(sourceShape(b)));\n    const def = mergeDefs(a._zod.def, {\n        shape: newShape,\n        get catchall() {\n            return b._zod.def.catchall;\n        },\n        checks: b._zod.def.checks ?? [],\n    });\n    return clone(a, def);\n}\nexport function partial(Class, schema, mask, name = \"partial\") {\n    const currDef = schema._zod.def;\n    const checks = currDef.checks;\n    const hasChecks = checks && checks.length > 0;\n    if (hasChecks) {\n        throw new Error(`.${name}() cannot be used on object schemas containing refinements`);\n    }\n    const selected = mask ? new Set(maskedKeys(schema, mask)) : undefined;\n    const newShape = {};\n    mirrorShape(newShape, schema, Reflect.ownKeys(sourceShape(schema)), Class &&\n        ((value, key) => (selected && !selected.has(key) ? value : new Class({ type: \"optional\", innerType: value }))));\n    return clone(schema, mergeDefs(schema._zod.def, { shape: newShape, checks: [] }));\n}\nexport function required(Class, schema, mask) {\n    const selected = mask ? new Set(maskedKeys(schema, mask)) : undefined;\n    const newShape = {};\n    mirrorShape(newShape, schema, Reflect.ownKeys(sourceShape(schema)), (value, key) => \n    // overwrite with non-optional\n    selected && !selected.has(key) ? value : new Class({ type: \"nonoptional\", innerType: value }));\n    return clone(schema, mergeDefs(schema._zod.def, { shape: newShape }));\n}\n// invalid_type | too_big | too_small | invalid_format | not_multiple_of | unrecognized_keys | invalid_union | invalid_key | invalid_element | invalid_value | custom\nexport function aborted(x, startIndex = 0) {\n    if (x.aborted === true)\n        return true;\n    for (let i = startIndex; i < x.issues.length; i++) {\n        if (x.issues[i]?.continue !== true) {\n            return true;\n        }\n    }\n    return false;\n}\n// 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.\nexport function explicitlyAborted(x, startIndex = 0) {\n    if (x.aborted === true)\n        return true;\n    for (let i = startIndex; i < x.issues.length; i++) {\n        if (x.issues[i]?.continue === false) {\n            return true;\n        }\n    }\n    return false;\n}\nexport function prefixIssues(path, issues) {\n    return issues.map((iss) => {\n        var _a;\n        (_a = iss).path ?? (_a.path = []);\n        iss.path.unshift(path);\n        return iss;\n    });\n}\nexport function unwrapMessage(message) {\n    return typeof message === \"string\" ? message : message?.message;\n}\n/* 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. */\n/** The leading size checks of `defChecks` that set an upper bound, each paired with it. */\nexport function sizeCaps(defChecks) {\n    const caps = [];\n    for (const ch of defChecks ?? []) {\n        const d = ch._zod.def;\n        // a later check may rewrite the value\n        if (!/_(length|size)$|_equals$/.test(d.check))\n            break;\n        const max = d.maximum ?? d.length ?? d.size;\n        if (max >= 0)\n            caps.push([max, ch]);\n    }\n    return caps;\n}\nexport function attachSchema(issues, start, inst) {\n    var _a;\n    for (let i = start; i < issues.length; i++) {\n        (_a = issues[i]).schema ?? (_a.schema = inst);\n    }\n}\nexport function finalizeIssue(iss, ctx, config) {\n    var _a;\n    // 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.\n    const traits = iss.inst?._zod?.traits;\n    if (traits?.has(\"$ZodType\")) {\n        if (traits.has(\"$ZodCheck\"))\n            (_a = iss).schema ?? (_a.schema = iss.inst);\n        else\n            iss.schema = iss.inst;\n    }\n    // 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.\n    const schemaError = iss.schema !== iss.inst ? iss.schema?._zod.def?.error : undefined;\n    const message = iss.message\n        ? iss.message\n        : (unwrapMessage(iss.inst?._zod.def?.error?.(iss)) ??\n            unwrapMessage(schemaError?.(iss)) ??\n            unwrapMessage(ctx?.error?.(iss)) ??\n            unwrapMessage(config.customError?.(iss)) ??\n            unwrapMessage(config.localeError?.(iss)) ??\n            \"Invalid input\");\n    // an explicit own-key copy beats object rest with excluded keys, which v8 routes through a generic runtime call; Object.keys rather than for-in so an issue pushed with a prototype does not leak inherited keys, and an own __proto__ key is dropped rather than assigned through the setter\n    const full = {};\n    for (const k of Object.keys(iss)) {\n        if (k === \"inst\" || k === \"schema\" || k === \"continue\" || k === \"input\" || k === \"__proto__\")\n            continue;\n        full[k] = iss[k];\n    }\n    full.path ?? (full.path = []);\n    full.message = message;\n    if (ctx?.reportInput) {\n        full.input = iss.input;\n    }\n    return full;\n}\nexport function getSizableOrigin(input) {\n    if (input instanceof Set)\n        return \"set\";\n    if (input instanceof Map)\n        return \"map\";\n    // @ts-ignore\n    if (input instanceof File)\n        return \"file\";\n    return \"unknown\";\n}\nconst highSurrogate = /[\\uD800-\\uDBFF]/;\n// 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.\nexport function codePointLength(str) {\n    const units = str.length;\n    if (!highSurrogate.test(str))\n        return units;\n    let count = units;\n    for (let i = 0; i < units - 1; i++) {\n        if ((str.charCodeAt(i) & 0xfc00) === 0xd800 && (str.charCodeAt(i + 1) & 0xfc00) === 0xdc00) {\n            count--;\n            i++;\n        }\n    }\n    return count;\n}\nexport function getLengthableOrigin(input) {\n    if (Array.isArray(input))\n        return \"array\";\n    if (typeof input === \"string\")\n        return \"string\";\n    return \"unknown\";\n}\nexport function parsedType(data) {\n    const t = typeof data;\n    switch (t) {\n        case \"number\": {\n            return Number.isNaN(data) ? \"nan\" : \"number\";\n        }\n        case \"object\": {\n            if (data === null) {\n                return \"null\";\n            }\n            if (Array.isArray(data)) {\n                return \"array\";\n            }\n            const obj = data;\n            if (obj && Object.getPrototypeOf(obj) !== Object.prototype && \"constructor\" in obj && obj.constructor) {\n                return obj.constructor.name;\n            }\n        }\n    }\n    return t;\n}\nexport function issue(...args) {\n    const [iss, input, inst] = args;\n    if (typeof iss === \"string\") {\n        return {\n            message: iss,\n            code: \"custom\",\n            input,\n            inst,\n        };\n    }\n    return { ...iss };\n}\nexport function cleanEnum(obj) {\n    return Object.entries(obj)\n        .filter(([k, _]) => {\n        // return true if NaN, meaning it's not a number, thus a string key\n        return Number.isNaN(Number.parseInt(k, 10));\n    })\n        .map((el) => el[1]);\n}\n// Codec utility functions\nexport function base64ToUint8Array(base64) {\n    const binaryString = atob(base64);\n    const bytes = new Uint8Array(binaryString.length);\n    for (let i = 0; i < binaryString.length; i++) {\n        bytes[i] = binaryString.charCodeAt(i);\n    }\n    return bytes;\n}\nexport function uint8ArrayToBase64(bytes) {\n    let binaryString = \"\";\n    for (let i = 0; i < bytes.length; i++) {\n        binaryString += String.fromCharCode(bytes[i]);\n    }\n    return btoa(binaryString);\n}\nexport function base64urlToUint8Array(base64url) {\n    const base64 = base64url.replace(/-/g, \"+\").replace(/_/g, \"/\");\n    const padding = \"=\".repeat((4 - (base64.length % 4)) % 4);\n    return base64ToUint8Array(base64 + padding);\n}\nexport function uint8ArrayToBase64url(bytes) {\n    return uint8ArrayToBase64(bytes).replace(/\\+/g, \"-\").replace(/\\//g, \"_\").replace(/=/g, \"\");\n}\nexport function hexToUint8Array(hex) {\n    const cleanHex = hex.replace(/^0x/, \"\");\n    if (cleanHex.length % 2 !== 0) {\n        throw new Error(\"Invalid hex string length\");\n    }\n    const bytes = new Uint8Array(cleanHex.length / 2);\n    for (let i = 0; i < cleanHex.length; i += 2) {\n        bytes[i / 2] = Number.parseInt(cleanHex.slice(i, i + 2), 16);\n    }\n    return bytes;\n}\nexport function uint8ArrayToHex(bytes) {\n    return Array.from(bytes)\n        .map((b) => b.toString(16).padStart(2, \"0\"))\n        .join(\"\");\n}\n// instanceof\nexport class Class {\n    constructor(..._args) { }\n}\n//////////    PROTOTYPE INSTALLERS     //////////\n//\n// 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.\n/**\n * 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.\n *\n * Call this from a `proto` initializer, which runs once per prototype — never per instance.\n */\nexport function members(proto, table) {\n    for (const key in table) {\n        const desc = Object.getOwnPropertyDescriptor(table, key);\n        // 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\n        if (desc.get)\n            Object.defineProperty(proto, key, { ...desc, enumerable: false });\n        // a method materializes bound on first read, which is what keeps a detached member working: `const opt = schema.optional; opt()`\n        else\n            defineBound(proto, key, desc.value);\n    }\n}\n/** Shadows a prototype member with an own value, so a getter that builds from the instance runs once. */\nexport function own(inst, key, value, enumerable = true) {\n    Object.defineProperty(inst, key, { configurable: true, writable: true, enumerable, value });\n    return value;\n}\n/** Like {@link own}, for a member that was never an own data property and has to stay out of `Object.keys`. */\nexport function hide(inst, key, value) {\n    return own(inst, key, value, false);\n}\n/** Adds members a table derives from the instance: each builds on first read and shadows as own data, and assignment shadows the same way, as when these were own properties. */\nexport /*@__NO_SIDE_EFFECTS__*/ function derived(computes, table) {\n    for (const key in computes) {\n        const compute = computes[key];\n        // an object literal's accessor is configurable and enumerable, and `members` copies the descriptor as written\n        Object.defineProperty(table, key, {\n            configurable: true,\n            enumerable: true,\n            get() {\n                return own(this, key, compute(this));\n            },\n            set(value) {\n                own(this, key, value);\n            },\n        });\n    }\n    return table;\n}\nfunction defineBound(proto, key, fn) {\n    Object.defineProperty(proto, key, {\n        configurable: true,\n        get() {\n            // vitest's spyOn calls a prototype getter bare to find the function it wraps, so a nullish receiver answers the raw method\n            return this == null ? fn : own(this, key, fn.bind(this));\n        },\n        set(value) {\n            own(this, key, value);\n        },\n    });\n}\n/** Returns the prototype to install on, or `undefined` if this group is already installed on it. */\nfunction claim(inst, sentinel) {\n    const proto = Object.getPrototypeOf(inst);\n    // Runs on every construction, so `in` rather than the costlier `hasOwnProperty.call`. Sentinels are keys the group itself defines.\n    return sentinel in proto ? undefined : proto;\n}\n// 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.\nlet installing;\n// 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.\nlet broke = false;\nconst breaker = {\n    configurable: true,\n    get() {\n        broke = true;\n        return undefined;\n    },\n};\n/**\n * Installs a lazily-derived internal on the `_zod` prototype of `inst`'s\n * constructor, computed from the internals object itself and cached there on\n * first read. One accessor per constructor rather than one per instance.\n */\nexport function defineLazyInternal(inst, key, compute) {\n    const proto = Object.getPrototypeOf(inst._zod);\n    if (key in proto && installing !== inst._zod) {\n        // A repeat construction: everything is installed already. Cleared here so the reference is not held past the first construction of every type.\n        installing = undefined;\n        return;\n    }\n    installing = inst._zod;\n    Object.defineProperty(proto, key, {\n        configurable: true,\n        get() {\n            // Shadowed before computing so a re-entrant read from a recursive schema resolves to undefined instead of running the getter again.\n            Object.defineProperty(this, key, breaker);\n            const outer = broke;\n            broke = false;\n            try {\n                const value = compute(this);\n                // A result that resolved through a recursion break is recomputed once the graph is complete; everything else memoizes, undefined included.\n                if (broke)\n                    delete this[key];\n                else\n                    Object.defineProperty(this, key, { configurable: true, writable: true, value });\n                broke = broke || outer;\n                return value;\n            }\n            catch (err) {\n                // 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.\n                delete this[key];\n                broke = broke || outer;\n                throw err;\n            }\n        },\n        set(value) {\n            Object.defineProperty(this, key, { configurable: true, writable: true, value });\n        },\n    });\n}\n/**\n * Installs `key` on `inst`'s prototype, computed by `make` on first read and cached there as an own\n * data property. One accessor per constructor rather than one per instance, because an own accessor\n * puts every instance after the first into v8 dictionary mode. The key doubles as the sentinel.\n */\nexport function installLazyProp(inst, key, make, enumerable) {\n    const proto = claim(inst, key);\n    if (!proto)\n        return;\n    Object.defineProperty(proto, key, {\n        configurable: true,\n        get() {\n            // 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.\n            const desc = { configurable: true, writable: true, enumerable, value: undefined };\n            Object.defineProperty(this, key, desc);\n            // 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\n            desc.value = make(this);\n            Object.defineProperty(this, key, desc);\n            return desc.value;\n        },\n        set(value) {\n            Object.defineProperty(this, key, { configurable: true, writable: true, enumerable, value });\n        },\n    });\n}\n/** 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. */\nexport const CONSTANT_CATCH = \"~constantCatch\";\n/** Wraps a constant catch value in a thunk tagged with {@link CONSTANT_CATCH}. */\nexport function constantCatch(value) {\n    const fn = () => value;\n    fn[CONSTANT_CATCH] = true;\n    return fn;\n}\n","var _a;\nimport { members as installMembers } from \"./util.js\";\n/** A special constant with type `never` */\nexport const NEVER = /*@__PURE__*/ Object.freeze({\n    status: \"aborted\",\n});\n/* Shared descriptor for installing `_zod`; defineProperty reads it\n * synchronously, so reusing one object avoids a per-instance allocation. */\nconst _zodDesc = { value: undefined, enumerable: false };\n// 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\nlet _E = \"captureStackTrace\" in Error ? Error : null;\n// 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\nfunction newError(Definition) {\n    const E = _E;\n    if (E) {\n        const saved = E.stackTraceLimit;\n        if (typeof saved === \"number\") {\n            try {\n                E.stackTraceLimit = 0;\n            }\n            catch {\n                _E = null;\n                return new Definition();\n            }\n            try {\n                return new Definition();\n            }\n            finally {\n                E.stackTraceLimit = saved;\n            }\n        }\n    }\n    return new Definition();\n}\nexport /*@__NO_SIDE_EFFECTS__*/ function $constructor(name, initializer, \n/** 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. */\nproto, params) {\n    // Prototype for this constructor's `_zod` internals. Lazily-derived fields (`values`, `pattern`, `optin`, …) install here once rather than as an accessor on every instance.\n    const zodProto = {};\n    // 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.\n    function Internals(def) {\n        this.def = def;\n        this.constr = _;\n        this.traits = new Set();\n    }\n    Internals.prototype = zodProto;\n    const protoMembers = proto;\n    // One trait's members land on every prototype whose chain composes it, so the answer is per prototype rather than per trait.\n    const initialized = protoMembers && new WeakSet();\n    function init(inst, def) {\n        if (!inst._zod) {\n            _zodDesc.value = new Internals(def);\n            try {\n                Object.defineProperty(inst, \"_zod\", _zodDesc);\n            }\n            finally {\n                // Cleared even on throw, so the shared descriptor never leaks one instance's internals into the next.\n                _zodDesc.value = undefined;\n            }\n        }\n        else if (inst._zod.traits.has(name)) {\n            return;\n        }\n        inst._zod.traits.add(name);\n        initializer(inst, def);\n        if (initialized) {\n            // `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.\n            const own = Object.getPrototypeOf(inst);\n            const ctorProto = inst._zod.constr.prototype;\n            let up = own;\n            while (up && up !== ctorProto)\n                up = Object.getPrototypeOf(up);\n            const target = up ?? own;\n            if (!initialized.has(target)) {\n                initialized.add(target);\n                installMembers(target, protoMembers);\n            }\n        }\n        // support prototype modifications; for-in avoids the array allocation of Object.keys on the (usually empty) prototype\n        const proto = _.prototype;\n        for (const k in proto) {\n            if (!Object.prototype.hasOwnProperty.call(proto, k))\n                continue;\n            if (!(k in inst)) {\n                inst[k] = proto[k].bind(inst);\n            }\n        }\n    }\n    // doesn't work if Parent has a constructor with arguments\n    const Parent = params?.Parent ?? Object;\n    class Definition extends Parent {\n    }\n    Object.defineProperty(Definition, \"name\", { value: name });\n    function _(def) {\n        const inst = params?.Parent ? newError(Definition) : this;\n        init(inst, def);\n        const deferred = inst._zod.deferred;\n        if (deferred) {\n            for (const fn of deferred) {\n                fn();\n            }\n            // Released: initializers run once, and the list would otherwise be retained for the schema's lifetime.\n            inst._zod.deferred = undefined;\n        }\n        // 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.\n        const pp = globalThis.__zod_globalConfig?.postProcessor;\n        if (pp)\n            pp(inst);\n        return inst;\n    }\n    Object.defineProperty(_, \"init\", { value: init });\n    Object.defineProperty(_, Symbol.hasInstance, {\n        value: (inst) => {\n            if (params?.Parent && inst instanceof params.Parent)\n                return true;\n            return inst?._zod?.traits?.has(name);\n        },\n    });\n    Object.defineProperty(_, \"name\", { value: name });\n    return _;\n}\n//////////////////////////////   UTILITIES   ///////////////////////////////////////\nexport const $brand = /*@__PURE__*/ Symbol(\"zod_brand\");\nexport class $ZodAsyncError extends Error {\n    constructor() {\n        super(`Encountered Promise during synchronous parse. Use .parseAsync() instead.`);\n    }\n}\nexport class $ZodEncodeError extends Error {\n    constructor(name) {\n        super(`Encountered unidirectional transform during encode: ${name}`);\n        this.name = \"ZodEncodeError\";\n    }\n}\n(_a = globalThis).__zod_globalConfig ?? (_a.__zod_globalConfig = {});\nexport const globalConfig = globalThis.__zod_globalConfig;\nexport function config(newConfig) {\n    if (newConfig)\n        Object.assign(globalConfig, newConfig);\n    return globalConfig;\n}\n","import { $constructor } from \"./core.js\";\nimport * as util from \"./util.js\";\n/* Computing the message eagerly is expensive (pretty-printed JSON of all\n * issues), so defer it until first read. The accessor functions and\n * descriptors are shared across instances to keep error construction\n * cheap; the computed message is cached on the internals object. The\n * setter preserves plain assignment semantics for consumers that\n * overwrite `message`. */\nfunction _getMessage() {\n    const internals = this._zod;\n    internals.message ?? (internals.message = JSON.stringify(internals.def, util.jsonStringifyReplacer, 2));\n    return internals.message;\n}\nfunction _setMessage(value) {\n    this._zod.message = value;\n}\nconst _messageDesc = {\n    get: _getMessage,\n    set: _setMessage,\n    enumerable: true,\n    configurable: true,\n};\nconst _issuesDesc = { value: undefined, enumerable: false };\n/* Prototypes that already carry the lazy `toString`. Seeded with the\n * intrinsics so that `init` on a foreign object — it accepts any object —\n * can never install an accessor onto a prototype we do not own. */\nconst _installedToString = /* @__PURE__ */ new WeakSet([Object.prototype, Error.prototype]);\nconst initializer = (inst, def) => {\n    inst.name = \"$ZodError\";\n    // `_zod` is already non-enumerable: $constructor's init defined it with this same descriptor\n    _issuesDesc.value = def;\n    Object.defineProperty(inst, \"issues\", _issuesDesc);\n    // Clear the shared slot; a retained `value` pins the last error's issues.\n    _issuesDesc.value = undefined;\n    Object.defineProperty(inst, \"message\", _messageDesc);\n    /* `toString` lives as a non-enumerable lazy getter on the shared\n     * prototype; on first access it caches a per-instance closure so\n     * detached usage still works. */\n    const proto = Object.getPrototypeOf(inst);\n    if (!_installedToString.has(proto)) {\n        _installedToString.add(proto);\n        Object.defineProperty(proto, \"toString\", {\n            configurable: true,\n            enumerable: false,\n            get() {\n                const value = () => this.message;\n                Object.defineProperty(this, \"toString\", { value, configurable: true, writable: true });\n                return value;\n            },\n            set(value) {\n                Object.defineProperty(this, \"toString\", { value, configurable: true, writable: true });\n            },\n        });\n    }\n};\nexport const $ZodError = $constructor(\"$ZodError\", initializer);\nexport const $ZodRealError = $constructor(\"$ZodError\", initializer, undefined, {\n    Parent: Error,\n});\n/** Get-or-create `obj[key]` as an own data property. A path segment naming an inherited member\n * (\"toString\", \"constructor\") would otherwise read through to the prototype, and assigning\n * \"__proto__\" would hit the setter instead of creating a key. */\nfunction node(obj, key, make) {\n    if (!Object.prototype.hasOwnProperty.call(obj, key)) {\n        if (key === \"__proto__\") {\n            Object.defineProperty(obj, key, { value: make(), writable: true, enumerable: true, configurable: true });\n        }\n        else {\n            obj[key] = make();\n        }\n    }\n    return obj[key];\n}\nexport function flattenError(error, mapper = (issue) => issue.message) {\n    const fieldErrors = {};\n    const formErrors = [];\n    for (const sub of error.issues) {\n        if (sub.path.length > 0) {\n            node(fieldErrors, sub.path[0], () => []).push(mapper(sub));\n        }\n        else {\n            formErrors.push(mapper(sub));\n        }\n    }\n    return { formErrors, fieldErrors };\n}\nexport function formatError(error, mapper = (issue) => issue.message) {\n    const fieldErrors = { _errors: [] };\n    const processError = (error, path = []) => {\n        for (const issue of error.issues) {\n            if (issue.code === \"invalid_union\" && issue.errors.length) {\n                issue.errors.map((issues) => processError({ issues }, [...path, ...issue.path]));\n            }\n            else if (issue.code === \"invalid_key\") {\n                processError({ issues: issue.issues }, [...path, ...issue.path]);\n            }\n            else if (issue.code === \"invalid_element\") {\n                processError({ issues: issue.issues }, [...path, ...issue.path]);\n            }\n            else {\n                const fullpath = [...path, ...issue.path];\n                if (fullpath.length === 0) {\n                    fieldErrors._errors.push(mapper(issue));\n                }\n                else {\n                    let curr = fieldErrors;\n                    let i = 0;\n                    while (i < fullpath.length) {\n                        const el = fullpath[i];\n                        const terminal = i === fullpath.length - 1;\n                        // `_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.\n                        if (el === \"_errors\") {\n                            if (terminal)\n                                curr._errors.push(mapper(issue));\n                            i++;\n                            continue;\n                        }\n                        // A path element may collide with an inherited property name such as\n                        // \"__proto__\" or \"constructor\". Truthiness checks read the prototype\n                        // (so no node is created, then ._errors.push throws), and bracket\n                        // assignment of \"__proto__\" hits the setter instead of creating an\n                        // own key. Guard the read with hasOwnProperty and create the node\n                        // with defineProperty so any path element becomes a real own key.\n                        if (!Object.prototype.hasOwnProperty.call(curr, el)) {\n                            Object.defineProperty(curr, el, {\n                                value: { _errors: [] },\n                                enumerable: true,\n                                writable: true,\n                                configurable: true,\n                            });\n                        }\n                        const node = curr[el];\n                        if (terminal) {\n                            node._errors.push(mapper(issue));\n                        }\n                        curr = node;\n                        i++;\n                    }\n                }\n            }\n        }\n    };\n    processError(error);\n    return fieldErrors;\n}\nexport function treeifyError(error, mapper = (issue) => issue.message) {\n    const result = { errors: [] };\n    const processError = (error, path = []) => {\n        var _a;\n        for (const issue of error.issues) {\n            if (issue.code === \"invalid_union\" && issue.errors.length) {\n                // regular union error\n                issue.errors.map((issues) => processError({ issues }, [...path, ...issue.path]));\n            }\n            else if (issue.code === \"invalid_key\") {\n                processError({ issues: issue.issues }, [...path, ...issue.path]);\n            }\n            else if (issue.code === \"invalid_element\") {\n                processError({ issues: issue.issues }, [...path, ...issue.path]);\n            }\n            else {\n                const fullpath = [...path, ...issue.path];\n                if (fullpath.length === 0) {\n                    result.errors.push(mapper(issue));\n                    continue;\n                }\n                let curr = result;\n                let i = 0;\n                while (i < fullpath.length) {\n                    const el = fullpath[i];\n                    const terminal = i === fullpath.length - 1;\n                    if (typeof el === \"string\") {\n                        curr.properties ?? (curr.properties = {});\n                        // el may collide with an inherited property name (\"__proto__\",\n                        // \"constructor\", ...); ??= reads the prototype so the node is never\n                        // created and curr.errors.push throws. Guard with hasOwnProperty and\n                        // create the node with defineProperty so \"__proto__\" becomes a real\n                        // own key rather than invoking the prototype setter.\n                        if (!Object.prototype.hasOwnProperty.call(curr.properties, el)) {\n                            Object.defineProperty(curr.properties, el, {\n                                value: { errors: [] },\n                                enumerable: true,\n                                writable: true,\n                                configurable: true,\n                            });\n                        }\n                        curr = curr.properties[el];\n                    }\n                    else {\n                        curr.items ?? (curr.items = []);\n                        (_a = curr.items)[el] ?? (_a[el] = { errors: [] });\n                        curr = curr.items[el];\n                    }\n                    if (terminal) {\n                        curr.errors.push(mapper(issue));\n                    }\n                    i++;\n                }\n            }\n        }\n    };\n    processError(error);\n    return result;\n}\n/** Format a ZodError as a human-readable string in the following form.\n *\n * From\n *\n * ```ts\n * ZodError {\n *   issues: [\n *     {\n *       expected: 'string',\n *       code: 'invalid_type',\n *       path: [ 'username' ],\n *       message: 'Invalid input: expected string'\n *     },\n *     {\n *       expected: 'number',\n *       code: 'invalid_type',\n *       path: [ 'favoriteNumbers', 1 ],\n *       message: 'Invalid input: expected number'\n *     }\n *   ];\n * }\n * ```\n *\n * to\n *\n * ```\n * username\n *   ✖ Expected number, received string at \"username\n * favoriteNumbers[0]\n *   ✖ Invalid input: expected number\n * ```\n */\nexport function toDotPath(_path) {\n    const segs = [];\n    const path = _path.map((seg) => (typeof seg === \"object\" ? seg.key : seg));\n    for (const seg of path) {\n        if (typeof seg === \"number\")\n            segs.push(`[${seg}]`);\n        else if (typeof seg === \"symbol\")\n            segs.push(`[${JSON.stringify(String(seg))}]`);\n        else if (/[^\\w$]/.test(seg))\n            segs.push(`[${JSON.stringify(seg)}]`);\n        else {\n            if (segs.length)\n                segs.push(\".\");\n            segs.push(seg);\n        }\n    }\n    return segs.join(\"\");\n}\nexport function prettifyError(error) {\n    const lines = [];\n    // sort by path length\n    const issues = [...error.issues].sort((a, b) => (a.path ?? []).length - (b.path ?? []).length);\n    // Process each issue\n    for (const issue of issues) {\n        lines.push(`✖ ${issue.message}`);\n        if (issue.path?.length)\n            lines.push(`  → at ${toDotPath(issue.path)}`);\n    }\n    // Convert Map to formatted string\n    return lines.join(\"\\n\");\n}\n","import * as core from \"./core.js\";\nimport * as errors from \"./errors.js\";\nimport * as util from \"./util.js\";\n// Always both keys, so the `_params` read site in `_parse` sees one object shape rather than two.\nfunction finalizeParams(callee, params) {\n    return { callee: params?.callee ?? callee, Err: params?.Err };\n}\nexport const _parse = (_Err) => {\n    const fn = (schema, value, _ctx, _params) => {\n        const ctx = _ctx ? { ..._ctx, async: false } : { async: false };\n        const result = schema._zod.run({ value, issues: [] }, ctx);\n        if (result instanceof Promise) {\n            throw new core.$ZodAsyncError();\n        }\n        if (result.issues.length) {\n            const e = new (_params?.Err ?? _Err)(result.issues.map((iss) => util.finalizeIssue(iss, ctx, core.config())));\n            util.captureStackTrace(e, _params?.callee ?? fn);\n            throw e;\n        }\n        return result.value;\n    };\n    return fn;\n};\nexport const parse = /* @__PURE__*/ _parse(errors.$ZodRealError);\nexport const _parseAsync = (_Err) => {\n    const fn = async (schema, value, _ctx, params) => {\n        const ctx = _ctx ? { ..._ctx, async: true } : { async: true };\n        let result = schema._zod.run({ value, issues: [] }, ctx);\n        if (result instanceof Promise)\n            result = await result;\n        if (result.issues.length) {\n            const e = new (params?.Err ?? _Err)(result.issues.map((iss) => util.finalizeIssue(iss, ctx, core.config())));\n            util.captureStackTrace(e, params?.callee ?? fn);\n            throw e;\n        }\n        return result.value;\n    };\n    return fn;\n};\nexport const parseAsync = /* @__PURE__*/ _parseAsync(errors.$ZodRealError);\nexport const _safeParse = (_Err) => (schema, value, _ctx) => {\n    const ctx = _ctx ? { ..._ctx, async: false } : { async: false };\n    const result = schema._zod.run({ value, issues: [] }, ctx);\n    if (result instanceof Promise) {\n        throw new core.$ZodAsyncError();\n    }\n    return result.issues.length ? failure(_Err, result.issues, ctx) : { success: true, data: result.value };\n};\nexport const safeParse = /* @__PURE__*/ _safeParse(errors.$ZodRealError);\n// the error is built on the first read of `error`: finalizing the issues and constructing the instance is most of a failing parse, and a caller that only branches on `success` never pays it. a getter in the literal keeps this small; the alternative, one shared accessor descriptor plus a hidden state slot, reads ~15% faster but costs ~75 B gzipped in every bundle\nfunction failure(Err, issues, ctx) {\n    let error;\n    return {\n        success: false,\n        get error() {\n            if (!error) {\n                error = new Err(issues.map((iss) => util.finalizeIssue(iss, ctx, core.config())));\n                // finalizeIssue drops `input`, so the built error holds nothing; keeping the raw issues past this point pins the parsed value for the life of the result\n                issues = undefined;\n                ctx = undefined;\n            }\n            return error;\n        },\n        set error(e) {\n            error = e;\n            // a replacement makes the getter's branch unreachable, so the captures have to go here too\n            issues = undefined;\n            ctx = undefined;\n        },\n    };\n}\nexport const _safeParseAsync = (_Err) => async (schema, value, _ctx) => {\n    const ctx = _ctx ? { ..._ctx, async: true } : { async: true };\n    let result = schema._zod.run({ value, issues: [] }, ctx);\n    if (result instanceof Promise)\n        result = await result;\n    return result.issues.length ? failure(_Err, result.issues, ctx) : { success: true, data: result.value };\n};\nexport const safeParseAsync = /* @__PURE__*/ _safeParseAsync(errors.$ZodRealError);\n// registry mirrors of the compiler's sentinels, so this module never imports the compiler\nconst COMPILE_INVALID = /* @__PURE__ */ Symbol.for(\"zod.compile.invalid\");\nconst COMPILE_FALLBACK = /* @__PURE__ */ Symbol.for(\"zod.compile.fallback\");\n// 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.\nexport const validate = ((schema, value, _ctx) => {\n    const validator = schema._zod.bag.validator;\n    if (validator !== undefined) {\n        if (validator(value) !== COMPILE_INVALID)\n            return true;\n        // a definite sentinel means the runtime would reject, so skip the re-parse; a ctx can still change the answer\n        if (validator.definite === true && _ctx === undefined)\n            return false;\n    }\n    return validateFallback(schema, value, _ctx);\n});\nfunction validateFallback(schema, value, _ctx) {\n    const ctx = _ctx\n        ? { ..._ctx, async: false, abortEarly: true }\n        : { async: false, abortEarly: true };\n    const fallbackRun = schema._zod.bag.fallbackRun;\n    let result;\n    if (fallbackRun) {\n        // skip nested fast paths on the fallback, so user callbacks keep the at-most-twice bound\n        ctx[COMPILE_FALLBACK] = true;\n        result = fallbackRun({ value, issues: [] }, ctx);\n    }\n    else {\n        result = schema._zod.run({ value, issues: [] }, ctx);\n    }\n    if (result instanceof Promise) {\n        throw new core.$ZodAsyncError();\n    }\n    return result.issues.length === 0;\n}\n// 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\nexport const validateAsync = async (schema, value, _ctx) => {\n    const ctx = _ctx\n        ? { ..._ctx, async: true, abortEarly: true }\n        : { async: true, abortEarly: true };\n    let result = schema._zod.run({ value, issues: [] }, ctx);\n    if (result instanceof Promise)\n        result = await result;\n    return result.issues.length === 0;\n};\nexport const _encode = (_Err) => {\n    const parse = _parse(_Err);\n    const fn = (schema, value, _ctx, _params) => {\n        const ctx = _ctx ? { ..._ctx, direction: \"backward\" } : { direction: \"backward\" };\n        return parse(schema, value, ctx, finalizeParams(fn, _params));\n    };\n    return fn;\n};\nexport const encode = /* @__PURE__*/ _encode(errors.$ZodRealError);\nexport const _decode = (_Err) => {\n    const parse = _parse(_Err);\n    const fn = (schema, value, _ctx, _params) => {\n        return parse(schema, value, _ctx, finalizeParams(fn, _params));\n    };\n    return fn;\n};\nexport const decode = /* @__PURE__*/ _decode(errors.$ZodRealError);\nexport const _encodeAsync = (_Err) => {\n    const parseAsync = _parseAsync(_Err);\n    const fn = async (schema, value, _ctx, _params) => {\n        const ctx = _ctx ? { ..._ctx, direction: \"backward\" } : { direction: \"backward\" };\n        return (await parseAsync(schema, value, ctx, finalizeParams(fn, _params)));\n    };\n    return fn;\n};\nexport const encodeAsync = /* @__PURE__*/ _encodeAsync(errors.$ZodRealError);\nexport const _decodeAsync = (_Err) => {\n    const parseAsync = _parseAsync(_Err);\n    const fn = async (schema, value, _ctx, _params) => {\n        return await parseAsync(schema, value, _ctx, finalizeParams(fn, _params));\n    };\n    return fn;\n};\nexport const decodeAsync = /* @__PURE__*/ _decodeAsync(errors.$ZodRealError);\nexport const _safeEncode = (_Err) => (schema, value, _ctx) => {\n    const ctx = _ctx ? { ..._ctx, direction: \"backward\" } : { direction: \"backward\" };\n    return _safeParse(_Err)(schema, value, ctx);\n};\nexport const safeEncode = /* @__PURE__*/ _safeEncode(errors.$ZodRealError);\nexport const _safeDecode = (_Err) => (schema, value, _ctx) => {\n    return _safeParse(_Err)(schema, value, _ctx);\n};\nexport const safeDecode = /* @__PURE__*/ _safeDecode(errors.$ZodRealError);\nexport const _safeEncodeAsync = (_Err) => async (schema, value, _ctx) => {\n    const ctx = _ctx ? { ..._ctx, direction: \"backward\" } : { direction: \"backward\" };\n    return _safeParseAsync(_Err)(schema, value, ctx);\n};\nexport const safeEncodeAsync = /* @__PURE__*/ _safeEncodeAsync(errors.$ZodRealError);\nexport const _safeDecodeAsync = (_Err) => async (schema, value, _ctx) => {\n    return _safeParseAsync(_Err)(schema, value, _ctx);\n};\nexport const safeDecodeAsync = /* @__PURE__*/ _safeDecodeAsync(errors.$ZodRealError);\n","import * as util from \"./util.js\";\n/**\n * @deprecated CUID v1 is deprecated by its authors due to information leakage\n * (timestamps embedded in the id). Use {@link cuid2} instead.\n * See https://github.com/paralleldrive/cuid.\n */\nexport const cuid = /^[cC][0-9a-z]{6,}$/;\nexport const cuid2 = /^[0-9a-z]+$/;\nexport const ulid = /^[0-7][0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{25}$/;\nexport const xid = /^[0-9a-vA-V]{20}$/;\nexport const ksuid = /^[A-Za-z0-9]{27}$/;\nexport const nanoid = /^[a-zA-Z0-9_-]{21}$/;\nexport function nanoidOfLength(length) {\n    return new RegExp(`^[a-zA-Z0-9_-]{${length}}$`);\n}\n/** ISO 8601-1 duration regex. Does not support the 8601-2 extensions like negative durations or fractional/negative components. */\nexport const duration = /^P(?:(\\d+W)|(?!.*W)(?=\\d|T\\d)(\\d+Y)?(\\d+M)?(\\d+D)?(T(?=\\d)(\\d+H)?(\\d+M)?(\\d+([.,]\\d+)?S)?)?)$/;\n/** Implements ISO 8601-2 extensions like explicit +- prefixes, mixing weeks with other units, and fractional/negative components. */\nexport 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)?)??$/;\n/** A regex for any UUID-like identifier: 8-4-4-4-12 hex pattern */\nexport 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})$/;\n/** Returns a regex for validating an RFC 9562/4122 UUID.\n *\n * @param version Optionally specify a version 1-8. If no version is specified, all versions are supported. */\nexport const uuid = (version) => {\n    if (!version)\n        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)$/;\n    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})$`);\n};\nexport const uuid4 = /*@__PURE__*/ uuid(4);\nexport const uuid6 = /*@__PURE__*/ uuid(6);\nexport const uuid7 = /*@__PURE__*/ uuid(7);\n/** Practical email validation */\nexport const email = /^(?:[A-Za-z0-9_'+\\-]+\\.)*[A-Za-z0-9_'+\\-]*[A-Za-z0-9_+-]@(?:[A-Za-z0-9][A-Za-z0-9\\-]*\\.)+[A-Za-z]{2,}$/;\n/** Equivalent to the HTML5 input[type=email] validation implemented by browsers. Source: https://developer.mozilla.org/en-US/docs/Web/HTML/Element/input/email */\nexport 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])?)*$/;\n/** The classic emailregex.com regex for RFC 5322-compliant emails */\nexport 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,}))$/;\n/** A loose regex that allows Unicode characters, enforces length limits, and that's about it. */\nexport const unicodeEmail = /^[^\\s@\"]{1,64}@[^\\s@]{1,255}$/u;\nexport const idnEmail = unicodeEmail;\nexport 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])?)*$/;\n// from https://thekevinscott.com/emojis-in-javascript/#writing-a-regular-expression\n// Single character class, not an alternation: the two properties overlap (U+1F9B0-U+1F9B3), so `(A|B)+` backtracks exponentially on a failed match. The leading lookahead then demands one anchor — a pictograph, a regional indicator, or the enclosing keycap — because `\\p{Emoji_Component}` on its own covers ASCII digits, `#`, `*`, ZWJ, variation selectors and skin tone modifiers, none of which is an emoji without a base.\nconst _emoji = `^(?=[\\\\s\\\\S]*[\\\\p{Extended_Pictographic}\\\\p{Regional_Indicator}\\\\u20E3])[\\\\p{Extended_Pictographic}\\\\p{Emoji_Component}]+$`;\nexport function emoji() {\n    return new RegExp(_emoji, \"u\");\n}\nexport 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])$/;\nexport const 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}|:))$/;\nexport const mac = (delimiter) => {\n    const escapedDelim = util.escapeRegex(delimiter ?? \":\");\n    return new RegExp(`^(?:[0-9A-F]{2}${escapedDelim}){5}[0-9A-F]{2}$|^(?:[0-9a-f]{2}${escapedDelim}){5}[0-9a-f]{2}$`);\n};\nexport 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])$/;\nexport 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])$/;\n// https://stackoverflow.com/questions/7860392/determine-if-string-is-in-base64-using-javascript\nexport const base64 = /^$|^(?:[0-9a-zA-Z+/]{4})*(?:(?:[0-9a-zA-Z+/]{2}==)|(?:[0-9a-zA-Z+/]{3}=))?$/;\nexport const base64url = /^(?:[A-Za-z0-9_-]{4})*(?:[A-Za-z0-9_-]{2,3})?$/;\n// based on https://stackoverflow.com/questions/106179/regular-expression-to-match-dns-hostname-or-ip-address\n// export const hostname: RegExp = /^([a-zA-Z0-9-]+\\.)*[a-zA-Z0-9-]+$/;\nexport const 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])?)*\\.?$/;\nexport const domain = /^(?=.{1,253}$)([a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?\\.)+[a-zA-Z]{2,63}$/;\nexport const httpProtocol = /^https?$/;\n// 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\nexport const e164 = /^\\+[1-9]\\d{6,14}$/;\n// 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).\nexport const creditCard = /^\\d(?:[ -]?\\d){11,18}$/;\n// ISO 4217 alpha codes from the SIX list, regenerated by scripts/update-iso-4217.ts\nexport const currencyCode = /^(?:AED|AFN|ALL|AMD|AOA|ARS|AUD|AWG|AZN|BAM|BBD|BDT|BHD|BIF|BMD|BND|BOB|BOV|BRL|BSD|BTN|BWP|BYN|BZD|CAD|CDF|CHE|CHF|CHW|CLF|CLP|CNY|COP|COU|CRC|CUP|CVE|CZK|DJF|DKK|DOP|DZD|EGP|ERN|ETB|EUR|FJD|FKP|GBP|GEL|GHS|GIP|GMD|GNF|GTQ|GYD|HKD|HNL|HTG|HUF|IDR|ILS|INR|IQD|IRR|ISK|JMD|JOD|JPY|KES|KGS|KHR|KMF|KPW|KRW|KWD|KYD|KZT|LAK|LBP|LKR|LRD|LSL|LYD|MAD|MDL|MGA|MKD|MMK|MNT|MOP|MRU|MUR|MVR|MWK|MXN|MXV|MYR|MZN|NAD|NGN|NIO|NOK|NPR|NZD|OMR|PAB|PEN|PGK|PHP|PKR|PLN|PYG|QAR|RON|RSD|RUB|RWF|SAR|SBD|SCR|SDG|SEK|SGD|SHP|SLE|SOS|SRD|SSP|STN|SVC|SYP|SZL|THB|TJS|TMT|TND|TOP|TRY|TTD|TWD|TZS|UAH|UGX|USD|USN|UYI|UYU|UYW|UZS|VED|VES|VND|VUV|WST|XAD|XAF|XAG|XAU|XBA|XBB|XBC|XBD|XCD|XCG|XDR|XOF|XPD|XPF|XPT|XSU|XTS|XUA|XXX|YER|ZAR|ZMW|ZWG)$/;\n// iban electronic format: 2-letter country, check digits 02-98 (the only values `98 - remainder` can produce), 11-30 bban characters\nexport const iban = /^[A-Z]{2}(?!00|01|99)\\d{2}[A-Z0-9]{11,30}$/;\nconst 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])))`;\n/** Anchors a pattern source. The interpolation lives here rather than at the call site because\n * esbuild will not drop a `@__PURE__` call whose own argument interpolates a variable, but it\n * will drop `anchor(dateSource)`. Keeping it inline pinned `date` into every bundle. */\nfunction anchor(source) {\n    return new RegExp(`^${source}$`);\n}\nexport const date = /*@__PURE__*/ anchor(dateSource);\nfunction timeSource(args) {\n    const hhmm = `(?:[01]\\\\d|2[0-3]):[0-5]\\\\d`;\n    const regex = typeof args.precision === \"number\"\n        ? args.precision === -1\n            ? `${hhmm}`\n            : args.precision === 0\n                ? `${hhmm}:[0-5]\\\\d`\n                : `${hhmm}:[0-5]\\\\d\\\\.\\\\d{${args.precision}}`\n        : args.seconds\n            ? `${hhmm}:[0-5]\\\\d(?:\\\\.\\\\d+)?`\n            : `${hhmm}(?::[0-5]\\\\d(?:\\\\.\\\\d+)?)?`;\n    return regex;\n}\nexport function time(args) {\n    return new RegExp(`^${timeSource(args)}$`);\n}\n// Adapted from https://stackoverflow.com/a/3143231\nexport function datetime(args) {\n    const opts = [\"Z\"];\n    // if (args.offset) opts.push(`([+-]\\\\d{2}:\\\\d{2})`);\n    if (args.offset)\n        opts.push(`([+-](?:[01]\\\\d|2[0-3]):[0-5]\\\\d)`);\n    // RFC 3339 mandates seconds wherever the time carries a `Z` or an offset, so only the unqualified form `local` adds may omit them\n    const qualified = `${timeSource({ precision: args.precision, seconds: true })}(?:${opts.join(\"|\")})`;\n    const timeRegex = args.local ? `${qualified}|${timeSource({ precision: args.precision })}` : qualified;\n    return new RegExp(`^${dateSource}T(?:${timeRegex})$`);\n}\n// the unbounded form of `string()` as a literal, so every plain string shares one instance instead of building its own\nexport const anyString = /^[\\s\\S]{0,}$/;\nexport const string = (params) => {\n    const regex = params ? `[\\\\s\\\\S]{${params?.minimum ?? 0},${params?.maximum ?? \"\"}}` : `[\\\\s\\\\S]*`;\n    return new RegExp(`^${regex}$`);\n};\nexport const bigint = /^-?\\d+n?$/;\nexport const integer = /^-?\\d+$/;\nexport const number = /^-?\\d+(?:\\.\\d+)?$/;\nexport const boolean = /^(?:true|false)$/i;\nconst _null = /^null$/i;\nexport { _null as null };\nconst _undefined = /^undefined$/i;\nexport { _undefined as undefined };\n// regex for string with no uppercase letters\nexport const lowercase = /^[^A-Z]*$/;\n// regex for string with no lowercase letters\nexport const uppercase = /^[^a-z]*$/;\n// regex for hexadecimal strings (any length)\nexport const hex = /^[0-9a-fA-F]*$/;\n// Hash regexes for different algorithms and encodings\n// Helper function to create base64 regex with exact length and padding\nfunction fixedBase64(bodyLength, padding) {\n    return new RegExp(`^[A-Za-z0-9+/]{${bodyLength}}${padding}$`);\n}\n// Helper function to create base64url regex with exact length (no padding)\nfunction fixedBase64url(length) {\n    return new RegExp(`^[A-Za-z0-9_-]{${length}}$`);\n}\n// MD5 (16 bytes): base64 = 24 chars total (22 + \"==\")\nexport const md5_hex = /^[0-9a-fA-F]{32}$/;\nexport const md5_base64 = /*@__PURE__*/ fixedBase64(22, \"==\");\nexport const md5_base64url = /*@__PURE__*/ fixedBase64url(22);\n// SHA1 (20 bytes): base64 = 28 chars total (27 + \"=\")\nexport const sha1_hex = /^[0-9a-fA-F]{40}$/;\nexport const sha1_base64 = /*@__PURE__*/ fixedBase64(27, \"=\");\nexport const sha1_base64url = /*@__PURE__*/ fixedBase64url(27);\n// SHA256 (32 bytes): base64 = 44 chars total (43 + \"=\")\nexport const sha256_hex = /^[0-9a-fA-F]{64}$/;\nexport const sha256_base64 = /*@__PURE__*/ fixedBase64(43, \"=\");\nexport const sha256_base64url = /*@__PURE__*/ fixedBase64url(43);\n// SHA384 (48 bytes): base64 = 64 chars total (no padding)\nexport const sha384_hex = /^[0-9a-fA-F]{96}$/;\nexport const sha384_base64 = /*@__PURE__*/ fixedBase64(64, \"\");\nexport const sha384_base64url = /*@__PURE__*/ fixedBase64url(64);\n// SHA512 (64 bytes): base64 = 88 chars total (86 + \"==\")\nexport const sha512_hex = /^[0-9a-fA-F]{128}$/;\nexport const sha512_base64 = /*@__PURE__*/ fixedBase64(86, \"==\");\nexport const sha512_base64url = /*@__PURE__*/ fixedBase64url(86);\n","// import { $ZodType } from \"./schemas.js\";\nimport * as core from \"./core.js\";\nimport * as regexes from \"./regexes.js\";\nimport * as util from \"./util.js\";\nexport const $ZodCheck = /*@__PURE__*/ core.$constructor(\"$ZodCheck\", (inst, def) => {\n    var _a;\n    inst._zod ?? (inst._zod = {});\n    inst._zod.def = def;\n    (_a = inst._zod).onattach ?? (_a.onattach = []);\n});\n/** Default `when` for size-based checks: run only on non-nullish values with a `size`. */\nconst _whenHasSize = (payload) => {\n    const val = payload.value;\n    return !util.nullish(val) && val.size !== undefined;\n};\n/** Default `when` for length-based checks: run only on non-nullish values with a `length`. */\nconst _whenHasLength = (payload) => {\n    const val = payload.value;\n    return !util.nullish(val) && val.length !== undefined;\n};\nconst numericOriginMap = {\n    number: \"number\",\n    bigint: \"bigint\",\n    object: \"date\",\n};\nexport const $ZodCheckLessThan = /*@__PURE__*/ core.$constructor(\"$ZodCheckLessThan\", (inst, def) => {\n    $ZodCheck.init(inst, def);\n    const origin = numericOriginMap[typeof def.value];\n    inst._zod.check = (payload) => {\n        if (def.inclusive ? payload.value <= def.value : payload.value < def.value) {\n            return;\n        }\n        payload.issues.push({\n            origin: numericOriginMap[typeof payload.value] ?? origin,\n            code: \"too_big\",\n            maximum: typeof def.value === \"object\" ? def.value.getTime() : def.value,\n            input: payload.value,\n            inclusive: def.inclusive,\n            inst,\n            continue: !def.abort,\n        });\n    };\n});\nexport const $ZodCheckGreaterThan = /*@__PURE__*/ core.$constructor(\"$ZodCheckGreaterThan\", (inst, def) => {\n    $ZodCheck.init(inst, def);\n    const origin = numericOriginMap[typeof def.value];\n    inst._zod.check = (payload) => {\n        if (def.inclusive ? payload.value >= def.value : payload.value > def.value) {\n            return;\n        }\n        payload.issues.push({\n            origin: numericOriginMap[typeof payload.value] ?? origin,\n            code: \"too_small\",\n            minimum: typeof def.value === \"object\" ? def.value.getTime() : def.value,\n            input: payload.value,\n            inclusive: def.inclusive,\n            inst,\n            continue: !def.abort,\n        });\n    };\n});\nexport const $ZodCheckMultipleOf = \n/*@__PURE__*/ core.$constructor(\"$ZodCheckMultipleOf\", (inst, def) => {\n    $ZodCheck.init(inst, def);\n    inst._zod.check = (payload) => {\n        if (typeof payload.value !== typeof def.value)\n            throw new Error(\"Cannot mix number and bigint in multiple_of check.\");\n        const isMultiple = typeof payload.value === \"bigint\"\n            ? // `value % 0n` throws, and nothing is a multiple of zero — the number branch already fails this way via NaN\n                def.value !== BigInt(0) && payload.value % def.value === BigInt(0)\n            : util.floatSafeRemainder(payload.value, def.value) === 0;\n        if (isMultiple)\n            return;\n        payload.issues.push({\n            origin: typeof payload.value,\n            code: \"not_multiple_of\",\n            divisor: def.value,\n            input: payload.value,\n            inst,\n            continue: !def.abort,\n        });\n    };\n});\nexport const $ZodCheckNumberFormat = /*@__PURE__*/ core.$constructor(\"$ZodCheckNumberFormat\", (inst, def) => {\n    $ZodCheck.init(inst, def); // no format checks\n    def.format = def.format || \"float64\";\n    const isInt = def.format?.includes(\"int\");\n    const origin = isInt ? \"int\" : \"number\";\n    const [minimum, maximum] = util.NUMBER_FORMAT_RANGES[def.format];\n    inst._zod.check = (payload) => {\n        const input = payload.value;\n        if (isInt) {\n            if (!Number.isInteger(input)) {\n                // invalid_format issue\n                // payload.issues.push({\n                //   expected: def.format,\n                //   format: def.format,\n                //   code: \"invalid_format\",\n                //   input,\n                //   inst,\n                // });\n                // invalid_type issue\n                payload.issues.push({\n                    expected: origin,\n                    format: def.format,\n                    code: \"invalid_type\",\n                    continue: false,\n                    input,\n                    inst,\n                });\n                return;\n                // not_multiple_of issue\n                // payload.issues.push({\n                //   code: \"not_multiple_of\",\n                //   origin: \"number\",\n                //   input,\n                //   inst,\n                //   divisor: 1,\n                // });\n            }\n            if (!Number.isSafeInteger(input)) {\n                if (input > 0) {\n                    // too_big\n                    payload.issues.push({\n                        input,\n                        code: \"too_big\",\n                        maximum: Number.MAX_SAFE_INTEGER,\n                        note: \"Integers must be within the safe integer range.\",\n                        inst,\n                        origin,\n                        inclusive: true,\n                        continue: !def.abort,\n                    });\n                }\n                else {\n                    // too_small\n                    payload.issues.push({\n                        input,\n                        code: \"too_small\",\n                        minimum: Number.MIN_SAFE_INTEGER,\n                        note: \"Integers must be within the safe integer range.\",\n                        inst,\n                        origin,\n                        inclusive: true,\n                        continue: !def.abort,\n                    });\n                }\n                return;\n            }\n        }\n        if (input < minimum) {\n            payload.issues.push({\n                origin: \"number\",\n                input,\n                code: \"too_small\",\n                minimum,\n                inclusive: true,\n                inst,\n                continue: !def.abort,\n            });\n        }\n        if (input > maximum) {\n            payload.issues.push({\n                origin: \"number\",\n                input,\n                code: \"too_big\",\n                maximum,\n                inclusive: true,\n                inst,\n                continue: !def.abort,\n            });\n        }\n    };\n});\nexport const $ZodCheckBigIntFormat = /*@__PURE__*/ core.$constructor(\"$ZodCheckBigIntFormat\", (inst, def) => {\n    $ZodCheck.init(inst, def); // no format checks\n    const [minimum, maximum] = util.BIGINT_FORMAT_RANGES[def.format];\n    inst._zod.check = (payload) => {\n        const input = payload.value;\n        if (input < minimum) {\n            payload.issues.push({\n                origin: \"bigint\",\n                input,\n                code: \"too_small\",\n                minimum: minimum,\n                inclusive: true,\n                inst,\n                continue: !def.abort,\n            });\n        }\n        if (input > maximum) {\n            payload.issues.push({\n                origin: \"bigint\",\n                input,\n                code: \"too_big\",\n                maximum,\n                inclusive: true,\n                inst,\n                continue: !def.abort,\n            });\n        }\n    };\n});\nexport const $ZodCheckMaxSize = /*@__PURE__*/ core.$constructor(\"$ZodCheckMaxSize\", (inst, def) => {\n    var _a;\n    $ZodCheck.init(inst, def);\n    (_a = inst._zod.def).when ?? (_a.when = _whenHasSize);\n    inst._zod.check = (payload) => {\n        const input = payload.value;\n        const size = input.size;\n        if (size <= def.maximum)\n            return;\n        payload.issues.push({\n            origin: util.getSizableOrigin(input),\n            code: \"too_big\",\n            maximum: def.maximum,\n            inclusive: true,\n            input,\n            inst,\n            continue: !def.abort,\n        });\n    };\n});\nexport const $ZodCheckMinSize = /*@__PURE__*/ core.$constructor(\"$ZodCheckMinSize\", (inst, def) => {\n    var _a;\n    $ZodCheck.init(inst, def);\n    (_a = inst._zod.def).when ?? (_a.when = _whenHasSize);\n    inst._zod.check = (payload) => {\n        const input = payload.value;\n        const size = input.size;\n        if (size >= def.minimum)\n            return;\n        payload.issues.push({\n            origin: util.getSizableOrigin(input),\n            code: \"too_small\",\n            minimum: def.minimum,\n            inclusive: true,\n            input,\n            inst,\n            continue: !def.abort,\n        });\n    };\n});\nexport const $ZodCheckSizeEquals = /*@__PURE__*/ core.$constructor(\"$ZodCheckSizeEquals\", (inst, def) => {\n    var _a;\n    $ZodCheck.init(inst, def);\n    (_a = inst._zod.def).when ?? (_a.when = _whenHasSize);\n    inst._zod.check = (payload) => {\n        const input = payload.value;\n        const size = input.size;\n        if (size === def.size)\n            return;\n        const tooBig = size > def.size;\n        payload.issues.push({\n            origin: util.getSizableOrigin(input),\n            ...(tooBig ? { code: \"too_big\", maximum: def.size } : { code: \"too_small\", minimum: def.size }),\n            inclusive: true,\n            exact: true,\n            input: payload.value,\n            inst,\n            continue: !def.abort,\n        });\n    };\n});\nexport const $ZodCheckMaxLength = /*@__PURE__*/ core.$constructor(\"$ZodCheckMaxLength\", (inst, def) => {\n    var _a;\n    $ZodCheck.init(inst, def);\n    (_a = inst._zod.def).when ?? (_a.when = _whenHasLength);\n    inst._zod.check = (payload) => {\n        const input = payload.value;\n        const units = input.length;\n        // 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.\n        const length = typeof input === \"string\" && units > def.maximum ? util.codePointLength(input) : units;\n        if (length <= def.maximum)\n            return;\n        const origin = util.getLengthableOrigin(input);\n        payload.issues.push({\n            origin,\n            code: \"too_big\",\n            maximum: def.maximum,\n            inclusive: true,\n            input,\n            inst,\n            continue: !def.abort,\n        });\n    };\n});\nexport const $ZodCheckMinLength = /*@__PURE__*/ core.$constructor(\"$ZodCheckMinLength\", (inst, def) => {\n    var _a;\n    $ZodCheck.init(inst, def);\n    (_a = inst._zod.def).when ?? (_a.when = _whenHasLength);\n    inst._zod.check = (payload) => {\n        const input = payload.value;\n        const units = input.length;\n        // 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.\n        const length = typeof input === \"string\" && units >= def.minimum && units < def.minimum * 2\n            ? util.codePointLength(input)\n            : units;\n        if (length >= def.minimum)\n            return;\n        const origin = util.getLengthableOrigin(input);\n        payload.issues.push({\n            origin,\n            code: \"too_small\",\n            minimum: def.minimum,\n            inclusive: true,\n            input,\n            inst,\n            continue: !def.abort,\n        });\n    };\n});\nexport const $ZodCheckLengthEquals = /*@__PURE__*/ core.$constructor(\"$ZodCheckLengthEquals\", (inst, def) => {\n    var _a;\n    $ZodCheck.init(inst, def);\n    (_a = inst._zod.def).when ?? (_a.when = _whenHasLength);\n    inst._zod.check = (payload) => {\n        const input = payload.value;\n        const units = input.length;\n        // 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.\n        const length = typeof input === \"string\" && units >= def.length && units <= def.length * 2\n            ? util.codePointLength(input)\n            : units;\n        if (length === def.length)\n            return;\n        const origin = util.getLengthableOrigin(input);\n        const tooBig = length > def.length;\n        payload.issues.push({\n            origin,\n            ...(tooBig ? { code: \"too_big\", maximum: def.length } : { code: \"too_small\", minimum: def.length }),\n            inclusive: true,\n            exact: true,\n            input: payload.value,\n            inst,\n            continue: !def.abort,\n        });\n    };\n});\nexport const $ZodCheckStringFormat = /*@__PURE__*/ core.$constructor(\"$ZodCheckStringFormat\", (inst, def) => {\n    var _a, _b;\n    $ZodCheck.init(inst, def);\n    if (def.pattern)\n        (_a = inst._zod).check ?? (_a.check = (payload) => {\n            def.pattern.lastIndex = 0;\n            if (def.pattern.test(payload.value))\n                return;\n            payload.issues.push({\n                origin: \"string\",\n                code: \"invalid_format\",\n                format: def.format,\n                input: payload.value,\n                ...(def.pattern ? { pattern: def.pattern.toString() } : {}),\n                inst,\n                continue: !def.abort,\n            });\n        });\n    else\n        (_b = inst._zod).check ?? (_b.check = () => { });\n});\nexport const $ZodCheckRegex = /*@__PURE__*/ core.$constructor(\"$ZodCheckRegex\", (inst, def) => {\n    $ZodCheckStringFormat.init(inst, def);\n    inst._zod.check = (payload) => {\n        def.pattern.lastIndex = 0;\n        if (def.pattern.test(payload.value))\n            return;\n        payload.issues.push({\n            origin: \"string\",\n            code: \"invalid_format\",\n            format: \"regex\",\n            input: payload.value,\n            pattern: def.pattern.toString(),\n            inst,\n            continue: !def.abort,\n        });\n    };\n});\nexport const $ZodCheckLowerCase = /*@__PURE__*/ core.$constructor(\"$ZodCheckLowerCase\", (inst, def) => {\n    def.pattern ?? (def.pattern = regexes.lowercase);\n    $ZodCheckStringFormat.init(inst, def);\n});\nexport const $ZodCheckUpperCase = /*@__PURE__*/ core.$constructor(\"$ZodCheckUpperCase\", (inst, def) => {\n    def.pattern ?? (def.pattern = regexes.uppercase);\n    $ZodCheckStringFormat.init(inst, def);\n});\nexport const $ZodCheckIncludes = /*@__PURE__*/ core.$constructor(\"$ZodCheckIncludes\", (inst, def) => {\n    $ZodCheck.init(inst, def);\n    const escapedRegex = util.escapeRegex(def.includes);\n    // `String.prototype.includes(sub, position)` matches `sub` at `position`\n    // OR LATER, so the pattern must allow at least `position` leading chars\n    // (`{N,}`), not exactly `position` chars (`{N}`).\n    const pattern = new RegExp(typeof def.position === \"number\" ? `^.{${def.position},}${escapedRegex}` : escapedRegex);\n    def.pattern = pattern;\n    inst._zod.check = (payload) => {\n        if (payload.value.includes(def.includes, def.position))\n            return;\n        payload.issues.push({\n            origin: \"string\",\n            code: \"invalid_format\",\n            format: \"includes\",\n            includes: def.includes,\n            input: payload.value,\n            inst,\n            continue: !def.abort,\n        });\n    };\n});\nexport const $ZodCheckStartsWith = /*@__PURE__*/ core.$constructor(\"$ZodCheckStartsWith\", (inst, def) => {\n    $ZodCheck.init(inst, def);\n    const pattern = new RegExp(`^${util.escapeRegex(def.prefix)}.*`);\n    def.pattern ?? (def.pattern = pattern);\n    inst._zod.check = (payload) => {\n        if (payload.value.startsWith(def.prefix))\n            return;\n        payload.issues.push({\n            origin: \"string\",\n            code: \"invalid_format\",\n            format: \"starts_with\",\n            prefix: def.prefix,\n            input: payload.value,\n            inst,\n            continue: !def.abort,\n        });\n    };\n});\nexport const $ZodCheckEndsWith = /*@__PURE__*/ core.$constructor(\"$ZodCheckEndsWith\", (inst, def) => {\n    $ZodCheck.init(inst, def);\n    const pattern = new RegExp(`.*${util.escapeRegex(def.suffix)}$`);\n    def.pattern ?? (def.pattern = pattern);\n    inst._zod.check = (payload) => {\n        if (payload.value.endsWith(def.suffix))\n            return;\n        payload.issues.push({\n            origin: \"string\",\n            code: \"invalid_format\",\n            format: \"ends_with\",\n            suffix: def.suffix,\n            input: payload.value,\n            inst,\n            continue: !def.abort,\n        });\n    };\n});\n///////////////////////////////////\n/////    $ZodCheckProperty    /////\n///////////////////////////////////\nfunction handleCheckPropertyResult(result, payload, property) {\n    if (result.issues.length) {\n        payload.issues.push(...util.prefixIssues(property, result.issues));\n    }\n}\nexport const $ZodCheckProperty = /*@__PURE__*/ core.$constructor(\"$ZodCheckProperty\", (inst, def) => {\n    $ZodCheck.init(inst, def);\n    inst._zod.check = (payload) => {\n        const result = def.schema._zod.run({\n            value: payload.value[def.property],\n            issues: [],\n        }, {});\n        if (result instanceof Promise) {\n            return result.then((result) => handleCheckPropertyResult(result, payload, def.property));\n        }\n        handleCheckPropertyResult(result, payload, def.property);\n        return;\n    };\n});\nexport const $ZodCheckProperties = /*@__PURE__*/ core.$constructor(\"$ZodCheckProperties\", (inst, def) => {\n    $ZodCheck.init(inst, def);\n    util.hide(inst, Symbol.iterator, function* () {\n        yield inst;\n    });\n    // key and schema snapshotted together: reading one live and the other cached lets a later mutation of the caller's shape object pair a stale key with a missing schema\n    let entries;\n    inst._zod.check = (payload) => {\n        // the base schema already typed the value, so only a nullish one is rejected here: the properties read on a primitive too, matching z.property() on a string's length\n        if (payload.value == null) {\n            payload.issues.push({ expected: \"object\", code: \"invalid_type\", input: payload.value, inst });\n            return undefined;\n        }\n        entries ?? (entries = Reflect.ownKeys(def.shape).map((key) => [key, def.shape[key]]));\n        const input = payload.value;\n        let proms;\n        for (const [key, schema] of entries) {\n            const result = schema._zod.run({ value: input[key], issues: [] }, {});\n            if (result instanceof Promise) {\n                proms ?? (proms = []);\n                proms.push(result.then((result) => handleCheckPropertyResult(result, payload, key)));\n            }\n            else {\n                handleCheckPropertyResult(result, payload, key);\n            }\n        }\n        if (proms)\n            return Promise.all(proms).then(() => undefined);\n        return undefined;\n    };\n});\nexport const $ZodCheckMimeType = /*@__PURE__*/ core.$constructor(\"$ZodCheckMimeType\", (inst, def) => {\n    $ZodCheck.init(inst, def);\n    const mimeSet = new Set(def.mime);\n    inst._zod.check = (payload) => {\n        if (mimeSet.has(payload.value.type))\n            return;\n        payload.issues.push({\n            code: \"invalid_value\",\n            values: def.mime,\n            input: payload.value.type,\n            inst,\n            continue: !def.abort,\n        });\n    };\n});\nexport const $ZodCheckOverwrite = /*@__PURE__*/ core.$constructor(\"$ZodCheckOverwrite\", (inst, def) => {\n    $ZodCheck.init(inst, def);\n    inst._zod.check = (payload) => {\n        payload.value = def.tx(payload.value);\n    };\n});\n","export class Doc {\n    constructor(args = [], closed = {}) {\n        this.content = [];\n        this.indent = 0;\n        this.args = args;\n        this.closed = closed;\n    }\n    // the compiler catches a child's throw and keeps writing into this doc, so the indent has to unwind with it\n    indented(fn) {\n        this.indent += 1;\n        try {\n            fn(this);\n        }\n        finally {\n            this.indent -= 1;\n        }\n    }\n    write(arg) {\n        if (typeof arg === \"function\") {\n            arg(this, { execution: \"sync\" });\n            arg(this, { execution: \"async\" });\n            return;\n        }\n        const content = arg;\n        const lines = content.split(\"\\n\").filter((x) => x);\n        const minIndent = Math.min(...lines.map((x) => x.length - x.trimStart().length));\n        const dedented = lines.map((x) => x.slice(minIndent)).map((x) => \" \".repeat(this.indent * 2) + x);\n        for (const line of dedented) {\n            this.content.push(line);\n        }\n    }\n    compile() {\n        const F = Function;\n        const content = this?.content ?? [``];\n        const factory = new F(...Object.keys(this.closed), `return function (${this.args.join(\", \")}) {\\n${content.join(\"\\n\")}\\n};`);\n        return factory(...Object.values(this.closed));\n    }\n}\n","export const version = {\n    major: 4,\n    minor: 6,\n    patch: 7,\n};\n","import * as checks from \"./checks.js\";\nimport * as core from \"./core.js\";\nimport { Doc } from \"./doc.js\";\nimport { parse, parseAsync } from \"./parse.js\";\nimport * as regexes from \"./regexes.js\";\nimport * as util from \"./util.js\";\nimport { version } from \"./versions.js\";\nexport const $ZodType = /*@__PURE__*/ core.$constructor(\"$ZodType\", (inst, def) => {\n    var _a;\n    inst ?? (inst = {});\n    inst._zod.def = def; // set _def property\n    inst._zod.bag = inst._zod.bag || {}; // initialize _bag object\n    inst._zod.version = version;\n    const defChecks = inst._zod.def.checks;\n    // if inst is itself a checks.$ZodCheck, run it as a check\n    const checks = inst._zod.traits.has(\"$ZodCheck\")\n        ? [inst, ...(defChecks ?? [])]\n        : defChecks?.length\n            ? [...defChecks]\n            : [];\n    for (const ch of checks) {\n        for (const fn of ch._zod.onattach) {\n            fn(inst);\n        }\n    }\n    if (checks.length === 0) {\n        // deferred initializer inst._zod.parse is not yet defined\n        (_a = inst._zod).deferred ?? (_a.deferred = []);\n        inst._zod.deferred?.push(() => {\n            inst._zod.run = inst._zod.parse;\n        });\n    }\n    else {\n        const runChecks = (payload, checks, ctx) => {\n            if (payload.memo)\n                return payload;\n            let isAborted = util.aborted(payload);\n            let asyncResult;\n            for (const ch of checks) {\n                if (ch._zod.def.when) {\n                    if (util.explicitlyAborted(payload))\n                        continue;\n                    const shouldRun = ch._zod.def.when(payload);\n                    if (!shouldRun)\n                        continue;\n                }\n                else if (isAborted) {\n                    continue;\n                }\n                const currLen = payload.issues.length;\n                const _ = ch._zod.check(payload);\n                if (_ instanceof Promise && ctx?.async === false) {\n                    throw new core.$ZodAsyncError();\n                }\n                if (asyncResult || _ instanceof Promise) {\n                    asyncResult = (asyncResult ?? Promise.resolve()).then(async () => {\n                        await _;\n                        const nextLen = payload.issues.length;\n                        if (nextLen === currLen)\n                            return;\n                        util.attachSchema(payload.issues, currLen, inst);\n                        if (!isAborted)\n                            isAborted = util.aborted(payload, currLen);\n                    });\n                }\n                else {\n                    const nextLen = payload.issues.length;\n                    if (nextLen === currLen)\n                        continue;\n                    util.attachSchema(payload.issues, currLen, inst);\n                    if (!isAborted)\n                        isAborted = util.aborted(payload, currLen);\n                }\n            }\n            if (asyncResult) {\n                return asyncResult.then(() => {\n                    return payload;\n                });\n            }\n            return payload;\n        };\n        const handleCanaryResult = (canary, payload, ctx) => {\n            // abort if the canary is aborted\n            if (util.aborted(canary)) {\n                canary.aborted = true;\n                return canary;\n            }\n            // run checks first, then\n            const checkResult = runChecks(payload, checks, ctx);\n            if (checkResult instanceof Promise) {\n                if (ctx.async === false)\n                    throw new core.$ZodAsyncError();\n                return checkResult.then((checkResult) => inst._zod.parse(checkResult, ctx));\n            }\n            return inst._zod.parse(checkResult, ctx);\n        };\n        inst._zod.run = (payload, ctx) => {\n            if (ctx.skipChecks) {\n                return inst._zod.parse(payload, ctx);\n            }\n            if (ctx.direction === \"backward\") {\n                // run canary initial pass (no checks)\n                const canary = inst._zod.parse({ value: payload.value, issues: [] }, { ...ctx, skipChecks: true });\n                if (canary instanceof Promise) {\n                    return canary.then((canary) => {\n                        return handleCanaryResult(canary, payload, ctx);\n                    });\n                }\n                return handleCanaryResult(canary, payload, ctx);\n            }\n            // forward\n            const result = inst._zod.parse(payload, ctx);\n            if (result instanceof Promise) {\n                if (ctx.async === false)\n                    throw new core.$ZodAsyncError();\n                return result.then((result) => runChecks(result, checks, ctx));\n            }\n            return runChecks(result, checks, ctx);\n        };\n    }\n}, {\n    // Wrappers extend this by installing a richer factory over it; reading it eagerly would defeat the laziness.\n    get \"~standard\"() {\n        return util.hide(this, \"~standard\", standardProps(this));\n    },\n    set \"~standard\"(value) {\n        util.own(this, \"~standard\", value);\n    },\n});\n/** The Standard Schema surface for `inst`. Shared so wrappers can extend it without forcing it. */\n// a Standard Schema result only reports issues, so a failure finalizes them straight off the raw payload: no ZodError, and no lazy result to read through\nconst toStandardResult = (r, ctx) => r.issues.length ? { issues: r.issues.map((iss) => util.finalizeIssue(iss, ctx, core.config())) } : { value: r.value };\nasync function validateAsync(inst, value) {\n    const ctx = { async: true };\n    return toStandardResult((await inst._zod.run({ value, issues: [] }, ctx)), ctx);\n}\nexport function standardProps(inst) {\n    return {\n        validate: (value) => {\n            const ctx = { async: false };\n            try {\n                const r = inst._zod.run({ value, issues: [] }, ctx);\n                if (!(r instanceof Promise))\n                    return toStandardResult(r, ctx);\n            }\n            catch (_) { }\n            // async function so a synchronously throwing check rejects instead of escaping validate\n            return validateAsync(inst, value);\n        },\n        vendor: \"zod\",\n        version: 1,\n    };\n}\nexport { clone } from \"./util.js\";\nexport const $ZodString = /*@__PURE__*/ core.$constructor(\"$ZodString\", (inst, def) => {\n    $ZodType.init(inst, def);\n    // a format's own pattern, else unbounded; a template literal derives the check-aware form itself\n    inst._zod.pattern = def.pattern ?? regexes.anyString;\n    inst._zod.parse = (payload, _) => {\n        if (def.coerce)\n            try {\n                payload.value = String(payload.value);\n            }\n            catch (_) { }\n        if (typeof payload.value === \"string\")\n            return payload;\n        payload.issues.push({\n            expected: \"string\",\n            code: \"invalid_type\",\n            input: payload.value,\n            inst,\n        });\n        return payload;\n    };\n});\nexport const $ZodStringFormat = /*@__PURE__*/ core.$constructor(\"$ZodStringFormat\", (inst, def) => {\n    // check initialization must come first\n    checks.$ZodCheckStringFormat.init(inst, def);\n    $ZodString.init(inst, def);\n});\nexport const $ZodGUID = /*@__PURE__*/ core.$constructor(\"$ZodGUID\", (inst, def) => {\n    def.pattern ?? (def.pattern = regexes.guid);\n    $ZodStringFormat.init(inst, def);\n});\nexport const $ZodUUID = /*@__PURE__*/ core.$constructor(\"$ZodUUID\", (inst, def) => {\n    if (def.version) {\n        const versionMap = {\n            v1: 1,\n            v2: 2,\n            v3: 3,\n            v4: 4,\n            v5: 5,\n            v6: 6,\n            v7: 7,\n            v8: 8,\n        };\n        const v = versionMap[def.version];\n        if (v === undefined)\n            throw new Error(`Invalid UUID version: \"${def.version}\"`);\n        def.pattern ?? (def.pattern = regexes.uuid(v));\n    }\n    else\n        def.pattern ?? (def.pattern = regexes.uuid());\n    $ZodStringFormat.init(inst, def);\n});\nexport const $ZodEmail = /*@__PURE__*/ core.$constructor(\"$ZodEmail\", (inst, def) => {\n    def.pattern ?? (def.pattern = regexes.email);\n    $ZodStringFormat.init(inst, def);\n});\n/** The `://` guard rejected the input before the URL constructor saw it. */\nexport const URL_BAD_FORMAT = 1;\n/** The URL parser rejected the input. */\nexport const URL_UNPARSEABLE = 2;\nexport function canParseURL(input) {\n    try {\n        if (typeof URL !== \"undefined\" && typeof URL.canParse === \"function\")\n            return URL.canParse(input);\n        new URL(input);\n        return true;\n    }\n    catch {\n        return false;\n    }\n}\nexport function validateURL(trimmed, def) {\n    if (!(\"normalize\" in def) && !(\"hostname\" in def) && !(\"protocol\" in def)) {\n        return canParseURL(trimmed) || URL_UNPARSEABLE;\n    }\n    return parseURLObject(trimmed, def);\n}\n/** Parses a URL while preserving the non-normalizing HTTP guard. */\nexport function parseURLObject(trimmed, def) {\n    // When normalize is off, require :// for http/https URLs. This prevents strings like \"http:example.com\" or \"https:/path\" from being silently accepted\n    if (!def.normalize && def.protocol?.source === regexes.httpProtocol.source && !/^https?:\\/\\//i.test(trimmed)) {\n        return URL_BAD_FORMAT;\n    }\n    try {\n        if (typeof URL !== \"undefined\") {\n            const URLStatic = URL;\n            if (typeof URLStatic.parse === \"function\")\n                return URLStatic.parse(trimmed) ?? URL_UNPARSEABLE;\n        }\n        // @ts-ignore\n        return new URL(trimmed);\n    }\n    catch {\n        return URL_UNPARSEABLE;\n    }\n}\nconst asciiTabOrNewline = /[\\t\\n\\r]/g;\n/** 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. */\nexport function stripTabAndNewline(value) {\n    return value.replace(asciiTabOrNewline, \"\");\n}\nexport function urlHostnameOk(url, hostname) {\n    hostname.lastIndex = 0;\n    return hostname.test(url.hostname);\n}\nexport function urlProtocolOk(url, protocol) {\n    protocol.lastIndex = 0;\n    return protocol.test(url.protocol.endsWith(\":\") ? url.protocol.slice(0, -1) : url.protocol);\n}\nexport const $ZodURL = /*@__PURE__*/ core.$constructor(\"$ZodURL\", (inst, def) => {\n    $ZodStringFormat.init(inst, def);\n    inst._zod.check = (payload) => {\n        try {\n            // Trim whitespace from input\n            const trimmed = payload.value.trim();\n            const url = validateURL(trimmed, def);\n            if (url === URL_BAD_FORMAT) {\n                payload.issues.push({\n                    code: \"invalid_format\",\n                    format: \"url\",\n                    note: \"Invalid URL format\",\n                    input: payload.value,\n                    inst,\n                    continue: !def.abort,\n                });\n                return;\n            }\n            if (url === URL_UNPARSEABLE) {\n                payload.issues.push({\n                    code: \"invalid_format\",\n                    format: \"url\",\n                    input: payload.value,\n                    inst,\n                    continue: !def.abort,\n                });\n                return;\n            }\n            if (url === true) {\n                payload.value = stripTabAndNewline(trimmed);\n                return;\n            }\n            if (def.hostname && !urlHostnameOk(url, def.hostname)) {\n                payload.issues.push({\n                    code: \"invalid_format\",\n                    format: \"url\",\n                    note: \"Invalid hostname\",\n                    pattern: def.hostname.source,\n                    input: payload.value,\n                    inst,\n                    continue: !def.abort,\n                });\n            }\n            if (def.protocol && !urlProtocolOk(url, def.protocol)) {\n                payload.issues.push({\n                    code: \"invalid_format\",\n                    format: \"url\",\n                    note: \"Invalid protocol\",\n                    pattern: def.protocol.source,\n                    input: payload.value,\n                    inst,\n                    continue: !def.abort,\n                });\n            }\n            // Set the output value based on normalize flag\n            payload.value = def.normalize ? url.href : stripTabAndNewline(trimmed);\n            return;\n        }\n        catch (_) {\n            payload.issues.push({\n                code: \"invalid_format\",\n                format: \"url\",\n                input: payload.value,\n                inst,\n                continue: !def.abort,\n            });\n        }\n    };\n});\nexport const $ZodEmoji = /*@__PURE__*/ core.$constructor(\"$ZodEmoji\", (inst, def) => {\n    def.pattern ?? (def.pattern = regexes.emoji());\n    $ZodStringFormat.init(inst, def);\n});\nexport const $ZodNanoID = /*@__PURE__*/ core.$constructor(\"$ZodNanoID\", (inst, def) => {\n    if (def.length !== undefined && (!Number.isInteger(def.length) || def.length < 1))\n        throw new Error(`Invalid nanoid length: ${def.length}`);\n    def.pattern ?? (def.pattern = def.length === undefined ? regexes.nanoid : regexes.nanoidOfLength(def.length));\n    $ZodStringFormat.init(inst, def);\n});\n/**\n * @deprecated CUID v1 is deprecated by its authors due to information leakage\n * (timestamps embedded in the id). Use {@link $ZodCUID2} instead.\n * See https://github.com/paralleldrive/cuid.\n */\nexport const $ZodCUID = /*@__PURE__*/ core.$constructor(\"$ZodCUID\", (inst, def) => {\n    def.pattern ?? (def.pattern = regexes.cuid);\n    $ZodStringFormat.init(inst, def);\n});\nexport const $ZodCUID2 = /*@__PURE__*/ core.$constructor(\"$ZodCUID2\", (inst, def) => {\n    def.pattern ?? (def.pattern = regexes.cuid2);\n    $ZodStringFormat.init(inst, def);\n});\nexport const $ZodULID = /*@__PURE__*/ core.$constructor(\"$ZodULID\", (inst, def) => {\n    def.pattern ?? (def.pattern = regexes.ulid);\n    $ZodStringFormat.init(inst, def);\n});\nexport const $ZodXID = /*@__PURE__*/ core.$constructor(\"$ZodXID\", (inst, def) => {\n    def.pattern ?? (def.pattern = regexes.xid);\n    $ZodStringFormat.init(inst, def);\n});\nexport const $ZodKSUID = /*@__PURE__*/ core.$constructor(\"$ZodKSUID\", (inst, def) => {\n    def.pattern ?? (def.pattern = regexes.ksuid);\n    $ZodStringFormat.init(inst, def);\n});\nexport const $ZodISODateTime = /*@__PURE__*/ core.$constructor(\"$ZodISODateTime\", (inst, def) => {\n    def.pattern ?? (def.pattern = regexes.datetime(def));\n    $ZodStringFormat.init(inst, def);\n});\nexport const $ZodISODate = /*@__PURE__*/ core.$constructor(\"$ZodISODate\", (inst, def) => {\n    def.pattern ?? (def.pattern = regexes.date);\n    $ZodStringFormat.init(inst, def);\n});\nexport const $ZodISOTime = /*@__PURE__*/ core.$constructor(\"$ZodISOTime\", (inst, def) => {\n    def.pattern ?? (def.pattern = regexes.time(def));\n    $ZodStringFormat.init(inst, def);\n});\nexport const $ZodISODuration = /*@__PURE__*/ core.$constructor(\"$ZodISODuration\", (inst, def) => {\n    def.pattern ?? (def.pattern = regexes.duration);\n    $ZodStringFormat.init(inst, def);\n});\nexport const $ZodIPv4 = /*@__PURE__*/ core.$constructor(\"$ZodIPv4\", (inst, def) => {\n    def.pattern ?? (def.pattern = regexes.ipv4);\n    $ZodStringFormat.init(inst, def);\n});\n/** 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`. */\nconst ipv6Alphabet = /^[0-9a-fA-F:.]+$/;\nexport function isValidIPv6(value) {\n    if (!ipv6Alphabet.test(value))\n        return false;\n    return canParseURL(`http://[${value}]`);\n}\nexport const $ZodIPv6 = /*@__PURE__*/ core.$constructor(\"$ZodIPv6\", (inst, def) => {\n    def.pattern ?? (def.pattern = regexes.ipv6);\n    $ZodStringFormat.init(inst, def);\n    inst._zod.check = (payload) => {\n        if (!isValidIPv6(payload.value)) {\n            payload.issues.push({\n                code: \"invalid_format\",\n                format: \"ipv6\",\n                input: payload.value,\n                inst,\n                continue: !def.abort,\n            });\n        }\n    };\n});\nexport const $ZodMAC = /*@__PURE__*/ core.$constructor(\"$ZodMAC\", (inst, def) => {\n    def.pattern ?? (def.pattern = regexes.mac(def.delimiter));\n    $ZodStringFormat.init(inst, def);\n});\nexport const $ZodCIDRv4 = /*@__PURE__*/ core.$constructor(\"$ZodCIDRv4\", (inst, def) => {\n    def.pattern ?? (def.pattern = regexes.cidrv4);\n    $ZodStringFormat.init(inst, def);\n});\nexport function isValidCIDRv6(value) {\n    const parts = value.split(\"/\");\n    if (parts.length !== 2)\n        return false;\n    const [address, prefix] = parts;\n    if (!prefix)\n        return false;\n    const prefixNum = Number(prefix);\n    if (`${prefixNum}` !== prefix)\n        return false;\n    if (prefixNum < 0 || prefixNum > 128)\n        return false;\n    return isValidIPv6(address);\n}\nexport const $ZodCIDRv6 = /*@__PURE__*/ core.$constructor(\"$ZodCIDRv6\", (inst, def) => {\n    def.pattern ?? (def.pattern = regexes.cidrv6); // not used for validation\n    $ZodStringFormat.init(inst, def);\n    inst._zod.check = (payload) => {\n        if (!isValidCIDRv6(payload.value)) {\n            payload.issues.push({\n                code: \"invalid_format\",\n                format: \"cidrv6\",\n                input: payload.value,\n                inst,\n                continue: !def.abort,\n            });\n        }\n    };\n});\n//////////////////////////////   ZodBase64   //////////////////////////////\nexport function isValidBase64(data) {\n    if (data === \"\")\n        return true;\n    // atob ignores whitespace, so reject it up front.\n    if (/\\s/.test(data))\n        return false;\n    if (data.length % 4 !== 0)\n        return false;\n    try {\n        // @ts-ignore\n        atob(data);\n        return true;\n    }\n    catch {\n        return false;\n    }\n}\n// lax on purpose: the quantified regexes.base64 overflows the regex stack on multi-MB input and its leading ^$| alternation leaks through template-literal composition; isValidBase64 enforces length and padding\nexport const base64Charset = /^[0-9a-zA-Z+/]*={0,2}$/;\nexport const $ZodBase64 = /*@__PURE__*/ core.$constructor(\"$ZodBase64\", (inst, def) => {\n    def.pattern ?? (def.pattern = base64Charset);\n    $ZodStringFormat.init(inst, def);\n    inst._zod.check = (payload) => {\n        if (isValidBase64(payload.value))\n            return;\n        payload.issues.push({\n            code: \"invalid_format\",\n            format: \"base64\",\n            input: payload.value,\n            inst,\n            continue: !def.abort,\n        });\n    };\n});\n//////////////////////////////   ZodBase64URL   //////////////////////////////\n// lax on purpose: the quantified regexes.base64url overflows the regex stack on multi-MB input; isValidBase64 enforces length on the padded string\nexport const base64urlCharset = /^[A-Za-z0-9_-]*$/;\nexport function isValidBase64URL(data) {\n    if (!base64urlCharset.test(data))\n        return false;\n    const base64 = data.replace(/[-_]/g, (c) => (c === \"-\" ? \"+\" : \"/\"));\n    const padded = base64.padEnd(Math.ceil(base64.length / 4) * 4, \"=\");\n    return isValidBase64(padded);\n}\nexport const $ZodBase64URL = /*@__PURE__*/ core.$constructor(\"$ZodBase64URL\", (inst, def) => {\n    def.pattern ?? (def.pattern = base64urlCharset);\n    $ZodStringFormat.init(inst, def);\n    inst._zod.check = (payload) => {\n        if (isValidBase64URL(payload.value))\n            return;\n        payload.issues.push({\n            code: \"invalid_format\",\n            format: \"base64url\",\n            input: payload.value,\n            inst,\n            continue: !def.abort,\n        });\n    };\n});\nexport const $ZodE164 = /*@__PURE__*/ core.$constructor(\"$ZodE164\", (inst, def) => {\n    def.pattern ?? (def.pattern = regexes.e164);\n    $ZodStringFormat.init(inst, def);\n});\n//////////////////////////////   ZodCreditCard   //////////////////////////////\nconst CC_SANITIZE = /[- ]/g;\n/** Luhn checksum on a digit-only string. Adapted from valibot (MIT). */\nfunction isLuhnAlgo(digits) {\n    let length = digits.length;\n    let bit = 1;\n    let sum = 0;\n    while (length) {\n        const value = digits.charCodeAt(--length) - 48;\n        bit ^= 1;\n        sum += bit ? [0, 2, 4, 6, 8, 1, 3, 5, 7, 9][value] : value;\n    }\n    return sum % 10 === 0;\n}\nexport function isValidCreditCard(input) {\n    if (!regexes.creditCard.test(input))\n        return false;\n    return isLuhnAlgo(input.replace(CC_SANITIZE, \"\"));\n}\nexport const $ZodCreditCard = /*@__PURE__*/ core.$constructor(\"$ZodCreditCard\", (inst, def) => {\n    // 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.\n    def.pattern ?? (def.pattern = regexes.creditCard);\n    $ZodStringFormat.init(inst, def);\n    inst._zod.check = (payload) => {\n        if (isValidCreditCard(payload.value))\n            return;\n        payload.issues.push({\n            code: \"invalid_format\",\n            format: \"credit_card\",\n            input: payload.value,\n            inst,\n            continue: !def.abort,\n        });\n    };\n});\n//////////////////////////////   ZodIBAN   //////////////////////////////\n// iso 7064 mod 97-10 checksum without BigInt\nfunction isIso7064Mod97(iban) {\n    let remainder = 0;\n    const len = iban.length;\n    for (let i = 4; i < len; i++) {\n        const code = iban.charCodeAt(i);\n        remainder = (code >= 65 ? remainder * 100 + (code - 55) : remainder * 10 + (code - 48)) % 97;\n    }\n    for (let i = 0; i < 4; i++) {\n        const code = iban.charCodeAt(i);\n        remainder = (code >= 65 ? remainder * 100 + (code - 55) : remainder * 10 + (code - 48)) % 97;\n    }\n    return remainder === 1;\n}\nexport function isValidIBAN(input) {\n    if (!regexes.iban.test(input))\n        return false;\n    return isIso7064Mod97(input);\n}\nexport const $ZodIBAN = /*@__PURE__*/ core.$constructor(\"$ZodIBAN\", (inst, def) => {\n    // shape only — checksum is not expressible as a pattern\n    def.pattern ?? (def.pattern = regexes.iban);\n    $ZodStringFormat.init(inst, def);\n    inst._zod.check = (payload) => {\n        if (isValidIBAN(payload.value))\n            return;\n        payload.issues.push({\n            code: \"invalid_format\",\n            format: \"iban\",\n            input: payload.value,\n            inst,\n            continue: !def.abort,\n        });\n    };\n});\n//////////////////////////////   ZodJWT   //////////////////////////////\nexport function isValidJWT(token, algorithm = null) {\n    try {\n        const tokensParts = token.split(\".\");\n        if (tokensParts.length !== 3)\n            return false;\n        const [header] = tokensParts;\n        if (!header)\n            return false;\n        // @ts-ignore\n        const parsedHeader = JSON.parse(atob(header));\n        if (\"typ\" in parsedHeader && parsedHeader?.typ !== \"JWT\")\n            return false;\n        if (!parsedHeader.alg)\n            return false;\n        if (algorithm && (!(\"alg\" in parsedHeader) || parsedHeader.alg !== algorithm))\n            return false;\n        return true;\n    }\n    catch {\n        return false;\n    }\n}\nexport const $ZodJWT = /*@__PURE__*/ core.$constructor(\"$ZodJWT\", (inst, def) => {\n    $ZodStringFormat.init(inst, def);\n    inst._zod.check = (payload) => {\n        if (isValidJWT(payload.value, def.alg))\n            return;\n        payload.issues.push({\n            code: \"invalid_format\",\n            format: \"jwt\",\n            input: payload.value,\n            inst,\n            continue: !def.abort,\n        });\n    };\n});\nexport const $ZodCustomStringFormat = /*@__PURE__*/ core.$constructor(\"$ZodCustomStringFormat\", (inst, def) => {\n    $ZodStringFormat.init(inst, def);\n    inst._zod.check = (payload) => {\n        if (def.fn(payload.value))\n            return;\n        payload.issues.push({\n            code: \"invalid_format\",\n            format: def.format,\n            input: payload.value,\n            inst,\n            continue: !def.abort,\n        });\n    };\n});\nexport const $ZodNumber = /*@__PURE__*/ core.$constructor(\"$ZodNumber\", (inst, def) => {\n    $ZodType.init(inst, def);\n    inst._zod.pattern = regexes.number;\n    inst._zod.parse = (payload, _ctx) => {\n        if (def.coerce)\n            try {\n                payload.value = Number(payload.value);\n            }\n            catch (_) { }\n        const input = payload.value;\n        if (typeof input === \"number\" && !Number.isNaN(input) && Number.isFinite(input)) {\n            return payload;\n        }\n        const received = typeof input === \"number\"\n            ? Number.isNaN(input)\n                ? \"NaN\"\n                : !Number.isFinite(input)\n                    ? String(input)\n                    : undefined\n            : undefined;\n        payload.issues.push({\n            expected: \"number\",\n            code: \"invalid_type\",\n            input,\n            inst,\n            ...(received ? { received } : {}),\n        });\n        return payload;\n    };\n});\nexport const $ZodNumberFormat = /*@__PURE__*/ core.$constructor(\"$ZodNumberFormat\", (inst, def) => {\n    checks.$ZodCheckNumberFormat.init(inst, def);\n    $ZodNumber.init(inst, def); // no format checks\n});\nexport const $ZodBoolean = /*@__PURE__*/ core.$constructor(\"$ZodBoolean\", (inst, def) => {\n    $ZodType.init(inst, def);\n    inst._zod.pattern = regexes.boolean;\n    inst._zod.parse = (payload, _ctx) => {\n        if (def.coerce)\n            try {\n                payload.value = Boolean(payload.value);\n            }\n            catch (_) { }\n        const input = payload.value;\n        if (typeof input === \"boolean\")\n            return payload;\n        payload.issues.push({\n            expected: \"boolean\",\n            code: \"invalid_type\",\n            input,\n            inst,\n        });\n        return payload;\n    };\n});\nexport const $ZodBigInt = /*@__PURE__*/ core.$constructor(\"$ZodBigInt\", (inst, def) => {\n    $ZodType.init(inst, def);\n    inst._zod.pattern = regexes.bigint;\n    inst._zod.parse = (payload, _ctx) => {\n        if (def.coerce)\n            try {\n                payload.value = BigInt(payload.value);\n            }\n            catch (_) { }\n        if (typeof payload.value === \"bigint\")\n            return payload;\n        payload.issues.push({\n            expected: \"bigint\",\n            code: \"invalid_type\",\n            input: payload.value,\n            inst,\n        });\n        return payload;\n    };\n});\nexport const $ZodBigIntFormat = /*@__PURE__*/ core.$constructor(\"$ZodBigIntFormat\", (inst, def) => {\n    checks.$ZodCheckBigIntFormat.init(inst, def);\n    $ZodBigInt.init(inst, def); // no format checks\n});\nexport const $ZodSymbol = /*@__PURE__*/ core.$constructor(\"$ZodSymbol\", (inst, def) => {\n    $ZodType.init(inst, def);\n    inst._zod.parse = (payload, _ctx) => {\n        const input = payload.value;\n        if (typeof input === \"symbol\")\n            return payload;\n        payload.issues.push({\n            expected: \"symbol\",\n            code: \"invalid_type\",\n            input,\n            inst,\n        });\n        return payload;\n    };\n});\nexport const $ZodUndefined = /*@__PURE__*/ core.$constructor(\"$ZodUndefined\", (inst, def) => {\n    $ZodType.init(inst, def);\n    inst._zod.pattern = regexes.undefined;\n    inst._zod.values = new Set([undefined]);\n    inst._zod.parse = (payload, _ctx) => {\n        const input = payload.value;\n        if (typeof input === \"undefined\")\n            return payload;\n        payload.issues.push({\n            expected: \"undefined\",\n            code: \"invalid_type\",\n            input,\n            inst,\n        });\n        return payload;\n    };\n});\nexport const $ZodNull = /*@__PURE__*/ core.$constructor(\"$ZodNull\", (inst, def) => {\n    $ZodType.init(inst, def);\n    inst._zod.pattern = regexes.null;\n    inst._zod.values = new Set([null]);\n    inst._zod.parse = (payload, _ctx) => {\n        const input = payload.value;\n        if (input === null)\n            return payload;\n        payload.issues.push({\n            expected: \"null\",\n            code: \"invalid_type\",\n            input,\n            inst,\n        });\n        return payload;\n    };\n});\nexport const $ZodAny = /*@__PURE__*/ core.$constructor(\"$ZodAny\", (inst, def) => {\n    $ZodType.init(inst, def);\n    inst._zod.parse = (payload) => payload;\n});\nexport const $ZodUnknown = /*@__PURE__*/ core.$constructor(\"$ZodUnknown\", (inst, def) => {\n    $ZodType.init(inst, def);\n    inst._zod.parse = (payload) => payload;\n});\nexport const $ZodNever = /*@__PURE__*/ core.$constructor(\"$ZodNever\", (inst, def) => {\n    $ZodType.init(inst, def);\n    inst._zod.parse = (payload, _ctx) => {\n        payload.issues.push({\n            expected: \"never\",\n            code: \"invalid_type\",\n            input: payload.value,\n            inst,\n        });\n        return payload;\n    };\n});\nexport const $ZodVoid = /*@__PURE__*/ core.$constructor(\"$ZodVoid\", (inst, def) => {\n    $ZodType.init(inst, def);\n    inst._zod.parse = (payload, _ctx) => {\n        const input = payload.value;\n        if (typeof input === \"undefined\")\n            return payload;\n        payload.issues.push({\n            expected: \"void\",\n            code: \"invalid_type\",\n            input,\n            inst,\n        });\n        return payload;\n    };\n});\nexport const $ZodDate = /*@__PURE__*/ core.$constructor(\"$ZodDate\", (inst, def) => {\n    $ZodType.init(inst, def);\n    inst._zod.parse = (payload, _ctx) => {\n        if (def.coerce) {\n            try {\n                payload.value = new Date(payload.value);\n            }\n            catch (_err) { }\n        }\n        const input = payload.value;\n        const isDate = input instanceof Date;\n        const isValidDate = isDate && !Number.isNaN(input.getTime());\n        if (isValidDate)\n            return payload;\n        payload.issues.push({\n            expected: \"date\",\n            code: \"invalid_type\",\n            input,\n            ...(isDate ? { received: \"Invalid Date\" } : {}),\n            inst,\n        });\n        return payload;\n    };\n});\n// an oversized container fails its leading size checks before any element is parsed\nfunction capSize(inst, size) {\n    const caps = util.sizeCaps(inst._zod.def.checks);\n    if (!caps.length)\n        return;\n    const cap = Math.min(...caps.map((c) => c[0]));\n    const parse = inst._zod.parse;\n    inst._zod.parse = (payload, ctx) => {\n        const n = size(payload.value);\n        if (n > cap && !ctx?.skipChecks && ctx?.direction !== \"backward\") {\n            for (const [max, ch] of util.sizeCaps(inst._zod.def.checks)) {\n                if (n > max && ch._zod.def.when(payload)) {\n                    const start = payload.issues.length;\n                    ch._zod.check(payload);\n                    // the value is still the raw input, so no later check may read it\n                    payload.issues[start].continue = false;\n                    util.attachSchema(payload.issues, start, inst);\n                    return payload;\n                }\n            }\n        }\n        return parse(payload, ctx);\n    };\n}\nconst arraySize = (input) => (Array.isArray(input) ? input.length : -1);\nconst mapSize = (input) => (input instanceof Map ? input.size : -1);\nconst setSize = (input) => (input instanceof Set ? input.size : -1);\nfunction handleArrayResult(result, final, index) {\n    if (result.issues.length) {\n        final.issues.push(...util.prefixIssues(index, result.issues));\n    }\n    final.value[index] = result.value;\n}\nexport const $ZodArray = /*@__PURE__*/ core.$constructor(\"$ZodArray\", (inst, def) => {\n    $ZodType.init(inst, def);\n    const memo = core.globalConfig.memoizer;\n    memo?.attach(inst);\n    inst._zod.parse = (payload, ctx) => {\n        const input = payload.value;\n        if (!Array.isArray(input)) {\n            payload.issues.push({\n                expected: \"array\",\n                code: \"invalid_type\",\n                input,\n                inst,\n            });\n            return payload;\n        }\n        payload.value = memo ? memo.alloc(inst, payload, Array(input.length), ctx) : Array(input.length);\n        const proms = [];\n        const abortEarly = ctx?.abortEarly;\n        for (let i = 0; i < input.length; i++) {\n            const item = input[i];\n            const result = def.element._zod.run({\n                value: item,\n                issues: [],\n            }, ctx);\n            if (result instanceof Promise) {\n                proms.push(result.then((result) => handleArrayResult(result, payload, i)));\n            }\n            else {\n                handleArrayResult(result, payload, i);\n                // the element's payload is authoritative here, since handleArrayResult forwards every issue; an object's is not, because it drops a failed absent optional\n                if (abortEarly && result.issues.length !== 0 && util.aborted(result))\n                    break;\n            }\n        }\n        if (proms.length) {\n            return Promise.all(proms).then(() => payload);\n        }\n        return payload; //handleArrayResultsAsync(parseResults, final);\n    };\n    capSize(inst, arraySize);\n});\nfunction handlePropertyResult(result, final, key, input, optin, optout) {\n    const isPresent = key in input;\n    const isOptionalOut = optout === \"optional\";\n    // 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.\n    if (!isPresent && isOptionalOut && optin === \"optional\") {\n        return;\n    }\n    if (result.issues.length) {\n        // For optional-in/out schemas, ignore errors on absent keys.\n        if (optin !== undefined && isOptionalOut && !isPresent) {\n            return;\n        }\n        final.issues.push(...util.prefixIssues(key, result.issues));\n    }\n    if (!isPresent && optin === undefined) {\n        if (!result.issues.length) {\n            final.issues.push({\n                code: \"invalid_type\",\n                expected: \"nonoptional\",\n                input: undefined,\n                path: [key],\n            });\n        }\n        return;\n    }\n    if (result.value === undefined) {\n        if (isPresent || (optin === \"defaulted\" && !isOptionalOut)) {\n            final.value[key] = undefined;\n        }\n    }\n    else {\n        final.value[key] = result.value;\n    }\n}\n// one shared instance; a fresh [] per schema cost 56 bytes retained\nconst NO_SYMBOL_KEYS = [];\nfunction normalizeDef(def) {\n    const keys = Object.keys(def.shape);\n    const ownSymbols = Object.getOwnPropertySymbols(def.shape);\n    const symbolKeys = ownSymbols.length ? ownSymbols : NO_SYMBOL_KEYS;\n    // aliases `keys` when there are no symbols, so a string-only shape keeps one array\n    const allKeys = symbolKeys.length ? [...keys, ...symbolKeys] : keys;\n    for (const k of allKeys) {\n        if (!def.shape?.[k]?._zod?.traits?.has(\"$ZodType\")) {\n            throw new Error(`Invalid element at key \"${String(k)}\": expected a Zod schema`);\n        }\n    }\n    const okeys = util.optionalKeys(def.shape);\n    return {\n        ...def,\n        allKeys,\n        symbolKeys,\n        // string-only: handleCatchall matches it against `for...in`, which never yields a symbol\n        keySet: new Set(keys),\n        numKeys: keys.length,\n        optionalKeys: new Set(okeys),\n    };\n}\nfunction handleCatchall(proms, input, payload, ctx, def, inst, abortEarly) {\n    const unrecognized = [];\n    const keySet = def.keySet;\n    const _catchall = def.catchall._zod;\n    const t = _catchall.def.type;\n    const optin = _catchall.optin;\n    const optout = _catchall.optout;\n    // starts at 0, not the current length: the shape phase already ran and may have aborted\n    let seen = 0;\n    for (const key in input) {\n        if (abortEarly && payload.issues.length !== seen) {\n            if (util.aborted(payload, seen))\n                break;\n            seen = payload.issues.length;\n        }\n        // Must precede the __proto__ branch: a declared key is not unrecognized, even though the shape loop deliberately strips __proto__ from the parsed output.\n        if (keySet.has(key))\n            continue;\n        // 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.\n        if (key === \"__proto__\") {\n            if (t === \"never\")\n                unrecognized.push(key);\n            continue;\n        }\n        if (t === \"never\") {\n            unrecognized.push(key);\n            continue;\n        }\n        const r = _catchall.run({ value: input[key], issues: [] }, ctx);\n        if (r instanceof Promise) {\n            proms.push(r.then((r) => handlePropertyResult(r, payload, key, input, optin, optout)));\n        }\n        else {\n            handlePropertyResult(r, payload, key, input, optin, optout);\n        }\n    }\n    if (unrecognized.length) {\n        payload.issues.push({\n            code: \"unrecognized_keys\",\n            keys: unrecognized,\n            input,\n            inst,\n            // 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.\n            continue: true,\n        });\n    }\n    if (!proms.length)\n        return payload;\n    return Promise.all(proms).then(() => {\n        return payload;\n    });\n}\nexport const $ZodObject = /*@__PURE__*/ core.$constructor(\"$ZodObject\", (inst, def) => {\n    // requires cast because technically $ZodObject doesn't extend\n    $ZodType.init(inst, def);\n    const desc = Object.getOwnPropertyDescriptor(def, \"shape\");\n    // a cloned def carries its source's accessor, which knows the shape it answers from; adopting that keeps the clone's keys readable without running it\n    const sh = desc?.get ? desc.get.raw : (def.shape ?? {});\n    if (sh) {\n        // Freezes the shape on first read, so its getters resolve once and every later read sees the same schemas.\n        const get = () => {\n            const newSh = { ...sh };\n            Object.defineProperty(def, \"shape\", { value: newSh });\n            get.raw = newSh;\n            return newSh;\n        };\n        get.raw = sh;\n        Object.defineProperty(def, \"shape\", { get });\n    }\n    const _normalized = util.cached(() => normalizeDef(def));\n    util.defineLazyInternal(inst, \"propValues\", (zod) => {\n        const shape = zod.def.shape;\n        const propValues = {};\n        for (const key in shape) {\n            const field = shape[key]._zod;\n            if (field.values) {\n                if (!Object.prototype.hasOwnProperty.call(propValues, key)) {\n                    util.assignProp(propValues, key, new Set());\n                }\n                for (const v of field.values)\n                    propValues[key].add(v);\n                // 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.\n                if (field.optin !== undefined)\n                    propValues[key].add(undefined);\n            }\n        }\n        return propValues;\n    });\n    const isObject = util.isObject;\n    const catchall = def.catchall;\n    let value;\n    const memo = core.globalConfig.memoizer;\n    memo?.attach(inst);\n    inst._zod.parse = (payload, ctx) => {\n        value ?? (value = _normalized.value);\n        const input = payload.value;\n        if (!isObject(input)) {\n            payload.issues.push({\n                expected: \"object\",\n                code: \"invalid_type\",\n                input,\n                inst,\n            });\n            return payload;\n        }\n        payload.value = memo ? memo.alloc(inst, payload, {}, ctx) : {};\n        const proms = [];\n        const shape = value.shape;\n        const abortEarly = ctx?.abortEarly;\n        let seen = payload.issues.length;\n        for (const key of value.allKeys) {\n            if (abortEarly && payload.issues.length !== seen) {\n                if (util.aborted(payload, seen))\n                    break;\n                seen = payload.issues.length;\n            }\n            if (key === \"__proto__\")\n                continue;\n            const el = shape[key];\n            const optin = el._zod.optin;\n            const optout = el._zod.optout;\n            const r = el._zod.run({ value: input[key], issues: [] }, ctx);\n            if (r instanceof Promise) {\n                proms.push(r.then((r) => handlePropertyResult(r, payload, key, input, optin, optout)));\n            }\n            else {\n                handlePropertyResult(r, payload, key, input, optin, optout);\n            }\n        }\n        if (!catchall) {\n            return proms.length ? Promise.all(proms).then(() => payload) : payload;\n        }\n        return handleCatchall(proms, input, payload, ctx, _normalized.value, inst, abortEarly === true);\n    };\n});\nexport const $ZodObjectJIT = /*@__PURE__*/ core.$constructor(\"$ZodObjectJIT\", (inst, def) => {\n    // requires cast because technically $ZodObject doesn't extend\n    $ZodObject.init(inst, def);\n    const superParse = inst._zod.parse;\n    const _normalized = util.cached(() => normalizeDef(def));\n    const memo = core.globalConfig.memoizer;\n    const generateFastpass = (shape) => {\n        const normalized = _normalized.value;\n        const syms = normalized.symbolKeys;\n        // a symbol has no source literal, so it is read as `syms[i]` off the closed-over scope\n        const doc = new Doc([\"payload\", \"ctx\"], { shape, inst, memo, syms });\n        const parseStr = (k) => `shape[${k}]._zod.run({ value: input[${k}], issues: [] }, ctx)`;\n        // prefixes in place, like util.prefixIssues. newResult must land before the early return: a catchall runs after this and would otherwise write onto the caller's input\n        const prefixStr = (id, k) => `\n          let ${id}_ab = false;\n          for (let i = 0; i < ${id}.issues.length; i++) {\n            const iss = ${id}.issues[i];\n            iss.path = iss.path ? [${k}, ...iss.path] : [${k}];\n            payload.issues.push(iss);\n            if (iss.continue !== true) ${id}_ab = true;\n          }\n          if (${id}_ab && ctx && ctx.abortEarly) {\n            payload.value = newResult;\n            return payload;\n          }`;\n        doc.write(`const input = payload.value;`);\n        const ids = Object.create(null);\n        let counter = 0;\n        for (const key of normalized.allKeys) {\n            ids[key] = `key_${counter++}`;\n        }\n        // A: preserve key order {\n        doc.write(memo ? `const newResult = memo.alloc(inst, payload, {}, ctx);` : `const newResult = {};`);\n        for (const key of normalized.allKeys) {\n            if (key === \"__proto__\")\n                continue;\n            const id = ids[key];\n            const k = typeof key === \"symbol\" ? `syms[${syms.indexOf(key)}]` : util.esc(key);\n            const isPresent = `${k} in input`;\n            const schema = shape[key];\n            const optin = schema?._zod?.optin;\n            const isOptionalIn = optin !== undefined;\n            const isOptionalOut = schema?._zod?.optout === \"optional\";\n            doc.write(`const ${id} = ${parseStr(k)};`);\n            if (isOptionalIn && isOptionalOut) {\n                // 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.\n                const assign = optin === \"optional\" ? `${id}_present` : `${id}.value !== undefined || ${id}_present`;\n                doc.write(`\n        const ${id}_present = ${isPresent};\n        if (!${id}.issues.length || ${id}_present) {\n          if (${id}.issues.length) {${prefixStr(id, k)}\n          }\n\n          if (${assign}) {\n            newResult[${k}] = ${id}.value;\n          }\n        }\n\n      `);\n            }\n            else if (!isOptionalIn) {\n                doc.write(`\n        const ${id}_present = ${isPresent};\n        if (${id}.issues.length) {${prefixStr(id, k)}\n        }\n        if (!${id}_present && !${id}.issues.length) {\n          payload.issues.push({\n            code: \"invalid_type\",\n            expected: \"nonoptional\",\n            input: undefined,\n            path: [${k}]\n          });\n          if (ctx && ctx.abortEarly) {\n            payload.value = newResult;\n            return payload;\n          }\n        }\n\n        if (${id}_present) {\n          newResult[${k}] = ${id}.value;\n        }\n\n      `);\n            }\n            else {\n                doc.write(`\n        if (${id}.issues.length) {${prefixStr(id, k)}\n        }\n      `);\n                if (optin === \"defaulted\") {\n                    doc.write(`newResult[${k}] = ${id}.value;`);\n                }\n                else {\n                    doc.write(`\n        if (${id}.value !== undefined || ${isPresent}) {\n          newResult[${k}] = ${id}.value;\n        }\n      `);\n                }\n            }\n        }\n        doc.write(`payload.value = newResult;`);\n        doc.write(`return payload;`);\n        // 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\n        return doc.compile();\n    };\n    let fastpass;\n    const isObject = util.isObject;\n    const jit = !core.globalConfig.jitless;\n    const allowsEval = util.allowsEval;\n    const fastEnabled = jit && allowsEval.value; // && !def.catchall;\n    const catchall = def.catchall;\n    let value;\n    inst._zod.parse = (payload, ctx) => {\n        value ?? (value = _normalized.value);\n        const input = payload.value;\n        if (!isObject(input)) {\n            payload.issues.push({\n                expected: \"object\",\n                code: \"invalid_type\",\n                input,\n                inst,\n            });\n            return payload;\n        }\n        if (jit && fastEnabled && ctx?.async === false && ctx.jitless !== true) {\n            // always synchronous\n            if (!fastpass)\n                fastpass = generateFastpass(def.shape);\n            payload = fastpass(payload, ctx);\n            if (!catchall)\n                return payload;\n            return handleCatchall([], input, payload, ctx, value, inst, ctx?.abortEarly === true);\n        }\n        return superParse(payload, ctx);\n    };\n});\nfunction handleUnionResults(results, final, inst, ctx) {\n    for (const result of results) {\n        if (result.issues.length === 0) {\n            final.value = result.value;\n            return final;\n        }\n    }\n    const nonaborted = results.filter((r) => !util.aborted(r));\n    if (nonaborted.length === 1) {\n        final.value = nonaborted[0].value;\n        return nonaborted[0];\n    }\n    final.issues.push({\n        code: \"invalid_union\",\n        input: final.value,\n        inst,\n        errors: results.map((result) => result.issues.map((iss) => util.finalizeIssue(iss, ctx, core.config()))),\n    });\n    return final;\n}\nexport const $ZodUnion = /*@__PURE__*/ core.$constructor(\"$ZodUnion\", (inst, def) => {\n    $ZodType.init(inst, def);\n    util.defineLazyInternal(inst, \"optin\", (zod) => zod.def.options.some((o) => o._zod.optin === \"defaulted\")\n        ? \"defaulted\"\n        : zod.def.options.some((o) => o._zod.optin !== undefined)\n            ? \"optional\"\n            : undefined);\n    util.defineLazyInternal(inst, \"optout\", (zod) => zod.def.options.some((o) => o._zod.optout === \"optional\") ? \"optional\" : undefined);\n    util.defineLazyInternal(inst, \"values\", (zod) => {\n        if (zod.def.options.every((o) => o._zod.values)) {\n            return new Set(zod.def.options.flatMap((option) => Array.from(option._zod.values)));\n        }\n        return undefined;\n    });\n    util.defineLazyInternal(inst, \"pattern\", (zod) => {\n        if (zod.def.options.every((o) => o._zod.pattern)) {\n            const patterns = zod.def.options.map((o) => o._zod.pattern);\n            return new RegExp(`^(${patterns.map((p) => util.cleanRegex(p.source)).join(\"|\")})$`);\n        }\n        return undefined;\n    });\n    const first = def.options.length === 1 ? def.options[0]._zod.run : null;\n    inst._zod.parse = (payload, ctx) => {\n        if (first) {\n            return first(payload, ctx);\n        }\n        let async = false;\n        const results = [];\n        for (const option of def.options) {\n            const result = option._zod.run({\n                value: payload.value,\n                issues: [],\n            }, ctx);\n            if (result instanceof Promise) {\n                results.push(result);\n                async = true;\n            }\n            else {\n                if (result.issues.length === 0)\n                    return result;\n                results.push(result);\n            }\n        }\n        if (!async)\n            return handleUnionResults(results, payload, inst, ctx);\n        return Promise.all(results).then((results) => {\n            return handleUnionResults(results, payload, inst, ctx);\n        });\n    };\n});\nfunction handleExclusiveUnionResults(results, final, inst, ctx) {\n    const matches = [];\n    for (let i = 0; i < results.length; i++) {\n        if (results[i].issues.length === 0)\n            matches.push(i);\n    }\n    if (matches.length === 1) {\n        final.value = results[matches[0]].value;\n        return final;\n    }\n    if (matches.length === 0) {\n        // No matches - same as regular union\n        final.issues.push({\n            code: \"invalid_union\",\n            input: final.value,\n            inst,\n            errors: results.map((result) => result.issues.map((iss) => util.finalizeIssue(iss, ctx, core.config()))),\n        });\n    }\n    else {\n        // Multiple matches - exclusive union failure\n        final.issues.push({\n            code: \"invalid_union\",\n            input: final.value,\n            inst,\n            errors: [],\n            inclusive: false,\n            matches,\n        });\n    }\n    return final;\n}\nexport const $ZodXor = /*@__PURE__*/ core.$constructor(\"$ZodXor\", (inst, def) => {\n    $ZodUnion.init(inst, def);\n    def.inclusive = false;\n    const first = def.options.length === 1 ? def.options[0]._zod.run : null;\n    inst._zod.parse = (payload, ctx) => {\n        if (first) {\n            return first(payload, ctx);\n        }\n        let async = false;\n        const results = [];\n        for (const option of def.options) {\n            const result = option._zod.run({\n                value: payload.value,\n                issues: [],\n            }, ctx);\n            if (result instanceof Promise) {\n                results.push(result);\n                async = true;\n            }\n            else {\n                results.push(result);\n            }\n        }\n        if (!async)\n            return handleExclusiveUnionResults(results, payload, inst, ctx);\n        return Promise.all(results).then((results) => {\n            return handleExclusiveUnionResults(results, payload, inst, ctx);\n        });\n    };\n});\n/** Returns the option whose discriminator claims `value`, or throws if ambiguous. */\nexport function getDiscriminatedOption(union, value) {\n    const internals = union._zod;\n    let map = internals.bag.optionsMap;\n    if (!map) {\n        map = discriminatorMap(internals.def);\n        internals.bag.optionsMap = map;\n    }\n    const option = map.get(value);\n    if (option === null)\n        throw new Error(`Ambiguous discriminator value \"${String(value)}\"`);\n    return option;\n}\nfunction discriminatorMap(def) {\n    const map = new Map();\n    for (const option of def.options) {\n        const values = option._zod.propValues?.[def.discriminator];\n        if (!values || values.size === 0)\n            throw new Error(`Invalid discriminated union option at index \"${def.options.indexOf(option)}\"`);\n        for (const value of values) {\n            if (map.has(value)) {\n                if (value !== undefined)\n                    throw new Error(`Duplicate discriminator value \"${String(value)}\"`);\n                // keep the collision marked so a later member cannot reclaim it\n                map.set(value, null);\n            }\n            else {\n                map.set(value, option);\n            }\n        }\n    }\n    return map;\n}\nexport const $ZodDiscriminatedUnion = \n/*@__PURE__*/\ncore.$constructor(\"$ZodDiscriminatedUnion\", (inst, def) => {\n    def.inclusive = false;\n    $ZodUnion.init(inst, def);\n    const _super = inst._zod.parse;\n    util.defineLazyInternal(inst, \"propValues\", (zod) => {\n        const propValues = {};\n        let undefinedCount = 0;\n        for (const option of zod.def.options) {\n            const pv = option._zod.propValues;\n            if (!pv || Object.keys(pv).length === 0)\n                throw new Error(`Invalid discriminated union option at index \"${zod.def.options.indexOf(option)}\"`);\n            if (pv[zod.def.discriminator]?.has(undefined))\n                undefinedCount++;\n            for (const [k, v] of Object.entries(pv)) {\n                if (!Object.prototype.hasOwnProperty.call(propValues, k)) {\n                    util.assignProp(propValues, k, new Set());\n                }\n                for (const val of v) {\n                    propValues[k].add(val);\n                }\n            }\n        }\n        if (!zod.def.unionFallback && undefinedCount > 1)\n            propValues[zod.def.discriminator]?.delete(undefined);\n        return propValues;\n    });\n    // 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 and lazies — are left to the map.\n    def.options.forEach((option, i) => {\n        const propShape = util.rawShape(option._zod.def);\n        if (propShape && !Object.prototype.hasOwnProperty.call(propShape, def.discriminator)) {\n            throw new Error(`Invalid discriminated union option at index \"${i}\"`);\n        }\n    });\n    const disc = util.cached(() => discriminatorMap(def));\n    inst._zod.parse = (payload, ctx) => {\n        const input = payload.value;\n        if (!util.isObject(input)) {\n            payload.issues.push({\n                code: \"invalid_type\",\n                expected: \"object\",\n                input,\n                inst,\n            });\n            return payload;\n        }\n        const value = input?.[def.discriminator];\n        const opt = disc.value.get(value);\n        // forward metadata cannot choose an encoder for an absent tag\n        if (opt && (value !== undefined || ctx.direction !== \"backward\")) {\n            return opt._zod.run(payload, ctx);\n        }\n        // Fall back to union matching when the fast discriminator path fails:\n        // - explicitly enabled via unionFallback, or\n        // - during backward direction (encode), since codec-based discriminators have different values in forward vs backward directions\n        if (def.unionFallback || ctx.direction === \"backward\") {\n            return _super(payload, ctx);\n        }\n        // no matching discriminator\n        payload.issues.push({\n            code: \"invalid_union\",\n            errors: [],\n            note: \"No matching discriminator\",\n            discriminator: def.discriminator,\n            options: Array.from(disc.value.keys()).filter((value) => disc.value.get(value) !== null),\n            input,\n            path: [def.discriminator],\n            inst,\n        });\n        return payload;\n    };\n});\nexport const $ZodIntersection = /*@__PURE__*/ core.$constructor(\"$ZodIntersection\", (inst, def) => {\n    $ZodType.init(inst, def);\n    inst._zod.parse = (payload, ctx) => {\n        const input = payload.value;\n        const left = def.left._zod.run({ value: input, issues: [] }, ctx);\n        const right = def.right._zod.run({ value: input, issues: [] }, ctx);\n        const async = left instanceof Promise || right instanceof Promise;\n        if (async) {\n            return Promise.all([left, right]).then(([left, right]) => {\n                return handleIntersectionResults(payload, left, right);\n            });\n        }\n        return handleIntersectionResults(payload, left, right);\n    };\n});\nexport function mergeValues(a, b) {\n    // const aType = parse.t(a);\n    // const bType = parse.t(b);\n    if (a === b) {\n        return { valid: true, data: a };\n    }\n    if (a instanceof Date && b instanceof Date && +a === +b) {\n        return { valid: true, data: a };\n    }\n    if (util.isPlainObject(a) && util.isPlainObject(b)) {\n        const bKeys = Object.keys(b);\n        const sharedKeys = Object.keys(a).filter((key) => bKeys.indexOf(key) !== -1);\n        const newObj = { ...a, ...b };\n        if (Object.prototype.hasOwnProperty.call(newObj, \"__proto__\"))\n            delete newObj.__proto__;\n        for (const key of sharedKeys) {\n            if (key === \"__proto__\")\n                continue;\n            const sharedValue = mergeValues(a[key], b[key]);\n            if (!sharedValue.valid) {\n                return {\n                    valid: false,\n                    mergeErrorPath: [key, ...sharedValue.mergeErrorPath],\n                };\n            }\n            newObj[key] = sharedValue.data;\n        }\n        return { valid: true, data: newObj };\n    }\n    if (Array.isArray(a) && Array.isArray(b)) {\n        if (a.length !== b.length) {\n            return { valid: false, mergeErrorPath: [] };\n        }\n        const newArray = [];\n        for (let index = 0; index < a.length; index++) {\n            const itemA = a[index];\n            const itemB = b[index];\n            const sharedValue = mergeValues(itemA, itemB);\n            if (!sharedValue.valid) {\n                return {\n                    valid: false,\n                    mergeErrorPath: [index, ...sharedValue.mergeErrorPath],\n                };\n            }\n            newArray.push(sharedValue.data);\n        }\n        return { valid: true, data: newArray };\n    }\n    return { valid: false, mergeErrorPath: [] };\n}\nfunction handleIntersectionResults(result, left, right) {\n    // 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.\n    const unrecKeys = new Map();\n    let unrecIssue;\n    const keyIssues = new Map();\n    const collect = (iss, side) => {\n        let keys;\n        if (iss.code === \"unrecognized_keys\" && !iss.path?.length) {\n            unrecIssue ?? (unrecIssue = iss);\n            keys = iss.keys;\n        }\n        else if (iss.code === \"invalid_key\" && iss.origin === \"record\" && iss.path?.length === 1) {\n            const k = String(iss.path[0]);\n            if (!keyIssues.has(k))\n                keyIssues.set(k, iss);\n            keys = [k];\n        }\n        else {\n            return false;\n        }\n        for (const k of keys) {\n            if (!unrecKeys.has(k))\n                unrecKeys.set(k, {});\n            unrecKeys.get(k)[side] = true;\n        }\n        return true;\n    };\n    for (const iss of left.issues) {\n        if (!collect(iss, \"l\"))\n            result.issues.push(iss);\n    }\n    for (const iss of right.issues) {\n        if (!collect(iss, \"r\"))\n            result.issues.push(iss);\n    }\n    // Report only keys rejected by BOTH sides\n    const bothKeys = [...unrecKeys].filter(([, f]) => f.l && f.r).map(([k]) => k);\n    if (bothKeys.length) {\n        const aggregated = unrecIssue ? bothKeys.filter((k) => unrecIssue.keys.includes(k)) : [];\n        if (aggregated.length)\n            result.issues.push({ ...unrecIssue, keys: aggregated });\n        for (const k of bothKeys) {\n            if (!aggregated.includes(k) && keyIssues.has(k))\n                result.issues.push(keyIssues.get(k));\n        }\n    }\n    const merged = mergeValues(left.value, right.value);\n    if (!merged.valid) {\n        if (util.aborted(result))\n            return result;\n        throw new Error(`Unmergable intersection. Error path: ` + `${JSON.stringify(merged.mergeErrorPath)}`);\n    }\n    result.value = merged.data;\n    return result;\n}\nexport const $ZodTuple = /*@__PURE__*/ core.$constructor(\"$ZodTuple\", (inst, def) => {\n    $ZodType.init(inst, def);\n    const items = def.items;\n    const memo = core.globalConfig.memoizer;\n    memo?.attach(inst);\n    inst._zod.parse = (payload, ctx) => {\n        const input = payload.value;\n        if (!Array.isArray(input)) {\n            payload.issues.push({\n                input,\n                inst,\n                expected: \"tuple\",\n                code: \"invalid_type\",\n            });\n            return payload;\n        }\n        payload.value = memo ? memo.alloc(inst, payload, [], ctx) : [];\n        const proms = [];\n        const optinStart = getTupleOptStart(items, \"optin\");\n        const optoutStart = getTupleOptStart(items, \"optout\");\n        if (!def.rest) {\n            if (input.length < optinStart) {\n                payload.issues.push({\n                    code: \"too_small\",\n                    minimum: optinStart,\n                    inclusive: true,\n                    input,\n                    inst,\n                    origin: \"array\",\n                });\n                return payload;\n            }\n            if (input.length > items.length) {\n                payload.issues.push({\n                    code: \"too_big\",\n                    maximum: items.length,\n                    inclusive: true,\n                    input,\n                    inst,\n                    origin: \"array\",\n                });\n            }\n        }\n        // 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.\n        const itemResults = new Array(items.length);\n        // only tracked when there is a rest loop to skip\n        const abortEarly = def.rest ? ctx?.abortEarly : undefined;\n        let itemAborted = false;\n        for (let i = 0; i < items.length; i++) {\n            const r = items[i]._zod.run({ value: input[i], issues: [] }, ctx);\n            if (r instanceof Promise) {\n                proms.push(r.then((rr) => {\n                    itemResults[i] = rr;\n                }));\n            }\n            else {\n                itemResults[i] = r;\n                if (abortEarly && !itemAborted && r.issues.length)\n                    itemAborted = util.aborted(r);\n            }\n        }\n        // sound because rest is non-empty exactly when every fixed index is present, the one case handleTupleResults cannot discard an item's issues\n        if (def.rest && !itemAborted) {\n            let i = items.length - 1;\n            const rest = input.slice(items.length);\n            let seen = payload.issues.length;\n            for (const el of rest) {\n                if (abortEarly && payload.issues.length !== seen) {\n                    if (util.aborted(payload, seen))\n                        break;\n                    seen = payload.issues.length;\n                }\n                i++;\n                const result = def.rest._zod.run({ value: el, issues: [] }, ctx);\n                if (result instanceof Promise) {\n                    proms.push(result.then((r) => handleTupleResult(r, payload, i)));\n                }\n                else {\n                    handleTupleResult(result, payload, i);\n                }\n            }\n        }\n        if (proms.length) {\n            return Promise.all(proms).then(() => handleTupleResults(itemResults, payload, items, input, optoutStart));\n        }\n        return handleTupleResults(itemResults, payload, items, input, optoutStart);\n    };\n});\nfunction getTupleOptStart(items, key) {\n    for (let i = items.length - 1; i >= 0; i--) {\n        // optin is a three-rung ladder so any rung above `undefined` permits an absent slot; optout stays two-valued.\n        const omittable = key === \"optin\" ? items[i]._zod.optin !== undefined : items[i]._zod.optout === \"optional\";\n        if (!omittable)\n            return i + 1;\n    }\n    return 0;\n}\nfunction handleTupleResult(result, final, index) {\n    if (result.issues.length) {\n        final.issues.push(...util.prefixIssues(index, result.issues));\n    }\n    final.value[index] = result.value;\n}\nfunction handleTupleResults(itemResults, final, items, input, optoutStart) {\n    // 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.\n    for (let i = 0; i < items.length; i++) {\n        const r = itemResults[i];\n        const isPresent = i < input.length;\n        // 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`.\n        if (!isPresent && i >= optoutStart && items[i]._zod.optin === \"optional\") {\n            final.value.length = i;\n            break;\n        }\n        if (r.issues.length) {\n            if (!isPresent && i >= optoutStart) {\n                final.value.length = i;\n                break;\n            }\n            final.issues.push(...util.prefixIssues(i, r.issues));\n        }\n        final.value[i] = r.value;\n    }\n    // Drop trailing slots that produced `undefined` for absent input\n    // (the array analog of an absent optional key on an object). The\n    // `i >= input.length` floor is critical: an explicit `undefined`\n    // *inside* the input must be preserved even when the schema is\n    // optional-out (e.g. `z.string().or(z.undefined())` accepting an\n    // explicit undefined value).\n    for (let i = final.value.length - 1; i >= input.length; i--) {\n        if (items[i]._zod.optout === \"optional\" && final.value[i] === undefined) {\n            final.value.length = i;\n        }\n        else {\n            break;\n        }\n    }\n    return final;\n}\nexport const $ZodRecord = /*@__PURE__*/ core.$constructor(\"$ZodRecord\", (inst, def) => {\n    $ZodType.init(inst, def);\n    const memo = core.globalConfig.memoizer;\n    memo?.attach(inst);\n    inst._zod.parse = (payload, ctx) => {\n        const input = payload.value;\n        if (!util.isPlainObject(input)) {\n            payload.issues.push({\n                expected: \"record\",\n                code: \"invalid_type\",\n                input,\n                inst,\n            });\n            return payload;\n        }\n        // no guard in either loop below: a record's invalid_key aborts but an enclosing intersection can reconcile it, so a stopped loop hides keys the sibling does not own and the intersection then rejects nothing\n        const proms = [];\n        const values = def.keyType._zod.values;\n        if (values && !def.partial) {\n            payload.value = memo ? memo.alloc(inst, payload, {}, ctx) : {};\n            const recordKeys = new Set();\n            for (const key of values) {\n                if (typeof key === \"string\" || typeof key === \"number\" || typeof key === \"symbol\") {\n                    recordKeys.add(typeof key === \"number\" ? key.toString() : key);\n                    // A declared __proto__ is stripped but is not an unrecognized key.\n                    if (key === \"__proto__\")\n                        continue;\n                    const keyResult = def.keyType._zod.run({ value: key, issues: [] }, ctx);\n                    if (keyResult instanceof Promise) {\n                        throw new Error(\"Async schemas not supported in object keys currently\");\n                    }\n                    if (keyResult.issues.length) {\n                        payload.issues.push({\n                            code: \"invalid_key\",\n                            origin: \"record\",\n                            issues: keyResult.issues.map((iss) => util.finalizeIssue(iss, ctx, core.config())),\n                            input: key,\n                            path: [key],\n                            inst,\n                        });\n                        continue;\n                    }\n                    const outKey = keyResult.value;\n                    if (outKey === \"__proto__\")\n                        continue;\n                    const result = def.valueType._zod.run({ value: input[key], issues: [] }, ctx);\n                    if (result instanceof Promise) {\n                        proms.push(result.then((result) => {\n                            if (result.issues.length) {\n                                payload.issues.push(...util.prefixIssues(key, result.issues));\n                            }\n                            payload.value[outKey] = result.value;\n                        }));\n                    }\n                    else {\n                        if (result.issues.length) {\n                            payload.issues.push(...util.prefixIssues(key, result.issues));\n                        }\n                        payload.value[outKey] = result.value;\n                    }\n                }\n            }\n            let unrecognized;\n            for (const key in input) {\n                if (!recordKeys.has(key)) {\n                    if (def.mode === \"loose\") {\n                        // skip __proto__ so it can't replace the result prototype via the assignment setter on the plain {} we build into\n                        if (key === \"__proto__\")\n                            continue;\n                        payload.value[key] = input[key];\n                    }\n                    else {\n                        unrecognized = unrecognized ?? [];\n                        unrecognized.push(key);\n                    }\n                }\n            }\n            if (unrecognized && unrecognized.length > 0) {\n                payload.issues.push({\n                    code: \"unrecognized_keys\",\n                    input,\n                    inst,\n                    keys: unrecognized,\n                    continue: true,\n                });\n            }\n        }\n        else {\n            payload.value = memo ? memo.alloc(inst, payload, {}, ctx) : {};\n            // 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.\n            let unrecognized;\n            // Reflect.ownKeys for Symbol-key support; filter non-enumerable to match z.object()\n            for (const key of Reflect.ownKeys(input)) {\n                if (key === \"__proto__\")\n                    continue;\n                if (!Object.prototype.propertyIsEnumerable.call(input, key))\n                    continue;\n                let keyResult = def.keyType._zod.run({ value: key, issues: [] }, ctx);\n                if (keyResult instanceof Promise) {\n                    throw new Error(\"Async schemas not supported in object keys currently\");\n                }\n                // 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\n                const checkNumericKey = typeof key === \"string\" && regexes.number.test(key) && keyResult.issues.length;\n                if (checkNumericKey) {\n                    const retryResult = def.keyType._zod.run({ value: Number(key), issues: [] }, ctx);\n                    if (retryResult instanceof Promise) {\n                        throw new Error(\"Async schemas not supported in object keys currently\");\n                    }\n                    if (retryResult.issues.length === 0) {\n                        keyResult = retryResult;\n                    }\n                }\n                if (keyResult.issues.length) {\n                    if (def.mode === \"loose\") {\n                        // Pass through unchanged\n                        payload.value[key] = input[key];\n                    }\n                    else if (values) {\n                        unrecognized = unrecognized ?? [];\n                        unrecognized.push(key);\n                    }\n                    else {\n                        // Default \"strict\" behavior: error on invalid key\n                        payload.issues.push({\n                            code: \"invalid_key\",\n                            origin: \"record\",\n                            issues: keyResult.issues.map((iss) => util.finalizeIssue(iss, ctx, core.config())),\n                            input: key,\n                            path: [key],\n                            inst,\n                        });\n                    }\n                    continue;\n                }\n                // 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\n                const outKey = keyResult.value;\n                if (outKey === \"__proto__\")\n                    continue;\n                const result = def.valueType._zod.run({ value: input[key], issues: [] }, ctx);\n                if (result instanceof Promise) {\n                    proms.push(result.then((result) => {\n                        if (result.issues.length) {\n                            payload.issues.push(...util.prefixIssues(key, result.issues));\n                        }\n                        payload.value[outKey] = result.value;\n                    }));\n                }\n                else {\n                    if (result.issues.length) {\n                        payload.issues.push(...util.prefixIssues(key, result.issues));\n                    }\n                    payload.value[outKey] = result.value;\n                }\n            }\n            if (unrecognized && unrecognized.length > 0) {\n                payload.issues.push({\n                    code: \"unrecognized_keys\",\n                    input,\n                    inst,\n                    keys: unrecognized,\n                    continue: true,\n                });\n            }\n        }\n        if (proms.length) {\n            return Promise.all(proms).then(() => payload);\n        }\n        return payload;\n    };\n});\nexport const $ZodMap = /*@__PURE__*/ core.$constructor(\"$ZodMap\", (inst, def) => {\n    $ZodType.init(inst, def);\n    const memo = core.globalConfig.memoizer;\n    memo?.attach(inst);\n    inst._zod.parse = (payload, ctx) => {\n        const input = payload.value;\n        if (!(input instanceof Map)) {\n            payload.issues.push({\n                expected: \"map\",\n                code: \"invalid_type\",\n                input,\n                inst,\n            });\n            return payload;\n        }\n        const proms = [];\n        payload.value = memo ? memo.alloc(inst, payload, new Map(), ctx) : new Map();\n        const abortEarly = ctx?.abortEarly;\n        let seen = payload.issues.length;\n        for (const [key, value] of input) {\n            if (abortEarly && payload.issues.length !== seen) {\n                if (util.aborted(payload, seen))\n                    break;\n                seen = payload.issues.length;\n            }\n            const keyResult = def.keyType._zod.run({ value: key, issues: [] }, ctx);\n            const valueResult = def.valueType._zod.run({ value: value, issues: [] }, ctx);\n            if (keyResult instanceof Promise || valueResult instanceof Promise) {\n                proms.push(Promise.all([keyResult, valueResult]).then(([keyResult, valueResult]) => {\n                    handleMapResult(keyResult, valueResult, payload, key, input, inst, ctx);\n                }));\n            }\n            else {\n                handleMapResult(keyResult, valueResult, payload, key, input, inst, ctx);\n            }\n        }\n        if (proms.length)\n            return Promise.all(proms).then(() => payload);\n        return payload;\n    };\n    capSize(inst, mapSize);\n});\nfunction handleMapResult(keyResult, valueResult, final, key, input, inst, ctx) {\n    if (keyResult.issues.length) {\n        if (util.propertyKeyTypes.has(typeof key)) {\n            final.issues.push(...util.prefixIssues(key, keyResult.issues));\n        }\n        else {\n            final.issues.push({\n                code: \"invalid_key\",\n                origin: \"map\",\n                input,\n                inst,\n                issues: keyResult.issues.map((iss) => util.finalizeIssue(iss, ctx, core.config())),\n            });\n        }\n    }\n    if (valueResult.issues.length) {\n        if (util.propertyKeyTypes.has(typeof key)) {\n            final.issues.push(...util.prefixIssues(key, valueResult.issues));\n        }\n        else {\n            final.issues.push({\n                origin: \"map\",\n                code: \"invalid_element\",\n                input,\n                inst,\n                key: key,\n                issues: valueResult.issues.map((iss) => util.finalizeIssue(iss, ctx, core.config())),\n            });\n        }\n    }\n    final.value.set(keyResult.value, valueResult.value);\n}\nexport const $ZodSet = /*@__PURE__*/ core.$constructor(\"$ZodSet\", (inst, def) => {\n    $ZodType.init(inst, def);\n    const memo = core.globalConfig.memoizer;\n    memo?.attach(inst);\n    inst._zod.parse = (payload, ctx) => {\n        const input = payload.value;\n        if (!(input instanceof Set)) {\n            payload.issues.push({\n                input,\n                inst,\n                expected: \"set\",\n                code: \"invalid_type\",\n            });\n            return payload;\n        }\n        const proms = [];\n        payload.value = memo ? memo.alloc(inst, payload, new Set(), ctx) : new Set();\n        const abortEarly = ctx?.abortEarly;\n        let seen = payload.issues.length;\n        for (const item of input) {\n            if (abortEarly && payload.issues.length !== seen) {\n                if (util.aborted(payload, seen))\n                    break;\n                seen = payload.issues.length;\n            }\n            const result = def.valueType._zod.run({ value: item, issues: [] }, ctx);\n            if (result instanceof Promise) {\n                proms.push(result.then((result) => handleSetResult(result, payload)));\n            }\n            else\n                handleSetResult(result, payload);\n        }\n        if (proms.length)\n            return Promise.all(proms).then(() => payload);\n        return payload;\n    };\n    capSize(inst, setSize);\n});\nfunction handleSetResult(result, final) {\n    if (result.issues.length) {\n        final.issues.push(...result.issues);\n    }\n    final.value.add(result.value);\n}\nexport const $ZodEnum = /*@__PURE__*/ core.$constructor(\"$ZodEnum\", (inst, def) => {\n    $ZodType.init(inst, def);\n    const values = util.getEnumValues(def.entries);\n    const valuesSet = new Set(values);\n    inst._zod.values = valuesSet;\n    util.defineLazyInternal(inst, \"pattern\", (zod) => {\n        const patternValues = util.getEnumValues(zod.def.entries).filter((k) => util.propertyKeyTypes.has(typeof k));\n        // unmatchable fallback, RE2-safe: an empty alternation would compile to /^()$/, which matches \"\"\n        return new RegExp(patternValues.length ? `^(${patternValues.map((o) => util.escapeRegex(o.toString())).join(\"|\")})$` : \"^[^\\\\s\\\\S]$\");\n    });\n    inst._zod.parse = (payload, _ctx) => {\n        const input = payload.value;\n        if (valuesSet.has(input)) {\n            return payload;\n        }\n        payload.issues.push({\n            code: \"invalid_value\",\n            values,\n            input,\n            inst,\n        });\n        return payload;\n    };\n});\nexport const $ZodLiteral = /*@__PURE__*/ core.$constructor(\"$ZodLiteral\", (inst, def) => {\n    $ZodType.init(inst, def);\n    const values = new Set(def.values);\n    inst._zod.values = values;\n    util.defineLazyInternal(inst, \"pattern\", (zod) => {\n        const vals = zod.def.values;\n        // unmatchable fallback, RE2-safe: an empty alternation would compile to /^()$/, which matches \"\"\n        return new RegExp(vals.length\n            ? `^(${vals\n                .map((o) => typeof o === \"string\" ? util.escapeRegex(o) : o ? util.escapeRegex(o.toString()) : String(o))\n                .join(\"|\")})$`\n            : \"^[^\\\\s\\\\S]$\");\n    });\n    inst._zod.parse = (payload, _ctx) => {\n        const input = payload.value;\n        if (values.has(input)) {\n            return payload;\n        }\n        payload.issues.push({\n            code: \"invalid_value\",\n            values: def.values,\n            input,\n            inst,\n        });\n        return payload;\n    };\n});\nexport const $ZodFile = /*@__PURE__*/ core.$constructor(\"$ZodFile\", (inst, def) => {\n    $ZodType.init(inst, def);\n    inst._zod.parse = (payload, _ctx) => {\n        const input = payload.value;\n        // @ts-ignore\n        if (input instanceof File)\n            return payload;\n        payload.issues.push({\n            expected: \"file\",\n            code: \"invalid_type\",\n            input,\n            inst,\n        });\n        return payload;\n    };\n});\nexport const $ZodTransform = /*@__PURE__*/ core.$constructor(\"$ZodTransform\", (inst, def) => {\n    $ZodType.init(inst, def);\n    inst._zod.optin = \"optional\";\n    core.globalConfig.memoizer?.guard(inst);\n    inst._zod.parse = (payload, ctx) => {\n        if (ctx.direction === \"backward\") {\n            throw new core.$ZodEncodeError(inst.constructor.name);\n        }\n        const _out = def.transform(payload.value, payload);\n        if (ctx.async) {\n            const output = _out instanceof Promise ? _out : Promise.resolve(_out);\n            return output.then((output) => {\n                payload.value = output;\n                return payload;\n            });\n        }\n        if (_out instanceof Promise) {\n            throw new core.$ZodAsyncError();\n        }\n        payload.value = _out;\n        return payload;\n    };\n});\nfunction handleOptionalResult(payload, result) {\n    // 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.\n    payload.value = result.issues.length ? undefined : result.value;\n    return payload;\n}\nexport const $ZodOptional = /*@__PURE__*/ core.$constructor(\"$ZodOptional\", (inst, def) => {\n    $ZodType.init(inst, def);\n    // .optional() propagates absence rather than substituting for it, so a defaulted inner keeps its rung.\n    util.defineLazyInternal(inst, \"optin\", (zod) => zod.def.innerType._zod.optin === \"defaulted\" ? \"defaulted\" : \"optional\");\n    inst._zod.optout = \"optional\";\n    util.defineLazyInternal(inst, \"values\", (zod) => {\n        const values = zod.def.innerType._zod.values;\n        return values ? new Set([...values, undefined]) : undefined;\n    });\n    util.defineLazyInternal(inst, \"pattern\", (zod) => {\n        const pattern = zod.def.innerType._zod.pattern;\n        return pattern ? new RegExp(`^(${util.cleanRegex(pattern.source)})?$`) : undefined;\n    });\n    inst._zod.parse = (payload, ctx) => {\n        if (payload.value === undefined) {\n            // Only the top rung substitutes a value for absence; everything else leaves it intact, which is what .optional() means.\n            if (def.innerType._zod.optin !== \"defaulted\")\n                return payload;\n            // 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.\n            const result = def.innerType._zod.run({ value: payload.value, issues: [] }, ctx);\n            if (result instanceof Promise)\n                return result.then((result) => handleOptionalResult(payload, result));\n            return handleOptionalResult(payload, result);\n        }\n        return def.innerType._zod.run(payload, ctx);\n    };\n});\nexport const $ZodExactOptional = /*@__PURE__*/ core.$constructor(\"$ZodExactOptional\", (inst, def) => {\n    // Call parent init - inherits optin/optout = \"optional\"\n    $ZodOptional.init(inst, def);\n    // Override values/pattern to NOT add undefined\n    util.defineLazyInternal(inst, \"values\", (zod) => zod.def.innerType._zod.values);\n    util.defineLazyInternal(inst, \"pattern\", (zod) => zod.def.innerType._zod.pattern);\n    // Override parse to just delegate (no undefined handling)\n    inst._zod.parse = (payload, ctx) => {\n        return def.innerType._zod.run(payload, ctx);\n    };\n});\nexport const $ZodNullable = /*@__PURE__*/ core.$constructor(\"$ZodNullable\", (inst, def) => {\n    $ZodType.init(inst, def);\n    util.defineLazyInternal(inst, \"optin\", (zod) => zod.def.innerType._zod.optin);\n    util.defineLazyInternal(inst, \"optout\", (zod) => zod.def.innerType._zod.optout);\n    util.defineLazyInternal(inst, \"pattern\", (zod) => {\n        const pattern = zod.def.innerType._zod.pattern;\n        return pattern ? new RegExp(`^(${util.cleanRegex(pattern.source)}|null)$`) : undefined;\n    });\n    util.defineLazyInternal(inst, \"values\", (zod) => {\n        return zod.def.innerType._zod.values ? new Set([...zod.def.innerType._zod.values, null]) : undefined;\n    });\n    inst._zod.parse = (payload, ctx) => {\n        // Forward direction (decode): allow null to pass through\n        if (payload.value === null)\n            return payload;\n        return def.innerType._zod.run(payload, ctx);\n    };\n});\nexport const $ZodDefault = /*@__PURE__*/ core.$constructor(\"$ZodDefault\", (inst, def) => {\n    $ZodType.init(inst, def);\n    // inst._zod.qin = \"true\";\n    inst._zod.optin = \"defaulted\";\n    util.defineLazyInternal(inst, \"values\", (zod) => zod.def.innerType._zod.values);\n    inst._zod.parse = (payload, ctx) => {\n        if (ctx.direction === \"backward\") {\n            return def.innerType._zod.run(payload, ctx);\n        }\n        // Forward direction (decode): apply defaults for undefined input\n        if (payload.value === undefined) {\n            payload.value = def.defaultValue;\n            /**\n             * $ZodDefault returns the default value immediately in forward direction.\n             * 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.   */\n            return payload;\n        }\n        // Forward direction: continue with default handling\n        const result = def.innerType._zod.run(payload, ctx);\n        if (result instanceof Promise) {\n            return result.then((result) => handleDefaultResult(result, def));\n        }\n        return handleDefaultResult(result, def);\n    };\n});\nfunction handleDefaultResult(payload, def) {\n    if (payload.value === undefined) {\n        payload.value = def.defaultValue;\n    }\n    return payload;\n}\nexport const $ZodPrefault = /*@__PURE__*/ core.$constructor(\"$ZodPrefault\", (inst, def) => {\n    $ZodType.init(inst, def);\n    inst._zod.optin = \"defaulted\";\n    util.defineLazyInternal(inst, \"values\", (zod) => zod.def.innerType._zod.values);\n    inst._zod.parse = (payload, ctx) => {\n        if (ctx.direction === \"backward\") {\n            return def.innerType._zod.run(payload, ctx);\n        }\n        // Forward direction (decode): apply prefault for undefined input\n        if (payload.value === undefined) {\n            payload.value = def.defaultValue;\n        }\n        return def.innerType._zod.run(payload, ctx);\n    };\n});\nexport const $ZodNonOptional = /*@__PURE__*/ core.$constructor(\"$ZodNonOptional\", (inst, def) => {\n    $ZodType.init(inst, def);\n    util.defineLazyInternal(inst, \"values\", (zod) => {\n        const v = zod.def.innerType._zod.values;\n        return v ? new Set([...v].filter((x) => x !== undefined)) : undefined;\n    });\n    inst._zod.parse = (payload, ctx) => {\n        const result = def.innerType._zod.run(payload, ctx);\n        if (result instanceof Promise) {\n            return result.then((result) => handleNonOptionalResult(result, inst));\n        }\n        return handleNonOptionalResult(result, inst);\n    };\n});\nfunction handleNonOptionalResult(payload, inst) {\n    if (!payload.issues.length && payload.value === undefined) {\n        payload.issues.push({\n            code: \"invalid_type\",\n            expected: \"nonoptional\",\n            input: payload.value,\n            inst,\n        });\n    }\n    return payload;\n}\nexport const $ZodSuccess = /*@__PURE__*/ core.$constructor(\"$ZodSuccess\", (inst, def) => {\n    $ZodType.init(inst, def);\n    inst._zod.parse = (payload, ctx) => {\n        if (ctx.direction === \"backward\") {\n            throw new core.$ZodEncodeError(\"ZodSuccess\");\n        }\n        const result = def.innerType._zod.run(payload, ctx);\n        if (result instanceof Promise) {\n            return result.then((result) => {\n                payload.value = result.issues.length === 0;\n                return payload;\n            });\n        }\n        payload.value = result.issues.length === 0;\n        return payload;\n    };\n});\nfunction handleCatchResult(payload, result, def, ctx) {\n    if (!result.issues.length) {\n        payload.value = result.value;\n        // 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.\n        if (result.memo)\n            payload.memo = true;\n        return payload;\n    }\n    // 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.\n    payload.value = def.catchValue({\n        ...result,\n        value: payload.value,\n        error: {\n            issues: result.issues.map((iss) => util.finalizeIssue(iss, ctx, core.config())),\n        },\n        input: payload.value,\n    });\n    return payload;\n}\nexport const $ZodCatch = /*@__PURE__*/ core.$constructor(\"$ZodCatch\", (inst, def) => {\n    $ZodType.init(inst, def);\n    util.defineLazyInternal(inst, \"optin\", (zod) => zod.def.innerType._zod.optin === \"defaulted\" ? \"defaulted\" : \"optional\");\n    util.defineLazyInternal(inst, \"optout\", (zod) => zod.def.innerType._zod.optout);\n    util.defineLazyInternal(inst, \"values\", (zod) => zod.def.innerType._zod.values);\n    inst._zod.parse = (payload, ctx) => {\n        if (ctx.direction === \"backward\") {\n            return def.innerType._zod.run(payload, ctx);\n        }\n        // Forward direction (decode): apply catch logic\n        const result = def.innerType._zod.run({ value: payload.value, issues: [] }, ctx);\n        if (result instanceof Promise) {\n            return result.then((result) => handleCatchResult(payload, result, def, ctx));\n        }\n        return handleCatchResult(payload, result, def, ctx);\n    };\n});\nexport const $ZodNaN = /*@__PURE__*/ core.$constructor(\"$ZodNaN\", (inst, def) => {\n    $ZodType.init(inst, def);\n    inst._zod.parse = (payload, _ctx) => {\n        if (typeof payload.value !== \"number\" || !Number.isNaN(payload.value)) {\n            payload.issues.push({\n                input: payload.value,\n                inst,\n                expected: \"nan\",\n                code: \"invalid_type\",\n            });\n            return payload;\n        }\n        return payload;\n    };\n});\nexport const $ZodPipe = /*@__PURE__*/ core.$constructor(\"$ZodPipe\", (inst, def) => {\n    $ZodType.init(inst, def);\n    util.defineLazyInternal(inst, \"values\", (zod) => zod.def.in._zod.values);\n    util.defineLazyInternal(inst, \"optin\", (zod) => zod.def.in._zod.optin);\n    util.defineLazyInternal(inst, \"optout\", (zod) => zod.def.out._zod.optout);\n    util.defineLazyInternal(inst, \"propValues\", (zod) => zod.def.in._zod.propValues);\n    inst._zod.parse = (payload, ctx) => {\n        if (ctx.direction === \"backward\") {\n            const right = def.out._zod.run(payload, ctx);\n            if (right instanceof Promise) {\n                return right.then((right) => handlePipeResult(right, def.in, ctx));\n            }\n            return handlePipeResult(right, def.in, ctx);\n        }\n        const left = def.in._zod.run(payload, ctx);\n        if (left instanceof Promise) {\n            return left.then((left) => handlePipeResult(left, def.out, ctx));\n        }\n        return handlePipeResult(left, def.out, ctx);\n    };\n});\nfunction handlePipeResult(left, next, ctx) {\n    // 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.\n    if (left.issues.some((iss) => iss.code !== \"unrecognized_keys\")) {\n        // prevent further checks\n        left.aborted = true;\n        return left;\n    }\n    return next._zod.run({ value: left.value, issues: left.issues }, ctx);\n}\nexport const $ZodCodec = /*@__PURE__*/ core.$constructor(\"$ZodCodec\", (inst, def) => {\n    $ZodType.init(inst, def);\n    util.defineLazyInternal(inst, \"values\", (zod) => zod.def.in._zod.values);\n    util.defineLazyInternal(inst, \"optin\", (zod) => zod.def.in._zod.optin);\n    util.defineLazyInternal(inst, \"optout\", (zod) => zod.def.out._zod.optout);\n    util.defineLazyInternal(inst, \"propValues\", (zod) => zod.def.in._zod.propValues);\n    inst._zod.parse = (payload, ctx) => {\n        const direction = ctx.direction || \"forward\";\n        if (direction === \"forward\") {\n            const left = def.in._zod.run(payload, ctx);\n            if (left instanceof Promise) {\n                return left.then((left) => handleCodecAResult(left, def, ctx));\n            }\n            return handleCodecAResult(left, def, ctx);\n        }\n        else {\n            const right = def.out._zod.run(payload, ctx);\n            if (right instanceof Promise) {\n                return right.then((right) => handleCodecAResult(right, def, ctx));\n            }\n            return handleCodecAResult(right, def, ctx);\n        }\n    };\n});\nfunction handleCodecAResult(result, def, ctx) {\n    if (result.issues.length) {\n        // prevent further checks\n        result.aborted = true;\n        return result;\n    }\n    const direction = ctx.direction || \"forward\";\n    if (direction === \"forward\") {\n        const transformed = def.transform(result.value, result);\n        if (transformed instanceof Promise) {\n            return transformed.then((value) => handleCodecTxResult(result, value, def.out, ctx));\n        }\n        return handleCodecTxResult(result, transformed, def.out, ctx);\n    }\n    else {\n        const transformed = def.reverseTransform(result.value, result);\n        if (transformed instanceof Promise) {\n            return transformed.then((value) => handleCodecTxResult(result, value, def.in, ctx));\n        }\n        return handleCodecTxResult(result, transformed, def.in, ctx);\n    }\n}\nfunction handleCodecTxResult(left, value, nextSchema, ctx) {\n    // Check if transform added any issues\n    if (left.issues.length) {\n        left.aborted = true;\n        return left;\n    }\n    return nextSchema._zod.run({ value, issues: left.issues }, ctx);\n}\nexport const $ZodPreprocess = /*@__PURE__*/ core.$constructor(\"$ZodPreprocess\", (inst, def) => {\n    $ZodPipe.init(inst, def);\n});\nexport const $ZodReadonly = /*@__PURE__*/ core.$constructor(\"$ZodReadonly\", (inst, def) => {\n    $ZodType.init(inst, def);\n    util.defineLazyInternal(inst, \"propValues\", (zod) => zod.def.innerType._zod.propValues);\n    util.defineLazyInternal(inst, \"values\", (zod) => zod.def.innerType._zod.values);\n    util.defineLazyInternal(inst, \"optin\", (zod) => zod.def.innerType?._zod?.optin);\n    util.defineLazyInternal(inst, \"optout\", (zod) => zod.def.innerType?._zod?.optout);\n    inst._zod.parse = (payload, ctx) => {\n        if (ctx.direction === \"backward\") {\n            return def.innerType._zod.run(payload, ctx);\n        }\n        const result = def.innerType._zod.run(payload, ctx);\n        if (result instanceof Promise) {\n            return result.then(handleReadonlyResult);\n        }\n        return handleReadonlyResult(result);\n    };\n});\nfunction handleReadonlyResult(payload) {\n    // 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.\n    if (!payload.memo)\n        payload.value = Object.freeze(payload.value);\n    return payload;\n}\n// a leaf's pattern source with its own checks folded in: the last pattern-carrying check wins, else length bounds narrow the catch-all, else an integer format narrows the number form. the fold lives here instead of on `_zod.pattern` so a bundle without template literals never pays for it\nfunction leafPattern(schema) {\n    const def = schema._zod.def;\n    let pattern = def.pattern;\n    let isInt = !!def.format?.includes(\"int\");\n    let minimum;\n    let maximum;\n    for (const ch of def.checks ?? []) {\n        const d = ch._zod.def;\n        if (d.pattern)\n            pattern = d.pattern;\n        isInt || (isInt = !!d.format?.includes(\"int\"));\n        const lo = d.minimum ?? d.length;\n        const hi = d.maximum ?? d.length;\n        if (lo !== undefined && (minimum === undefined || lo > minimum))\n            minimum = lo;\n        if (hi !== undefined && (maximum === undefined || hi < maximum))\n            maximum = hi;\n    }\n    if (pattern)\n        return pattern.source;\n    // an empty range matches nothing at runtime, and `{8,5}` is not a legal quantifier\n    if (minimum !== undefined && maximum !== undefined && minimum > maximum)\n        return \"(?!)\";\n    if (minimum !== undefined || maximum !== undefined)\n        return regexes.string({ minimum, maximum }).source;\n    const own = schema._zod.pattern;\n    return (isInt && own === regexes.number ? regexes.integer : own)?.source;\n}\n// a part's pattern source. a wrapper's pattern embeds its inner pattern's source verbatim, so the folded form is substituted in place without knowing the wrapper's own composition; a union's options are joined the way the union builds its own pattern\nfunction partPattern(schema) {\n    const def = schema._zod.def;\n    const own = schema._zod.pattern?.source;\n    // lazy resolves its inner on the internals, not the def\n    const inner = def.innerType ?? schema._zod.innerType;\n    if (inner) {\n        const before = inner._zod.pattern?.source;\n        const after = partPattern(inner);\n        if (own && before && after && after !== before) {\n            return own.replace(util.cleanRegex(before), () => util.cleanRegex(after));\n        }\n        return own;\n    }\n    if (def.options) {\n        const sources = def.options.map(partPattern);\n        if (sources.every(Boolean))\n            return `^(${sources.map((s) => util.cleanRegex(s)).join(\"|\")})$`;\n    }\n    return leafPattern(schema);\n}\nexport const $ZodTemplateLiteral = /*@__PURE__*/ core.$constructor(\"$ZodTemplateLiteral\", (inst, def) => {\n    $ZodType.init(inst, def);\n    const regexParts = [];\n    for (const part of def.parts) {\n        if (typeof part === \"object\" && part !== null) {\n            // is Zod schema\n            const source = partPattern(part);\n            if (!source) {\n                throw new Error(`Invalid template literal part, no pattern found: ${[...part._zod.traits].shift()}`);\n            }\n            regexParts.push(util.cleanRegex(source));\n        }\n        else if (part === null || util.primitiveTypes.has(typeof part)) {\n            regexParts.push(util.escapeRegex(`${part}`));\n        }\n        else {\n            throw new Error(`Invalid template literal part: ${part}`);\n        }\n    }\n    inst._zod.pattern = new RegExp(`^${regexParts.join(\"\")}$`);\n    inst._zod.parse = (payload, _ctx) => {\n        if (typeof payload.value !== \"string\") {\n            payload.issues.push({\n                input: payload.value,\n                inst,\n                expected: \"string\",\n                code: \"invalid_type\",\n            });\n            return payload;\n        }\n        inst._zod.pattern.lastIndex = 0;\n        if (!inst._zod.pattern.test(payload.value)) {\n            payload.issues.push({\n                input: payload.value,\n                inst,\n                code: \"invalid_format\",\n                format: def.format ?? \"template_literal\",\n                pattern: inst._zod.pattern.source,\n            });\n            return payload;\n        }\n        return payload;\n    };\n});\nexport const $ZodFunction = /*@__PURE__*/ core.$constructor(\"$ZodFunction\", (inst, def) => {\n    $ZodType.init(inst, def);\n    // Defined, not assigned: the classic prototype exposes `_def` as a getter with no setter.\n    Object.defineProperty(inst, \"_def\", { value: def });\n    inst._zod.def = def;\n    inst.implement = (func) => {\n        if (typeof func !== \"function\") {\n            throw new Error(\"implement() must be called with a function\");\n        }\n        // Defined inline so the closure stays anonymous: binding it to a `const` first names it, which costs 256 bytes per implemented function.\n        return Object.defineProperty(function (...args) {\n            const parsedArgs = inst._def.input ? parse(inst._def.input, args) : args;\n            const result = Reflect.apply(func, this, parsedArgs);\n            if (inst._def.output) {\n                return parse(inst._def.output, result);\n            }\n            return result;\n        }, \"_zod\", { value: inst._zod, enumerable: false });\n    };\n    inst.implementAsync = (func) => {\n        if (typeof func !== \"function\") {\n            throw new Error(\"implementAsync() must be called with a function\");\n        }\n        return Object.defineProperty(async function (...args) {\n            const parsedArgs = inst._def.input ? await parseAsync(inst._def.input, args) : args;\n            const result = await Reflect.apply(func, this, parsedArgs);\n            if (inst._def.output) {\n                return await parseAsync(inst._def.output, result);\n            }\n            return result;\n        }, \"_zod\", { value: inst._zod, enumerable: false });\n    };\n    inst._zod.parse = (payload, _ctx) => {\n        if (typeof payload.value !== \"function\") {\n            payload.issues.push({\n                code: \"invalid_type\",\n                expected: \"function\",\n                input: payload.value,\n                inst,\n            });\n            return payload;\n        }\n        // Check if output is a promise type to determine if we should use async implementation\n        const hasPromiseOutput = inst._def.output && inst._def.output._zod.def.type === \"promise\";\n        if (hasPromiseOutput) {\n            payload.value = inst.implementAsync(payload.value);\n        }\n        else {\n            payload.value = inst.implement(payload.value);\n        }\n        return payload;\n    };\n    inst.input = (...args) => {\n        const F = inst.constructor;\n        if (Array.isArray(args[0])) {\n            return new F({\n                type: \"function\",\n                input: new $ZodTuple({\n                    type: \"tuple\",\n                    items: args[0],\n                    rest: args[1],\n                }),\n                output: inst._def.output,\n            });\n        }\n        return new F({\n            type: \"function\",\n            input: args[0],\n            output: inst._def.output,\n        });\n    };\n    inst.output = (output) => {\n        const F = inst.constructor;\n        return new F({\n            type: \"function\",\n            input: inst._def.input,\n            output,\n        });\n    };\n    return inst;\n});\nexport const $ZodPromise = /*@__PURE__*/ core.$constructor(\"$ZodPromise\", (inst, def) => {\n    $ZodType.init(inst, def);\n    inst._zod.parse = (payload, ctx) => {\n        return Promise.resolve(payload.value).then((inner) => def.innerType._zod.run({ value: inner, issues: [] }, ctx));\n    };\n});\nexport const $ZodLazy = /*@__PURE__*/ core.$constructor(\"$ZodLazy\", (inst, def) => {\n    $ZodType.init(inst, def);\n    // 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.\n    util.defineLazy(inst._zod, \"innerType\", () => {\n        const d = def;\n        if (!d._cachedInner)\n            d._cachedInner = def.getter();\n        return d._cachedInner;\n    });\n    util.defineLazyInternal(inst, \"pattern\", (zod) => zod.innerType?._zod?.pattern);\n    util.defineLazyInternal(inst, \"propValues\", (zod) => zod.innerType?._zod?.propValues);\n    util.defineLazyInternal(inst, \"optin\", (zod) => zod.innerType?._zod?.optin ?? undefined);\n    util.defineLazyInternal(inst, \"optout\", (zod) => zod.innerType?._zod?.optout ?? undefined);\n    inst._zod.parse = (payload, ctx) => {\n        const inner = inst._zod.innerType;\n        return inner._zod.run(payload, ctx);\n    };\n});\nexport const $ZodCustom = /*@__PURE__*/ core.$constructor(\"$ZodCustom\", (inst, def) => {\n    checks.$ZodCheck.init(inst, def);\n    $ZodType.init(inst, def);\n    inst._zod.parse = (payload, _) => {\n        return payload;\n    };\n    inst._zod.check = (payload) => {\n        const input = payload.value;\n        const r = def.fn(input);\n        if (r instanceof Promise) {\n            return r.then((r) => handleRefineResult(r, payload, input, inst));\n        }\n        handleRefineResult(r, payload, input, inst);\n        return;\n    };\n});\nfunction handleRefineResult(result, payload, input, inst) {\n    if (!result) {\n        const _iss = {\n            code: \"custom\",\n            input,\n            inst, // incorporates params.error into issue reporting\n            path: [...(inst._zod.def.path ?? [])], // incorporates params.error into issue reporting\n            continue: !inst._zod.def.abort,\n            // params: inst._zod.def.params,\n        };\n        if (inst._zod.def.params)\n            _iss.params = inst._zod.def.params;\n        payload.issues.push(util.issue(_iss));\n    }\n}\n","import * as util from \"./util.js\";\nexport class $ZodCyclicError extends Error {\n    constructor() {\n        super(`Cannot parse a reference cycle that closes through a transform`);\n        this.name = \"ZodCyclicError\";\n    }\n}\n/** Keyed off the context object every schema in one parse call already shares. */\nconst STATE = \"~memo\";\nconst NO_ISSUES = [];\n// a value a cycle can close through\nfunction isRef(value) {\n    return value !== null && typeof value === \"object\";\n}\n// Receivers prefix paths in place, so the cache and every hand-out need their own copies.\nfunction cloneIssues(issues) {\n    return issues.map((iss) => (iss.path ? { ...iss, path: iss.path.slice() } : { ...iss }));\n}\nconst recursive = /*@__PURE__*/ new WeakMap();\n/** What the walk established, in order of certainty: ordered so the strongest answer among children wins. */\nconst NONE = 0;\nconst ASSUMED = 1;\nconst PROVEN = 2;\n/** Whether this schema's subtree contains a cycle, so one parse can re-enter it. */\nfunction isRecursive(inst, stack, resolve) {\n    const cached = recursive.get(inst);\n    if (cached !== undefined)\n        return cached ? PROVEN : NONE;\n    // Relative to the walk in progress, so not cached.\n    if (stack.has(inst))\n        return PROVEN;\n    stack.add(inst);\n    let result = NONE;\n    const check = (child) => {\n        if (result !== PROVEN && child?._zod) {\n            const answer = isRecursive(child, stack, resolve);\n            if (answer > result)\n                result = answer;\n        }\n    };\n    // `Reflect.ownKeys` rather than `Object.keys`, so a cycle through a declared symbol key is still seen\n    const shape = (sh, spread) => {\n        let answer = NONE;\n        for (const key of Reflect.ownKeys(sh)) {\n            const desc = Object.getOwnPropertyDescriptor(sh, key);\n            // an object resolves its shape by spread, so a key it does not enumerate is never parsed; `z.properties` reads every own key and so keeps them all\n            if (spread && !desc.enumerable)\n                continue;\n            // resolving runs user code, and a factory mints a fresh subtree per read, so an edge the walk can't follow counts as a cycle\n            const child = desc.get ? ASSUMED : desc.value?._zod ? isRecursive(desc.value, stack, resolve) : NONE;\n            if (child > answer)\n                answer = child;\n        }\n        return answer;\n    };\n    const merge = (answer) => {\n        if (answer > result)\n            result = answer;\n    };\n    const def = inst._zod.def;\n    const kind = def.type;\n    switch (kind) {\n        case \"object\": {\n            const raw = util.rawShape(def);\n            // a def with no raw shape answers `shape` from an accessor of its own, and running that can mint a whole fresh subtree\n            merge(raw ? shape(raw, true) : ASSUMED);\n            check(def.catchall);\n            break;\n        }\n        case \"array\":\n            check(def.element);\n            break;\n        case \"tuple\":\n            for (const el of def.items)\n                check(el);\n            check(def.rest);\n            break;\n        case \"record\":\n        case \"map\":\n            check(def.keyType);\n            check(def.valueType);\n            break;\n        case \"set\":\n            check(def.valueType);\n            break;\n        case \"union\":\n            for (const el of def.options)\n                check(el);\n            break;\n        case \"intersection\":\n            check(def.left);\n            check(def.right);\n            break;\n        case \"optional\":\n        case \"nullable\":\n        case \"default\":\n        case \"prefault\":\n        case \"catch\":\n        case \"readonly\":\n        case \"nonoptional\":\n        case \"promise\":\n        case \"success\":\n            check(def.innerType);\n            break;\n        case \"pipe\":\n            check(def.in);\n            check(def.out);\n            break;\n        case \"function\":\n            check(def.input);\n            check(def.output);\n            break;\n        // `$ZodLazy` caches its inner on the def, so a resolved edge is followed exactly\n        case \"lazy\": {\n            const inner = def._cachedInner ?? (resolve ? inst._zod.innerType : undefined);\n            // walked with resolution off: one hop sees past the deferral, and a lazy that yields only another unresolved lazy is generative, so it stops there\n            merge(inner ? isRecursive(inner, stack, false) : ASSUMED);\n            break;\n        }\n        // a leaf by choice: `parts` are regex fragments, not data positions\n        case \"template_literal\":\n        // leaves\n        case \"string\":\n        case \"number\":\n        case \"int\":\n        case \"boolean\":\n        case \"bigint\":\n        case \"symbol\":\n        case \"undefined\":\n        case \"null\":\n        case \"void\":\n        case \"never\":\n        case \"any\":\n        case \"unknown\":\n        case \"date\":\n        case \"nan\":\n        case \"enum\":\n        case \"literal\":\n        case \"file\":\n        case \"transform\":\n        case \"custom\":\n            break;\n        default: {\n            // a new built-in kind becomes a compile error here\n            kind;\n            // 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\n            for (const key in def) {\n                const desc = Object.getOwnPropertyDescriptor(def, key);\n                if (!desc || desc.get)\n                    continue;\n                const value = desc.value;\n                if (!value || typeof value !== \"object\")\n                    continue;\n                if (value._zod)\n                    check(value);\n                else if (Array.isArray(value))\n                    for (const el of value)\n                        check(el);\n            }\n        }\n    }\n    stack.delete(inst);\n    return settle(inst, result);\n}\n/** An assumed answer must not outlive the resolution that settles it, so only a certain one is cached. */\nfunction settle(inst, answer) {\n    if (answer !== ASSUMED)\n        recursive.set(inst, answer === PROVEN);\n    return answer;\n}\n/**\n * Whether one parse can re-enter this schema, i.e. its subtree contains a cycle.\n * Exported for `z.compile`, which refuses to compile such a schema: cycle\n * breaking is driven from here off state keyed on the parse context, and a\n * generated fast path has no context to key on.\n */\nexport function isRecursiveSchema(inst) {\n    // z.compile never parses, so nothing would ever resolve a lazy for it; it runs once and already treats a throw here as recursive\n    return isRecursive(inst, new Set(), true) !== NONE;\n}\nfunction bucketFor(state, inst) {\n    let bucket = state.buckets.get(inst);\n    if (!bucket) {\n        bucket = new WeakMap();\n        state.buckets.set(inst, bucket);\n    }\n    return bucket;\n}\n// Set immediately before delegating to core and cleared immediately after, so `alloc` registers only for a visit this module is driving.\nlet handoff;\n// 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.\nconst open = [];\nconst memo = {\n    alloc(_inst, payload, empty) {\n        const bucket = handoff;\n        if (!bucket)\n            return empty;\n        handoff = undefined;\n        const entry = { value: empty, issues: null };\n        bucket.set(payload.value, entry);\n        open.push(entry);\n        return empty;\n    },\n    guard(inst) {\n        var _a;\n        (_a = inst._zod).deferred ?? (_a.deferred = []);\n        inst._zod.deferred.push(() => {\n            const base = inst._zod.parse;\n            const wrapped = (payload, ctx) => {\n                // 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.\n                if (ctx.direction !== \"backward\" && isBackEdge(ctx, payload.value))\n                    throw new $ZodCyclicError();\n                return base(payload, ctx);\n            };\n            inst._zod.parse = wrapped;\n            if (inst._zod.run === base)\n                inst._zod.run = wrapped;\n        });\n    },\n    attach(inst) {\n        var _a;\n        let isRecursiveInst;\n        let rechecked = false;\n        // a recursive schema is re-entered many times per parse and its bucket never changes\n        let lastCtx;\n        let lastBucket;\n        // 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.\n        (_a = inst._zod).deferred ?? (_a.deferred = []);\n        inst._zod.deferred.push(() => {\n            const base = inst._zod.parse;\n            const wrapped = (payload, ctx) => {\n                if (isRecursiveInst === undefined) {\n                    const walked = isRecursive(inst, new Set(), false);\n                    if (walked === NONE) {\n                        // Nothing here can ever fire, so take it back out.\n                        inst._zod.parse = base;\n                        if (inst._zod.run === wrapped)\n                            inst._zod.run = base;\n                        return base(payload, ctx);\n                    }\n                    // this parse resolves the deferred edges on its own path, so ask once more before latching\n                    if (walked === PROVEN || rechecked)\n                        isRecursiveInst = true;\n                    else\n                        rechecked = true;\n                }\n                const input = payload.value;\n                if (!isRef(input))\n                    return base(payload, ctx);\n                let state = ctx[STATE];\n                if (!state) {\n                    state = { buckets: new WeakMap(), backEdges: undefined };\n                    ctx[STATE] = state;\n                }\n                let bucket;\n                if (lastCtx === ctx) {\n                    bucket = lastBucket;\n                }\n                else {\n                    bucket = bucketFor(state, inst);\n                    lastCtx = ctx;\n                    lastBucket = bucket;\n                }\n                const hit = bucket.get(input);\n                if (hit) {\n                    payload.value = hit.value;\n                    if (hit.issues) {\n                        if (hit.issues.length)\n                            payload.issues.push(...cloneIssues(hit.issues));\n                    }\n                    else {\n                        // Still being parsed: its own checks cover it, so skip them here.\n                        payload.memo = true;\n                        state.backEdges ?? (state.backEdges = new WeakSet());\n                        state.backEdges.add(hit.value);\n                    }\n                    return payload;\n                }\n                handoff = bucket;\n                const depth = open.length;\n                const result = base(payload, ctx);\n                handoff = undefined;\n                // A container that rejected its input outright allocated nothing.\n                const entry = open.length > depth ? open.pop() : undefined;\n                // 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.\n                if (result instanceof Promise) {\n                    return result.then((r) => {\n                        if (entry)\n                            entry.issues = r.issues.length ? cloneIssues(r.issues) : NO_ISSUES;\n                        return r;\n                    });\n                }\n                if (entry)\n                    entry.issues = result.issues.length ? cloneIssues(result.issues) : NO_ISSUES;\n                return result;\n            };\n            inst._zod.parse = wrapped;\n            if (inst._zod.run === base)\n                inst._zod.run = wrapped;\n        });\n    },\n};\n/** The memoizer that gives containers cycle support. `zod` installs it by default; `zod/mini` opts in with `config({ memoizer: memoizer() })`. */\nexport function memoizer() {\n    return memo;\n}\n/** Whether this value is a node a back-edge resolved to before it finished. */\nexport function isBackEdge(ctx, value) {\n    const backEdges = ctx[STATE]?.backEdges;\n    return backEdges !== undefined && isRef(value) && backEdges.has(value);\n}\n","import * as util from \"../core/util.js\";\nconst error = () => {\n    const Sizable = {\n        string: { unit: \"characters\", verb: \"to have\" },\n        file: { unit: \"bytes\", verb: \"to have\" },\n        array: { unit: \"items\", verb: \"to have\" },\n        set: { unit: \"items\", verb: \"to have\" },\n        map: { unit: \"entries\", verb: \"to have\" },\n    };\n    function getSizing(origin) {\n        return Sizable[origin] ?? null;\n    }\n    const FormatDictionary = {\n        regex: \"input\",\n        email: \"email address\",\n        url: \"URL\",\n        emoji: \"emoji\",\n        uuid: \"UUID\",\n        uuidv4: \"UUIDv4\",\n        uuidv6: \"UUIDv6\",\n        nanoid: \"nanoid\",\n        guid: \"GUID\",\n        cuid: \"cuid\",\n        cuid2: \"cuid2\",\n        ulid: \"ULID\",\n        xid: \"XID\",\n        ksuid: \"KSUID\",\n        datetime: \"ISO datetime\",\n        date: \"ISO date\",\n        time: \"ISO time\",\n        duration: \"ISO duration\",\n        ipv4: \"IPv4 address\",\n        ipv6: \"IPv6 address\",\n        mac: \"MAC address\",\n        cidrv4: \"IPv4 range\",\n        cidrv6: \"IPv6 range\",\n        base64: \"base64-encoded string\",\n        base64url: \"base64url-encoded string\",\n        json_string: \"JSON string\",\n        e164: \"E.164 number\",\n        currency_code: \"currency code\",\n        credit_card: \"credit card number\",\n        iban: \"IBAN\",\n        jwt: \"JWT\",\n        template_literal: \"input\",\n    };\n    // type names: missing keys = do not translate (use raw value via ?? fallback)\n    const TypeDictionary = {\n        // Compatibility: \"nan\" -> \"NaN\" for display\n        nan: \"NaN\",\n        // All other type names omitted - they fall back to raw values via ?? operator\n    };\n    function getTypeName(type, input) {\n        if (type === \"number\" && typeof input === \"number\" && !Number.isFinite(input)) {\n            return String(input);\n        }\n        return TypeDictionary[type] ?? type;\n    }\n    return (issue) => {\n        switch (issue.code) {\n            case \"invalid_type\": {\n                const expected = getTypeName(issue.expected);\n                const receivedType = util.parsedType(issue.input);\n                const received = getTypeName(receivedType, issue.input);\n                return `Invalid input: expected ${expected}, received ${received}`;\n            }\n            case \"invalid_value\":\n                if (issue.values.length === 1)\n                    return `Invalid input: expected ${util.stringifyPrimitive(issue.values[0])}`;\n                return `Invalid option: expected one of ${util.joinValues(issue.values, \"|\")}`;\n            case \"too_big\": {\n                const adj = issue.exact ? \"exactly \" : issue.inclusive ? \"<=\" : \"<\";\n                const sizing = getSizing(issue.origin);\n                if (sizing)\n                    return `Too big: expected ${issue.origin ?? \"value\"} to have ${adj}${issue.maximum.toString()} ${sizing.unit ?? \"elements\"}`;\n                return `Too big: expected ${issue.origin ?? \"value\"} to be ${adj}${issue.maximum.toString()}`;\n            }\n            case \"too_small\": {\n                const adj = issue.exact ? \"exactly \" : issue.inclusive ? \">=\" : \">\";\n                const sizing = getSizing(issue.origin);\n                if (sizing) {\n                    return `Too small: expected ${issue.origin} to have ${adj}${issue.minimum.toString()} ${sizing.unit}`;\n                }\n                return `Too small: expected ${issue.origin} to be ${adj}${issue.minimum.toString()}`;\n            }\n            case \"invalid_format\": {\n                const _issue = issue;\n                if (_issue.format === \"starts_with\") {\n                    return `Invalid string: must start with \"${_issue.prefix}\"`;\n                }\n                if (_issue.format === \"ends_with\")\n                    return `Invalid string: must end with \"${_issue.suffix}\"`;\n                if (_issue.format === \"includes\")\n                    return `Invalid string: must include \"${_issue.includes}\"`;\n                if (_issue.format === \"regex\")\n                    return `Invalid string: must match pattern ${_issue.pattern}`;\n                return `Invalid ${FormatDictionary[_issue.format] ?? issue.format}`;\n            }\n            case \"not_multiple_of\":\n                return `Invalid number: must be a multiple of ${issue.divisor}`;\n            case \"unrecognized_keys\":\n                return `Unrecognized key${issue.keys.length > 1 ? \"s\" : \"\"}: ${util.joinValues(issue.keys, \", \")}`;\n            case \"invalid_key\":\n                return `Invalid key in ${issue.origin}`;\n            case \"invalid_union\":\n                if (issue.options && Array.isArray(issue.options) && issue.options.length > 0) {\n                    const opts = issue.options.map((o) => `'${o}'`).join(\" | \");\n                    return `Invalid discriminator value. Expected ${opts}`;\n                }\n                if (issue.inclusive === false) {\n                    return \"Invalid input: more than one option matched\";\n                }\n                return \"Invalid input\";\n            case \"invalid_element\":\n                return `Invalid value in ${issue.origin}`;\n            default:\n                return `Invalid input`;\n        }\n    };\n};\nexport default function () {\n    return {\n        localeError: error(),\n    };\n}\n","export { default as ar } from \"./ar.js\";\nexport { default as az } from \"./az.js\";\nexport { default as be } from \"./be.js\";\nexport { default as bg } from \"./bg.js\";\nexport { default as bn } from \"./bn.js\";\nexport { default as ca } from \"./ca.js\";\nexport { default as ckb } from \"./ckb.js\";\nexport { default as cs } from \"./cs.js\";\nexport { default as da } from \"./da.js\";\nexport { default as de } from \"./de.js\";\nexport { default as el } from \"./el.js\";\nexport { default as en } from \"./en.js\";\nexport { default as eo } from \"./eo.js\";\nexport { default as es } from \"./es.js\";\nexport { default as fa } from \"./fa.js\";\nexport { default as fi } from \"./fi.js\";\nexport { default as fr } from \"./fr.js\";\nexport { default as frCA } from \"./fr-CA.js\";\nexport { default as gu } from \"./gu.js\";\nexport { default as he } from \"./he.js\";\nexport { default as hi } from \"./hi.js\";\nexport { default as hr } from \"./hr.js\";\nexport { default as hu } from \"./hu.js\";\nexport { default as hy } from \"./hy.js\";\nexport { default as id } from \"./id.js\";\nexport { default as is } from \"./is.js\";\nexport { default as it } from \"./it.js\";\nexport { default as ja } from \"./ja.js\";\nexport { default as ka } from \"./ka.js\";\nexport { default as kh } from \"./kh.js\";\nexport { default as km } from \"./km.js\";\nexport { default as kn } from \"./kn.js\";\nexport { default as ko } from \"./ko.js\";\nexport { default as lt } from \"./lt.js\";\nexport { default as mk } from \"./mk.js\";\nexport { default as ms } from \"./ms.js\";\nexport { default as ne } from \"./ne.js\";\nexport { default as nl } from \"./nl.js\";\nexport { default as nn } from \"./nn.js\";\nexport { default as no } from \"./no.js\";\nexport { default as ota } from \"./ota.js\";\nexport { default as ps } from \"./ps.js\";\nexport { default as pl } from \"./pl.js\";\nexport { default as pt } from \"./pt.js\";\nexport { default as ptBR } from \"./pt-BR.js\";\nexport { default as ro } from \"./ro.js\";\nexport { default as ru } from \"./ru.js\";\nexport { default as sk } from \"./sk.js\";\nexport { default as sl } from \"./sl.js\";\nexport { default as sv } from \"./sv.js\";\nexport { default as ta } from \"./ta.js\";\nexport { default as tg } from \"./tg.js\";\nexport { default as th } from \"./th.js\";\nexport { default as tk } from \"./tk.js\";\nexport { default as tr } from \"./tr.js\";\nexport { default as ua } from \"./ua.js\";\nexport { default as uk } from \"./uk.js\";\nexport { default as ur } from \"./ur.js\";\nexport { default as uz } from \"./uz.js\";\nexport { default as vi } from \"./vi.js\";\nexport { default as zhCN } from \"./zh-CN.js\";\nexport { default as zhTW } from \"./zh-TW.js\";\nexport { default as yo } from \"./yo.js\";\n","var _a;\nexport const $output = /*@__PURE__*/ Symbol(\"ZodOutput\");\nexport const $input = /*@__PURE__*/ Symbol(\"ZodInput\");\nexport class $ZodRegistry {\n    constructor() {\n        this._map = new WeakMap();\n        this._idmap = new Map();\n    }\n    add(schema, ..._meta) {\n        const meta = _meta[0];\n        this._map.set(schema, meta);\n        if (meta && typeof meta === \"object\" && \"id\" in meta) {\n            this._idmap.set(meta.id, schema);\n        }\n        return this;\n    }\n    clear() {\n        this._map = new WeakMap();\n        this._idmap = new Map();\n        return this;\n    }\n    remove(schema) {\n        const meta = this._map.get(schema);\n        if (meta && typeof meta === \"object\" && \"id\" in meta) {\n            this._idmap.delete(meta.id);\n        }\n        this._map.delete(schema);\n        return this;\n    }\n    get(schema) {\n        // return this._map.get(schema) as any;\n        // inherit metadata\n        const p = schema._zod.parent;\n        if (p) {\n            const pm = { ...(this.get(p) ?? {}) };\n            delete pm.id; // do not inherit id\n            const f = { ...pm, ...this._map.get(schema) };\n            return Object.keys(f).length ? f : undefined;\n        }\n        return this._map.get(schema);\n    }\n    has(schema) {\n        return this._map.has(schema);\n    }\n}\n// registries\nexport function registry() {\n    return new $ZodRegistry();\n}\n(_a = globalThis).__zod_globalRegistry ?? (_a.__zod_globalRegistry = registry());\nexport const globalRegistry = globalThis.__zod_globalRegistry;\n","import { $ZodAsyncError } from \"./core.js\";\nimport { Doc } from \"./doc.js\";\nimport { isBackEdge, isRecursiveSchema } from \"./memoizer.js\";\nimport * as regexes from \"./regexes.js\";\nimport { isValidBase64, isValidBase64URL, isValidCIDRv6, isValidCreditCard, isValidIBAN, isValidIPv6, isValidJWT, mergeValues, stripTabAndNewline, urlHostnameOk, urlProtocolOk, validateURL, } from \"./schemas.js\";\nimport * as util from \"./util.js\";\n/** @internal Sentinel the compiled fast path returns when validation fails. */\nexport const INVALID = Symbol.for(\"zod.compile.invalid\");\n// Set on the parse ctx when a compiled wrapper falls back to the runtime, so nested compiled wrappers skip their fast paths for the rest of that parse.\nconst FALLBACK_FLAG = Symbol.for(\"zod.compile.fallback\");\n/** Raised when the schema contains async refinements or transforms. Surfaces only under `compile(schema, { strict: true })`. */\nexport class ZodCompileAsyncError extends Error {\n    constructor(message = \"z.compile does not support async refinements, transforms, or checks\") {\n        super(message);\n        this.name = \"ZodCompileAsyncError\";\n    }\n}\n/**\n * Raised when the schema contains a feature whose semantics the fast path\n * can't fully model. Both the shim in `zod/compile` and the default\n * `compile()` fall back to the runtime parser for that schema; only\n * `compile(schema, { strict: true })` lets it surface.\n */\nexport class ZodCompileUnsupportedError extends Error {\n    constructor(feature, islandable = true) {\n        super(`z.compile does not support ${feature}; this schema must use the runtime parser`);\n        this.name = \"ZodCompileUnsupportedError\";\n        this.islandable = islandable;\n    }\n}\n/**\n * Build the validator `validate` calls: the same codegen as the parser with the output construction\n * dropped. A schema the flag cannot express reuses the parser, which still answers correctly — it\n * just builds a value nothing reads.\n */\nfunction compileValidator(schema, parser) {\n    try {\n        return compileFn(schema, { assertOnly: true });\n    }\n    catch {\n        return parser;\n    }\n}\n/**\n * AOT-compile a Zod schema. Returns a clone whose `_zod.run` calls a generated\n * fast path first and falls back to the original runtime parser on failure.\n *\n * - Forward direction only. Backward (encode), async, and `skipChecks` paths\n *   bypass the fast path and use the runtime directly.\n * - Never throws. A schema the fast path can't model is returned unchanged and\n *   keeps using the runtime parser. Pass `{ strict: true }` to get the refusal\n *   as a thrown `ZodCompileUnsupportedError` / `ZodCompileAsyncError` instead.\n * - The original schema is unchanged. The clone shares children by reference.\n */\nexport function compile(schema, options) {\n    try {\n        const parser = compileFn(schema);\n        const clone = withParser(schema, parser);\n        // withParser leaves the parser as its own validator; the generated assert-only variant is better when we have one\n        clone._zod.bag.validator = compileValidator(schema, parser);\n        return clone;\n    }\n    catch (err) {\n        if (options?.strict)\n            throw err;\n        // a schema we can't compile still has to work, so hand it back untouched on the runtime parser — the same silent fallback global mode already does\n        return schema;\n    }\n}\n/**\n * Install an already-generated parser as a schema's fast path. Returns a clone; the original is\n * unchanged.\n *\n * The parser takes the input and returns the parsed value, or `INVALID` to hand the parse to the\n * runtime. It must be synchronous and forward-direction, and it must build fresh output rather than\n * return its input — Zod cannot check either, and a wrong *success* is returned to the caller as-is.\n *\n * `compile()` is the ordinary entry point. This is for a build-time or native compiler that produces\n * a parser where `new Function` is unavailable.\n */\nexport function withParser(schema, parser) {\n    // generated code never receives the parse context, so only the runtime can close a reference cycle; compileFn refuses these too\n    if (isRecursiveSchema(schema)) {\n        throw new ZodCompileUnsupportedError(\"a schema whose subtree contains a reference cycle\");\n    }\n    const clone = util.clone(schema);\n    // Capture the source-of-truth runtime eagerly. If schema._zod.run is itself a shim installed by global-mode (`__originalRun` set), unwrap past it. Otherwise capturing the live property lazily would let a later self- replacement of schema._zod.run feed our wrapper back into itself.\n    const liveRun = schema._zod.run;\n    const originalRun = liveRun.__originalRun ?? liveRun;\n    // Delegate to the *original* schema's run on bypass/fallback, not the clone's. The original closed over its own `inst` at construction time, and issue payloads use that reference to derive things like the class name for `z.instanceof(Test)`; calling the clone's freshly-initialized run would push issues with `inst === clone` and diverge from the original schema's error messages.\n    const wrapped = (payload, ctx) => {\n        if (ctx?.async ||\n            ctx?.direction === \"backward\" ||\n            ctx?.skipChecks ||\n            ctx?.[FALLBACK_FLAG]) {\n            return originalRun(payload, ctx);\n        }\n        // A memoized back-edge: only the runtime can close a reference cycle, and a transform on one must raise $ZodCyclicError from its own parse.\n        if (ctx && isBackEdge(ctx, payload.value)) {\n            return originalRun(payload, ctx);\n        }\n        const out = parser(payload.value);\n        if (out !== INVALID) {\n            payload.value = out;\n            return payload;\n        }\n        // Mark this parse as runtime-driven: under global mode every nested schema carries its own compiled wrapper, and without the flag the parent's runtime fallback re-enters each child's fast path, running user callbacks a third time on invalid input.\n        if (ctx)\n            ctx[FALLBACK_FLAG] = true;\n        return originalRun(payload, ctx);\n    };\n    // Let later compiles of (or through) this run unwrap to the true runtime — both the global shim and repeated z.compile calls rely on this. The bag also carries the parser and the validator, so the standalone validate can skip the payload and wrapper on the happy path.\n    wrapped.__originalRun = originalRun;\n    clone._zod.bag.fallbackRun = originalRun;\n    // a supplied parser answers `validate` too: one implementation means parse and validate cannot disagree, and its undefined `definite` keeps the runtime re-parse on every rejection\n    clone._zod.bag.validator = parser;\n    clone._zod.run = wrapped;\n    // The fast parse/safeParse closures fall back through the source schema's methods. If the source is shim- or wrapper-managed, those methods route into a compiled run and would execute user callbacks a third time on invalid input — the plain method → wrapper path is exactly 2x, so skip.\n    if (!liveRun.__originalRun)\n        installCompiledUserMethods(clone, schema, parser);\n    return clone;\n}\nfunction installCompiledUserMethods(target, source, parser) {\n    const targetAny = target;\n    const sourceAny = source;\n    if (typeof sourceAny.safeParse === \"function\") {\n        const originalSafeParse = sourceAny.safeParse;\n        targetAny.safeParse = (data, params) => {\n            const out = parser(data);\n            if (out !== INVALID) {\n                return { success: true, data: out };\n            }\n            return originalSafeParse(data, params);\n        };\n    }\n    if (typeof sourceAny.parse === \"function\") {\n        const originalParse = sourceAny.parse;\n        targetAny.parse = (data, params) => {\n            const out = parser(data);\n            if (out !== INVALID) {\n                return out;\n            }\n            return originalParse(data, params);\n        };\n    }\n}\n/**\n * @internal Generate the standalone compiled function: a parser by default, a validator under\n * `assertOnly`. Returns the parsed value, `true` where nothing reads the output, or `INVALID`. Consumers use `compile()`.\n */\nexport function compileFn(schema, options) {\n    // Cycle-breaking is keyed on the parse context, which generated code never receives. `shape` can be a getter that throws (z.pick() with an unrecognized mask key), so treat \"can't tell\" as recursive.\n    let recursive = true;\n    try {\n        recursive = isRecursiveSchema(schema);\n    }\n    catch { }\n    if (recursive) {\n        throw new ZodCompileUnsupportedError(\"a schema whose subtree contains a reference cycle\");\n    }\n    const ctx = {\n        constants: new Map(),\n        constantCounter: 0,\n        varCounter: 0,\n        definite: true,\n    };\n    const doc = new Doc([\"input\"]);\n    const outputAccessor = generateCheck(doc, ctx, schema, \"input\", !options?.assertOnly);\n    // In assert mode a root that built nothing has already returned INVALID on every failure, so reaching the end means valid.\n    doc.write(outputAccessor === null ? `return true;` : `return ${outputAccessor};`);\n    // Build the function with hoisted constants Always include INVALID as the first constant\n    const constantNames = [\"INVALID\", ...ctx.constants.keys()];\n    const constantValues = [INVALID, ...ctx.constants.values()];\n    const code = doc.content.join(\"\\n\");\n    const fullCode = options?.debug\n        ? constantNames.length > 0\n            ? `// Constants: ${constantNames.join(\", \")}\\n${code}`\n            : code\n        : \"\";\n    const F = Function;\n    const factoryCode = `return (input) => {\\n${code}\\n}`;\n    let fn;\n    try {\n        const factory = new F(...constantNames, factoryCode);\n        fn = factory(...constantValues);\n    }\n    catch (err) {\n        // Malformed generated code (or a CSP environment rejecting `new Function`) surfaces as a typed error so the global shim falls back to the runtime instead of crashing with a raw SyntaxError/EvalError.\n        throw new ZodCompileUnsupportedError(`this schema (generated code failed to evaluate: ${err.message})`);\n    }\n    if (options?.debug) {\n        fn.code = fullCode;\n    }\n    fn.definite = ctx.definite;\n    return fn;\n}\nfunction addConstant(ctx, value) {\n    // Check if we already have this constant\n    for (const [name, v] of ctx.constants) {\n        if (v === value)\n            return name;\n    }\n    const name = `c${ctx.constantCounter++}`;\n    ctx.constants.set(name, value);\n    return name;\n}\n/** Hoists a user-supplied callback. Anything the schema's author wrote can throw, and generated code can reject an earlier sibling before ever reaching it, so this clears `definite` — a rejection is then no longer proof that the interpreter would have rejected rather than thrown. */\nfunction addUserConstant(ctx, fn) {\n    ctx.definite = false;\n    return addConstant(ctx, fn);\n}\nfunction newVar(ctx) {\n    return `v${ctx.varCounter++}`;\n}\n// Runs a child schema as a black box: its value, or INVALID for a failure or an async run.\nfunction runtimeRun(schema, value) {\n    const result = schema._zod.run({ value, issues: [] }, {});\n    if (result && typeof result.then === \"function\")\n        return INVALID;\n    const r = result;\n    return r.issues.length === 0 ? r.value : INVALID;\n}\n// `null` means the node built no value because nothing reads it. The overloads keep that case out of the 20-odd callers that always want one, so only a caller passing needsValue has to handle it.\nfunction compileChild(doc, ctx, schema, accessor, needsValue = true) {\n    const contentLen = doc.content.length;\n    const constantCount = ctx.constants.size;\n    const constantCounter = ctx.constantCounter;\n    const varCounter = ctx.varCounter;\n    try {\n        return generateCheck(doc, ctx, schema, accessor, needsValue);\n    }\n    catch (err) {\n        if (!(err instanceof ZodCompileUnsupportedError) || !err.islandable)\n            throw err;\n        doc.content.length = contentLen;\n        if (ctx.constants.size > constantCount) {\n            const trailing = Array.from(ctx.constants.keys()).slice(constantCount);\n            for (const k of trailing)\n                ctx.constants.delete(k);\n        }\n        ctx.constantCounter = constantCounter;\n        ctx.varCounter = varCounter;\n        return emitRuntimeIsland(doc, ctx, schema, accessor);\n    }\n}\nfunction emitRuntimeIsland(doc, ctx, schema, accessor) {\n    // an islanded child answers INVALID for an async run too, which the interpreter throws for\n    ctx.definite = false;\n    const schemaConst = addConstant(ctx, schema);\n    const runConst = addConstant(ctx, runtimeRun);\n    const outVar = newVar(ctx);\n    doc.write(`const ${outVar} = ${runConst}(${schemaConst}, ${accessor});`);\n    doc.write(`if (${outVar} === INVALID) return INVALID;`);\n    return outVar;\n}\n// Check classes whose `when` is auto-defaulted at init (checks.ts `when ??=`).\nconst WHEN_DEFAULTED_CHECKS = new Set([\n    \"max_size\",\n    \"min_size\",\n    \"size_equals\",\n    \"max_length\",\n    \"min_length\",\n    \"length_equals\",\n]);\nfunction generateChecks(doc, ctx, schema, accessor) {\n    const schemaChecks = schema._zod.def.checks;\n    if (!schemaChecks || schemaChecks.length === 0)\n        return accessor;\n    // Track current accessor - may change if overwrite checks are encountered\n    let currentAccessor = accessor;\n    for (const check of schemaChecks) {\n        const def = check._zod.def;\n        // A custom `when` skips a check the fast path always runs; the one auto-defaulted on size/length classes matches its bail-on-first-failure.\n        if (def.when && !WHEN_DEFAULTED_CHECKS.has(def.check)) {\n            throw new ZodCompileUnsupportedError(`check with a custom \"when\" condition`);\n        }\n        switch (def.check) {\n            case \"greater_than\":\n                generateGreaterThanCheck(doc, ctx, def, currentAccessor);\n                break;\n            case \"less_than\":\n                generateLessThanCheck(doc, ctx, def, currentAccessor);\n                break;\n            case \"multiple_of\":\n                generateMultipleOfCheck(doc, ctx, def, currentAccessor);\n                break;\n            case \"number_format\":\n                generateNumberFormatCheck(doc, def, currentAccessor);\n                break;\n            case \"min_length\": {\n                const min = numericOperand(def.minimum, \"min_length\");\n                const len = codePointLengthVar(doc, ctx, currentAccessor, `${currentAccessor}.length >= ${min} && ${currentAccessor}.length < ${def.minimum * 2}`);\n                doc.write(`if (${len} < ${min}) return INVALID;`);\n                break;\n            }\n            case \"max_length\": {\n                const max = numericOperand(def.maximum, \"max_length\");\n                const len = codePointLengthVar(doc, ctx, currentAccessor, `${currentAccessor}.length > ${max}`);\n                doc.write(`if (${len} > ${max}) return INVALID;`);\n                break;\n            }\n            case \"length_equals\": {\n                const exact = numericOperand(def.length, \"length_equals\");\n                const len = codePointLengthVar(doc, ctx, currentAccessor, `${currentAccessor}.length >= ${exact} && ${currentAccessor}.length <= ${def.length * 2}`);\n                doc.write(`if (${len} !== ${exact}) return INVALID;`);\n                break;\n            }\n            case \"min_size\":\n                doc.write(`if (${currentAccessor}.size < ${numericOperand(def.minimum, \"min_size\")}) return INVALID;`);\n                break;\n            case \"max_size\":\n                doc.write(`if (${currentAccessor}.size > ${numericOperand(def.maximum, \"max_size\")}) return INVALID;`);\n                break;\n            case \"size_equals\":\n                doc.write(`if (${currentAccessor}.size !== ${numericOperand(def.size, \"size_equals\")}) return INVALID;`);\n                break;\n            case \"string_format\":\n                currentAccessor = generateStringFormatCheck(doc, ctx, def, currentAccessor);\n                break;\n            case \"custom\":\n                currentAccessor = generateCustomRefineCheck(doc, ctx, check, currentAccessor);\n                break;\n            case \"bigint_format\":\n                generateBigIntFormatCheck(doc, def, currentAccessor);\n                break;\n            case \"mime_type\":\n                generateMimeTypeCheck(doc, ctx, def, currentAccessor);\n                break;\n            case \"property\":\n                generatePropertyCheck(doc, ctx, def, currentAccessor);\n                break;\n            case \"properties\":\n                generatePropertiesChecks(doc, ctx, def, currentAccessor);\n                break;\n            case \"overwrite\": {\n                // Overwrite transforms the value - create new variable for transformed result\n                const newAccessor = newVar(ctx);\n                generateOverwriteCheck(doc, ctx, check, currentAccessor, newAccessor);\n                currentAccessor = newAccessor;\n                break;\n            }\n            default: {\n                void def;\n                throw new ZodCompileUnsupportedError(`check type ${def.check}`);\n            }\n        }\n    }\n    return currentAccessor;\n}\n// Emit the length operand for a length check, mirroring `$ZodCheckMinLength` and friends: strings measure in code points, everything else in `.length`. `inDoubt` is the caller's cheap UTF-16 bound test — outside it the unit count already settles the comparison, so the scan is skipped.\nfunction codePointLengthVar(doc, ctx, accessor, inDoubt) {\n    const cpLen = addConstant(ctx, util.codePointLength);\n    const v = newVar(ctx);\n    doc.write(`const ${v} = typeof ${accessor} === \"string\" && ${inDoubt} ? ${cpLen}(${accessor}) : ${accessor}.length;`);\n    return v;\n}\n// Emit a source operand for a gt/lt bound. Numbers inline; Dates hoist as a constant (relational operators compare via valueOf). NaN and Invalid Date bounds can't compile to a comparison that matches runtime semantics.\n/**\n * A count bound reaches generated source verbatim, so a non-number would be\n * emitted as code rather than as a value — `min('0) {} evil(); if (0')` writes an\n * arbitrary statement into the function body. TypeScript types these as `number`\n * and fromJSONSchema guards them, so this is a backstop rather than a live hole,\n * but generated source is the one place a wrong type stops being a type error.\n */\nfunction numericOperand(value, label) {\n    if (typeof value !== \"number\" || !Number.isFinite(value)) {\n        throw new ZodCompileUnsupportedError(`${label} bound of type ${typeof value}`);\n    }\n    return `${value}`;\n}\nfunction comparisonOperand(ctx, value) {\n    if (typeof value === \"bigint\")\n        return `${value}n`;\n    if (typeof value === \"number\") {\n        if (Number.isNaN(value))\n            throw new ZodCompileUnsupportedError(\"comparison check with NaN bound\");\n        return `${value}`;\n    }\n    if (value instanceof Date) {\n        if (Number.isNaN(value.getTime())) {\n            throw new ZodCompileUnsupportedError(\"comparison check with Invalid Date bound\");\n        }\n        return addConstant(ctx, value);\n    }\n    throw new ZodCompileUnsupportedError(`comparison check bound of type ${typeof value}`);\n}\nfunction generateGreaterThanCheck(doc, ctx, def, accessor) {\n    const op = def.inclusive ? \"<\" : \"<=\";\n    doc.write(`if (${accessor} ${op} ${comparisonOperand(ctx, def.value)}) return INVALID;`);\n}\nfunction generateLessThanCheck(doc, ctx, def, accessor) {\n    const op = def.inclusive ? \">\" : \">=\";\n    doc.write(`if (${accessor} ${op} ${comparisonOperand(ctx, def.value)}) return INVALID;`);\n}\nfunction generateMultipleOfCheck(doc, ctx, def, accessor) {\n    if (typeof def.value === \"bigint\") {\n        // a zero divisor has no compiled form: `x % 0n` throws\n        if (def.value === BigInt(0))\n            throw new ZodCompileUnsupportedError(\"multiple_of check with a zero divisor\");\n        doc.write(`if (${accessor} % ${def.value}n !== 0n) return INVALID;`);\n    }\n    else {\n        // Float `%` has well-known precision issues for sub-integer steps\n        // (`1.5 % 0.1`, `2.5e-7 % 1e-7`). Defer to util.floatSafeRemainder so the\n        // exact tolerance logic stays in one place — single function call is fine\n        // since `multipleOf` runs at most once per number.\n        const remainder = addConstant(ctx, util.floatSafeRemainder);\n        doc.write(`if (${remainder}(${accessor}, ${numericOperand(def.value, \"multiple_of\")}) !== 0) return INVALID;`);\n    }\n}\nfunction generateNumberFormatCheck(doc, def, accessor) {\n    const format = def.format;\n    switch (format) {\n        case \"safeint\":\n            doc.write(`if (!Number.isSafeInteger(${accessor})) return INVALID;`);\n            break;\n        case \"int32\":\n            doc.write(`if (!Number.isInteger(${accessor}) || ${accessor} < -2147483648 || ${accessor} > 2147483647) return INVALID;`);\n            break;\n        case \"uint32\":\n            doc.write(`if (!Number.isInteger(${accessor}) || ${accessor} < 0 || ${accessor} > 4294967295) return INVALID;`);\n            break;\n        case \"float32\":\n            // Float32 range per util.NUMBER_FORMAT_RANGES\n            doc.write(`if (!Number.isFinite(${accessor}) || ${accessor} < -3.4028234663852886e38 || ${accessor} > 3.4028234663852886e38) return INVALID;`);\n            break;\n        case \"float64\":\n            doc.write(`if (!Number.isFinite(${accessor})) return INVALID;`);\n            break;\n        default: {\n            void format;\n            throw new ZodCompileUnsupportedError(`number format ${format}`);\n        }\n    }\n}\nfunction generateBigIntFormatCheck(doc, def, accessor) {\n    const format = def.format;\n    if (!format)\n        return; // undefined format means no range check\n    switch (format) {\n        case \"int64\":\n            doc.write(`if (${accessor} < -9223372036854775808n || ${accessor} > 9223372036854775807n) return INVALID;`);\n            break;\n        case \"uint64\":\n            doc.write(`if (${accessor} < 0n || ${accessor} > 18446744073709551615n) return INVALID;`);\n            break;\n        default: {\n            void format;\n            throw new ZodCompileUnsupportedError(`bigint format ${format}`);\n        }\n    }\n}\nfunction generateMimeTypeCheck(doc, ctx, def, accessor) {\n    const mimeTypes = def.mime;\n    if (mimeTypes && mimeTypes.length > 0) {\n        const mimeSet = addConstant(ctx, new Set(mimeTypes));\n        doc.write(`if (!${mimeSet}.has(${accessor}.type)) return INVALID;`);\n    }\n}\n// asserts each named property in place; children compile assert-only because z.properties never rebuilds its input\nfunction generatePropertiesChecks(doc, ctx, def, accessor) {\n    // a custom `when` gates the assertion at runtime; inside a union a wrongly-run branch is absorbed as a branch failure rather than falling back, so refuse at codegen\n    if (def.when) {\n        throw new ZodCompileUnsupportedError(`check with a custom \"when\" condition`);\n    }\n    // matches the runtime gate: the base schema already typed the value, so only a nullish one is rejected\n    doc.write(`if (${accessor} == null) return INVALID;`);\n    const shape = def.shape;\n    for (const key of Reflect.ownKeys(shape)) {\n        // a symbol has no source literal, so it is hoisted as a constant\n        const keyExpr = typeof key === \"symbol\" ? addConstant(ctx, key) : util.esc(key);\n        // cache the property read so a getter runs exactly once, matching the runtime\n        const inputVar = newVar(ctx);\n        doc.write(`const ${inputVar} = ${accessor}[${keyExpr}];`);\n        compileChild(doc, ctx, shape[key], inputVar, false);\n    }\n}\nfunction generatePropertyCheck(doc, ctx, def, accessor) {\n    const propAccessor = `${accessor}[${JSON.stringify(def.property)}]`;\n    generateCheck(doc, ctx, def.schema, propAccessor);\n}\nfunction generateOverwriteCheck(doc, ctx, check, currentAccessor, newAccessor) {\n    const tx = check._zod.def.tx;\n    if (!tx) {\n        throw new ZodCompileUnsupportedError(\"overwrite check without a transform function\");\n    }\n    // Check for async transform\n    if (isAsyncFunction(tx)) {\n        throw new ZodCompileAsyncError(\"z.compile: async overwrite transforms are not supported\");\n    }\n    // Hoist the transform function as a constant and apply it\n    const txConst = addConstant(ctx, tx);\n    doc.write(`const ${newAccessor} = ${txConst}(${currentAccessor});`);\n}\n/** A predicate that hands back a thenable is an async check reached synchronously, and the interpreter throws `$ZodAsyncError` for it. Returning INVALID instead would be a bail-out, and a union reads a bail-out as a rejected branch and answers with a later one — so the throw has to survive into generated code. */\nfunction throwAsync() {\n    throw new $ZodAsyncError();\n}\n/** Shared `addIssue` for the spoofed payloads a refine, check or transform receives. Allocating one per call — a fresh closure plus a `this`-bound method on a fresh literal — pinned every payload-allocating schema at ~2.7M ops/sec against 135M for a plain object literal. It captures nothing per call; it only reaches `this.issues`. */\nfunction pushIssue(issue) {\n    this.issues.push(issue);\n}\nfunction generateCustomRefineCheck(doc, ctx, check, accessor) {\n    const def = check._zod.def;\n    if (def.fn) {\n        // Simple predicate function (from .refine())\n        if (isAsyncFunction(def.fn)) {\n            throw new ZodCompileAsyncError(\"z.compile: async .refine() predicates are not supported\");\n        }\n        const fnConst = addUserConstant(ctx, def.fn);\n        const throwAsyncConst = addConstant(ctx, throwAsync);\n        const resVar = newVar(ctx);\n        doc.write(`const ${resVar} = ${fnConst}(${accessor});`);\n        // A thenable is truthy, so it would otherwise read as a pass. It is not a rejection either: the interpreter throws, and INVALID inside a union would just hand the parse to the next branch.\n        doc.write(`if (${resVar} instanceof Promise) ${throwAsyncConst}();`);\n        doc.write(`if (!${resVar}) return INVALID;`);\n        // A `.refine()` predicate only answers yes or no; it cannot rewrite the value.\n        return accessor;\n    }\n    if (check._zod.check) {\n        if (isAsyncFunction(check._zod.check)) {\n            throw new ZodCompileAsyncError(\"z.compile: async .superRefine() / check functions are not supported\");\n        }\n        // SuperRefine or other check function - need to spoof context Create a helper that runs the check and returns true if no issues\n        const checkFn = check._zod.check;\n        // `$RefinementCtx` extends the parse payload, so a check may rewrite\n        // `ctx.value` as well as push issues — `.superRefine((v, ctx) => { ctx.value =\n        // v.trim() })` is a value transform. Returning only a boolean discarded that\n        // write and emitted the untrimmed input. Hand the value back and thread it on.\n        const helperFn = (value) => {\n            const fakePayload = { value, issues: [], addIssue: pushIssue };\n            const result = checkFn(fakePayload);\n            // Throw rather than return INVALID: the interpreter throws here, and a union would read INVALID as a rejected branch.\n            if (result instanceof Promise)\n                throwAsync();\n            return fakePayload.issues.length === 0 ? fakePayload.value : INVALID;\n        };\n        const helperConst = addUserConstant(ctx, helperFn);\n        const outVar = newVar(ctx);\n        doc.write(`const ${outVar} = ${helperConst}(${accessor});`);\n        doc.write(`if (${outVar} === INVALID) return INVALID;`);\n        return outVar;\n    }\n    throw new ZodCompileUnsupportedError(\"custom check without a predicate or check function\");\n}\n/**\n * Built-in formats that validate with nothing but `def.pattern`, so compiling\n * the regex reproduces the runtime exactly. Deliberately an allowlist: a format\n * missing from it loses its fast path, while a format wrongly added to it\n * silently accepts input the runtime rejects. Formats that layer extra\n * validation over a shape-only pattern (`credit_card`, `base64`, `ipv6`, …) are\n * handled above by hoisting the runtime validator itself.\n */\nconst PATTERN_IS_COMPLETE = new Set([\n    \"cidrv4\",\n    \"cuid\",\n    \"cuid2\",\n    \"date\",\n    \"datetime\",\n    \"duration\",\n    \"e164\",\n    \"email\",\n    \"emoji\",\n    \"ends_with\",\n    \"guid\",\n    \"includes\",\n    \"ipv4\",\n    \"ksuid\",\n    \"lowercase\",\n    \"mac\",\n    \"nanoid\",\n    \"regex\",\n    \"starts_with\",\n    \"time\",\n    \"ulid\",\n    \"uppercase\",\n    \"uuid\",\n    \"xid\",\n]);\nfunction generateStringFormatCheck(doc, ctx, def, accessor, needsValue = true) {\n    // Some string formats do runtime validation beyond their advertised pattern. For cheap pure utility checks, hoist the runtime function and call it so the fast path stays correct without cloning the utility logic into codegen.\n    const fmt = def.format;\n    if (fmt === \"base64\") {\n        const validator = addConstant(ctx, isValidBase64);\n        doc.write(`if (!${validator}(${accessor})) return INVALID;`);\n        return accessor;\n    }\n    if (fmt === \"base64url\") {\n        const validator = addConstant(ctx, isValidBase64URL);\n        doc.write(`if (!${validator}(${accessor})) return INVALID;`);\n        return accessor;\n    }\n    if (fmt === \"jwt\") {\n        const validator = addConstant(ctx, isValidJWT);\n        const alg = addConstant(ctx, def.alg ?? null);\n        doc.write(`if (!${validator}(${accessor}, ${alg})) return INVALID;`);\n        return accessor;\n    }\n    if (fmt === \"ipv6\") {\n        const validator = addConstant(ctx, isValidIPv6);\n        doc.write(`if (!${validator}(${accessor})) return INVALID;`);\n        return accessor;\n    }\n    if (fmt === \"cidrv6\") {\n        const validator = addConstant(ctx, isValidCIDRv6);\n        doc.write(`if (!${validator}(${accessor})) return INVALID;`);\n        return accessor;\n    }\n    if (fmt === \"credit_card\") {\n        const validator = addConstant(ctx, isValidCreditCard);\n        doc.write(`if (!${validator}(${accessor})) return INVALID;`);\n        return accessor;\n    }\n    if (fmt === \"iban\") {\n        const validator = addConstant(ctx, isValidIBAN);\n        doc.write(`if (!${validator}(${accessor})) return INVALID;`);\n        return accessor;\n    }\n    const formatDef = def;\n    if (fmt === \"url\" ||\n        fmt === \"httpurl\" ||\n        formatDef.normalize ||\n        formatDef.hostname !== undefined ||\n        formatDef.protocol !== undefined) {\n        // Same three predicates the runtime calls, in the same order, so there is no second URL implementation to drift. Which options exist is known now, so the calls the runtime makes conditionally are emitted conditionally instead.\n        const parseConst = addConstant(ctx, validateURL);\n        const defConst = addConstant(ctx, def);\n        const trimVar = newVar(ctx);\n        const urlVar = newVar(ctx);\n        doc.write(`const ${trimVar} = ${accessor}.trim();`);\n        doc.write(`const ${urlVar} = ${parseConst}(${trimVar}, ${defConst});`);\n        doc.write(`if (typeof ${urlVar} === \"number\") return INVALID;`);\n        if (formatDef.hostname !== undefined) {\n            const hostnameConst = addConstant(ctx, urlHostnameOk);\n            doc.write(`if (!${hostnameConst}(${urlVar}, ${defConst}.hostname)) return INVALID;`);\n        }\n        if (formatDef.protocol !== undefined) {\n            const protocolConst = addConstant(ctx, urlProtocolOk);\n            doc.write(`if (!${protocolConst}(${urlVar}, ${defConst}.protocol)) return INVALID;`);\n        }\n        if (!needsValue)\n            return null;\n        const outputVar = newVar(ctx);\n        const outputExpr = formatDef.normalize ? `${urlVar}.href` : `${addConstant(ctx, stripTabAndNewline)}(${trimVar})`;\n        doc.write(`const ${outputVar} = ${outputExpr};`);\n        return outputVar;\n    }\n    // A custom string format carries the predicate the runtime actually calls. Hoist and call it instead of testing `def.pattern`: the two only coincide when the format was built from a RegExp, and relying on that coupling is how supplemental validation gets dropped.\n    const customFn = def.fn;\n    if (customFn) {\n        if (isAsyncFunction(customFn))\n            throw new ZodCompileUnsupportedError(`async string format ${fmt}`);\n        const fnConst = addConstant(ctx, customFn);\n        doc.write(`if (!${fnConst}(${accessor})) return INVALID;`);\n        return accessor;\n    }\n    // Formats whose `pattern` IS the whole check. An allowlist rather than `if (def.pattern)`, because credit_card, base64 and ipv6 carry a shape-only pattern and validate the rest separately.\n    if (PATTERN_IS_COMPLETE.has(fmt) && def.pattern) {\n        const patternConst = addConstant(ctx, def.pattern);\n        doc.write(`${patternConst}.lastIndex = 0;`);\n        doc.write(`if (!${patternConst}.test(${accessor})) return INVALID;`);\n        return accessor;\n    }\n    const format = def.format;\n    switch (format) {\n        case \"regex\":\n            // A regex check with a pattern returned above. Reaching here means there is no pattern to test, and accepting unconditionally would pass every input, so hand the schema back to the runtime.\n            throw new ZodCompileUnsupportedError(\"regex format without a pattern\");\n        case \"lowercase\":\n            doc.write(`if (${accessor} !== ${accessor}.toLowerCase()) return INVALID;`);\n            break;\n        case \"uppercase\":\n            doc.write(`if (${accessor} !== ${accessor}.toUpperCase()) return INVALID;`);\n            break;\n        case \"includes\":\n            doc.write(`if (!${accessor}.includes(${util.esc(def.includes)})) return INVALID;`);\n            break;\n        case \"starts_with\": {\n            const prefix = def.prefix;\n            doc.write(`if (${accessor}.slice(0, ${prefix.length}) !== ${util.esc(prefix)}) return INVALID;`);\n            break;\n        }\n        case \"ends_with\": {\n            const suffix = def.suffix;\n            doc.write(`if (${accessor}.slice(-${suffix.length}) !== ${util.esc(suffix)}) return INVALID;`);\n            break;\n        }\n        default: {\n            void format;\n            throw new ZodCompileUnsupportedError(`string format ${format}`);\n        }\n    }\n    return accessor;\n}\nfunction generateCheck(doc, ctx, schema, accessor, needsValue = true) {\n    const def = schema._zod.def;\n    const type = def.type;\n    // A coercing schema would compile to the bare type test and reject what it should convert; inside a union that reads as a rejected branch, so refuse at codegen.\n    if (def.coerce) {\n        throw new ZodCompileUnsupportedError(`coercion (z.coerce.${type}())`);\n    }\n    // A node builds its output when its caller reads one, or when it carries checks of its own, since a check reads what was built. One polarity for the whole walk: this is what the node does, and it is what its children are told they need.\n    const buildsValue = needsValue || !!def.checks?.length;\n    let typeAccessor;\n    switch (type) {\n        case \"string\":\n            typeAccessor = generateStringCheck(doc, ctx, schema, accessor, buildsValue);\n            break;\n        case \"number\":\n            typeAccessor = generateNumberCheck(doc, schema, accessor);\n            break;\n        case \"boolean\":\n            typeAccessor = generateBooleanCheck(doc, accessor);\n            break;\n        case \"bigint\":\n            typeAccessor = generateBigIntCheck(doc, schema, accessor);\n            break;\n        case \"symbol\":\n            typeAccessor = generateSymbolCheck(doc, accessor);\n            break;\n        case \"undefined\":\n            typeAccessor = generateUndefinedCheck(doc, accessor);\n            break;\n        case \"null\":\n            typeAccessor = generateNullCheck(doc, accessor);\n            break;\n        case \"any\":\n        case \"unknown\":\n            // No check needed - pass through\n            typeAccessor = accessor;\n            break;\n        case \"never\":\n            doc.write(\"return INVALID;\");\n            typeAccessor = accessor;\n            break;\n        case \"void\":\n            typeAccessor = generateVoidCheck(doc, accessor);\n            break;\n        case \"nan\":\n            typeAccessor = generateNaNCheck(doc, accessor);\n            break;\n        case \"date\":\n            typeAccessor = generateDateCheck(doc, accessor);\n            break;\n        case \"object\":\n            typeAccessor = generateObjectCheck(doc, ctx, schema, accessor, buildsValue);\n            break;\n        case \"optional\":\n            typeAccessor = generateOptionalCheck(doc, ctx, schema, accessor, buildsValue);\n            break;\n        case \"nullable\":\n            typeAccessor = generateNullableCheck(doc, ctx, schema, accessor, buildsValue);\n            break;\n        case \"array\":\n            typeAccessor = generateArrayCheck(doc, ctx, schema, accessor, buildsValue);\n            break;\n        case \"literal\":\n            typeAccessor = generateLiteralCheck(doc, ctx, schema, accessor);\n            break;\n        case \"enum\":\n            typeAccessor = generateEnumCheck(doc, ctx, schema, accessor);\n            break;\n        case \"readonly\": {\n            const innerOut = generateWrapperCheck(doc, ctx, schema, accessor);\n            // Runtime freezes the parsed value (schemas.ts handleReadonlyResult).\n            const frozenVar = newVar(ctx);\n            doc.write(`const ${frozenVar} = Object.freeze(${innerOut});`);\n            typeAccessor = frozenVar;\n            break;\n        }\n        case \"success\":\n            // Runtime output is `issues.length === 0`. The fast path only reaches\n            // here when the inner check passed (failure returns INVALID and the\n            // runtime fallback reproduces the inner issues), so the output is\n            // always `true`.\n            generateWrapperCheck(doc, ctx, schema, accessor);\n            typeAccessor = \"true\";\n            break;\n        case \"default\":\n        case \"prefault\":\n            typeAccessor = generateDefaultCheck(doc, ctx, schema, accessor);\n            break;\n        case \"nonoptional\":\n            typeAccessor = generateNonOptionalCheck(doc, ctx, schema, accessor);\n            break;\n        case \"tuple\":\n            typeAccessor = generateTupleCheck(doc, ctx, schema, accessor);\n            break;\n        case \"union\":\n            typeAccessor = generateUnionCheck(doc, ctx, schema, accessor);\n            break;\n        case \"intersection\":\n            typeAccessor = generateIntersectionCheck(doc, ctx, schema, accessor);\n            break;\n        case \"record\":\n            typeAccessor = generateRecordCheck(doc, ctx, schema, accessor);\n            break;\n        case \"map\":\n            typeAccessor = generateMapCheck(doc, ctx, schema, accessor);\n            break;\n        case \"set\":\n            typeAccessor = generateSetCheck(doc, ctx, schema, accessor);\n            break;\n        case \"file\":\n            typeAccessor = generateFileCheck(doc, accessor);\n            break;\n        case \"template_literal\":\n            typeAccessor = generateTemplateLiteralCheck(doc, ctx, schema, accessor);\n            break;\n        case \"lazy\":\n            typeAccessor = generateLazyCheck(doc, ctx, schema, accessor);\n            break;\n        case \"pipe\":\n            typeAccessor = generatePipeCheck(doc, ctx, schema, accessor);\n            break;\n        case \"custom\":\n            typeAccessor = generateCustomCheck(doc, ctx, schema, accessor);\n            break;\n        case \"transform\":\n            typeAccessor = generateTransformCheck(doc, ctx, schema, accessor);\n            break;\n        case \"catch\":\n            typeAccessor = generateCatchCheck(doc, ctx, schema, accessor);\n            break;\n        default: {\n            void type;\n            throw new ZodCompileUnsupportedError(`schema type ${type}`);\n        }\n    }\n    // a node that built nothing has no checks to run: not building requires an empty check list\n    if (typeAccessor === null)\n        return null;\n    // Generate checks after the type-specific validation (may transform value)\n    return generateChecks(doc, ctx, schema, typeAccessor);\n}\nfunction generateStringCheck(doc, ctx, schema, accessor, needsValue = true) {\n    doc.write(`if (typeof ${accessor} !== \"string\") return INVALID;`);\n    // z.email() carries its format on the def, z.string().email() in def.checks; both route here so the format table has no second copy to drift from.\n    const def = schema._zod.def;\n    if (def.format === undefined)\n        return accessor;\n    return generateStringFormatCheck(doc, ctx, def, accessor, needsValue);\n}\nfunction generateNumberCheck(doc, schema, accessor) {\n    // Runtime z.number() rejects NaN and ±Infinity. Number.isFinite covers both.\n    doc.write(`if (typeof ${accessor} !== \"number\" || !Number.isFinite(${accessor})) return INVALID;`);\n    // Mini factories like z.int(), z.int32(), z.uint32(), z.float32() bake a number_format check into the schema def itself (not into def.checks). Apply the same constraint here.\n    const def = schema._zod.def;\n    if (def.check === \"number_format\" && def.format) {\n        generateNumberFormatCheck(doc, { format: def.format }, accessor);\n    }\n    return accessor;\n}\nfunction generateBooleanCheck(doc, accessor) {\n    doc.write(`if (typeof ${accessor} !== \"boolean\") return INVALID;`);\n    return accessor;\n}\nfunction generateBigIntCheck(doc, schema, accessor) {\n    doc.write(`if (typeof ${accessor} !== \"bigint\") return INVALID;`);\n    // Handle bigint format (int64, uint64) directly on the schema def\n    const def = schema._zod.def;\n    if (def.format) {\n        switch (def.format) {\n            case \"int64\":\n                doc.write(`if (${accessor} < -9223372036854775808n || ${accessor} > 9223372036854775807n) return INVALID;`);\n                break;\n            case \"uint64\":\n                doc.write(`if (${accessor} < 0n || ${accessor} > 18446744073709551615n) return INVALID;`);\n                break;\n        }\n    }\n    return accessor;\n}\nfunction generateSymbolCheck(doc, accessor) {\n    doc.write(`if (typeof ${accessor} !== \"symbol\") return INVALID;`);\n    return accessor;\n}\nfunction generateUndefinedCheck(doc, accessor) {\n    doc.write(`if (${accessor} !== undefined) return INVALID;`);\n    return accessor;\n}\nfunction generateNullCheck(doc, accessor) {\n    doc.write(`if (${accessor} !== null) return INVALID;`);\n    return accessor;\n}\nfunction generateVoidCheck(doc, accessor) {\n    doc.write(`if (${accessor} !== undefined) return INVALID;`);\n    return accessor;\n}\nfunction generateNaNCheck(doc, accessor) {\n    doc.write(`if (typeof ${accessor} !== \"number\" || !Number.isNaN(${accessor})) return INVALID;`);\n    return accessor;\n}\nfunction generateDateCheck(doc, accessor) {\n    doc.write(`if (!(${accessor} instanceof Date) || Number.isNaN(${accessor}.getTime())) return INVALID;`);\n    return accessor;\n}\nfunction generateObjectCheck(doc, ctx, schema, accessor, buildsValue = true) {\n    const def = schema._zod.def;\n    // Check that input is a non-null, non-array object\n    doc.write(`if (typeof ${accessor} !== \"object\" || ${accessor} === null || Array.isArray(${accessor})) return INVALID;`);\n    const shape = def.shape;\n    const keys = Object.keys(shape);\n    const symbolKeys = Object.getOwnPropertySymbols(shape);\n    // a symbol has no source literal, so it is hoisted as a constant; `keys` stays string-only where the emitted code uses `for...in`\n    const allKeys = symbolKeys.length ? [...keys, ...symbolKeys] : keys;\n    const keyExpr = (k) => (typeof k === \"symbol\" ? addConstant(ctx, k) : util.esc(k));\n    const propKey = (k) => (typeof k === \"symbol\" ? `[${keyExpr(k)}]` : util.esc(k));\n    const propShape = shape;\n    // `__proto__` as an own shape key can't be expressed in an output object literal (the literal form sets the prototype instead of an own property).\n    if (keys.includes(\"__proto__\")) {\n        throw new ZodCompileUnsupportedError('object shape key \"__proto__\"');\n    }\n    // Map from key to output accessor for that property\n    const propOutputs = new Map();\n    // Validate each property and collect output accessors\n    for (const key of allKeys) {\n        const propSchema = propShape[key];\n        const kx = keyExpr(key);\n        // Always cache the property read: the runtime reads input[key] exactly once, so a getter must not be re-read by checks or output assembly.\n        const inputVar = newVar(ctx);\n        doc.write(`const ${inputVar} = ${accessor}[${kx}];`);\n        if (propSchema._zod.optin !== undefined) {\n            // Any optin rung means the key may be omitted. The runtime runs the property anyway and ignores issues only when the key is genuinely absent, which is what makes exactOptional compositional.\n            const outputVar = newVar(ctx);\n            doc.write(`let ${outputVar} = (() => {`);\n            doc.indented((d) => {\n                const outputAccessor = compileChild(d, ctx, propSchema, inputVar);\n                d.write(`return ${outputAccessor};`);\n            });\n            doc.write(`})();`);\n            if (propSchema._zod.optout === \"optional\") {\n                doc.write(`if (${outputVar} === INVALID) {`);\n                doc.indented((d) => {\n                    d.write(`if (${kx} in ${accessor}) return INVALID;`);\n                    d.write(`${outputVar} = undefined;`);\n                });\n                doc.write(`}`);\n            }\n            else {\n                doc.write(`if (${outputVar} === INVALID) return INVALID;`);\n            }\n            propOutputs.set(key, outputVar);\n        }\n        else {\n            if (requiresPresenceCheck(propSchema)) {\n                doc.write(`if (!(${kx} in ${accessor})) return INVALID;`);\n            }\n            // Generate check and get output accessor\n            const outputAccessor = compileChild(doc, ctx, propSchema, inputVar, buildsValue);\n            if (outputAccessor !== null)\n                propOutputs.set(key, outputAccessor);\n        }\n    }\n    // Handle catchall\n    const catchall = def.catchall;\n    let unknownKeysMode = \"none\";\n    if (catchall) {\n        const catchallType = catchall._zod.def.type;\n        if (catchallType === \"never\") {\n            // Strict: one `for...in`, as the runtime does, so inherited enumerable keys count. An undeclared `__proto__` is reported here and excluded only from the output (#6221); an own-key count would wrongly reject a class instance.\n            const condition = keys.map((k) => `k !== ${util.esc(k)}`).join(\" && \") || \"true\";\n            doc.write(`for (const k in ${accessor}) {`);\n            doc.indented((d) => {\n                d.write(`if (${condition}) return INVALID;`);\n            });\n            doc.write(`}`);\n        }\n        else if ((catchallType === \"unknown\" || catchallType === \"any\") && !catchall._zod.def.checks?.length) {\n            unknownKeysMode = \"passthrough\";\n        }\n        else {\n            unknownKeysMode = \"schema\";\n        }\n    }\n    // else: strip mode (no catchall) - unknown keys ignored, only include known keys\n    // defaulted required outputs keep their keys even when undefined\n    const outputVar = newVar(ctx);\n    const hasConditionalKeys = allKeys.some((k) => mayOmitUndefined(propShape[k]) || dropsWhenAbsent(propShape[k]));\n    // Assert mode: every declared key is validated above, so the output literal and the unknown-key copy are pure waste. A `never` catchall already emitted its rejection loop; a schema catchall still has to validate the values it would otherwise have stored.\n    if (!buildsValue) {\n        if (unknownKeysMode === \"schema\") {\n            const knownSet = keys.length > 0 ? addConstant(ctx, new Set(keys)) : null;\n            doc.write(`for (const k in ${accessor}) {`);\n            doc.indented((d) => {\n                d.write(`if (k === \"__proto__\") continue;`);\n                if (knownSet)\n                    d.write(`if (${knownSet}.has(k)) continue;`);\n                const valVar = newVar(ctx);\n                d.write(`const ${valVar} = ${accessor}[k];`);\n                compileChild(d, ctx, catchall, valVar, false);\n            });\n            doc.write(`}`);\n        }\n        return null;\n    }\n    if (!hasConditionalKeys) {\n        const propLiterals = allKeys.map((k) => `${propKey(k)}: ${propOutputs.get(k)}`).join(\", \");\n        doc.write(`const ${outputVar} = { ${propLiterals} };`);\n    }\n    else {\n        doc.write(`const ${outputVar} = {};`);\n        for (const k of allKeys) {\n            const kx = keyExpr(k);\n            const out = propOutputs.get(k);\n            if (dropsWhenAbsent(propShape[k])) {\n                doc.write(`if (${kx} in ${accessor}) ${outputVar}[${kx}] = ${out};`);\n            }\n            else if (mayOmitUndefined(propShape[k])) {\n                doc.write(`if (${out} !== undefined || ${kx} in ${accessor}) ${outputVar}[${kx}] = ${out};`);\n            }\n            else {\n                doc.write(`${outputVar}[${kx}] = ${out};`);\n            }\n        }\n    }\n    if (unknownKeysMode !== \"none\") {\n        // Unknown keys are written directly into the output after shape keys — for...in (like the runtime) so inherited enumerables participate.\n        const knownSet = keys.length > 0 ? addConstant(ctx, new Set(keys)) : null;\n        doc.write(`for (const k in ${accessor}) {`);\n        doc.indented((d) => {\n            // Skip __proto__: assigning obj[\"__proto__\"] on a plain {} replaces the prototype via the setter rather than adding an own property. Mirrors the runtime catchall fix (#5898).\n            d.write(`if (k === \"__proto__\") continue;`);\n            if (knownSet)\n                d.write(`if (${knownSet}.has(k)) continue;`);\n            if (unknownKeysMode === \"passthrough\") {\n                d.write(`${outputVar}[k] = ${accessor}[k];`);\n            }\n            else {\n                const valVar = newVar(ctx);\n                d.write(`const ${valVar} = ${accessor}[k];`);\n                const catchallOut = compileChild(d, ctx, catchall, valVar);\n                d.write(`${outputVar}[k] = ${catchallOut};`);\n            }\n        });\n        doc.write(`}`);\n    }\n    return outputVar;\n}\nfunction generateOptionalCheck(doc, ctx, schema, accessor, buildsValue = true) {\n    const def = schema._zod.def;\n    if (isExactOptional(schema)) {\n        return generateCheck(doc, ctx, def.innerType, accessor, buildsValue);\n    }\n    // Same question $ZodOptional asks: only the top rung of the optin ladder substitutes a value for an absent input, so only it is worth running on `undefined`. Every other rung leaves the value intact, which is the skip branch below.\n    if (def.innerType._zod.optin === \"defaulted\") {\n        const outputVar = newVar(ctx);\n        const branchVar = newVar(ctx);\n        doc.write(`let ${outputVar};`);\n        doc.write(`if (${accessor} === undefined) {`);\n        doc.indented((d) => {\n            d.write(`const ${branchVar} = (() => {`);\n            d.indented((d2) => {\n                const innerOutput = generateCheck(d2, ctx, def.innerType, accessor);\n                d2.write(`return ${innerOutput};`);\n            });\n            d.write(`})();`);\n            d.write(`if (${branchVar} !== INVALID) ${outputVar} = ${branchVar};`);\n        });\n        doc.write(`} else {`);\n        doc.indented((d) => {\n            const innerOutput = generateCheck(d, ctx, def.innerType, accessor);\n            d.write(`${outputVar} = ${innerOutput};`);\n        });\n        doc.write(`}`);\n        return outputVar;\n    }\n    const outputVar = buildsValue ? newVar(ctx) : null;\n    if (outputVar)\n        doc.write(`let ${outputVar};`);\n    doc.write(`if (${accessor} !== undefined) {`);\n    doc.indented((d) => {\n        const innerOutput = generateCheck(d, ctx, def.innerType, accessor, buildsValue);\n        if (outputVar && innerOutput !== null)\n            d.write(`${outputVar} = ${innerOutput};`);\n    });\n    doc.write(`}`);\n    return outputVar;\n}\nfunction isExactOptional(schema) {\n    return schema._zod.traits?.has(\"$ZodExactOptional\") === true;\n}\n// A value-level fast path reads an absent key as `undefined`, so z.undefined(), z.any() and unions containing undefined would accept a missing property the runtime rejects.\nfunction requiresPresenceCheck(schema) {\n    return schema._zod.optin === undefined && fastPathAcceptsAbsence(schema);\n}\nfunction fastPathAcceptsAbsence(schema) {\n    // An island is handed `input[key]` and cannot tell absent from explicitly undefined, so report absence-accepting and let the object emit the presence guard (#6405).\n    if (schema._zod.def.coerce)\n        return true;\n    const def = schema._zod.def;\n    switch (def.type) {\n        case \"any\":\n        case \"unknown\":\n        case \"undefined\":\n        case \"void\":\n        case \"default\":\n        case \"prefault\":\n        case \"transform\":\n        case \"custom\":\n        case \"lazy\":\n            return true;\n        case \"string\":\n        case \"number\":\n        case \"boolean\":\n        case \"bigint\":\n        case \"symbol\":\n        case \"null\":\n        case \"never\":\n        case \"nan\":\n        case \"date\":\n        case \"object\":\n        case \"array\":\n        case \"tuple\":\n        case \"record\":\n        case \"map\":\n        case \"set\":\n        case \"file\":\n        case \"template_literal\":\n            return false;\n        case \"nonoptional\":\n            // Normally rejects an absent key, but not when something inside supplies a value for it: `.default(v).optional().nonoptional()` accepts absence and yields v. Defer to the inner — over-reporting here only costs a presence check, and a fast path that wrongly rejects still falls back to the runtime.\n            return def.innerType ? fastPathAcceptsAbsence(def.innerType) : false;\n        case \"literal\":\n            return !!def.values?.includes(undefined);\n        case \"enum\":\n            return !!schema._zod.values?.has(undefined);\n        case \"optional\":\n        case \"nullable\":\n        case \"readonly\":\n        case \"success\":\n            return def.innerType ? fastPathAcceptsAbsence(def.innerType) : true;\n        case \"catch\":\n            // catch always produces a value (inner may fail → catchValue substitutes), so it accepts an absent key regardless of inner.\n            return true;\n        case \"union\":\n            return def.options ? def.options.some(fastPathAcceptsAbsence) : true;\n        case \"intersection\":\n            if (!def.left || !def.right)\n                return true;\n            return fastPathAcceptsAbsence(def.left) && fastPathAcceptsAbsence(def.right);\n        case \"pipe\":\n            return def.in ? fastPathAcceptsAbsence(def.in) : true;\n        default:\n            return true;\n    }\n}\n/** The middle rung permits absence without supplying anything in its place, so an absent key contributes nothing — mirrors the leading gate in `handlePropertyResult`. */\nfunction dropsWhenAbsent(schema) {\n    return schema._zod.optin === \"optional\" && schema._zod.optout === \"optional\";\n}\nfunction mayOmitUndefined(schema) {\n    return (schema._zod.optin !== \"defaulted\" || schema._zod.optout === \"optional\") && mayOutputUndefined(schema);\n}\n// whether a schema's success-path output can be undefined\nfunction mayOutputUndefined(schema) {\n    const def = schema._zod.def;\n    switch (def.type) {\n        case \"string\":\n        case \"number\":\n        case \"boolean\":\n        case \"bigint\":\n        case \"symbol\":\n        case \"null\":\n        case \"nan\":\n        case \"date\":\n        case \"object\":\n        case \"array\":\n        case \"tuple\":\n        case \"record\":\n        case \"map\":\n        case \"set\":\n        case \"file\":\n        case \"template_literal\":\n        case \"never\":\n        case \"success\":\n            return false;\n        case \"literal\":\n            return !!def.values?.includes(undefined);\n        case \"enum\":\n            return !!schema._zod.values?.has(undefined);\n        case \"optional\":\n            return true;\n        case \"nullable\":\n        case \"readonly\":\n        case \"nonoptional\":\n            return def.innerType ? mayOutputUndefined(def.innerType) : true;\n        case \"union\":\n            return def.options ? def.options.some(mayOutputUndefined) : true;\n        case \"intersection\":\n            return !def.left || !def.right || mayOutputUndefined(def.left) || mayOutputUndefined(def.right);\n        case \"pipe\":\n            return def.out ? mayOutputUndefined(def.out) : true;\n        default:\n            // any/unknown/undefined/void/default/prefault/transform/custom/lazy/catch\n            return true;\n    }\n}\nfunction generateNullableCheck(doc, ctx, schema, accessor, buildsValue = true) {\n    const def = schema._zod.def;\n    const outputVar = buildsValue ? newVar(ctx) : null;\n    if (outputVar)\n        doc.write(`let ${outputVar} = null;`);\n    doc.write(`if (${accessor} !== null) {`);\n    doc.indented((d) => {\n        const innerOutput = generateCheck(d, ctx, def.innerType, accessor, buildsValue);\n        if (outputVar && innerOutput !== null)\n            d.write(`${outputVar} = ${innerOutput};`);\n    });\n    doc.write(`}`);\n    return outputVar;\n}\nfunction generateSizeGate(doc, schema, size) {\n    for (const [max, check] of util.sizeCaps(schema._zod.def.checks)) {\n        doc.write(`if (${size} > ${numericOperand(max, check._zod.def.check)}) return INVALID;`);\n    }\n}\nfunction generateArrayCheck(doc, ctx, schema, accessor, buildsValue = true) {\n    const def = schema._zod.def;\n    doc.write(`if (!Array.isArray(${accessor})) return INVALID;`);\n    generateSizeGate(doc, schema, `${accessor}.length`);\n    // Build a new array with validated/transformed elements.\n    const outputVar = buildsValue ? newVar(ctx) : null;\n    const iVar = newVar(ctx);\n    const elemVar = newVar(ctx);\n    if (outputVar)\n        doc.write(`const ${outputVar} = new Array(${accessor}.length);`);\n    doc.write(`for (let ${iVar} = 0; ${iVar} < ${accessor}.length; ${iVar}++) {`);\n    doc.indented((d) => {\n        d.write(`const ${elemVar} = ${accessor}[${iVar}];`);\n        const elemOutput = compileChild(d, ctx, def.element, elemVar, buildsValue);\n        if (outputVar && elemOutput !== null)\n            d.write(`${outputVar}[${iVar}] = ${elemOutput};`);\n    });\n    doc.write(`}`);\n    return outputVar;\n}\nfunction generateLiteralCheck(doc, ctx, schema, accessor) {\n    const def = schema._zod.def;\n    const values = def.values;\n    // Anything but a single value goes through Set.has: multi-value so every value participates, empty so nothing does — values[0] would be undefined and compile to an `!== undefined` check that accepts it. Single-value stays inlined for speed.\n    if (values.length !== 1) {\n        const literalSet = addConstant(ctx, new Set(values));\n        doc.write(`if (!${literalSet}.has(${accessor})) return INVALID;`);\n        return accessor;\n    }\n    const value = values[0];\n    // `$ZodLiteral` matches with `values.has`, i.e. SameValueZero, so NaN matches itself. `x !== NaN` is true for every input, which would reject everything — hand it to the same Set form the multi-value path uses.\n    if (typeof value === \"number\" && Number.isNaN(value)) {\n        const literalSet = addConstant(ctx, new Set(values));\n        doc.write(`if (!${literalSet}.has(${accessor})) return INVALID;`);\n        return accessor;\n    }\n    if (typeof value === \"string\") {\n        doc.write(`if (${accessor} !== ${util.esc(value)}) return INVALID;`);\n    }\n    else if (typeof value === \"number\" || typeof value === \"boolean\") {\n        doc.write(`if (${accessor} !== ${value}) return INVALID;`);\n    }\n    else if (value === null) {\n        doc.write(`if (${accessor} !== null) return INVALID;`);\n    }\n    else if (value === undefined) {\n        doc.write(`if (${accessor} !== undefined) return INVALID;`);\n    }\n    else if (typeof value === \"bigint\") {\n        doc.write(`if (${accessor} !== ${value}n) return INVALID;`);\n    }\n    else {\n        throw new ZodCompileUnsupportedError(`literal type ${typeof value}`);\n    }\n    return accessor;\n}\nfunction generateEnumCheck(doc, ctx, schema, accessor) {\n    const values = schema._zod.values;\n    // z.partialRecord and friends clear `_zod.values`, leaving no set to test membership against. Throw rather than emit INVALID so a union falls back whole instead of counting a false rejection.\n    if (!values) {\n        throw new ZodCompileUnsupportedError(\"enum schema without enumerated values\");\n    }\n    const enumSet = addConstant(ctx, values);\n    doc.write(`if (!${enumSet}.has(${accessor})) return INVALID;`);\n    return accessor;\n}\nfunction generateWrapperCheck(doc, ctx, schema, accessor) {\n    const def = schema._zod.def;\n    return generateCheck(doc, ctx, def.innerType, accessor);\n}\nfunction generateDefaultCheck(doc, ctx, schema, accessor) {\n    const def = schema._zod.def;\n    // `defaultValue` is an accessor on schemas built through the classic/mini\n    // factories and a plain data property on ones rebuilt programmatically\n    // (deepPartial and friends). Read it off the def either way — taking only\n    // `descriptor.get` silently dropped the default for the second kind, so\n    // `.default(v)` compiled to `undefined` instead of `v`.\n    const descriptor = Object.getOwnPropertyDescriptor(schema._zod.def, \"defaultValue\");\n    const defaultGetter = descriptor\n        ? () => schema._zod.def.defaultValue\n        : undefined;\n    // prefault differs from default: undefined-input is first replaced with the prefault value, then run through the inner schema.\n    if (schema._zod.def.type === \"prefault\") {\n        if (!defaultGetter) {\n            return generateCheck(doc, ctx, def.innerType, accessor);\n        }\n        const defaultFn = addConstant(ctx, defaultGetter);\n        const inputVar = newVar(ctx);\n        doc.write(`let ${inputVar} = ${accessor};`);\n        doc.write(`if (${accessor} === undefined) ${inputVar} = ${defaultFn}();`);\n        return generateCheck(doc, ctx, def.innerType, inputVar);\n    }\n    const outputVar = newVar(ctx);\n    // Default allows undefined (replaces with default value), otherwise validates inner type\n    if (defaultGetter) {\n        const defaultFn = addConstant(ctx, defaultGetter);\n        const cloneFn = addConstant(ctx, util.shallowClone);\n        doc.write(`let ${outputVar};`);\n        doc.write(`if (${accessor} === undefined) {`);\n        doc.indented((d) => {\n            // Shallow-clone the default so callers can mutate the result without affecting subsequent parses (#5855 — also covers Map/Set).\n            d.write(`${outputVar} = ${cloneFn}(${defaultFn}());`);\n        });\n        doc.write(`} else {`);\n        doc.indented((d) => {\n            const innerOutput = generateCheck(d, ctx, def.innerType, accessor);\n            d.write(`${outputVar} = ${innerOutput} === undefined ? ${cloneFn}(${defaultFn}()) : ${innerOutput};`);\n        });\n        doc.write(`}`);\n    }\n    else {\n        doc.write(`let ${outputVar};`);\n        doc.write(`if (${accessor} !== undefined) {`);\n        doc.indented((d) => {\n            const innerOutput = generateCheck(d, ctx, def.innerType, accessor);\n            d.write(`${outputVar} = ${innerOutput};`);\n        });\n        doc.write(`}`);\n    }\n    return outputVar;\n}\nfunction generateNonOptionalCheck(doc, ctx, schema, accessor) {\n    const def = schema._zod.def;\n    // The runtime inspects what the inner produced, not what it was given: a catch can turn a defined input into undefined, a default an absent one into a value.\n    const innerOutput = generateCheck(doc, ctx, def.innerType, accessor);\n    const outputVar = newVar(ctx);\n    doc.write(`const ${outputVar} = ${innerOutput};`);\n    doc.write(`if (${outputVar} === undefined) return INVALID;`);\n    return outputVar;\n}\nfunction generateTupleCheck(doc, ctx, schema, accessor) {\n    const def = schema._zod.def;\n    const items = def.items;\n    const rest = def.rest;\n    doc.write(`if (!Array.isArray(${accessor})) return INVALID;`);\n    // Mirror the runtime's getTupleOptStart: find the first index where every subsequent slot accepts `undefined` (i.e. is optional on input). Anything shorter than this is too_small; trailing absent slots are legal.\n    const optinStart = getTupleOptStart(items, \"optin\");\n    const optoutStart = getTupleOptStart(items, \"optout\");\n    // Length bounds\n    if (rest) {\n        // With rest: minimum length is the last required input slot\n        doc.write(`if (${accessor}.length < ${optinStart}) return INVALID;`);\n    }\n    else {\n        // No rest: input must be in [optinStart, items.length]\n        doc.write(`if (${accessor}.length < ${optinStart} || ${accessor}.length > ${items.length}) return INVALID;`);\n    }\n    // Build the output in assignment order so absent optional-output tail slots can truncate while default/prefault slots still fill missing positions.\n    const outputVar = newVar(ctx);\n    doc.write(`const ${outputVar} = [];`);\n    // Validate and collect each fixed item\n    for (let i = 0; i < items.length; i++) {\n        const itemSchema = items[i];\n        if (i >= optoutStart) {\n            doc.write(`if (${outputVar}.length === ${i}) {`);\n            doc.indented((d) => {\n                d.write(`if (${i} < ${accessor}.length) {`);\n                d.indented((d2) => {\n                    const elemVar = newVar(ctx);\n                    d2.write(`const ${elemVar} = ${accessor}[${i}];`);\n                    const elemOutput = compileChild(d2, ctx, itemSchema, elemVar);\n                    d2.write(`${outputVar}[${i}] = ${elemOutput};`);\n                });\n                d.write(`} else {`);\n                d.indented((d2) => {\n                    // Middle rung: absence supplies nothing in its place, so truncate rather than running the item on `undefined` and keeping what it invents. Mirrors the leading gate in `handleTupleResults`.\n                    if (dropsWhenAbsent(itemSchema)) {\n                        d2.write(`${outputVar}.length = ${i};`);\n                        return;\n                    }\n                    const elemVar = newVar(ctx);\n                    const branchVar = newVar(ctx);\n                    d2.write(`const ${elemVar} = undefined;`);\n                    d2.write(`const ${branchVar} = (() => {`);\n                    d2.indented((d3) => {\n                        const elemOutput = compileChild(d3, ctx, itemSchema, elemVar);\n                        d3.write(`return ${elemOutput};`);\n                    });\n                    d2.write(`})();`);\n                    d2.write(`if (${branchVar} === INVALID || ${branchVar} === undefined) ${outputVar}.length = ${i};`);\n                    d2.write(`else ${outputVar}[${i}] = ${branchVar};`);\n                });\n                d.write(`}`);\n            });\n            doc.write(`}`);\n        }\n        else {\n            const elemVar = newVar(ctx);\n            doc.write(`const ${elemVar} = ${accessor}[${i}];`);\n            const elemOutput = compileChild(doc, ctx, itemSchema, elemVar);\n            doc.write(`${outputVar}[${i}] = ${elemOutput};`);\n        }\n    }\n    // Validate and collect rest elements if present\n    if (rest) {\n        const iVar = newVar(ctx);\n        const elemVar = newVar(ctx);\n        doc.write(`for (let ${iVar} = ${items.length}; ${iVar} < ${accessor}.length; ${iVar}++) {`);\n        doc.indented((d) => {\n            d.write(`const ${elemVar} = ${accessor}[${iVar}];`);\n            const elemOutput = compileChild(d, ctx, rest, elemVar);\n            d.write(`${outputVar}[${iVar}] = ${elemOutput};`);\n        });\n        doc.write(`}`);\n    }\n    return outputVar;\n}\nfunction getTupleOptStart(items, key) {\n    for (let i = items.length - 1; i >= 0; i--) {\n        // Mirrors the runtime: optin is a three-rung ladder so any rung above `undefined` permits an absent slot; optout stays two-valued.\n        const omittable = key === \"optin\" ? items[i]._zod.optin !== undefined : items[i]._zod.optout === \"optional\";\n        if (!omittable)\n            return i + 1;\n    }\n    return 0;\n}\nfunction generateUnionCheck(doc, ctx, schema, accessor) {\n    const def = schema._zod.def;\n    const options = def.options;\n    if (def.discriminator) {\n        return generateDiscriminatedUnionCheck(doc, ctx, def, accessor);\n    }\n    // z.xor requires *exactly one* option to match. Match-counting in the fast path is only sound if every branch is exactly as strict as the runtime — any falsely-rejecting branch silently turns a multi-match rejection into an accept. Force the runtime for this rare combinator.\n    if (def.inclusive === false) {\n        throw new ZodCompileUnsupportedError(\"exclusive unions (z.xor)\");\n    }\n    if (options.length === 0) {\n        doc.write(\"return INVALID;\");\n        return accessor;\n    }\n    if (options.length === 1) {\n        return generateCheck(doc, ctx, options[0], accessor);\n    }\n    // Check if all options are bare literals - use Set optimization. A literal option carrying checks (e.g. .refine) must take the general path or the Set would accept values its checks reject.\n    const allLiterals = options.every((opt) => opt._zod.def.type === \"literal\" && !opt._zod.def.checks?.length);\n    if (allLiterals) {\n        const values = new Set(options.flatMap((opt) => opt._zod.def.values));\n        const valuesConst = addConstant(ctx, values);\n        doc.write(`if (!${valuesConst}.has(${accessor})) return INVALID;`);\n        return accessor;\n    }\n    // General case: try each option until one succeeds Use IIFEs that return the output or INVALID\n    const outputVar = newVar(ctx);\n    doc.write(`let ${outputVar};`);\n    for (let i = 0; i < options.length; i++) {\n        const opt = options[i];\n        if (i === 0) {\n            doc.write(`${outputVar} = (() => {`);\n        }\n        else {\n            doc.write(`if (${outputVar} === INVALID) ${outputVar} = (() => {`);\n        }\n        doc.indented((d) => {\n            // Generate check inside IIFE - returns INVALID on failure\n            const branchOutput = generateCheck(d, ctx, opt, accessor);\n            d.write(`return ${branchOutput};`);\n        });\n        doc.write(`})();`);\n    }\n    doc.write(`if (${outputVar} === INVALID) return INVALID;`);\n    return outputVar;\n}\nfunction generateDiscriminatedUnionCheck(doc, ctx, def, accessor) {\n    if (def.unionFallback) {\n        throw new ZodCompileUnsupportedError(\"discriminated union with unionFallback\");\n    }\n    if (def.options.length === 0) {\n        doc.write(\"return INVALID;\");\n        return accessor;\n    }\n    const discVar = newVar(ctx);\n    const outputVar = newVar(ctx);\n    doc.write(`const ${discVar} = ${accessor}?.[${util.esc(def.discriminator)}];`);\n    doc.write(`let ${outputVar};`);\n    let firstBranch = true;\n    const claimed = new Set();\n    for (const option of def.options) {\n        const values = option._zod.propValues?.[def.discriminator];\n        if (!values || values.size === 0) {\n            throw new ZodCompileUnsupportedError(\"discriminated union option without static discriminator values\");\n        }\n        // let the interpreter handle collisions instead of compiling first-match dispatch\n        for (const value of values) {\n            if (claimed.has(value)) {\n                throw new ZodCompileUnsupportedError(`duplicate discriminator value ${String(value)}`);\n            }\n            claimed.add(value);\n        }\n        const conditions = Array.from(values, (value) => literalEquality(ctx, discVar, value));\n        const prefix = firstBranch ? \"if\" : \"else if\";\n        doc.write(`${prefix} (${conditions.join(\" || \")}) {`);\n        doc.indented((d) => {\n            const branchOutput = generateCheck(d, ctx, option, accessor);\n            d.write(`${outputVar} = ${branchOutput};`);\n        });\n        doc.write(`}`);\n        firstBranch = false;\n    }\n    doc.write(`else { return INVALID; }`);\n    return outputVar;\n}\nfunction literalEquality(ctx, accessor, value) {\n    if (typeof value === \"string\")\n        return `${accessor} === ${util.esc(value)}`;\n    if (typeof value === \"number\") {\n        if (Number.isNaN(value))\n            return `Number.isNaN(${accessor})`;\n        return `${accessor} === ${value}`;\n    }\n    if (typeof value === \"boolean\")\n        return `${accessor} === ${value}`;\n    if (value === null)\n        return `${accessor} === null`;\n    if (value === undefined)\n        return `${accessor} === undefined`;\n    if (typeof value === \"bigint\")\n        return `${accessor} === ${value}n`;\n    if (typeof value === \"symbol\") {\n        const symbolConst = addConstant(ctx, value);\n        return `${accessor} === ${symbolConst}`;\n    }\n    throw new ZodCompileUnsupportedError(`literal discriminator value ${String(value)}`);\n}\nfunction generateIntersectionCheck(doc, ctx, schema, accessor) {\n    const def = schema._zod.def;\n    // An unmergeable merge, and a child failing before the merge is even reached, both return INVALID for a case the interpreter answers with a throw.\n    ctx.definite = false;\n    const leftOutput = compileChild(doc, ctx, def.left, accessor);\n    const rightOutput = compileChild(doc, ctx, def.right, accessor);\n    // Hoist the runtime merge helper so recursive object/array merge semantics stay in one place. If the merge is invalid, return INVALID and let the runtime fallback construct canonical errors.\n    const mergeConst = addConstant(ctx, mergeValues);\n    const mergedVar = newVar(ctx);\n    doc.write(`const ${mergedVar} = ${mergeConst}(${leftOutput}, ${rightOutput});`);\n    doc.write(`if (!${mergedVar}.valid) return INVALID;`);\n    return `${mergedVar}.data`;\n}\nfunction generateRecordCheck(doc, ctx, schema, accessor) {\n    const def = schema._zod.def;\n    // Use util.isPlainObject (rejects Date, Map, Set, class instances, etc.) to match runtime behavior. Hoisted call instead of inline so this stays a single source of truth with the runtime parser.\n    const isPlainObjectConst = addConstant(ctx, util.isPlainObject);\n    doc.write(`if (!${isPlainObjectConst}(${accessor})) return INVALID;`);\n    const outputVar = newVar(ctx);\n    const kVar = newVar(ctx);\n    const valVar = newVar(ctx);\n    doc.write(`const ${outputVar} = {};`);\n    // Exhaustive record. The runtime gates this on `values && !def.partial`, since z.partialRecord keeps its value set but makes every key optional; a loose record passes unrecognized keys through, which the per-key scan cannot express.\n    const recordDef = def;\n    const keyValues = recordDef.partial ? undefined : def.keyType._zod.values;\n    if (keyValues) {\n        const inputKeys = [];\n        for (const key of keyValues) {\n            if (!(typeof key === \"string\" || typeof key === \"number\" || typeof key === \"symbol\")) {\n                throw new ZodCompileUnsupportedError(`record key value ${String(key)}`);\n            }\n            const inputKey = typeof key === \"number\" ? key.toString() : key;\n            if (inputKey === \"__proto__\") {\n                // `out[\"__proto__\"] = v` would hit the prototype setter on the output.\n                throw new ZodCompileUnsupportedError('record key \"__proto__\"');\n            }\n            inputKeys.push(inputKey);\n            const keyConst = addConstant(ctx, key);\n            const outKey = generateCheck(doc, ctx, def.keyType, keyConst);\n            // Read the property once. Passing the raw expression let compileChild validate one read while the output write performed a second, so a getter could hand back a value nothing had checked.\n            const valueVar = newVar(ctx);\n            doc.write(`const ${valueVar} = ${accessor}[${literalPropertyKey(ctx, inputKey)}];`);\n            const valOutput = compileChild(doc, ctx, def.valueType, valueVar);\n            doc.write(`${outputVar}[${outKey}] = ${valOutput};`);\n        }\n        // `mode: \"loose\"` changes only what happens to unrecognized keys, so it belongs here rather than the per-present-key scan. Passing them through matches the runtime, which skips `__proto__`.\n        const knownKeysConst = addConstant(ctx, new Set(inputKeys));\n        doc.write(`for (const ${kVar} in ${accessor}) {`);\n        doc.indented((d) => {\n            d.write(`if (${knownKeysConst}.has(${kVar})) continue;`);\n            if (recordDef.mode === \"loose\") {\n                d.write(`if (${kVar} !== \"__proto__\") ${outputVar}[${kVar}] = ${accessor}[${kVar}];`);\n            }\n            else {\n                d.write(`return INVALID;`);\n            }\n        });\n        doc.write(`}`);\n        return outputVar;\n    }\n    // The bare-string shortcut below only tests `typeof key === \"string\"`, so it\n    // is correct exclusively for a `z.string()` carrying nothing else. A string\n    // *format* lives on the def rather than in `checks` — `z.record(z.email(), …)`\n    // reads as a plain string here — and coercion rewrites the key, so both have\n    // to take the general path or the shortcut accepts keys the runtime rejects.\n    const keyDef = def.keyType._zod.def;\n    const keyIsBareString = keyDef.type === \"string\" && keyDef.format === undefined && !keyDef.coerce && (keyDef.checks?.length ?? 0) === 0;\n    if (!keyIsBareString) {\n        // A key schema with no value set is a constraint every key must satisfy\n        // (`z.email()`, `z.string().min(3)`, `z.number()`, a template literal).\n        // The runtime runs it against each own enumerable key and writes the value\n        // under the key it produced, so compile it once and call it per key.\n        const isLoose = def.mode === \"loose\";\n        // the key compiles in its own context, so carry its verdict out: a key schema that can answer INVALID undecidably makes this validator undecidable too\n        const keyFn = compileFn(def.keyType);\n        if (keyFn.definite === false)\n            ctx.definite = false;\n        const keyFast = addConstant(ctx, keyFn);\n        const numericConst = addConstant(ctx, regexes.number);\n        const outKeyVar = newVar(ctx);\n        // the body runs once per string key and once per symbol key, since a key schema can accept symbols\n        emitOwnKeys(doc, ctx, accessor, kVar, (d) => {\n            d.write(`let ${outKeyVar} = ${keyFast}(${kVar});`);\n            // Numeric-string retry, mirroring the runtime: a key the schema rejects as a string is tried again as a number, so z.record(z.number(), …) matches the numeric keys JavaScript stringified on the way in.\n            d.write(`if (${outKeyVar} === INVALID && typeof ${kVar} === \"string\" && ${numericConst}.test(${kVar})) ${outKeyVar} = ${keyFast}(Number(${kVar}));`);\n            if (isLoose) {\n                // A loose record keeps a key its schema rejects, copying the value across unvalidated rather than failing the parse.\n                d.write(`if (${outKeyVar} === INVALID) { ${outputVar}[${kVar}] = ${accessor}[${kVar}]; continue; }`);\n            }\n            else {\n                d.write(`if (${outKeyVar} === INVALID) return INVALID;`);\n            }\n            // The guard above tested the input key, but the schema can normalize an ordinary key into __proto__; re-check the one actually written under.\n            d.write(`if (${outKeyVar} === \"__proto__\") continue;`);\n            // Read once: the raw expression would be evaluated again by the output write below, so an accessor could return an unvalidated second value.\n            const valueVar = newVar(ctx);\n            d.write(`const ${valueVar} = ${accessor}[${kVar}];`);\n            const valOutput = compileChild(d, ctx, def.valueType, valueVar);\n            d.write(`${outputVar}[${outKeyVar}] = ${valOutput};`);\n        });\n        return outputVar;\n    }\n    // Plain z.string() keys: every own enumerable string key's value is validated, and an own enumerable symbol key fails the string key schema, as it does in the runtime's Reflect.ownKeys walk.\n    emitOwnKeys(doc, ctx, accessor, kVar, (d) => {\n        d.write(`const ${valVar} = ${accessor}[${kVar}];`);\n        const valOutput = compileChild(d, ctx, def.valueType, valVar);\n        d.write(`${outputVar}[${kVar}] = ${valOutput};`);\n    }, `return INVALID;`);\n    return outputVar;\n}\n// Walks the own enumerable keys of a plain object in Reflect.ownKeys order — strings from getOwnPropertyNames, then symbols — instead of Reflect.ownKeys, whose accumulator made that walk 3–6x the cost of the loop it fed. Both snapshots are taken before any value is read and every key is rechecked with propertyIsEnumerable when visited, exactly the runtime's walk, so a getter that adds, deletes, hides or reveals a key mid-walk sees the runtime's verdict; for-in and Object.keys were no faster and each lost a case (for-in enumerates the prototype chain after the own keys, Object.keys drops a key that is non-enumerable at snapshot time). `body` is written once for the string loop and once for the symbol loop unless `onSymbol` replaces the latter.\nfunction emitOwnKeys(doc, ctx, accessor, kVar, body, onSymbol) {\n    const propIsEnumerableConst = addConstant(ctx, Object.prototype.propertyIsEnumerable);\n    const symsVar = newVar(ctx);\n    const keysVar = newVar(ctx);\n    const iVar = newVar(ctx);\n    doc.write(`const ${symsVar} = Object.getOwnPropertySymbols(${accessor});`);\n    doc.write(`const ${keysVar} = Object.getOwnPropertyNames(${accessor});`);\n    doc.write(`for (let ${iVar} = 0; ${iVar} < ${keysVar}.length; ${iVar}++) {`);\n    doc.indented((d) => {\n        d.write(`const ${kVar} = ${keysVar}[${iVar}];`);\n        d.write(`if (${kVar} === \"__proto__\" || !${propIsEnumerableConst}.call(${accessor}, ${kVar})) continue;`);\n        body(d);\n    });\n    doc.write(`}`);\n    doc.write(`for (let ${iVar} = 0; ${iVar} < ${symsVar}.length; ${iVar}++) {`);\n    doc.indented((d) => {\n        d.write(`const ${kVar} = ${symsVar}[${iVar}];`);\n        d.write(`if (!${propIsEnumerableConst}.call(${accessor}, ${kVar})) continue;`);\n        if (onSymbol)\n            d.write(onSymbol);\n        else\n            body(d);\n    });\n    doc.write(`}`);\n}\nfunction literalPropertyKey(ctx, key) {\n    if (typeof key === \"string\")\n        return util.esc(key);\n    return addConstant(ctx, key);\n}\nfunction generateMapCheck(doc, ctx, schema, accessor) {\n    const def = schema._zod.def;\n    doc.write(`if (!(${accessor} instanceof Map)) return INVALID;`);\n    generateSizeGate(doc, schema, `${accessor}.size`);\n    const outputVar = newVar(ctx);\n    const kVar = newVar(ctx);\n    const valVar = newVar(ctx);\n    doc.write(`const ${outputVar} = new Map();`);\n    doc.write(`for (const [${kVar}, ${valVar}] of ${accessor}) {`);\n    doc.indented((d) => {\n        const keyOutput = generateCheck(d, ctx, def.keyType, kVar);\n        const valOutput = generateCheck(d, ctx, def.valueType, valVar);\n        d.write(`${outputVar}.set(${keyOutput}, ${valOutput});`);\n    });\n    doc.write(`}`);\n    return outputVar;\n}\nfunction generateSetCheck(doc, ctx, schema, accessor) {\n    const def = schema._zod.def;\n    doc.write(`if (!(${accessor} instanceof Set)) return INVALID;`);\n    generateSizeGate(doc, schema, `${accessor}.size`);\n    const outputVar = newVar(ctx);\n    const valVar = newVar(ctx);\n    doc.write(`const ${outputVar} = new Set();`);\n    doc.write(`for (const ${valVar} of ${accessor}) {`);\n    doc.indented((d) => {\n        const valOutput = generateCheck(d, ctx, def.valueType, valVar);\n        d.write(`${outputVar}.add(${valOutput});`);\n    });\n    doc.write(`}`);\n    return outputVar;\n}\nfunction generateFileCheck(doc, accessor) {\n    // Runtime $ZodFile is a bare `instanceof File`, including the implicit global lookup. The previous duck-typed fallback accepted arbitrary {name, size} objects in File-less environments — behavior the runtime never had.\n    doc.write(`if (!(${accessor} instanceof File)) return INVALID;`);\n    return accessor;\n}\nfunction generateTemplateLiteralCheck(doc, ctx, schema, accessor) {\n    doc.write(`if (typeof ${accessor} !== \"string\") return INVALID;`);\n    // Template literal schemas have a pre-computed pattern in _zod.pattern\n    const pattern = schema._zod.pattern;\n    if (pattern) {\n        const patternConst = addConstant(ctx, pattern);\n        doc.write(`${patternConst}.lastIndex = 0;`);\n        doc.write(`if (!${patternConst}.test(${accessor})) return INVALID;`);\n    }\n    return accessor;\n}\nfunction generateLazyCheck(doc, ctx, schema, accessor) {\n    // For lazy schemas, we use a cached parser that falls back to runtime Zod parsing This handles recursive schemas correctly by avoiding infinite compilation loops\n    const def = schema._zod.def;\n    const getterConst = addUserConstant(ctx, def.getter);\n    const cacheConst = addConstant(ctx, { parser: null });\n    doc.write(`if (!${cacheConst}.parser) {`);\n    doc.indented((d) => {\n        d.write(`const inner = ${getterConst}();`);\n        d.write(`${cacheConst}.parser = function(input) {`);\n        d.indented((d2) => {\n            // Use runtime Zod parsing - this correctly handles recursive schemas Pass an empty ctx like runtimeRun does — runtime parsers read ctx.skipChecks/ctx.direction unconditionally and crash on undefined.\n            d2.write(`const result = inner._zod.run({ value: input, issues: [] }, {});`);\n            d2.write(`return result.issues.length === 0 ? result.value : INVALID;`);\n        });\n        d.write(`};`);\n    });\n    doc.write(`}`);\n    const outputVar = newVar(ctx);\n    doc.write(`const ${outputVar} = ${cacheConst}.parser(${accessor});`);\n    doc.write(`if (${outputVar} === INVALID) return INVALID;`);\n    return outputVar;\n}\nfunction generatePipeCheck(doc, ctx, schema, accessor) {\n    const def = schema._zod.def;\n    // Validate input type first\n    const inputOutput = generateCheck(doc, ctx, def.in, accessor);\n    if (def.transform) {\n        // Apply transform and validate output. The transform may read its second `payload` argument (codec transforms like z.stringbool() push issues there) so wrap the call in a helper that spoofs a payload. Pushed issues signal INVALID and the wrapper falls back to the runtime, and a plain function handing back a promise answers INVALID too — union parity, but not a decidable rejection at the top level.\n        if (isAsyncFunction(def.transform)) {\n            throw new ZodCompileAsyncError(\"z.compile: async transforms in pipes are not supported\");\n        }\n        const transformFn = def.transform;\n        const helperFn = (value) => {\n            // `addIssue` has to be here: a transform reporting through it is reporting, not failing. Without it the call threw a TypeError that the old catch swallowed into a fallback, so every ctx.addIssue transform quietly lost its fast path and the real error was never visible.\n            const fakePayload = { value, issues: [], addIssue: pushIssue };\n            // A throw is deliberately not caught. The interpreter lets one propagate out of the whole parse; swallowing it into INVALID turned a thrown error into a merely-rejected union branch, so a later branch answered instead.\n            const result = transformFn(value, fakePayload);\n            if (result instanceof Promise)\n                return INVALID;\n            return fakePayload.issues.length === 0 ? result : INVALID;\n        };\n        const helperConst = addUserConstant(ctx, helperFn);\n        const transformedVar = newVar(ctx);\n        doc.write(`const ${transformedVar} = ${helperConst}(${inputOutput});`);\n        doc.write(`if (${transformedVar} === INVALID) return INVALID;`);\n        return generateCheck(doc, ctx, def.out, transformedVar);\n    }\n    else {\n        // No transform - validate output type on same value\n        return generateCheck(doc, ctx, def.out, inputOutput);\n    }\n}\nfunction isAsyncFunction(fn) {\n    return (typeof fn === \"function\" &&\n        (fn.constructor.name === \"AsyncFunction\" ||\n            fn[Symbol.toStringTag] === \"AsyncFunction\"));\n}\nfunction generateCustomCheck(doc, ctx, schema, accessor) {\n    const def = schema._zod.def;\n    if (def.fn) {\n        // Check for async function\n        if (isAsyncFunction(def.fn)) {\n            throw new ZodCompileAsyncError(\"z.compile: async custom predicates are not supported\");\n        }\n        // Custom schema with a predicate function (e.g. z.instanceof). `isAsyncFunction` above is syntactic, so a plain function returning a promise reaches here, and a promise is truthy — it would read as a pass where the interpreter throws.\n        const fnConst = addUserConstant(ctx, def.fn);\n        const throwAsyncConst = addConstant(ctx, throwAsync);\n        const resVar = newVar(ctx);\n        doc.write(`const ${resVar} = ${fnConst}(${accessor});`);\n        doc.write(`if (${resVar} instanceof Promise) ${throwAsyncConst}();`);\n        doc.write(`if (!${resVar}) return INVALID;`);\n    }\n    else {\n        throw new ZodCompileUnsupportedError(\"custom schema without a predicate function\");\n    }\n    return accessor;\n}\n// Runtime helper for a compiled `catch`: runs the inner schema once and returns its value when it succeeded. Anything else — a failure the catch would handle, or an async inner — returns INVALID so the interpreter takes over.\nfunction runtimeCatch(innerSchema, catchValue, value) {\n    const result = innerSchema._zod.run({ value, issues: [] }, {});\n    if (result && typeof result.then === \"function\")\n        return INVALID;\n    const r = result;\n    if (r.issues.length === 0)\n        return r.value;\n    // Only reached for a catch value that ignores the parse context — codegen refuses the rest — so there are no issues to finalize and nothing here needs the caller's error map.\n    return catchValue();\n}\nfunction generateCatchCheck(doc, ctx, schema, accessor) {\n    const def = schema._zod.def;\n    // An untagged catchValue is a user callback, and one reading `ctx.error` needs the caller's per-parse error map. Catch *succeeds*, so a wrong message there is unobservable — refuse at codegen, and not islandable either, since `runtimeRun` has no context to hand it.\n    if (!def.catchValue[util.CONSTANT_CATCH]) {\n        throw new ZodCompileUnsupportedError(\"catch with a callback (only a constant catch value compiles)\", false);\n    }\n    const outputVar = newVar(ctx);\n    doc.write(`let ${outputVar} = (() => {`);\n    doc.indented((d) => {\n        const innerOut = compileChild(d, ctx, def.innerType, accessor);\n        d.write(`return ${innerOut};`);\n    });\n    doc.write(`})();`);\n    const innerConst = addConstant(ctx, def.innerType);\n    const catchConst = addUserConstant(ctx, def.catchValue);\n    const catchHelperConst = addConstant(ctx, runtimeCatch);\n    doc.write(`if (${outputVar} === INVALID) {`);\n    doc.indented((d) => {\n        d.write(`${outputVar} = ${catchHelperConst}(${innerConst}, ${catchConst}, ${accessor});`);\n        d.write(`if (${outputVar} === INVALID) return INVALID;`);\n    });\n    doc.write(`}`);\n    return outputVar;\n}\nfunction generateTransformCheck(doc, ctx, schema, accessor) {\n    const def = schema._zod.def;\n    if (def.transform) {\n        // Check for async transform\n        if (isAsyncFunction(def.transform)) {\n            throw new ZodCompileAsyncError(\"z.compile: async transforms are not supported\");\n        }\n        // Create a helper that runs the transform and returns the result or INVALID on error\n        const transformFn = def.transform;\n        const helperFn = (value) => {\n            const fakePayload = { value, issues: [], addIssue: pushIssue };\n            // As in the pipe helper: a throw propagates, because the interpreter lets it out of the whole parse rather than treating it as a failed branch.\n            const result = transformFn(value, fakePayload);\n            if (result instanceof Promise)\n                return INVALID;\n            return fakePayload.issues.length === 0 ? result : INVALID;\n        };\n        const helperConst = addUserConstant(ctx, helperFn);\n        const outputVar = newVar(ctx);\n        doc.write(`const ${outputVar} = ${helperConst}(${accessor});`);\n        doc.write(`if (${outputVar} === INVALID) return INVALID;`);\n        return outputVar;\n    }\n    return accessor;\n}\n","import * as checks from \"./checks.js\";\nimport * as registries from \"./registries.js\";\nimport * as schemas from \"./schemas.js\";\nimport * as util from \"./util.js\";\nfunction snapshotChecks(def) {\n    if (def.checks)\n        def.checks = [...def.checks];\n    return def;\n}\n// @__NO_SIDE_EFFECTS__\nexport function _string(Class, params) {\n    return new Class(snapshotChecks({ type: \"string\", ...util.normalizeParams(params) }));\n}\n// @__NO_SIDE_EFFECTS__\nexport function _coercedString(Class, params) {\n    return new Class(snapshotChecks({ type: \"string\", coerce: true, ...util.normalizeParams(params) }));\n}\n// @__NO_SIDE_EFFECTS__\nexport function _email(Class, params) {\n    return new Class({\n        type: \"string\",\n        format: \"email\",\n        check: \"string_format\",\n        abort: false,\n        ...util.normalizeParams(params),\n    });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _guid(Class, params) {\n    return new Class({\n        type: \"string\",\n        format: \"guid\",\n        check: \"string_format\",\n        abort: false,\n        ...util.normalizeParams(params),\n    });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _uuid(Class, params) {\n    return new Class({\n        type: \"string\",\n        format: \"uuid\",\n        check: \"string_format\",\n        abort: false,\n        ...util.normalizeParams(params),\n    });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _uuidv4(Class, params) {\n    return new Class({\n        type: \"string\",\n        format: \"uuid\",\n        check: \"string_format\",\n        abort: false,\n        version: \"v4\",\n        ...util.normalizeParams(params),\n    });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _uuidv6(Class, params) {\n    return new Class({\n        type: \"string\",\n        format: \"uuid\",\n        check: \"string_format\",\n        abort: false,\n        version: \"v6\",\n        ...util.normalizeParams(params),\n    });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _uuidv7(Class, params) {\n    return new Class({\n        type: \"string\",\n        format: \"uuid\",\n        check: \"string_format\",\n        abort: false,\n        version: \"v7\",\n        ...util.normalizeParams(params),\n    });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _url(Class, params) {\n    return new Class({\n        type: \"string\",\n        format: \"url\",\n        check: \"string_format\",\n        abort: false,\n        ...util.normalizeParams(params),\n    });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _emoji(Class, params) {\n    return new Class({\n        type: \"string\",\n        format: \"emoji\",\n        check: \"string_format\",\n        abort: false,\n        ...util.normalizeParams(params),\n    });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _nanoid(Class, params) {\n    return new Class({\n        type: \"string\",\n        format: \"nanoid\",\n        check: \"string_format\",\n        abort: false,\n        ...util.normalizeParams(params),\n    });\n}\n/**\n * @deprecated CUID v1 is deprecated by its authors due to information leakage\n * (timestamps embedded in the id). Use {@link _cuid2} instead.\n * See https://github.com/paralleldrive/cuid.\n */\n// @__NO_SIDE_EFFECTS__\nexport function _cuid(Class, params) {\n    return new Class({\n        type: \"string\",\n        format: \"cuid\",\n        check: \"string_format\",\n        abort: false,\n        ...util.normalizeParams(params),\n    });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _cuid2(Class, params) {\n    return new Class({\n        type: \"string\",\n        format: \"cuid2\",\n        check: \"string_format\",\n        abort: false,\n        ...util.normalizeParams(params),\n    });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _ulid(Class, params) {\n    return new Class({\n        type: \"string\",\n        format: \"ulid\",\n        check: \"string_format\",\n        abort: false,\n        ...util.normalizeParams(params),\n    });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _xid(Class, params) {\n    return new Class({\n        type: \"string\",\n        format: \"xid\",\n        check: \"string_format\",\n        abort: false,\n        ...util.normalizeParams(params),\n    });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _ksuid(Class, params) {\n    return new Class({\n        type: \"string\",\n        format: \"ksuid\",\n        check: \"string_format\",\n        abort: false,\n        ...util.normalizeParams(params),\n    });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _ipv4(Class, params) {\n    return new Class({\n        type: \"string\",\n        format: \"ipv4\",\n        check: \"string_format\",\n        abort: false,\n        ...util.normalizeParams(params),\n    });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _ipv6(Class, params) {\n    return new Class({\n        type: \"string\",\n        format: \"ipv6\",\n        check: \"string_format\",\n        abort: false,\n        ...util.normalizeParams(params),\n    });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _mac(Class, params) {\n    return new Class({\n        type: \"string\",\n        format: \"mac\",\n        check: \"string_format\",\n        abort: false,\n        ...util.normalizeParams(params),\n    });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _cidrv4(Class, params) {\n    return new Class({\n        type: \"string\",\n        format: \"cidrv4\",\n        check: \"string_format\",\n        abort: false,\n        ...util.normalizeParams(params),\n    });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _cidrv6(Class, params) {\n    return new Class({\n        type: \"string\",\n        format: \"cidrv6\",\n        check: \"string_format\",\n        abort: false,\n        ...util.normalizeParams(params),\n    });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _base64(Class, params) {\n    return new Class({\n        type: \"string\",\n        format: \"base64\",\n        check: \"string_format\",\n        abort: false,\n        ...util.normalizeParams(params),\n    });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _base64url(Class, params) {\n    return new Class({\n        type: \"string\",\n        format: \"base64url\",\n        check: \"string_format\",\n        abort: false,\n        ...util.normalizeParams(params),\n    });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _e164(Class, params) {\n    return new Class({\n        type: \"string\",\n        format: \"e164\",\n        check: \"string_format\",\n        abort: false,\n        ...util.normalizeParams(params),\n    });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _creditCard(Class, params) {\n    return new Class({\n        type: \"string\",\n        format: \"credit_card\",\n        check: \"string_format\",\n        abort: false,\n        ...util.normalizeParams(params),\n    });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _iban(Class, params) {\n    return new Class({\n        type: \"string\",\n        format: \"iban\",\n        check: \"string_format\",\n        abort: false,\n        ...util.normalizeParams(params),\n    });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _jwt(Class, params) {\n    return new Class({\n        type: \"string\",\n        format: \"jwt\",\n        check: \"string_format\",\n        abort: false,\n        ...util.normalizeParams(params),\n    });\n}\nexport const TimePrecision = {\n    Any: null,\n    Minute: -1,\n    Second: 0,\n    Millisecond: 3,\n    Microsecond: 6,\n};\n// @__NO_SIDE_EFFECTS__\nexport function _isoDateTime(Class, params) {\n    return new Class({\n        type: \"string\",\n        format: \"datetime\",\n        check: \"string_format\",\n        offset: false,\n        local: false,\n        precision: null,\n        ...util.normalizeParams(params),\n    });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _isoDate(Class, params) {\n    return new Class({\n        type: \"string\",\n        format: \"date\",\n        check: \"string_format\",\n        ...util.normalizeParams(params),\n    });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _isoTime(Class, params) {\n    return new Class({\n        type: \"string\",\n        format: \"time\",\n        check: \"string_format\",\n        precision: null,\n        ...util.normalizeParams(params),\n    });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _isoDuration(Class, params) {\n    return new Class({\n        type: \"string\",\n        format: \"duration\",\n        check: \"string_format\",\n        ...util.normalizeParams(params),\n    });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _number(Class, params) {\n    return new Class(snapshotChecks({ type: \"number\", checks: [], ...util.normalizeParams(params) }));\n}\n// @__NO_SIDE_EFFECTS__\nexport function _coercedNumber(Class, params) {\n    return new Class(snapshotChecks({ type: \"number\", coerce: true, checks: [], ...util.normalizeParams(params) }));\n}\n// @__NO_SIDE_EFFECTS__\nexport function _int(Class, params) {\n    return new Class({\n        type: \"number\",\n        check: \"number_format\",\n        abort: false,\n        format: \"safeint\",\n        ...util.normalizeParams(params),\n    });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _float32(Class, params) {\n    return new Class({\n        type: \"number\",\n        check: \"number_format\",\n        abort: false,\n        format: \"float32\",\n        ...util.normalizeParams(params),\n    });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _float64(Class, params) {\n    return new Class({\n        type: \"number\",\n        check: \"number_format\",\n        abort: false,\n        format: \"float64\",\n        ...util.normalizeParams(params),\n    });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _int32(Class, params) {\n    return new Class({\n        type: \"number\",\n        check: \"number_format\",\n        abort: false,\n        format: \"int32\",\n        ...util.normalizeParams(params),\n    });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _uint32(Class, params) {\n    return new Class({\n        type: \"number\",\n        check: \"number_format\",\n        abort: false,\n        format: \"uint32\",\n        ...util.normalizeParams(params),\n    });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _boolean(Class, params) {\n    return new Class({\n        type: \"boolean\",\n        ...util.normalizeParams(params),\n    });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _coercedBoolean(Class, params) {\n    return new Class({\n        type: \"boolean\",\n        coerce: true,\n        ...util.normalizeParams(params),\n    });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _bigint(Class, params) {\n    return new Class({\n        type: \"bigint\",\n        ...util.normalizeParams(params),\n    });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _coercedBigint(Class, params) {\n    return new Class({\n        type: \"bigint\",\n        coerce: true,\n        ...util.normalizeParams(params),\n    });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _int64(Class, params) {\n    return new Class({\n        type: \"bigint\",\n        check: \"bigint_format\",\n        abort: false,\n        format: \"int64\",\n        ...util.normalizeParams(params),\n    });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _uint64(Class, params) {\n    return new Class({\n        type: \"bigint\",\n        check: \"bigint_format\",\n        abort: false,\n        format: \"uint64\",\n        ...util.normalizeParams(params),\n    });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _symbol(Class, params) {\n    return new Class({\n        type: \"symbol\",\n        ...util.normalizeParams(params),\n    });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _undefined(Class, params) {\n    return new Class({\n        type: \"undefined\",\n        ...util.normalizeParams(params),\n    });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _null(Class, params) {\n    return new Class({\n        type: \"null\",\n        ...util.normalizeParams(params),\n    });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _any(Class) {\n    return new Class({\n        type: \"any\",\n    });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _unknown(Class) {\n    return new Class({\n        type: \"unknown\",\n    });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _never(Class, params) {\n    return new Class({\n        type: \"never\",\n        ...util.normalizeParams(params),\n    });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _void(Class, params) {\n    return new Class({\n        type: \"void\",\n        ...util.normalizeParams(params),\n    });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _date(Class, params) {\n    return new Class({\n        type: \"date\",\n        ...util.normalizeParams(params),\n    });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _coercedDate(Class, params) {\n    return new Class({\n        type: \"date\",\n        coerce: true,\n        ...util.normalizeParams(params),\n    });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _nan(Class, params) {\n    return new Class({\n        type: \"nan\",\n        ...util.normalizeParams(params),\n    });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _lt(value, params) {\n    return new checks.$ZodCheckLessThan({\n        check: \"less_than\",\n        ...util.normalizeParams(params),\n        value,\n        inclusive: false,\n    });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _lte(value, params) {\n    return new checks.$ZodCheckLessThan({\n        check: \"less_than\",\n        ...util.normalizeParams(params),\n        value,\n        inclusive: true,\n    });\n}\nexport { \n/** @deprecated Use `z.lte()` instead. */\n_lte as _max, };\n// @__NO_SIDE_EFFECTS__\nexport function _gt(value, params) {\n    return new checks.$ZodCheckGreaterThan({\n        check: \"greater_than\",\n        ...util.normalizeParams(params),\n        value,\n        inclusive: false,\n    });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _gte(value, params) {\n    return new checks.$ZodCheckGreaterThan({\n        check: \"greater_than\",\n        ...util.normalizeParams(params),\n        value,\n        inclusive: true,\n    });\n}\nexport { \n/** @deprecated Use `z.gte()` instead. */\n_gte as _min, };\n// @__NO_SIDE_EFFECTS__\nexport function _positive(params) {\n    return _gt(0, params);\n}\n// negative\n// @__NO_SIDE_EFFECTS__\nexport function _negative(params) {\n    return _lt(0, params);\n}\n// nonpositive\n// @__NO_SIDE_EFFECTS__\nexport function _nonpositive(params) {\n    return _lte(0, params);\n}\n// nonnegative\n// @__NO_SIDE_EFFECTS__\nexport function _nonnegative(params) {\n    return _gte(0, params);\n}\n// @__NO_SIDE_EFFECTS__\nexport function _multipleOf(value, params) {\n    return new checks.$ZodCheckMultipleOf({\n        check: \"multiple_of\",\n        ...util.normalizeParams(params),\n        value,\n    });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _maxSize(maximum, params) {\n    return new checks.$ZodCheckMaxSize({\n        check: \"max_size\",\n        ...util.normalizeParams(params),\n        maximum,\n    });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _minSize(minimum, params) {\n    return new checks.$ZodCheckMinSize({\n        check: \"min_size\",\n        ...util.normalizeParams(params),\n        minimum,\n    });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _size(size, params) {\n    return new checks.$ZodCheckSizeEquals({\n        check: \"size_equals\",\n        ...util.normalizeParams(params),\n        size,\n    });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _maxLength(maximum, params) {\n    const ch = new checks.$ZodCheckMaxLength({\n        check: \"max_length\",\n        ...util.normalizeParams(params),\n        maximum,\n    });\n    return ch;\n}\n// @__NO_SIDE_EFFECTS__\nexport function _minLength(minimum, params) {\n    return new checks.$ZodCheckMinLength({\n        check: \"min_length\",\n        ...util.normalizeParams(params),\n        minimum,\n    });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _length(length, params) {\n    return new checks.$ZodCheckLengthEquals({\n        check: \"length_equals\",\n        ...util.normalizeParams(params),\n        length,\n    });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _regex(pattern, params) {\n    return new checks.$ZodCheckRegex({\n        check: \"string_format\",\n        format: \"regex\",\n        ...util.normalizeParams(params),\n        pattern,\n    });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _lowercase(params) {\n    return new checks.$ZodCheckLowerCase({\n        check: \"string_format\",\n        format: \"lowercase\",\n        ...util.normalizeParams(params),\n    });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _uppercase(params) {\n    return new checks.$ZodCheckUpperCase({\n        check: \"string_format\",\n        format: \"uppercase\",\n        ...util.normalizeParams(params),\n    });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _includes(includes, params) {\n    return new checks.$ZodCheckIncludes({\n        check: \"string_format\",\n        format: \"includes\",\n        ...util.normalizeParams(params),\n        includes,\n    });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _startsWith(prefix, params) {\n    return new checks.$ZodCheckStartsWith({\n        check: \"string_format\",\n        format: \"starts_with\",\n        ...util.normalizeParams(params),\n        prefix,\n    });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _endsWith(suffix, params) {\n    return new checks.$ZodCheckEndsWith({\n        check: \"string_format\",\n        format: \"ends_with\",\n        ...util.normalizeParams(params),\n        suffix,\n    });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _property(property, schema, params) {\n    return new checks.$ZodCheckProperty({\n        check: \"property\",\n        property,\n        schema,\n        ...util.normalizeParams(params),\n    });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _properties(shape, params) {\n    return new checks.$ZodCheckProperties({\n        check: \"properties\",\n        shape,\n        ...util.normalizeParams(params),\n    });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _mime(types, params) {\n    return new checks.$ZodCheckMimeType({\n        check: \"mime_type\",\n        mime: types,\n        ...util.normalizeParams(params),\n    });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _overwrite(tx) {\n    return new checks.$ZodCheckOverwrite({\n        check: \"overwrite\",\n        tx,\n    });\n}\n// normalize\n// @__NO_SIDE_EFFECTS__\nexport function _normalize(form) {\n    return _overwrite((input) => input.normalize(form));\n}\n// trim\n// @__NO_SIDE_EFFECTS__\nexport function _trim() {\n    return _overwrite((input) => input.trim());\n}\n// toLowerCase\n// @__NO_SIDE_EFFECTS__\nexport function _toLowerCase() {\n    return _overwrite((input) => input.toLowerCase());\n}\n// toUpperCase\n// @__NO_SIDE_EFFECTS__\nexport function _toUpperCase() {\n    return _overwrite((input) => input.toUpperCase());\n}\n// slugify\n// @__NO_SIDE_EFFECTS__\nexport function _slugify() {\n    return _overwrite((input) => util.slugify(input));\n}\n// @__NO_SIDE_EFFECTS__\nexport function _array(Class, element, params) {\n    return new Class({\n        type: \"array\",\n        element,\n        // get element() {\n        //   return element;\n        // },\n        ...util.normalizeParams(params),\n    });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _union(Class, options, params) {\n    return new Class({\n        type: \"union\",\n        options,\n        ...util.normalizeParams(params),\n    });\n}\nexport function _xor(Class, options, params) {\n    return new Class({\n        type: \"union\",\n        options,\n        inclusive: false,\n        ...util.normalizeParams(params),\n    });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _discriminatedUnion(Class, discriminator, options, params) {\n    return new Class({\n        type: \"union\",\n        options: options,\n        discriminator,\n        ...util.normalizeParams(params),\n    });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _intersection(Class, left, right) {\n    return new Class({\n        type: \"intersection\",\n        left,\n        right,\n    });\n}\n// export function _tuple(\n//   Class: util.SchemaClass<schemas.$ZodTuple>,\n//   items: [],\n//   params?: string | $ZodTupleParams\n// ): schemas.$ZodTuple<[], null>;\n// @__NO_SIDE_EFFECTS__\nexport function _tuple(Class, items, _paramsOrRest, _params) {\n    const hasRest = _paramsOrRest instanceof schemas.$ZodType;\n    const params = hasRest ? _params : _paramsOrRest;\n    const rest = hasRest ? _paramsOrRest : null;\n    return new Class({\n        type: \"tuple\",\n        items,\n        rest,\n        ...util.normalizeParams(params),\n    });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _record(Class, keyType, valueType, params) {\n    return new Class({\n        type: \"record\",\n        keyType,\n        valueType,\n        ...util.normalizeParams(params),\n    });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _map(Class, keyType, valueType, params) {\n    return new Class({\n        type: \"map\",\n        keyType,\n        valueType,\n        ...util.normalizeParams(params),\n    });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _set(Class, valueType, params) {\n    return new Class({\n        type: \"set\",\n        valueType,\n        ...util.normalizeParams(params),\n    });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _enum(Class, values, params) {\n    const entries = Array.isArray(values) ? Object.fromEntries(values.map((v) => [v, v])) : values;\n    // if (Array.isArray(values)) {\n    //   for (const value of values) {\n    //     entries[value] = value;\n    //   }\n    // } else {\n    //   Object.assign(entries, values);\n    // }\n    // const entries: util.EnumLike = {};\n    // for (const val of values) {\n    //   entries[val] = val;\n    // }\n    return new Class({\n        type: \"enum\",\n        entries,\n        ...util.normalizeParams(params),\n    });\n}\n// @__NO_SIDE_EFFECTS__\n/** @deprecated This API has been merged into `z.enum()`. Use `z.enum()` instead.\n *\n * ```ts\n * enum Colors { red, green, blue }\n * z.enum(Colors);\n * ```\n */\nexport function _nativeEnum(Class, entries, params) {\n    return new Class({\n        type: \"enum\",\n        entries,\n        ...util.normalizeParams(params),\n    });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _literal(Class, value, params) {\n    return new Class({\n        type: \"literal\",\n        values: Array.isArray(value) ? value : [value],\n        ...util.normalizeParams(params),\n    });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _file(Class, params) {\n    return new Class({\n        type: \"file\",\n        ...util.normalizeParams(params),\n    });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _transform(Class, fn) {\n    return new Class({\n        type: \"transform\",\n        transform: fn,\n    });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _optional(Class, innerType) {\n    return new Class({\n        type: \"optional\",\n        innerType,\n    });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _nullable(Class, innerType) {\n    return new Class({\n        type: \"nullable\",\n        innerType,\n    });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _default(Class, innerType, defaultValue) {\n    return new Class({\n        type: \"default\",\n        innerType,\n        get defaultValue() {\n            return typeof defaultValue === \"function\" ? defaultValue() : util.shallowClone(defaultValue);\n        },\n    });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _nonoptional(Class, innerType, params) {\n    return new Class({\n        type: \"nonoptional\",\n        innerType,\n        ...util.normalizeParams(params),\n    });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _success(Class, innerType) {\n    return new Class({\n        type: \"success\",\n        innerType,\n    });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _catch(Class, innerType, catchValue) {\n    return new Class({\n        type: \"catch\",\n        innerType,\n        catchValue: (typeof catchValue === \"function\" ? catchValue : util.constantCatch(catchValue)),\n    });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _pipe(Class, in_, out) {\n    return new Class({\n        type: \"pipe\",\n        in: in_,\n        out,\n    });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _readonly(Class, innerType) {\n    return new Class({\n        type: \"readonly\",\n        innerType,\n    });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _templateLiteral(Class, parts, params) {\n    return new Class({\n        type: \"template_literal\",\n        parts,\n        ...util.normalizeParams(params),\n    });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _lazy(Class, getter) {\n    return new Class({\n        type: \"lazy\",\n        getter,\n    });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _promise(Class, innerType) {\n    return new Class({\n        type: \"promise\",\n        innerType,\n    });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _custom(Class, fn, _params) {\n    const norm = util.normalizeParams(_params);\n    norm.abort ?? (norm.abort = true); // default to abort:false\n    const schema = new Class({\n        type: \"custom\",\n        check: \"custom\",\n        fn: fn,\n        ...norm,\n    });\n    return schema;\n}\n// same as _custom but defaults to abort:false\n// @__NO_SIDE_EFFECTS__\nexport function _refine(Class, fn, _params) {\n    const schema = new Class({\n        type: \"custom\",\n        check: \"custom\",\n        fn: fn,\n        ...util.normalizeParams(_params),\n    });\n    return schema;\n}\n// @__NO_SIDE_EFFECTS__\nexport function _superRefine(fn, params) {\n    const ch = _check((payload) => {\n        payload.addIssue = (issue) => {\n            if (typeof issue === \"string\") {\n                payload.issues.push(util.issue(issue, payload.value, ch._zod.def));\n            }\n            else {\n                // for Zod 3 backwards compatibility\n                const _issue = issue;\n                if (_issue.fatal)\n                    _issue.continue = false;\n                _issue.code ?? (_issue.code = \"custom\");\n                if (!(\"input\" in _issue))\n                    _issue.input = payload.value;\n                _issue.inst ?? (_issue.inst = ch);\n                _issue.continue ?? (_issue.continue = !ch._zod.def.abort); // abort is always undefined, so this is always true...\n                payload.issues.push(util.issue(_issue));\n            }\n        };\n        return fn(payload.value, payload);\n    }, params);\n    return ch;\n}\n// @__NO_SIDE_EFFECTS__\nexport function _check(fn, params) {\n    const ch = new checks.$ZodCheck({\n        check: \"custom\",\n        ...util.normalizeParams(params),\n    });\n    ch._zod.check = fn;\n    return ch;\n}\n// @__NO_SIDE_EFFECTS__\nexport function describe(description) {\n    const ch = new checks.$ZodCheck({ check: \"describe\" });\n    ch._zod.onattach = [\n        (inst) => {\n            const existing = registries.globalRegistry.get(inst) ?? {};\n            registries.globalRegistry.add(inst, { ...existing, description });\n        },\n    ];\n    ch._zod.check = () => { }; // no-op check\n    return ch;\n}\n// @__NO_SIDE_EFFECTS__\nexport function meta(metadata) {\n    const ch = new checks.$ZodCheck({ check: \"meta\" });\n    ch._zod.onattach = [\n        (inst) => {\n            const existing = registries.globalRegistry.get(inst) ?? {};\n            registries.globalRegistry.add(inst, { ...existing, ...metadata });\n        },\n    ];\n    ch._zod.check = () => { }; // no-op check\n    return ch;\n}\n// @__NO_SIDE_EFFECTS__\nexport function _stringbool(Classes, _params) {\n    const params = util.normalizeParams(_params);\n    let truthyArray = params.truthy ?? [\"true\", \"1\", \"yes\", \"on\", \"y\", \"enabled\"];\n    let falsyArray = params.falsy ?? [\"false\", \"0\", \"no\", \"off\", \"n\", \"disabled\"];\n    if (params.case !== \"sensitive\") {\n        truthyArray = truthyArray.map((v) => (typeof v === \"string\" ? v.toLowerCase() : v));\n        falsyArray = falsyArray.map((v) => (typeof v === \"string\" ? v.toLowerCase() : v));\n    }\n    const truthySet = new Set(truthyArray);\n    const falsySet = new Set(falsyArray);\n    const _Codec = Classes.Codec ?? schemas.$ZodCodec;\n    const _Boolean = Classes.Boolean ?? schemas.$ZodBoolean;\n    const _String = Classes.String ?? schemas.$ZodString;\n    const stringSchema = new _String({ type: \"string\", error: params.error });\n    const booleanSchema = new _Boolean({ type: \"boolean\", error: params.error });\n    const codec = new _Codec({\n        type: \"pipe\",\n        in: stringSchema,\n        out: booleanSchema,\n        transform: ((input, payload) => {\n            let data = input;\n            if (params.case !== \"sensitive\")\n                data = data.toLowerCase();\n            if (truthySet.has(data)) {\n                return true;\n            }\n            else if (falsySet.has(data)) {\n                return false;\n            }\n            else {\n                payload.issues.push({\n                    code: \"invalid_value\",\n                    expected: \"stringbool\",\n                    values: [...truthySet, ...falsySet],\n                    input: payload.value,\n                    inst: codec,\n                    continue: false,\n                });\n                return {};\n            }\n        }),\n        reverseTransform: ((input, _payload) => {\n            if (input === true) {\n                return truthyArray[0] || \"true\";\n            }\n            else {\n                return falsyArray[0] || \"false\";\n            }\n        }),\n        error: params.error,\n    });\n    codec._zod.bag.truthy = truthyArray;\n    codec._zod.bag.falsy = falsyArray;\n    codec._zod.bag.case = params.case ?? \"insensitive\";\n    return codec;\n}\n// @__NO_SIDE_EFFECTS__\nexport function _stringFormat(Class, format, fnOrRegex, _params = {}) {\n    const params = util.normalizeParams(_params);\n    const def = {\n        check: \"string_format\",\n        type: \"string\",\n        format,\n        fn: typeof fnOrRegex === \"function\" ? fnOrRegex : (val) => fnOrRegex.test(val),\n        ...params,\n    };\n    if (fnOrRegex instanceof RegExp) {\n        def.pattern = fnOrRegex;\n    }\n    const inst = new Class(def);\n    return inst;\n}\n","import { globalRegistry } from \"./registries.js\";\nimport { assignProp } from \"./util.js\";\nfunction assignProps(target, ...sources) {\n    for (const source of sources) {\n        for (const key of Reflect.ownKeys(source)) {\n            if (Object.prototype.propertyIsEnumerable.call(source, key)) {\n                assignProp(target, key, source[key]);\n            }\n        }\n    }\n    return target;\n}\n// function initializeContext<T extends schemas.$ZodType>(inputs: JSONSchemaGeneratorParams<T>): ToJSONSchemaContext<T> {\n//   return {\n//     processor: inputs.processor,\n//     metadataRegistry: inputs.metadata ?? globalRegistry,\n//     target: inputs.target ?? \"draft-2020-12\",\n//     unrepresentable: inputs.unrepresentable ?? \"throw\",\n//   };\n// }\nexport function initializeContext(params) {\n    // Normalize target: convert old non-hyphenated versions to hyphenated versions\n    let target = params?.target ?? \"draft-2020-12\";\n    if (target === \"draft-4\")\n        target = \"draft-04\";\n    if (target === \"draft-7\")\n        target = \"draft-07\";\n    return {\n        processors: params.processors ?? {},\n        metadataRegistry: params?.metadata ?? globalRegistry,\n        target,\n        unrepresentable: params?.unrepresentable ?? \"throw\",\n        override: params?.override ?? (() => { }),\n        io: params?.io ?? \"output\",\n        counter: 0,\n        seen: new Map(),\n        sharedDefsExtractedFor: undefined,\n        sharedEmitDoneFor: undefined,\n        cycles: params?.cycles ?? \"ref\",\n        reused: params?.reused ?? \"inline\",\n        intersections: [],\n        deferred: [],\n        external: params?.external ?? undefined,\n    };\n}\n/**\n * Applies the `unrepresentable` setting at a site that has no JSON Schema equivalent. Throws\n * `message` unless the setting (or the handler's return value) says otherwise. Returns `true` if a\n * custom JSON Schema was written into `json`, in which case the caller must not write its own.\n */\nexport function handleUnrepresentable(schema, ctx, json, params, message) {\n    const result = typeof ctx.unrepresentable === \"function\"\n        ? ctx.unrepresentable({ zodSchema: schema, path: params.path, message })\n        : ctx.unrepresentable;\n    if (result === \"any\")\n        return false;\n    if (result === undefined || result === \"throw\")\n        throw new Error(message);\n    Object.assign(json, result);\n    return true;\n}\n// never rename this back to `process`: bundler polyfills inject a top-level `const process` that a lexical declaration of the same name collides with (#6397)\nexport function processSchema(schema, ctx, _params = { path: [], schemaPath: [] }) {\n    var _a;\n    const def = schema._zod.def;\n    // check for schema in seens\n    const seen = ctx.seen.get(schema);\n    if (seen) {\n        seen.count++;\n        // check if cycle\n        const isCycle = _params.schemaPath.includes(schema);\n        if (isCycle) {\n            seen.cycle = _params.path;\n        }\n        return seen.schema;\n    }\n    // initialize\n    const result = { schema: {}, count: 1, cycle: undefined, path: _params.path };\n    ctx.seen.set(schema, result);\n    ctx.sharedDefsExtractedFor = undefined;\n    ctx.sharedEmitDoneFor = undefined;\n    // custom method overrides default behavior\n    const overrideSchema = schema._zod.toJSONSchema?.();\n    if (overrideSchema) {\n        result.schema = overrideSchema;\n    }\n    else {\n        const params = {\n            ..._params,\n            schemaPath: [..._params.schemaPath, schema],\n            path: _params.path,\n        };\n        if (schema._zod.processJSONSchema) {\n            schema._zod.processJSONSchema(ctx, result.schema, params);\n        }\n        else {\n            const _json = result.schema;\n            const processor = ctx.processors[def.type];\n            if (!processor) {\n                throw new Error(`[toJSONSchema]: Non-representable type encountered: ${def.type}`);\n            }\n            processor(schema, ctx, _json, params);\n        }\n        const parent = schema._zod.parent;\n        if (parent) {\n            // Also set ref if processor didn't (for inheritance)\n            if (!result.ref)\n                result.ref = parent;\n            processSchema(parent, ctx, params);\n            ctx.seen.get(parent).isParent = true;\n        }\n    }\n    // metadata\n    const meta = ctx.metadataRegistry.get(schema);\n    if (meta)\n        assignProps(result.schema, meta);\n    if (ctx.io === \"input\" && isTransforming(schema)) {\n        // examples/defaults only apply to output type of pipe\n        delete result.schema.examples;\n        delete result.schema.default;\n    }\n    // set prefault as default\n    if (ctx.io === \"input\" && \"_prefault\" in result.schema)\n        (_a = result.schema).default ?? (_a.default = result.schema._prefault);\n    delete result.schema._prefault;\n    // pulling fresh from ctx.seen in case it was overwritten\n    const _result = ctx.seen.get(schema);\n    return _result.schema;\n}\n/** @deprecated Renamed to `processSchema`. An export alias declares no binding, so it is safe to keep. */\nexport { processSchema as process };\n// Escape a reference token for use in a JSON Pointer fragment (RFC 6901): `~` becomes `~0` and `/` becomes `~1`. The `~` replacement must run first.\nfunction encodeJSONPointerSegment(segment) {\n    return segment.replace(/~/g, \"~0\").replace(/\\//g, \"~1\");\n}\nexport function extractDefs(ctx, schema\n// params: EmitParams\n) {\n    // iterate over seen map;\n    const root = ctx.seen.get(schema);\n    if (!root)\n        throw new Error(\"Unprocessed schema. This is a bug in Zod.\");\n    // 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.\n    if (ctx.external && ctx.sharedDefsExtractedFor === ctx.external)\n        return;\n    // Track ids to detect duplicates across different schemas\n    const idToSchema = new Map();\n    for (const entry of ctx.seen.entries()) {\n        const id = ctx.metadataRegistry.get(entry[0])?.id;\n        if (id) {\n            const existing = idToSchema.get(id);\n            if (existing && existing !== entry[0]) {\n                throw new Error(`Duplicate schema id \"${id}\" detected during JSON Schema conversion. Two different schemas cannot share the same id when converted together.`);\n            }\n            idToSchema.set(id, entry[0]);\n        }\n    }\n    // returns a ref to the schema defId will be empty if the ref points to an external schema (or #)\n    const makeURI = (entry) => {\n        // comparing the seen objects because sometimes multiple schemas map to the same seen object. e.g. lazy\n        // external is configured\n        const defsSegment = ctx.target === \"draft-2020-12\" ? \"$defs\" : \"definitions\";\n        if (ctx.external) {\n            const externalId = ctx.external.registry.get(entry[0])?.id; // ?? \"__shared\";// `__schema${ctx.counter++}`;\n            // check if schema is in the external registry\n            const uriGenerator = ctx.external.uri ?? ((id) => id);\n            if (externalId) {\n                return { ref: uriGenerator(externalId) };\n            }\n            // otherwise, add to __shared\n            const id = entry[1].defId ?? entry[1].schema.id ?? `schema${ctx.counter++}`;\n            entry[1].defId = id; // set defId so it will be reused if needed\n            return { defId: id, ref: `${uriGenerator(\"__shared\")}#/${defsSegment}/${encodeJSONPointerSegment(id)}` };\n        }\n        const uriPrefix = `#`;\n        const defUriPrefix = `${uriPrefix}/${defsSegment}/`;\n        // an id-less root has nowhere to be extracted to, so it stays inline and self-references as `#`\n        if (entry[1] === root && !entry[1].schema.id) {\n            return { ref: uriPrefix };\n        }\n        // self-contained schema\n        const defId = entry[1].schema.id ?? `__schema${ctx.counter++}`;\n        return { defId, ref: defUriPrefix + encodeJSONPointerSegment(defId) };\n    };\n    // stored cached version in `def` property remove all properties, set $ref\n    const extractToDef = (entry) => {\n        // if the schema is already a reference, do not extract it\n        if (entry[1].schema.$ref) {\n            return;\n        }\n        const seen = entry[1];\n        const { ref, defId } = makeURI(entry);\n        seen.def = { ...seen.schema };\n        // defId won't be set if the schema is a reference to an external schema or if the schema is the root schema\n        if (defId)\n            seen.defId = defId;\n        // wipe away all properties except $ref\n        const schema = seen.schema;\n        for (const key in schema) {\n            delete schema[key];\n        }\n        schema.$ref = ref;\n    };\n    // throw on cycles\n    // break cycles\n    if (ctx.cycles === \"throw\") {\n        for (const entry of ctx.seen.entries()) {\n            const seen = entry[1];\n            if (seen.cycle) {\n                throw new Error(\"Cycle detected: \" +\n                    `#/${seen.cycle?.join(\"/\")}/<root>` +\n                    '\\n\\nSet the `cycles` parameter to `\"ref\"` to resolve cyclical schemas with defs.');\n            }\n        }\n    }\n    // extract schemas into $defs\n    for (const entry of ctx.seen.entries()) {\n        const seen = entry[1];\n        // convert root schema to # $ref\n        if (schema === entry[0]) {\n            extractToDef(entry); // this has special handling for the root schema\n            continue;\n        }\n        // extract schemas that are in the external registry\n        if (ctx.external) {\n            const ext = ctx.external.registry.get(entry[0])?.id;\n            if (schema !== entry[0] && ext) {\n                extractToDef(entry);\n                continue;\n            }\n        }\n        // extract schemas with `id` meta\n        const id = ctx.metadataRegistry.get(entry[0])?.id;\n        if (id) {\n            extractToDef(entry);\n            continue;\n        }\n        // break cycles\n        if (seen.cycle) {\n            // any\n            extractToDef(entry);\n            continue;\n        }\n        // extract reused schemas\n        if (seen.count > 1) {\n            if (ctx.reused === \"ref\") {\n                extractToDef(entry);\n            }\n        }\n    }\n    if (ctx.external)\n        ctx.sharedDefsExtractedFor = ctx.external;\n}\n/** 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. */\nfunction compactTypeUnion(schema) {\n    const options = schema.anyOf;\n    if (!Array.isArray(options) || options.length === 0 || schema.type !== undefined)\n        return;\n    const types = [];\n    for (const option of options) {\n        if (!option || typeof option !== \"object\")\n            return;\n        // 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.\n        compactTypeUnion(option);\n        const keys = Object.keys(option);\n        if (keys.length !== 1 || keys[0] !== \"type\")\n            return;\n        const type = option.type;\n        for (const member of Array.isArray(type) ? type : [type]) {\n            if (typeof member !== \"string\")\n                return;\n            if (!types.includes(member))\n                types.push(member);\n        }\n    }\n    delete schema.anyOf;\n    // A `type` array must be non-empty and unique (metaschema); a single member is spelled as a bare string.\n    schema.type = types.length === 1 ? types[0] : types;\n}\n/** Keywords `foldIntersection` knows how to combine. Anything else — `$ref`, `patternProperties`,\n * an annotation like `description` — makes a member unfoldable, so a constraint this does not\n * understand leaves the `allOf` alone instead of being silently dropped or misattributed. */\nconst FOLDABLE_KEYS = new Set([\"type\", \"properties\", \"required\", \"additionalProperties\"]);\nconst UNION_KEYS = [\"oneOf\", \"anyOf\"];\n/** 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. */\nfunction undeclaredConstraint(member) {\n    const extra = member.additionalProperties;\n    if (extra === undefined || extra === false || typeof extra !== \"object\" || extra === null)\n        return null;\n    return Object.keys(extra).length ? extra : null;\n}\n/** Combines object members into the single object they describe together, or returns `null` if any of them carries a keyword outside {@link FOLDABLE_KEYS}. */\nfunction foldObjects(members) {\n    const objects = [];\n    for (const member of members) {\n        // A boolean subschema is legal JSON Schema and carries no keywords to fold.\n        if (typeof member !== \"object\" || member.type !== \"object\")\n            return null;\n        for (const key in member) {\n            if (!FOLDABLE_KEYS.has(key))\n                return null;\n        }\n        objects.push(member);\n    }\n    const properties = {};\n    const required = new Set();\n    for (const object of objects) {\n        for (const key in object.properties) {\n            // `in` would report a `__proto__` key as already present via the prototype chain and skip it.\n            if (Object.prototype.hasOwnProperty.call(properties, key))\n                continue;\n            // 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.\n            const parts = [];\n            for (const other of objects) {\n                const part = other.properties?.[key] ?? undeclaredConstraint(other);\n                if (part === null || part === undefined)\n                    continue;\n                if (!parts.some((seen) => JSON.stringify(seen) === JSON.stringify(part)))\n                    parts.push(part);\n            }\n            const merged = parts.length === 1\n                ? parts[0]\n                : (foldObjects(parts) ?? { allOf: parts });\n            assignProp(properties, key, merged);\n        }\n        for (const key of object.required ?? [])\n            required.add(key);\n    }\n    const folded = { type: \"object\", properties };\n    if (required.size)\n        folded.required = [...required];\n    // 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.\n    if (objects.every((object) => object.additionalProperties === false)) {\n        folded.additionalProperties = false;\n    }\n    else {\n        const constraints = [];\n        for (const object of objects) {\n            const constraint = undeclaredConstraint(object);\n            if (constraint && !constraints.some((seen) => JSON.stringify(seen) === JSON.stringify(constraint)))\n                constraints.push(constraint);\n        }\n        if (constraints.length === 1)\n            folded.additionalProperties = constraints[0];\n        else if (constraints.length > 1)\n            folded.additionalProperties = { allOf: constraints };\n    }\n    return folded;\n}\n/** `additionalProperties` in an `allOf` member sees only that member's own `properties`, so two\n * closed object members reject each other's keys and the schema validates nothing. Zod's parser\n * pools the key sets instead — `handleIntersectionResults` reports a key as unrecognized only when\n * *every* side rejects it — so the emitted schema has to pool them too, and folding the members\n * into one object is the encoding that says so on every target.\n *\n * This runs from `finalize`, after `extractDefs`, which is what keeps it clear of the `$ref`\n * machinery: a member extracted into `$defs` is already a `$ref` by now and declines to fold, so it\n * keeps its reference and its own closedness rather than being inlined as a stale copy. */\nfunction foldIntersection(json) {\n    const allOf = json.allOf;\n    if (!Array.isArray(allOf) || allOf.length < 2)\n        return;\n    // 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.\n    for (const key of FOLDABLE_KEYS)\n        if (key in json)\n            return;\n    // 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.\n    const unions = allOf.filter((m) => UNION_KEYS.some((k) => Array.isArray(m[k])));\n    let folded = null;\n    if (!unions.length) {\n        folded = foldObjects(allOf);\n    }\n    else {\n        const union = unions[0];\n        const keyword = UNION_KEYS.find((k) => Array.isArray(union[k]));\n        if (Object.keys(union).length !== 1)\n            return;\n        const rest = allOf.filter((m) => m !== union);\n        const branches = union[keyword].map((branch) => foldObjects([...rest, branch]));\n        if (branches.some((b) => !b))\n            return;\n        folded = { [keyword]: branches };\n    }\n    if (!folded)\n        return;\n    delete json.allOf;\n    assignProps(json, folded);\n}\nexport function finalize(ctx, schema) {\n    const root = ctx.seen.get(schema);\n    if (!root)\n        throw new Error(\"Unprocessed schema. This is a bug in Zod.\");\n    // flatten refs - inherit properties from parent schemas\n    const flattenRef = (zodSchema) => {\n        const seen = ctx.seen.get(zodSchema);\n        // already processed\n        if (seen.ref === null)\n            return;\n        const schema = seen.def ?? seen.schema;\n        const _cached = { ...schema };\n        const ref = seen.ref;\n        seen.ref = null; // prevent infinite recursion\n        if (ref) {\n            flattenRef(ref);\n            const refSeen = ctx.seen.get(ref);\n            const refSchema = refSeen.schema;\n            // merge referenced schema into current\n            if (refSchema.$ref && (ctx.target === \"draft-07\" || ctx.target === \"draft-04\" || ctx.target === \"openapi-3.0\")) {\n                // older drafts can't combine $ref with other properties\n                schema.allOf = schema.allOf ?? [];\n                schema.allOf.push(refSchema);\n            }\n            else {\n                assignProps(schema, refSchema);\n            }\n            // restore child's own properties (child wins)\n            assignProps(schema, _cached);\n            const isParentRef = zodSchema._zod.parent === ref;\n            // For parent chain, child is a refinement - remove parent-only properties\n            if (isParentRef) {\n                for (const key in schema) {\n                    if (key === \"$ref\" || key === \"allOf\")\n                        continue;\n                    if (!(key in _cached)) {\n                        delete schema[key];\n                    }\n                }\n            }\n            // When ref was extracted to $defs, remove properties that match the definition\n            if (refSchema.$ref && refSeen.def) {\n                for (const key in schema) {\n                    if (key === \"$ref\" || key === \"allOf\")\n                        continue;\n                    if (key in refSeen.def && JSON.stringify(schema[key]) === JSON.stringify(refSeen.def[key])) {\n                        delete schema[key];\n                    }\n                }\n            }\n        }\n        // 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\n        const parent = zodSchema._zod.parent;\n        if (parent && parent !== ref) {\n            // Ensure parent is processed first so its def has inherited properties\n            flattenRef(parent);\n            const parentSeen = ctx.seen.get(parent);\n            if (parentSeen?.schema.$ref) {\n                schema.$ref = parentSeen.schema.$ref;\n                // De-duplicate with parent's definition\n                if (parentSeen.def) {\n                    for (const key in schema) {\n                        if (key === \"$ref\" || key === \"allOf\")\n                            continue;\n                        if (key in parentSeen.def && JSON.stringify(schema[key]) === JSON.stringify(parentSeen.def[key])) {\n                            delete schema[key];\n                        }\n                    }\n                }\n            }\n        }\n        // execute overrides\n        ctx.override({\n            zodSchema: zodSchema,\n            jsonSchema: schema,\n            path: seen.path ?? [],\n        });\n    };\n    // 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.\n    if (!ctx.external || ctx.sharedEmitDoneFor !== ctx.external) {\n        for (const entry of [...ctx.seen.entries()].reverse()) {\n            flattenRef(entry[0]);\n        }\n        if (ctx.target !== \"openapi-3.0\") {\n            for (const entry of ctx.seen.entries()) {\n                compactTypeUnion(entry[1].def ?? entry[1].schema);\n            }\n        }\n        for (const rewrite of ctx.deferred)\n            rewrite();\n        // 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.\n        if (ctx.intersections.length) {\n            const carriers = new Map();\n            for (const seen of ctx.seen.values()) {\n                for (const json of [seen.schema, seen.def]) {\n                    const allOf = json?.allOf;\n                    if (!Array.isArray(allOf))\n                        continue;\n                    const existing = carriers.get(allOf);\n                    if (existing)\n                        existing.push(json);\n                    else\n                        carriers.set(allOf, [json]);\n                }\n            }\n            for (const allOf of ctx.intersections) {\n                for (const json of carriers.get(allOf) ?? [])\n                    foldIntersection(json);\n            }\n        }\n    }\n    const result = {};\n    if (ctx.target === \"draft-2020-12\") {\n        result.$schema = \"https://json-schema.org/draft/2020-12/schema\";\n    }\n    else if (ctx.target === \"draft-07\") {\n        result.$schema = \"http://json-schema.org/draft-07/schema#\";\n    }\n    else if (ctx.target === \"draft-04\") {\n        result.$schema = \"http://json-schema.org/draft-04/schema#\";\n    }\n    else if (ctx.target === \"openapi-3.0\") {\n        // OpenAPI 3.0 schema objects should not include a $schema property\n    }\n    else {\n        // Arbitrary string values are allowed but won't have a $schema property set\n    }\n    if (ctx.external?.uri) {\n        const id = ctx.external.registry.get(schema)?.id;\n        if (!id)\n            throw new Error(\"Schema is missing an `id` property\");\n        result.$id = ctx.external.uri(id);\n    }\n    // when the root was extracted into $defs, `root.schema` is the `$ref` wrapper and `root.def` is the body that now lives under $defs\n    assignProps(result, root.defId ? root.schema : (root.def ?? root.schema));\n    // 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).\n    const rootMetaId = ctx.metadataRegistry.get(schema)?.id;\n    if (rootMetaId !== undefined && result.id === rootMetaId)\n        delete result.id;\n    // 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.\n    const defs = ctx.external?.defs ?? {};\n    if (!ctx.external || ctx.sharedEmitDoneFor !== ctx.external) {\n        for (const entry of ctx.seen.entries()) {\n            const seen = entry[1];\n            if (seen.def && seen.defId) {\n                if (seen.def.id === seen.defId)\n                    delete seen.def.id;\n                assignProp(defs, seen.defId, seen.def);\n            }\n        }\n    }\n    if (ctx.external)\n        ctx.sharedEmitDoneFor = ctx.external;\n    // set definitions in result\n    if (ctx.external) {\n    }\n    else {\n        if (Object.keys(defs).length > 0) {\n            if (ctx.target === \"draft-2020-12\") {\n                result.$defs = defs;\n            }\n            else {\n                result.definitions = defs;\n            }\n        }\n    }\n    try {\n        // this \"finalizes\" this schema and ensures all cycles are removed each call to finalize() is functionally independent though the seen map is shared\n        const finalized = JSON.parse(JSON.stringify(result));\n        Object.defineProperty(finalized, \"~standard\", {\n            value: {\n                ...schema[\"~standard\"],\n                jsonSchema: {\n                    input: createStandardJSONSchemaMethod(schema, \"input\", ctx.processors),\n                    output: createStandardJSONSchemaMethod(schema, \"output\", ctx.processors),\n                },\n            },\n            enumerable: false,\n            writable: false,\n        });\n        return finalized;\n    }\n    catch (_err) {\n        throw new Error(\"Error converting schema to JSON.\");\n    }\n}\nfunction isTransforming(_schema, _ctx) {\n    const ctx = _ctx ?? { seen: new Set() };\n    if (ctx.seen.has(_schema))\n        return false;\n    ctx.seen.add(_schema);\n    const def = _schema._zod.def;\n    if (def.type === \"transform\")\n        return true;\n    if (def.type === \"array\")\n        return isTransforming(def.element, ctx);\n    if (def.type === \"set\")\n        return isTransforming(def.valueType, ctx);\n    if (def.type === \"lazy\")\n        return isTransforming(def.getter(), ctx);\n    if (def.type === \"promise\" ||\n        def.type === \"optional\" ||\n        def.type === \"nonoptional\" ||\n        def.type === \"nullable\" ||\n        def.type === \"readonly\" ||\n        def.type === \"default\" ||\n        def.type === \"prefault\" ||\n        def.type === \"catch\") {\n        return isTransforming(def.innerType, ctx);\n    }\n    if (def.type === \"intersection\") {\n        return isTransforming(def.left, ctx) || isTransforming(def.right, ctx);\n    }\n    if (def.type === \"record\" || def.type === \"map\") {\n        return isTransforming(def.keyType, ctx) || isTransforming(def.valueType, ctx);\n    }\n    if (def.type === \"pipe\") {\n        if (_schema._zod.traits.has(\"$ZodCodec\"))\n            return true;\n        return isTransforming(def.in, ctx) || isTransforming(def.out, ctx);\n    }\n    if (def.type === \"object\") {\n        for (const key in def.shape) {\n            if (isTransforming(def.shape[key], ctx))\n                return true;\n        }\n        return false;\n    }\n    if (def.type === \"union\") {\n        for (const option of def.options) {\n            if (isTransforming(option, ctx))\n                return true;\n        }\n        return false;\n    }\n    if (def.type === \"tuple\") {\n        for (const item of def.items) {\n            if (isTransforming(item, ctx))\n                return true;\n        }\n        if (def.rest && isTransforming(def.rest, ctx))\n            return true;\n        return false;\n    }\n    return false;\n}\n/**\n * Creates a toJSONSchema method for a schema instance.\n * This encapsulates the logic of initializing context, processing, extracting defs, and finalizing.\n */\nexport const createToJSONSchemaMethod = (schema, processors = {}) => (params) => {\n    const ctx = initializeContext({ ...params, processors });\n    processSchema(schema, ctx);\n    extractDefs(ctx, schema);\n    return finalize(ctx, schema);\n};\nexport const createStandardJSONSchemaMethod = (schema, io, processors = {}) => (params) => {\n    const { libraryOptions, target } = params ?? {};\n    const ctx = initializeContext({ ...(libraryOptions ?? {}), target, io, processors });\n    processSchema(schema, ctx);\n    extractDefs(ctx, schema);\n    return finalize(ctx, schema);\n};\n","import * as regexes from \"./regexes.js\";\nimport { base64Charset, base64urlCharset } from \"./schemas.js\";\nimport { extractDefs, finalize, handleUnrepresentable, initializeContext, processSchema, } from \"./to-json-schema.js\";\nimport { BIGINT_FORMAT_RANGES, NUMBER_FORMAT_RANGES, assignProp, getEnumValues } from \"./util.js\";\nconst narrowMin = (agg, key, value) => {\n    if (agg[key] === undefined || value > agg[key])\n        agg[key] = value;\n};\nconst narrowMax = (agg, key, value) => {\n    if (agg[key] === undefined || value < agg[key])\n        agg[key] = value;\n};\nconst narrowBoth = (agg, value) => {\n    narrowMin(agg, \"minimum\", value);\n    narrowMax(agg, \"maximum\", value);\n};\nconst addDivisor = (agg, value) => {\n    agg.multipleOf ?? (agg.multipleOf = []);\n    if (!agg.multipleOf.includes(value))\n        agg.multipleOf.push(value);\n};\nconst addPattern = (agg, pattern) => {\n    agg.patterns ?? (agg.patterns = new Set());\n    agg.patterns.add(pattern);\n};\nconst intersectMime = (agg, mime) => {\n    agg.mime = agg.mime ? agg.mime.filter((m) => mime.includes(m)) : [...mime];\n};\n// last-wins, matching the bag's historical write order; the flag keeps an integer format from being lost to a later float one\nconst setFormat = (agg, format) => {\n    agg.format = format;\n    if (format.includes(\"int\"))\n        agg.isInt = true;\n};\nconst minContributor = (agg, def) => narrowMin(agg, \"minimum\", def.minimum);\nconst maxContributor = (agg, def) => narrowMax(agg, \"maximum\", def.maximum);\nconst formatContributor = (ranges) => (agg, def) => {\n    setFormat(agg, def.format);\n    const [minimum, maximum] = ranges[def.format];\n    narrowMin(agg, \"minimum\", minimum);\n    narrowMax(agg, \"maximum\", maximum);\n};\nconst contributors = {\n    greater_than: (agg, def) => narrowMin(agg, def.inclusive ? \"minimum\" : \"exclusiveMinimum\", def.value),\n    less_than: (agg, def) => narrowMax(agg, def.inclusive ? \"maximum\" : \"exclusiveMaximum\", def.value),\n    multiple_of: (agg, def) => addDivisor(agg, def.value),\n    number_format: formatContributor(NUMBER_FORMAT_RANGES),\n    bigint_format: formatContributor(BIGINT_FORMAT_RANGES),\n    min_length: minContributor,\n    max_length: maxContributor,\n    length_equals: (agg, def) => narrowBoth(agg, def.length),\n    min_size: minContributor,\n    max_size: maxContributor,\n    size_equals: (agg, def) => narrowBoth(agg, def.size),\n    string_format: (agg, def) => {\n        setFormat(agg, def.format);\n        if (def.pattern)\n            addPattern(agg, def.pattern);\n        if (def.format === \"base64\" || def.format === \"base64url\")\n            agg.contentEncoding = def.format;\n        if (def.local || def.precision === -1)\n            agg.laxFormat = true;\n    },\n    mime_type: (agg, def) => intersectMime(agg, def.mime),\n};\nexport function aggregateChecks(schema) {\n    const agg = {};\n    const def = schema._zod.def;\n    // a format schema is its own first check, same rule as $ZodType init\n    const list = schema._zod.traits.has(\"$ZodCheck\")\n        ? [schema, ...(def.checks ?? [])]\n        : (def.checks ?? []);\n    for (const ch of list)\n        contributors[ch._zod.def.check]?.(agg, ch._zod.def);\n    // reconcile with the bag so third-party onattach contributions still land; first-party residue is never tighter than the fold, so merging it back is idempotent for one and additive for the other\n    const bag = schema._zod.bag;\n    if (bag.minimum !== undefined)\n        narrowMin(agg, \"minimum\", bag.minimum);\n    if (bag.exclusiveMinimum !== undefined)\n        narrowMin(agg, \"exclusiveMinimum\", bag.exclusiveMinimum);\n    if (bag.maximum !== undefined)\n        narrowMax(agg, \"maximum\", bag.maximum);\n    if (bag.exclusiveMaximum !== undefined)\n        narrowMax(agg, \"exclusiveMaximum\", bag.exclusiveMaximum);\n    if (bag.multipleOf !== undefined)\n        addDivisor(agg, bag.multipleOf);\n    if (bag.format !== undefined) {\n        agg.format ?? (agg.format = bag.format);\n        if (bag.format.includes(\"int\"))\n            agg.isInt = true;\n    }\n    if (bag.mime)\n        intersectMime(agg, bag.mime);\n    for (const pattern of bag.patterns ?? [])\n        addPattern(agg, pattern);\n    return agg;\n}\nconst formatMap = {\n    guid: \"uuid\",\n    url: \"uri\",\n    datetime: \"date-time\",\n    json_string: \"json-string\",\n    regex: \"\", // do not set\n};\n// ==================== SIMPLE TYPE PROCESSORS ====================\n// the runtime patterns are lax so parse paths never overflow the regex stack; the emitted schema swaps in the exact block forms, which zod itself never executes\nconst exactPatterns = new Map([\n    [base64Charset, regexes.base64],\n    [base64urlCharset, regexes.base64url],\n]);\nconst exactPattern = (p) => exactPatterns.get(p) ?? p;\nexport const stringProcessor = (schema, ctx, _json, _params) => {\n    const json = _json;\n    json.type = \"string\";\n    const { minimum, maximum, format, patterns, contentEncoding, laxFormat } = aggregateChecks(schema);\n    if (typeof minimum === \"number\")\n        json.minLength = minimum;\n    if (typeof maximum === \"number\")\n        json.maxLength = maximum;\n    // custom pattern overrides format\n    if (format) {\n        json.format = formatMap[format] ?? format;\n        if (json.format === \"\")\n            delete json.format; // empty format is not valid\n        // `z.iso.time()` is never full-time, and `laxFormat` carries the datetime shapes that also accept what their keyword forbids\n        if (format === \"time\" || laxFormat) {\n            delete json.format;\n        }\n    }\n    if (contentEncoding)\n        json.contentEncoding = contentEncoding;\n    if (patterns && patterns.size > 0) {\n        const patternList = [...patterns].map(exactPattern);\n        if (patternList.length === 1)\n            json.pattern = patternList[0].source;\n        else if (patternList.length > 1) {\n            json.allOf = [\n                ...patternList.map((regex) => ({\n                    ...(ctx.target === \"draft-07\" || ctx.target === \"draft-04\" || ctx.target === \"openapi-3.0\"\n                        ? { type: \"string\" }\n                        : {}),\n                    pattern: regex.source,\n                })),\n            ];\n        }\n    }\n};\nexport const numberProcessor = (schema, ctx, _json, params) => {\n    const json = _json;\n    const { minimum, maximum, multipleOf, exclusiveMaximum, exclusiveMinimum, isInt } = aggregateChecks(schema);\n    json.type = isInt ? \"integer\" : \"number\";\n    // when both minimum and exclusiveMinimum exist, pick the more restrictive one\n    const exMin = typeof exclusiveMinimum === \"number\" && exclusiveMinimum >= (minimum ?? Number.NEGATIVE_INFINITY);\n    const exMax = typeof exclusiveMaximum === \"number\" && exclusiveMaximum <= (maximum ?? Number.POSITIVE_INFINITY);\n    const legacy = ctx.target === \"draft-04\" || ctx.target === \"openapi-3.0\";\n    if (exMin) {\n        if (legacy) {\n            json.minimum = exclusiveMinimum;\n            json.exclusiveMinimum = true;\n        }\n        else {\n            json.exclusiveMinimum = exclusiveMinimum;\n        }\n    }\n    else if (typeof minimum === \"number\") {\n        json.minimum = minimum;\n    }\n    if (exMax) {\n        if (legacy) {\n            json.maximum = exclusiveMaximum;\n            json.exclusiveMaximum = true;\n        }\n        else {\n            json.exclusiveMaximum = exclusiveMaximum;\n        }\n    }\n    else if (typeof maximum === \"number\") {\n        json.maximum = maximum;\n    }\n    if (multipleOf) {\n        // 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.\n        const divisors = new Set();\n        for (const divisor of multipleOf) {\n            if (Number.isFinite(divisor) && divisor !== 0)\n                divisors.add(Math.abs(divisor));\n            else\n                handleUnrepresentable(schema, ctx, json, params, `A multipleOf divisor of ${divisor} cannot be represented in JSON Schema`);\n        }\n        // chained divisors are a conjunction the keyword cannot carry alone, so extras ride an allOf, same as stacked patterns\n        const [first, ...rest] = divisors;\n        if (first !== undefined)\n            json.multipleOf = first;\n        if (rest.length)\n            json.allOf = [...(json.allOf ?? []), ...rest.map((m) => ({ multipleOf: m }))];\n    }\n};\nexport const booleanProcessor = (_schema, _ctx, json, _params) => {\n    json.type = \"boolean\";\n};\nexport const bigintProcessor = (schema, ctx, json, params) => {\n    handleUnrepresentable(schema, ctx, json, params, \"BigInt cannot be represented in JSON Schema\");\n};\nexport const symbolProcessor = (schema, ctx, json, params) => {\n    handleUnrepresentable(schema, ctx, json, params, \"Symbols cannot be represented in JSON Schema\");\n};\nexport const nullProcessor = (_schema, ctx, json, _params) => {\n    if (ctx.target === \"openapi-3.0\") {\n        json.type = \"string\";\n        json.nullable = true;\n        json.enum = [null];\n    }\n    else {\n        json.type = \"null\";\n    }\n};\nexport const undefinedProcessor = (schema, ctx, json, params) => {\n    handleUnrepresentable(schema, ctx, json, params, \"Undefined cannot be represented in JSON Schema\");\n};\nexport const voidProcessor = (schema, ctx, json, params) => {\n    handleUnrepresentable(schema, ctx, json, params, \"Void cannot be represented in JSON Schema\");\n};\nexport const neverProcessor = (_schema, _ctx, json, _params) => {\n    json.not = {};\n};\nexport const anyProcessor = (_schema, _ctx, _json, _params) => {\n    // empty schema accepts anything\n};\nexport const unknownProcessor = (_schema, _ctx, _json, _params) => {\n    // empty schema accepts anything\n};\nexport const dateProcessor = (schema, ctx, json, params) => {\n    handleUnrepresentable(schema, ctx, json, params, \"Date cannot be represented in JSON Schema\");\n};\nexport const enumProcessor = (schema, _ctx, json, _params) => {\n    const def = schema._zod.def;\n    const values = getEnumValues(def.entries);\n    // an empty enum accepts nothing, same as z.never()\n    if (values.length === 0) {\n        json.not = {};\n        return;\n    }\n    // Number enums can have both string and number values\n    if (values.every((v) => typeof v === \"number\"))\n        json.type = \"number\";\n    if (values.every((v) => typeof v === \"string\"))\n        json.type = \"string\";\n    json.enum = values;\n};\nexport const literalProcessor = (schema, ctx, json, params) => {\n    const def = schema._zod.def;\n    // a literal with no values accepts nothing, same as z.never()\n    if (def.values.length === 0) {\n        json.not = {};\n        return;\n    }\n    const vals = [];\n    for (const val of def.values) {\n        if (val === undefined) {\n            // a custom schema replaces the whole literal, so there is nothing left to accumulate\n            if (handleUnrepresentable(schema, ctx, json, params, \"Literal `undefined` cannot be represented in JSON Schema\"))\n                return;\n            // otherwise do not add to vals\n        }\n        else if (typeof val === \"bigint\") {\n            if (handleUnrepresentable(schema, ctx, json, params, \"BigInt literals cannot be represented in JSON Schema\"))\n                return;\n            vals.push(Number(val));\n        }\n        else {\n            vals.push(val);\n        }\n    }\n    if (vals.length === 0) {\n        // do nothing (an undefined literal was stripped)\n    }\n    else if (vals.length === 1) {\n        const val = vals[0];\n        json.type = val === null ? \"null\" : typeof val;\n        if (ctx.target === \"draft-04\" || ctx.target === \"openapi-3.0\") {\n            json.enum = [val];\n        }\n        else {\n            json.const = val;\n        }\n    }\n    else {\n        if (vals.every((v) => typeof v === \"number\"))\n            json.type = \"number\";\n        if (vals.every((v) => typeof v === \"string\"))\n            json.type = \"string\";\n        if (vals.every((v) => typeof v === \"boolean\"))\n            json.type = \"boolean\";\n        if (vals.every((v) => v === null))\n            json.type = \"null\";\n        json.enum = vals;\n    }\n};\nexport const nanProcessor = (schema, ctx, json, params) => {\n    handleUnrepresentable(schema, ctx, json, params, \"NaN cannot be represented in JSON Schema\");\n};\nexport const templateLiteralProcessor = (schema, _ctx, json, _params) => {\n    const _json = json;\n    const pattern = schema._zod.pattern;\n    if (!pattern)\n        throw new Error(\"Pattern not found in template literal\");\n    _json.type = \"string\";\n    _json.pattern = pattern.source;\n};\nexport const fileProcessor = (schema, _ctx, json, _params) => {\n    const _json = json;\n    _json.type = \"string\";\n    _json.format = \"binary\";\n    _json.contentEncoding = \"binary\";\n    const { minimum, maximum, mime } = aggregateChecks(schema);\n    if (minimum !== undefined)\n        _json.minLength = minimum;\n    if (maximum !== undefined)\n        _json.maxLength = maximum;\n    if (!mime)\n        return;\n    // an empty intersection means the mime checks share no value, so nothing passes at runtime; `anyOf` must be non-empty, so the false schema is `not: {}`\n    if (mime.length === 0)\n        _json.not = {};\n    else if (mime.length === 1)\n        _json.contentMediaType = mime[0];\n    // only contentMediaType differs, so the shared props stay at the root\n    else\n        _json.anyOf = mime.map((m) => ({ contentMediaType: m }));\n};\nexport const successProcessor = (_schema, _ctx, json, _params) => {\n    json.type = \"boolean\";\n};\nexport const customProcessor = (schema, ctx, json, params) => {\n    handleUnrepresentable(schema, ctx, json, params, \"Custom types cannot be represented in JSON Schema\");\n};\nexport const functionProcessor = (schema, ctx, json, params) => {\n    handleUnrepresentable(schema, ctx, json, params, \"Function types cannot be represented in JSON Schema\");\n};\nexport const transformProcessor = (schema, ctx, json, params) => {\n    handleUnrepresentable(schema, ctx, json, params, \"Transforms cannot be represented in JSON Schema\");\n};\nexport const mapProcessor = (schema, ctx, json, params) => {\n    handleUnrepresentable(schema, ctx, json, params, \"Map cannot be represented in JSON Schema\");\n};\nexport const setProcessor = (schema, ctx, json, params) => {\n    handleUnrepresentable(schema, ctx, json, params, \"Set cannot be represented in JSON Schema\");\n};\n// ==================== COMPOSITE TYPE PROCESSORS ====================\nexport const arrayProcessor = (schema, ctx, _json, params) => {\n    const json = _json;\n    const def = schema._zod.def;\n    const { minimum, maximum } = aggregateChecks(schema);\n    if (typeof minimum === \"number\")\n        json.minItems = minimum;\n    if (typeof maximum === \"number\")\n        json.maxItems = maximum;\n    json.type = \"array\";\n    json.items = processSchema(def.element, ctx, {\n        ...params,\n        path: [...params.path, \"items\"],\n    });\n};\n// Transform and catch set `optin = \"optional\"` at runtime so the parser lets them observe an\n// absent key, but their declared input type stays required. An input JSON Schema describes the\n// declared type, so resolve past them to the schema that actually carries the optionality.\n// Used by both `objectProcessor` (for `required`) and `tupleProcessor` (for `minItems`); see\n// wiki/optionality.md, \"The JSON Schema emitter reads the *static* value\".\nfunction inputOptin(schema) {\n    const def = schema._zod.def;\n    if (def.type === \"pipe\" && def.in._zod.traits.has(\"$ZodTransform\")) {\n        return inputOptin(def.out);\n    }\n    if (def.type === \"catch\") {\n        return inputOptin(def.innerType);\n    }\n    return schema._zod.optin;\n}\nexport const objectProcessor = (schema, ctx, _json, params) => {\n    const json = _json;\n    const def = schema._zod.def;\n    const shape = def.shape;\n    // dropping it while still emitting `additionalProperties: false` would emit a schema that rejects data this one requires\n    const symbolKeys = Object.getOwnPropertySymbols(shape);\n    if (symbolKeys.length &&\n        handleUnrepresentable(schema, ctx, json, params, \"Symbol keys cannot be represented in JSON Schema\")) {\n        return;\n    }\n    json.type = \"object\";\n    json.properties = {};\n    for (const key in shape) {\n        // assignProp so a __proto__ key becomes an own property instead of hitting the inherited setter on the plain {} we build into\n        assignProp(json.properties, key, processSchema(shape[key], ctx, {\n            ...params,\n            path: [...params.path, \"properties\", key],\n        }));\n    }\n    // required keys\n    const requiredKeys = [];\n    for (const key of Object.keys(shape)) {\n        const field = def.shape[key];\n        if (ctx.io === \"input\" ? inputOptin(field) === undefined : field._zod.optout === undefined) {\n            requiredKeys.push(key);\n        }\n    }\n    if (requiredKeys.length > 0) {\n        json.required = requiredKeys;\n    }\n    // catchall\n    if (def.catchall?._zod.def.type === \"never\") {\n        // strict\n        json.additionalProperties = false;\n    }\n    else if (!def.catchall) {\n        // regular\n        if (ctx.io === \"output\")\n            json.additionalProperties = false;\n    }\n    else if (def.catchall) {\n        json.additionalProperties = processSchema(def.catchall, ctx, {\n            ...params,\n            path: [...params.path, \"additionalProperties\"],\n        });\n    }\n};\nexport const unionProcessor = (schema, ctx, json, params) => {\n    const def = schema._zod.def;\n    // Exclusive unions (inclusive === false) use oneOf (exactly one match) instead of anyOf (one or more matches). This includes both z.xor() and discriminated unions\n    const isExclusive = def.inclusive === false;\n    const options = def.options.map((x, i) => processSchema(x, ctx, {\n        ...params,\n        path: [...params.path, isExclusive ? \"oneOf\" : \"anyOf\", i],\n    }));\n    if (isExclusive) {\n        json.oneOf = options;\n    }\n    else {\n        json.anyOf = options;\n    }\n};\nexport const intersectionProcessor = (schema, ctx, json, params) => {\n    const def = schema._zod.def;\n    const a = processSchema(def.left, ctx, {\n        ...params,\n        path: [...params.path, \"allOf\", 0],\n    });\n    const b = processSchema(def.right, ctx, {\n        ...params,\n        path: [...params.path, \"allOf\", 1],\n    });\n    const isSimpleIntersection = (val) => \"allOf\" in val && Object.keys(val).length === 1;\n    const allOf = [\n        ...(isSimpleIntersection(a) ? a.allOf : [a]),\n        ...(isSimpleIntersection(b) ? b.allOf : [b]),\n    ];\n    json.allOf = allOf;\n    // 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`.\n    ctx.intersections.push(allOf);\n};\nexport const tupleProcessor = (schema, ctx, _json, params) => {\n    const json = _json;\n    const def = schema._zod.def;\n    json.type = \"array\";\n    const prefixPath = ctx.target === \"draft-2020-12\" ? \"prefixItems\" : \"items\";\n    const restPath = ctx.target === \"draft-2020-12\" ? \"items\" : ctx.target === \"openapi-3.0\" ? \"items\" : \"additionalItems\";\n    const prefixItems = def.items.map((x, i) => processSchema(x, ctx, {\n        ...params,\n        path: [...params.path, prefixPath, i],\n    }));\n    const rest = def.rest\n        ? processSchema(def.rest, ctx, {\n            ...params,\n            path: [...params.path, restPath, ...(ctx.target === \"openapi-3.0\" ? [def.items.length] : [])],\n        })\n        : null;\n    let minItems = def.items.length;\n    while (minItems > 0) {\n        const item = def.items[minItems - 1];\n        const optional = ctx.io === \"input\" ? inputOptin(item) !== undefined : item._zod.optout === \"optional\";\n        if (!optional)\n            break;\n        minItems--;\n    }\n    const maxItems = def.items.length;\n    const isClosed = !def.rest;\n    if (ctx.target === \"draft-2020-12\") {\n        json.prefixItems = prefixItems;\n        if (isClosed) {\n            json.items = false;\n        }\n        else if (rest) {\n            json.items = rest;\n        }\n        if (minItems > 0)\n            json.minItems = minItems;\n        if (isClosed)\n            json.maxItems = maxItems;\n    }\n    else if (ctx.target === \"openapi-3.0\") {\n        json.items = {\n            anyOf: prefixItems,\n        };\n        if (rest) {\n            json.items.anyOf.push(rest);\n        }\n        if (minItems > 0)\n            json.minItems = minItems;\n        if (isClosed)\n            json.maxItems = maxItems;\n    }\n    else {\n        json.items = prefixItems;\n        if (isClosed) {\n            json.additionalItems = false;\n        }\n        else if (rest) {\n            json.additionalItems = rest;\n        }\n        if (minItems > 0)\n            json.minItems = minItems;\n        if (isClosed)\n            json.maxItems = maxItems;\n    }\n    // explicit user-defined length checks take precedence\n    const { minimum, maximum } = aggregateChecks(schema);\n    if (typeof minimum === \"number\")\n        json.minItems = minimum;\n    if (typeof maximum === \"number\")\n        json.maxItems = maximum;\n};\n/** JSON object keys are always strings, so a numeric record key schema is re-expressed over the\n * numeric-string form the record parser matches. Deferred to `finalize`, after the flatten: a key\n * behind a wrapper only carries its own `type` before then, and a union key only has its branches.\n *\n * A numeric bound cannot apply to a property name, so `minimum` and its siblings are dropped rather\n * than carried over: keeping them beside `type: \"string\"` reproduces the match-nothing schema this\n * exists to fix. A key that carries one therefore emits wider than the record parses — `z.record(z.number().min(5), V)`\n * accepts `\"3\"` — which is the deliberate trade, since throwing on it would reject an ordinary schema\n * outright. */\nfunction stringifyKeyNames(bySchema, json, visited) {\n    // 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`.\n    if (json.$ref) {\n        // a recursive key holds its own reference inside its definition, so a node already on the path is left alone rather than resolved again\n        if (visited.has(json))\n            return json;\n        visited.add(json);\n        const def = bySchema.get(json)?.def;\n        if (!def)\n            return json;\n        const inlined = stringifyKeyNames(bySchema, def, visited);\n        return inlined === def ? json : inlined;\n    }\n    for (const keyword of [\"anyOf\", \"oneOf\"]) {\n        const branches = json[keyword];\n        if (!Array.isArray(branches))\n            continue;\n        const mapped = branches.map((branch) => stringifyKeyNames(bySchema, branch, visited));\n        // rebuilding regardless would detach a key that had nothing to re-express, dropping its `$ref` and leaking the internal `id`\n        if (mapped.some((branch, i) => branch !== branches[i]))\n            json = { ...json, [keyword]: mapped };\n    }\n    // 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\n    const types = Array.isArray(json.type) ? json.type : [json.type];\n    const numericType = !types.includes(\"string\") && types.some((t) => t === \"number\" || t === \"integer\");\n    // a heterogeneous key carries no type at all, so its numeric members are caught here instead\n    const values = json.enum ?? (json.const !== undefined ? [json.const] : undefined);\n    if (!numericType && !values?.some((v) => typeof v === \"number\"))\n        return json;\n    const { minimum, maximum, exclusiveMinimum, exclusiveMaximum, multipleOf, format, id, ...rest } = json;\n    if (rest.enum)\n        rest.enum = rest.enum.map((v) => (typeof v === \"number\" ? String(v) : v));\n    else if (typeof rest.const === \"number\")\n        rest.const = String(rest.const);\n    // a heterogeneous key keeps its absent type: the stringified members already say what a key may be\n    if (!numericType)\n        return rest;\n    rest.type = \"string\";\n    if (!values)\n        rest.pattern = (types.includes(\"number\") ? regexes.number : regexes.integer).source;\n    return rest;\n}\n/** Every record of one conversion, so the carriers are found in a single pass rather than once per record. */\nconst pendingRecords = new WeakMap();\nfunction rewriteKeyNames(ctx) {\n    // 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.\n    const bySchema = new Map();\n    for (const entry of ctx.seen.values()) {\n        if (entry.def && !bySchema.has(entry.schema))\n            bySchema.set(entry.schema, entry);\n    }\n    const rewrites = new Map();\n    for (const record of pendingRecords.get(ctx) ?? []) {\n        const seen = ctx.seen.get(record);\n        const names = (seen?.def ?? seen?.schema)?.propertyNames;\n        if (!names || names === true || rewrites.has(names))\n            continue;\n        const rewritten = stringifyKeyNames(bySchema, names, new Set());\n        if (rewritten !== names)\n            rewrites.set(names, rewritten);\n    }\n    if (!rewrites.size)\n        return;\n    // 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\n    for (const entry of ctx.seen.values()) {\n        for (const carrier of [entry.schema, entry.def]) {\n            const rewritten = carrier && rewrites.get(carrier.propertyNames);\n            if (rewritten)\n                carrier.propertyNames = rewritten;\n        }\n    }\n}\nexport const recordProcessor = (schema, ctx, _json, params) => {\n    const json = _json;\n    const def = schema._zod.def;\n    json.type = \"object\";\n    // For looseRecord with regex patterns, use patternProperties. This correctly represents \"only validate keys matching the pattern\" semantics and composes well with allOf (intersections)\n    const keyType = def.keyType;\n    const patterns = aggregateChecks(keyType).patterns;\n    if (def.mode === \"loose\" && patterns && patterns.size > 0) {\n        // Use patternProperties for looseRecord with regex patterns\n        const valueSchema = processSchema(def.valueType, ctx, {\n            ...params,\n            path: [...params.path, \"patternProperties\", \"*\"],\n        });\n        json.patternProperties = {};\n        for (const pattern of patterns) {\n            assignProp(json.patternProperties, exactPattern(pattern).source, valueSchema);\n        }\n    }\n    else {\n        // Default behavior: use propertyNames + additionalProperties\n        if (ctx.target === \"draft-07\" || ctx.target === \"draft-2020-12\") {\n            json.propertyNames = processSchema(def.keyType, ctx, {\n                ...params,\n                path: [...params.path, \"propertyNames\"],\n            });\n            let pending = pendingRecords.get(ctx);\n            if (!pending) {\n                pending = [];\n                pendingRecords.set(ctx, pending);\n                ctx.deferred.push(() => rewriteKeyNames(ctx));\n            }\n            pending.push(schema);\n        }\n        json.additionalProperties = processSchema(def.valueType, ctx, {\n            ...params,\n            path: [...params.path, \"additionalProperties\"],\n        });\n    }\n    // Add required for keys with discrete values (enum, literal, etc.)\n    const keyValues = keyType._zod.values;\n    // 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.\n    const omittableOnInput = ctx.io === \"input\" && inputOptin(def.valueType) !== undefined;\n    if (keyValues && !def.partial && !omittableOnInput) {\n        const validKeyValues = [...keyValues].filter((v) => typeof v === \"string\" || typeof v === \"number\");\n        if (validKeyValues.length > 0) {\n            json.required = validKeyValues.map(String);\n        }\n    }\n};\nexport const nullableProcessor = (schema, ctx, json, params) => {\n    const def = schema._zod.def;\n    const inner = processSchema(def.innerType, ctx, params);\n    const seen = ctx.seen.get(schema);\n    if (ctx.target === \"openapi-3.0\") {\n        seen.ref = def.innerType;\n        json.nullable = true;\n    }\n    else {\n        json.anyOf = [inner, { type: \"null\" }];\n    }\n};\nexport const nonoptionalProcessor = (schema, ctx, _json, params) => {\n    const def = schema._zod.def;\n    processSchema(def.innerType, ctx, params);\n    const seen = ctx.seen.get(schema);\n    seen.ref = def.innerType;\n};\n/** Round-trips a default value through JSON so the emitted schema is guaranteed to be valid JSON.\n * A BigInt has no reliable encoding, so it goes through `unrepresentable` like any other\n * unrepresentable value. Returns a sentinel when the caller must not write a default of its own. */\nconst UNREPRESENTABLE_DEFAULT = Symbol();\nfunction serializeDefaultValue(value, schema, ctx, json, params) {\n    let unrepresentable = false;\n    const serialized = JSON.stringify(value, (_, val) => {\n        if (typeof val !== \"bigint\")\n            return val;\n        unrepresentable = true;\n        return null;\n    });\n    if (!unrepresentable)\n        return JSON.parse(serialized);\n    handleUnrepresentable(schema, ctx, json, params, \"BigInt defaults cannot be represented in JSON Schema\");\n    return UNREPRESENTABLE_DEFAULT;\n}\nexport const defaultProcessor = (schema, ctx, json, params) => {\n    const def = schema._zod.def;\n    processSchema(def.innerType, ctx, params);\n    const seen = ctx.seen.get(schema);\n    seen.ref = def.innerType;\n    const value = serializeDefaultValue(def.defaultValue, schema, ctx, json, params);\n    if (value !== UNREPRESENTABLE_DEFAULT)\n        json.default = value;\n};\nexport const prefaultProcessor = (schema, ctx, json, params) => {\n    const def = schema._zod.def;\n    processSchema(def.innerType, ctx, params);\n    const seen = ctx.seen.get(schema);\n    seen.ref = def.innerType;\n    if (ctx.io !== \"input\")\n        return;\n    const value = serializeDefaultValue(def.defaultValue, schema, ctx, json, params);\n    if (value !== UNREPRESENTABLE_DEFAULT)\n        json._prefault = value;\n};\nexport const catchProcessor = (schema, ctx, json, params) => {\n    const def = schema._zod.def;\n    processSchema(def.innerType, ctx, params);\n    const seen = ctx.seen.get(schema);\n    seen.ref = def.innerType;\n    let catchValue;\n    try {\n        catchValue = def.catchValue(undefined);\n    }\n    catch {\n        handleUnrepresentable(schema, ctx, json, params, \"Dynamic catch values are not supported in JSON Schema\");\n        return;\n    }\n    json.default = catchValue;\n};\nexport const pipeProcessor = (schema, ctx, _json, params) => {\n    const def = schema._zod.def;\n    const inIsTransform = def.in._zod.traits.has(\"$ZodTransform\");\n    const innerType = ctx.io === \"input\" ? (inIsTransform ? def.out : def.in) : def.out;\n    processSchema(innerType, ctx, params);\n    const seen = ctx.seen.get(schema);\n    seen.ref = innerType;\n};\nexport const readonlyProcessor = (schema, ctx, json, params) => {\n    const def = schema._zod.def;\n    processSchema(def.innerType, ctx, params);\n    const seen = ctx.seen.get(schema);\n    seen.ref = def.innerType;\n    json.readOnly = true;\n};\nexport const promiseProcessor = (schema, ctx, _json, params) => {\n    const def = schema._zod.def;\n    processSchema(def.innerType, ctx, params);\n    const seen = ctx.seen.get(schema);\n    seen.ref = def.innerType;\n};\nexport const optionalProcessor = (schema, ctx, _json, params) => {\n    const def = schema._zod.def;\n    processSchema(def.innerType, ctx, params);\n    const seen = ctx.seen.get(schema);\n    seen.ref = def.innerType;\n};\nexport const lazyProcessor = (schema, ctx, _json, params) => {\n    const innerType = schema._zod.innerType;\n    processSchema(innerType, ctx, params);\n    const seen = ctx.seen.get(schema);\n    seen.ref = innerType;\n};\n// ==================== ALL PROCESSORS ====================\nexport const allProcessors = {\n    string: stringProcessor,\n    number: numberProcessor,\n    boolean: booleanProcessor,\n    bigint: bigintProcessor,\n    symbol: symbolProcessor,\n    null: nullProcessor,\n    undefined: undefinedProcessor,\n    void: voidProcessor,\n    never: neverProcessor,\n    any: anyProcessor,\n    unknown: unknownProcessor,\n    date: dateProcessor,\n    enum: enumProcessor,\n    literal: literalProcessor,\n    nan: nanProcessor,\n    template_literal: templateLiteralProcessor,\n    file: fileProcessor,\n    success: successProcessor,\n    custom: customProcessor,\n    function: functionProcessor,\n    transform: transformProcessor,\n    map: mapProcessor,\n    set: setProcessor,\n    array: arrayProcessor,\n    object: objectProcessor,\n    union: unionProcessor,\n    intersection: intersectionProcessor,\n    tuple: tupleProcessor,\n    record: recordProcessor,\n    nullable: nullableProcessor,\n    nonoptional: nonoptionalProcessor,\n    default: defaultProcessor,\n    prefault: prefaultProcessor,\n    catch: catchProcessor,\n    pipe: pipeProcessor,\n    readonly: readonlyProcessor,\n    promise: promiseProcessor,\n    optional: optionalProcessor,\n    lazy: lazyProcessor,\n};\nexport function toJSONSchema(input, params) {\n    if (\"_idmap\" in input) {\n        // Registry case\n        const registry = input;\n        const ctx = initializeContext({ ...params, processors: allProcessors });\n        const defs = {};\n        // First pass: process all schemas to build the seen map\n        for (const entry of registry._idmap.entries()) {\n            const [_, schema] = entry;\n            processSchema(schema, ctx);\n        }\n        const schemas = {};\n        const external = {\n            registry,\n            uri: params?.uri,\n            defs,\n        };\n        // Update the context with external configuration\n        ctx.external = external;\n        // Second pass: emit each schema\n        for (const entry of registry._idmap.entries()) {\n            const [key, schema] = entry;\n            extractDefs(ctx, schema);\n            assignProp(schemas, key, finalize(ctx, schema));\n        }\n        if (Object.keys(defs).length > 0) {\n            const defsSegment = ctx.target === \"draft-2020-12\" ? \"$defs\" : \"definitions\";\n            schemas.__shared = {\n                [defsSegment]: defs,\n            };\n        }\n        return { schemas };\n    }\n    // Single schema case\n    const ctx = initializeContext({ ...params, processors: allProcessors });\n    processSchema(input, ctx);\n    extractDefs(ctx, input);\n    return finalize(ctx, input);\n}\n","export {};\n","export * from \"./core.js\";\nexport * from \"./parse.js\";\nexport * from \"./errors.js\";\nexport * from \"./schemas.js\";\nexport * from \"./memoizer.js\";\nexport * from \"./checks.js\";\nexport * from \"./versions.js\";\nexport * as util from \"./util.js\";\nexport { toZod } from \"./util.js\";\nexport * as regexes from \"./regexes.js\";\nexport * as locales from \"../locales/index.js\";\nexport * from \"./registries.js\";\nexport * from \"./doc.js\";\nexport * from \"./compile.js\";\nexport * from \"./api.js\";\nexport * from \"./to-json-schema.js\";\nexport { toJSONSchema } from \"./json-schema-processors.js\";\nexport { JSONSchemaGenerator } from \"./json-schema-generator.js\";\nexport * as JSONSchema from \"./json-schema.js\";\n","export { _lt as lt, _lte as lte, _gt as gt, _gte as gte, _positive as positive, _negative as negative, _nonpositive as nonpositive, _nonnegative as nonnegative, _multipleOf as multipleOf, _maxSize as maxSize, _minSize as minSize, _size as size, _maxLength as maxLength, _minLength as minLength, _length as length, _regex as regex, _lowercase as lowercase, _uppercase as uppercase, _includes as includes, _startsWith as startsWith, _endsWith as endsWith, _property as property, _properties as properties, _mime as mime, _overwrite as overwrite, _normalize as normalize, _trim as trim, _toLowerCase as toLowerCase, _toUpperCase as toUpperCase, _slugify as slugify, } from \"../core/index.js\";\n","import * as core from \"../core/index.js\";\nimport { $ZodError } from \"../core/index.js\";\nimport * as util from \"../core/util.js\";\n/* Prototypes that already carry the lazy helper methods. Seeded with the\n * intrinsics so that `init` on a foreign object — it accepts any object —\n * can never install an accessor onto a prototype we do not own. */\nconst _installedErrorProtos = /* @__PURE__ */ new WeakSet([Object.prototype, Error.prototype]);\n/* Helper methods live as non-enumerable lazy getters on the shared\n * prototype instead of own properties on every instance. On first\n * access the getter allocates the per-instance closure and caches it\n * as a non-enumerable own property, so detached usage still works and\n * the allocation only happens for methods actually touched. */\nfunction _lazyMethod(proto, key, make) {\n    Object.defineProperty(proto, key, {\n        configurable: true,\n        enumerable: false,\n        get() {\n            const value = make(this);\n            Object.defineProperty(this, key, { value, configurable: true, writable: true });\n            return value;\n        },\n        set(value) {\n            Object.defineProperty(this, key, { value, configurable: true, writable: true });\n        },\n    });\n}\nconst initializer = (inst, issues) => {\n    $ZodError.init(inst, issues);\n    inst.name = \"ZodError\";\n    const proto = Object.getPrototypeOf(inst);\n    if (_installedErrorProtos.has(proto))\n        return;\n    _installedErrorProtos.add(proto);\n    _lazyMethod(proto, \"format\", (self) => (mapper) => core.formatError(self, mapper));\n    _lazyMethod(proto, \"flatten\", (self) => (mapper) => core.flattenError(self, mapper));\n    _lazyMethod(proto, \"addIssue\", (self) => (issue) => {\n        self.issues.push(issue);\n        self.message = JSON.stringify(self.issues, util.jsonStringifyReplacer, 2);\n    });\n    _lazyMethod(proto, \"addIssues\", (self) => (issues) => {\n        self.issues.push(...issues);\n        self.message = JSON.stringify(self.issues, util.jsonStringifyReplacer, 2);\n    });\n    Object.defineProperty(proto, \"isEmpty\", {\n        configurable: true,\n        enumerable: false,\n        get() {\n            return this.issues.length === 0;\n        },\n    });\n};\nexport const ZodError = /*@__PURE__*/ core.$constructor(\"ZodError\", initializer);\nexport const ZodRealError = /*@__PURE__*/ core.$constructor(\"ZodError\", initializer, undefined, {\n    Parent: Error,\n});\n// /** @deprecated Use `z.core.$ZodErrorMapCtx` instead. */\n// export type ErrorMapCtx = core.$ZodErrorMapCtx;\n","import * as core from \"../core/index.js\";\nimport { ZodRealError } from \"./errors.js\";\nexport const parse = /* @__PURE__ */ core._parse(ZodRealError);\nexport const parseAsync = /* @__PURE__ */ core._parseAsync(ZodRealError);\nexport const safeParse = /* @__PURE__ */ core._safeParse(ZodRealError);\nexport const safeParseAsync = /* @__PURE__ */ core._safeParseAsync(ZodRealError);\nexport { validate, validateAsync } from \"../core/index.js\";\n// Codec functions\nexport const encode = /* @__PURE__ */ core._encode(ZodRealError);\nexport const decode = /* @__PURE__ */ core._decode(ZodRealError);\nexport const encodeAsync = /* @__PURE__ */ core._encodeAsync(ZodRealError);\nexport const decodeAsync = /* @__PURE__ */ core._decodeAsync(ZodRealError);\nexport const safeEncode = /* @__PURE__ */ core._safeEncode(ZodRealError);\nexport const safeDecode = /* @__PURE__ */ core._safeDecode(ZodRealError);\nexport const safeEncodeAsync = /* @__PURE__ */ core._safeEncodeAsync(ZodRealError);\nexport const safeDecodeAsync = /* @__PURE__ */ core._safeDecodeAsync(ZodRealError);\n","import * as core from \"../core/index.js\";\nimport { util } from \"../core/index.js\";\nimport * as processors from \"../core/json-schema-processors.js\";\nimport * as regexes from \"../core/regexes.js\";\nimport { createStandardJSONSchemaMethod, createToJSONSchemaMethod } from \"../core/to-json-schema.js\";\nimport en from \"../locales/en.js\";\nimport * as checks from \"./checks.js\";\nimport * as parse from \"./parse.js\";\n// 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.\nfunction _ensureDefaultLocale() {\n    if (!core.globalConfig.localeError)\n        core.config(en());\n}\n// the default memoizer is read by the core container init, which runs before `ZodType.init`, so each container calls this first\nfunction _ensureDefaultMemoizer() {\n    if (!core.globalConfig.memoizer)\n        core.config({ memoizer: core.memoizer() });\n}\nexport const ZodType = /*@__PURE__*/ core.$constructor(\"ZodType\", (inst, def) => {\n    _ensureDefaultLocale();\n    core.$ZodType.init(inst, def);\n    inst.def = def;\n    inst.type = def.type;\n    return inst;\n}, {\n    check(...chks) {\n        const def = this.def;\n        return this.clone(util.mergeDefs(def, {\n            checks: [\n                ...(def.checks ?? []),\n                ...chks.map((ch) => typeof ch === \"function\" ? { _zod: { check: ch, def: { check: \"custom\" }, onattach: [] } } : ch),\n            ],\n        }), { parent: true });\n    },\n    with(...chks) {\n        return this.check(...chks);\n    },\n    clone(def, params) {\n        return core.clone(this, def, params);\n    },\n    brand() {\n        return this;\n    },\n    register(reg, meta) {\n        reg.add(this, meta);\n        return this;\n    },\n    refine(check, params) {\n        return this.check(refine(check, params));\n    },\n    superRefine(refinement, params) {\n        return this.check(superRefine(refinement, params));\n    },\n    overwrite(fn) {\n        return this.check(checks.overwrite(fn));\n    },\n    optional() {\n        return optional(this);\n    },\n    exactOptional() {\n        return exactOptional(this);\n    },\n    nullable() {\n        return nullable(this);\n    },\n    nullish() {\n        return optional(nullable(this));\n    },\n    nonoptional(params) {\n        return nonoptional(this, params);\n    },\n    array() {\n        return array(this);\n    },\n    or(arg) {\n        return union([this, arg]);\n    },\n    and(arg) {\n        return intersection(this, arg);\n    },\n    transform(tx) {\n        return pipe(this, transform(tx));\n    },\n    default(d) {\n        return _default(this, d);\n    },\n    prefault(d) {\n        return prefault(this, d);\n    },\n    catch(params) {\n        return _catch(this, params);\n    },\n    pipe(target) {\n        return pipe(this, target);\n    },\n    readonly() {\n        return readonly(this);\n    },\n    describe(description) {\n        const cl = this.clone();\n        core.globalRegistry.add(cl, { description });\n        return cl;\n    },\n    meta(...args) {\n        // 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.\n        if (args.length === 0)\n            return core.globalRegistry.get(this);\n        const cl = this.clone();\n        core.globalRegistry.add(cl, args[0]);\n        return cl;\n    },\n    isOptional() {\n        return this.safeParse(undefined).success;\n    },\n    isNullable() {\n        return this.safeParse(null).success;\n    },\n    apply(fn, ...args) {\n        return args.length === 0 ? fn(this) : fn(this, ...args);\n    },\n    // Overrides core's `~standard` to add `jsonSchema`. Must stay a prototype entry: redefining it per instance demotes instances to dictionary mode.\n    get \"~standard\"() {\n        return util.hide(this, \"~standard\", {\n            ...core.standardProps(this),\n            jsonSchema: {\n                input: createStandardJSONSchemaMethod(this, \"input\"),\n                output: createStandardJSONSchemaMethod(this, \"output\"),\n            },\n        });\n    },\n    set \"~standard\"(value) {\n        util.own(this, \"~standard\", value);\n    },\n    parse: function _parse(data, params) {\n        return parse.parse(this, data, params, { callee: _parse });\n    },\n    parseAsync: async function _parseAsync(data, params) {\n        return await parse.parseAsync(this, data, params, { callee: _parseAsync });\n    },\n    safeParse(data, params) {\n        return parse.safeParse(this, data, params);\n    },\n    async safeParseAsync(data, params) {\n        return parse.safeParseAsync(this, data, params);\n    },\n    // `spa` is an alias: same function object as `safeParseAsync`, as before.\n    get spa() {\n        return this?.safeParseAsync;\n    },\n    set spa(value) {\n        util.own(this, \"spa\", value);\n    },\n    validate(data, params) {\n        return parse.validate(this, data, params);\n    },\n    validateAsync(data, params) {\n        return parse.validateAsync(this, data, params);\n    },\n    encode: function _encode(data, params) {\n        return parse.encode(this, data, params, { callee: _encode });\n    },\n    decode: function _decode(data, params) {\n        return parse.decode(this, data, params, { callee: _decode });\n    },\n    encodeAsync: async function _encodeAsync(data, params) {\n        return await parse.encodeAsync(this, data, params, { callee: _encodeAsync });\n    },\n    decodeAsync: async function _decodeAsync(data, params) {\n        return await parse.decodeAsync(this, data, params, { callee: _decodeAsync });\n    },\n    safeEncode(data, params) {\n        return parse.safeEncode(this, data, params);\n    },\n    safeDecode(data, params) {\n        return parse.safeDecode(this, data, params);\n    },\n    async safeEncodeAsync(data, params) {\n        return parse.safeEncodeAsync(this, data, params);\n    },\n    async safeDecodeAsync(data, params) {\n        return parse.safeDecodeAsync(this, data, params);\n    },\n    toJSONSchema(params) {\n        return createToJSONSchemaMethod(this, {})(params);\n    },\n    // Reads through to the registry on every access, so it must not cache.\n    get description() {\n        return core.globalRegistry.get(this)?.description;\n    },\n    // No setter: `schema._def = x` throws, as it did when `_def` was a non-writable own property.\n    get _def() {\n        return this._zod.def;\n    },\n});\n/** @internal */\nexport const _ZodString = /*@__PURE__*/ core.$constructor(\"_ZodString\", (inst, def) => {\n    core.$ZodString.init(inst, def);\n    ZodType.init(inst, def);\n    inst._zod.processJSONSchema = (ctx, json, params) => processors.stringProcessor(inst, ctx, json, params);\n}, \n/*@__PURE__*/ util.derived({\n    format: (inst) => processors.aggregateChecks(inst).format ?? null,\n    minLength: (inst) => processors.aggregateChecks(inst).minimum ?? null,\n    maxLength: (inst) => processors.aggregateChecks(inst).maximum ?? null,\n}, {\n    regex(...args) {\n        return this.check(checks.regex(...args));\n    },\n    includes(...args) {\n        return this.check(checks.includes(...args));\n    },\n    startsWith(...args) {\n        return this.check(checks.startsWith(...args));\n    },\n    endsWith(...args) {\n        return this.check(checks.endsWith(...args));\n    },\n    min(...args) {\n        return this.check(checks.minLength(...args));\n    },\n    max(...args) {\n        return this.check(checks.maxLength(...args));\n    },\n    length(...args) {\n        return this.check(checks.length(...args));\n    },\n    nonempty(...args) {\n        return this.check(checks.minLength(1, ...args));\n    },\n    lowercase(params) {\n        return this.check(checks.lowercase(params));\n    },\n    uppercase(params) {\n        return this.check(checks.uppercase(params));\n    },\n    trim() {\n        return this.check(checks.trim());\n    },\n    normalize(...args) {\n        return this.check(checks.normalize(...args));\n    },\n    toLowerCase() {\n        return this.check(checks.toLowerCase());\n    },\n    toUpperCase() {\n        return this.check(checks.toUpperCase());\n    },\n    slugify() {\n        return this.check(checks.slugify());\n    },\n}));\nexport const ZodString = /*@__PURE__*/ core.$constructor(\"ZodString\", (inst, def) => {\n    core.$ZodString.init(inst, def);\n    _ZodString.init(inst, def);\n}, {\n    email(params) {\n        return this.check(core._email(ZodEmail, params));\n    },\n    url(params) {\n        return this.check(core._url(ZodURL, params));\n    },\n    jwt(params) {\n        return this.check(core._jwt(ZodJWT, params));\n    },\n    emoji(params) {\n        return this.check(core._emoji(ZodEmoji, params));\n    },\n    guid(params) {\n        return this.check(core._guid(ZodGUID, params));\n    },\n    uuid(params) {\n        return this.check(core._uuid(ZodUUID, params));\n    },\n    uuidv4(params) {\n        return this.check(core._uuidv4(ZodUUID, params));\n    },\n    uuidv6(params) {\n        return this.check(core._uuidv6(ZodUUID, params));\n    },\n    uuidv7(params) {\n        return this.check(core._uuidv7(ZodUUID, params));\n    },\n    nanoid(params) {\n        return this.check(core._nanoid(ZodNanoID, params));\n    },\n    cuid(params) {\n        return this.check(core._cuid(ZodCUID, params));\n    },\n    cuid2(params) {\n        return this.check(core._cuid2(ZodCUID2, params));\n    },\n    ulid(params) {\n        return this.check(core._ulid(ZodULID, params));\n    },\n    base64(params) {\n        return this.check(core._base64(ZodBase64, params));\n    },\n    base64url(params) {\n        return this.check(core._base64url(ZodBase64URL, params));\n    },\n    xid(params) {\n        return this.check(core._xid(ZodXID, params));\n    },\n    ksuid(params) {\n        return this.check(core._ksuid(ZodKSUID, params));\n    },\n    ipv4(params) {\n        return this.check(core._ipv4(ZodIPv4, params));\n    },\n    ipv6(params) {\n        return this.check(core._ipv6(ZodIPv6, params));\n    },\n    cidrv4(params) {\n        return this.check(core._cidrv4(ZodCIDRv4, params));\n    },\n    cidrv6(params) {\n        return this.check(core._cidrv6(ZodCIDRv6, params));\n    },\n    e164(params) {\n        return this.check(core._e164(ZodE164, params));\n    },\n    datetime(params) {\n        return this.check(core._isoDateTime(ZodISODateTime, params));\n    },\n    date(params) {\n        return this.check(core._isoDate(ZodISODate, params));\n    },\n    time(params) {\n        return this.check(core._isoTime(ZodISOTime, params));\n    },\n    duration(params) {\n        return this.check(core._isoDuration(ZodISODuration, params));\n    },\n});\nexport function string(params) {\n    return core._string(ZodString, params);\n}\nexport const ZodStringFormat = /*@__PURE__*/ core.$constructor(\"ZodStringFormat\", (inst, def) => {\n    core.$ZodStringFormat.init(inst, def);\n    _ZodString.init(inst, def);\n});\nexport const ZodISODateTime = /*@__PURE__*/ core.$constructor(\"ZodISODateTime\", (inst, def) => {\n    core.$ZodISODateTime.init(inst, def);\n    ZodStringFormat.init(inst, def);\n});\nexport const ZodISODate = /*@__PURE__*/ core.$constructor(\"ZodISODate\", (inst, def) => {\n    core.$ZodISODate.init(inst, def);\n    ZodStringFormat.init(inst, def);\n});\nexport const ZodISOTime = /*@__PURE__*/ core.$constructor(\"ZodISOTime\", (inst, def) => {\n    core.$ZodISOTime.init(inst, def);\n    ZodStringFormat.init(inst, def);\n});\nexport const ZodISODuration = /*@__PURE__*/ core.$constructor(\"ZodISODuration\", (inst, def) => {\n    core.$ZodISODuration.init(inst, def);\n    ZodStringFormat.init(inst, def);\n});\nexport const ZodEmail = /*@__PURE__*/ core.$constructor(\"ZodEmail\", (inst, def) => {\n    // ZodStringFormat.init(inst, def);\n    core.$ZodEmail.init(inst, def);\n    ZodStringFormat.init(inst, def);\n});\nexport function email(params) {\n    return core._email(ZodEmail, params);\n}\nexport const ZodGUID = /*@__PURE__*/ core.$constructor(\"ZodGUID\", (inst, def) => {\n    // ZodStringFormat.init(inst, def);\n    core.$ZodGUID.init(inst, def);\n    ZodStringFormat.init(inst, def);\n});\nexport function guid(params) {\n    return core._guid(ZodGUID, params);\n}\nexport const ZodUUID = /*@__PURE__*/ core.$constructor(\"ZodUUID\", (inst, def) => {\n    // ZodStringFormat.init(inst, def);\n    core.$ZodUUID.init(inst, def);\n    ZodStringFormat.init(inst, def);\n});\nexport function uuid(params) {\n    return core._uuid(ZodUUID, params);\n}\nexport function uuidv4(params) {\n    return core._uuidv4(ZodUUID, params);\n}\n// ZodUUIDv6\nexport function uuidv6(params) {\n    return core._uuidv6(ZodUUID, params);\n}\n// ZodUUIDv7\nexport function uuidv7(params) {\n    return core._uuidv7(ZodUUID, params);\n}\nexport const ZodURL = /*@__PURE__*/ core.$constructor(\"ZodURL\", (inst, def) => {\n    // ZodStringFormat.init(inst, def);\n    core.$ZodURL.init(inst, def);\n    ZodStringFormat.init(inst, def);\n});\nexport function url(params) {\n    return core._url(ZodURL, params);\n}\nexport function httpUrl(params) {\n    return core._url(ZodURL, {\n        protocol: regexes.httpProtocol,\n        hostname: regexes.domain,\n        ...util.normalizeParams(params),\n    });\n}\nexport const ZodEmoji = /*@__PURE__*/ core.$constructor(\"ZodEmoji\", (inst, def) => {\n    // ZodStringFormat.init(inst, def);\n    core.$ZodEmoji.init(inst, def);\n    ZodStringFormat.init(inst, def);\n});\nexport function emoji(params) {\n    return core._emoji(ZodEmoji, params);\n}\nexport const ZodNanoID = /*@__PURE__*/ core.$constructor(\"ZodNanoID\", (inst, def) => {\n    // ZodStringFormat.init(inst, def);\n    core.$ZodNanoID.init(inst, def);\n    ZodStringFormat.init(inst, def);\n});\nexport function nanoid(params) {\n    return core._nanoid(ZodNanoID, params);\n}\n/**\n * @deprecated CUID v1 is deprecated by its authors due to information leakage\n * (timestamps embedded in the id). Use {@link ZodCUID2} instead.\n * See https://github.com/paralleldrive/cuid.\n */\nexport const ZodCUID = /*@__PURE__*/ core.$constructor(\"ZodCUID\", (inst, def) => {\n    // ZodStringFormat.init(inst, def);\n    core.$ZodCUID.init(inst, def);\n    ZodStringFormat.init(inst, def);\n});\n/**\n * Validates a CUID v1 string.\n *\n * @deprecated CUID v1 is deprecated by its authors due to information leakage\n * (timestamps embedded in the id). Use {@link cuid2 | `z.cuid2()`} instead.\n * See https://github.com/paralleldrive/cuid.\n */\nexport function cuid(params) {\n    return core._cuid(ZodCUID, params);\n}\nexport const ZodCUID2 = /*@__PURE__*/ core.$constructor(\"ZodCUID2\", (inst, def) => {\n    // ZodStringFormat.init(inst, def);\n    core.$ZodCUID2.init(inst, def);\n    ZodStringFormat.init(inst, def);\n});\nexport function cuid2(params) {\n    return core._cuid2(ZodCUID2, params);\n}\nexport const ZodULID = /*@__PURE__*/ core.$constructor(\"ZodULID\", (inst, def) => {\n    // ZodStringFormat.init(inst, def);\n    core.$ZodULID.init(inst, def);\n    ZodStringFormat.init(inst, def);\n});\nexport function ulid(params) {\n    return core._ulid(ZodULID, params);\n}\nexport const ZodXID = /*@__PURE__*/ core.$constructor(\"ZodXID\", (inst, def) => {\n    // ZodStringFormat.init(inst, def);\n    core.$ZodXID.init(inst, def);\n    ZodStringFormat.init(inst, def);\n});\nexport function xid(params) {\n    return core._xid(ZodXID, params);\n}\nexport const ZodKSUID = /*@__PURE__*/ core.$constructor(\"ZodKSUID\", (inst, def) => {\n    // ZodStringFormat.init(inst, def);\n    core.$ZodKSUID.init(inst, def);\n    ZodStringFormat.init(inst, def);\n});\nexport function ksuid(params) {\n    return core._ksuid(ZodKSUID, params);\n}\nexport const ZodIPv4 = /*@__PURE__*/ core.$constructor(\"ZodIPv4\", (inst, def) => {\n    // ZodStringFormat.init(inst, def);\n    core.$ZodIPv4.init(inst, def);\n    ZodStringFormat.init(inst, def);\n});\nexport function ipv4(params) {\n    return core._ipv4(ZodIPv4, params);\n}\nexport const ZodMAC = /*@__PURE__*/ core.$constructor(\"ZodMAC\", (inst, def) => {\n    // ZodStringFormat.init(inst, def);\n    core.$ZodMAC.init(inst, def);\n    ZodStringFormat.init(inst, def);\n});\nexport function mac(params) {\n    return core._mac(ZodMAC, params);\n}\nexport const ZodIPv6 = /*@__PURE__*/ core.$constructor(\"ZodIPv6\", (inst, def) => {\n    // ZodStringFormat.init(inst, def);\n    core.$ZodIPv6.init(inst, def);\n    ZodStringFormat.init(inst, def);\n});\nexport function ipv6(params) {\n    return core._ipv6(ZodIPv6, params);\n}\nexport const ZodCIDRv4 = /*@__PURE__*/ core.$constructor(\"ZodCIDRv4\", (inst, def) => {\n    core.$ZodCIDRv4.init(inst, def);\n    ZodStringFormat.init(inst, def);\n});\nexport function cidrv4(params) {\n    return core._cidrv4(ZodCIDRv4, params);\n}\nexport const ZodCIDRv6 = /*@__PURE__*/ core.$constructor(\"ZodCIDRv6\", (inst, def) => {\n    core.$ZodCIDRv6.init(inst, def);\n    ZodStringFormat.init(inst, def);\n});\nexport function cidrv6(params) {\n    return core._cidrv6(ZodCIDRv6, params);\n}\nexport const ZodBase64 = /*@__PURE__*/ core.$constructor(\"ZodBase64\", (inst, def) => {\n    // ZodStringFormat.init(inst, def);\n    core.$ZodBase64.init(inst, def);\n    ZodStringFormat.init(inst, def);\n});\nexport function base64(params) {\n    return core._base64(ZodBase64, params);\n}\nexport const ZodBase64URL = /*@__PURE__*/ core.$constructor(\"ZodBase64URL\", (inst, def) => {\n    // ZodStringFormat.init(inst, def);\n    core.$ZodBase64URL.init(inst, def);\n    ZodStringFormat.init(inst, def);\n});\nexport function base64url(params) {\n    return core._base64url(ZodBase64URL, params);\n}\nexport const ZodE164 = /*@__PURE__*/ core.$constructor(\"ZodE164\", (inst, def) => {\n    // ZodStringFormat.init(inst, def);\n    core.$ZodE164.init(inst, def);\n    ZodStringFormat.init(inst, def);\n});\nexport function e164(params) {\n    return core._e164(ZodE164, params);\n}\nexport const ZodCreditCard = /*@__PURE__*/ core.$constructor(\"ZodCreditCard\", (inst, def) => {\n    core.$ZodCreditCard.init(inst, def);\n    ZodStringFormat.init(inst, def);\n});\nexport function creditCard(params) {\n    return core._creditCard(ZodCreditCard, params);\n}\nexport const ZodIBAN = /*@__PURE__*/ core.$constructor(\"ZodIBAN\", (inst, def) => {\n    core.$ZodIBAN.init(inst, def);\n    ZodStringFormat.init(inst, def);\n});\nexport function iban(params) {\n    return core._iban(ZodIBAN, params);\n}\nexport const ZodJWT = /*@__PURE__*/ core.$constructor(\"ZodJWT\", (inst, def) => {\n    // ZodStringFormat.init(inst, def);\n    core.$ZodJWT.init(inst, def);\n    ZodStringFormat.init(inst, def);\n});\nexport function jwt(params) {\n    return core._jwt(ZodJWT, params);\n}\nexport const ZodCustomStringFormat = /*@__PURE__*/ core.$constructor(\"ZodCustomStringFormat\", (inst, def) => {\n    // ZodStringFormat.init(inst, def);\n    core.$ZodCustomStringFormat.init(inst, def);\n    ZodStringFormat.init(inst, def);\n});\nexport function stringFormat(format, fnOrRegex, _params = {}) {\n    return core._stringFormat(ZodCustomStringFormat, format, fnOrRegex, _params);\n}\nexport function hostname(_params) {\n    return core._stringFormat(ZodCustomStringFormat, \"hostname\", regexes.hostname, _params);\n}\nexport function hex(_params) {\n    return core._stringFormat(ZodCustomStringFormat, \"hex\", regexes.hex, _params);\n}\nexport function currencyCode(_params) {\n    return core._stringFormat(ZodCustomStringFormat, \"currency_code\", regexes.currencyCode, _params);\n}\nexport function hash(alg, params) {\n    const enc = params?.enc ?? \"hex\";\n    const format = `${alg}_${enc}`;\n    const regex = core.regexes[format];\n    if (!regex)\n        throw new Error(`Unrecognized hash format: ${format}`);\n    return core._stringFormat(ZodCustomStringFormat, format, regex, params);\n}\nexport const ZodNumber = /*@__PURE__*/ core.$constructor(\"ZodNumber\", (inst, def) => {\n    core.$ZodNumber.init(inst, def);\n    ZodType.init(inst, def);\n    inst._zod.processJSONSchema = (ctx, json, params) => processors.numberProcessor(inst, ctx, json, params);\n    inst.isFinite = true;\n}, \n/*@__PURE__*/ util.derived({\n    minValue: (inst) => {\n        const { minimum, exclusiveMinimum } = processors.aggregateChecks(inst);\n        return Math.max(minimum ?? Number.NEGATIVE_INFINITY, exclusiveMinimum ?? Number.NEGATIVE_INFINITY);\n    },\n    maxValue: (inst) => {\n        const { maximum, exclusiveMaximum } = processors.aggregateChecks(inst);\n        return Math.min(maximum ?? Number.POSITIVE_INFINITY, exclusiveMaximum ?? Number.POSITIVE_INFINITY);\n    },\n    isInt: (inst) => {\n        const { isInt, multipleOf } = processors.aggregateChecks(inst);\n        return !!isInt || !!multipleOf?.some(Number.isSafeInteger);\n    },\n    format: (inst) => processors.aggregateChecks(inst).format ?? null,\n}, {\n    gt(value, params) {\n        return this.check(checks.gt(value, params));\n    },\n    gte(value, params) {\n        return this.check(checks.gte(value, params));\n    },\n    min(value, params) {\n        return this.check(checks.gte(value, params));\n    },\n    lt(value, params) {\n        return this.check(checks.lt(value, params));\n    },\n    lte(value, params) {\n        return this.check(checks.lte(value, params));\n    },\n    max(value, params) {\n        return this.check(checks.lte(value, params));\n    },\n    int(params) {\n        return this.check(int(params));\n    },\n    safe(params) {\n        return this.check(int(params));\n    },\n    positive(params) {\n        return this.check(checks.gt(0, params));\n    },\n    nonnegative(params) {\n        return this.check(checks.gte(0, params));\n    },\n    negative(params) {\n        return this.check(checks.lt(0, params));\n    },\n    nonpositive(params) {\n        return this.check(checks.lte(0, params));\n    },\n    multipleOf(value, params) {\n        return this.check(checks.multipleOf(value, params));\n    },\n    step(value, params) {\n        return this.check(checks.multipleOf(value, params));\n    },\n    finite() {\n        return this;\n    },\n}));\nexport function number(params) {\n    return core._number(ZodNumber, params);\n}\nexport const ZodNumberFormat = /*@__PURE__*/ core.$constructor(\"ZodNumberFormat\", (inst, def) => {\n    core.$ZodNumberFormat.init(inst, def);\n    ZodNumber.init(inst, def);\n});\nexport function int(params) {\n    return core._int(ZodNumberFormat, params);\n}\nexport function float32(params) {\n    return core._float32(ZodNumberFormat, params);\n}\nexport function float64(params) {\n    return core._float64(ZodNumberFormat, params);\n}\nexport function int32(params) {\n    return core._int32(ZodNumberFormat, params);\n}\nexport function uint32(params) {\n    return core._uint32(ZodNumberFormat, params);\n}\nexport const ZodBoolean = /*@__PURE__*/ core.$constructor(\"ZodBoolean\", (inst, def) => {\n    core.$ZodBoolean.init(inst, def);\n    ZodType.init(inst, def);\n    inst._zod.processJSONSchema = (ctx, json, params) => processors.booleanProcessor(inst, ctx, json, params);\n});\nexport function boolean(params) {\n    return core._boolean(ZodBoolean, params);\n}\nexport const ZodBigInt = /*@__PURE__*/ core.$constructor(\"ZodBigInt\", (inst, def) => {\n    core.$ZodBigInt.init(inst, def);\n    ZodType.init(inst, def);\n    inst._zod.processJSONSchema = (ctx, json, params) => processors.bigintProcessor(inst, ctx, json, params);\n}, \n/*@__PURE__*/ util.derived({\n    minValue: (inst) => processors.aggregateChecks(inst).minimum ?? null,\n    maxValue: (inst) => processors.aggregateChecks(inst).maximum ?? null,\n    format: (inst) => processors.aggregateChecks(inst).format ?? null,\n}, {\n    gte(value, params) {\n        return this.check(checks.gte(value, params));\n    },\n    min(value, params) {\n        return this.check(checks.gte(value, params));\n    },\n    gt(value, params) {\n        return this.check(checks.gt(value, params));\n    },\n    lt(value, params) {\n        return this.check(checks.lt(value, params));\n    },\n    lte(value, params) {\n        return this.check(checks.lte(value, params));\n    },\n    max(value, params) {\n        return this.check(checks.lte(value, params));\n    },\n    positive(params) {\n        return this.check(checks.gt(BigInt(0), params));\n    },\n    negative(params) {\n        return this.check(checks.lt(BigInt(0), params));\n    },\n    nonpositive(params) {\n        return this.check(checks.lte(BigInt(0), params));\n    },\n    nonnegative(params) {\n        return this.check(checks.gte(BigInt(0), params));\n    },\n    multipleOf(value, params) {\n        return this.check(checks.multipleOf(value, params));\n    },\n}));\nexport function bigint(params) {\n    return core._bigint(ZodBigInt, params);\n}\nexport const ZodBigIntFormat = /*@__PURE__*/ core.$constructor(\"ZodBigIntFormat\", (inst, def) => {\n    core.$ZodBigIntFormat.init(inst, def);\n    ZodBigInt.init(inst, def);\n});\nexport function int64(params) {\n    return core._int64(ZodBigIntFormat, params);\n}\nexport function uint64(params) {\n    return core._uint64(ZodBigIntFormat, params);\n}\nexport const ZodSymbol = /*@__PURE__*/ core.$constructor(\"ZodSymbol\", (inst, def) => {\n    core.$ZodSymbol.init(inst, def);\n    ZodType.init(inst, def);\n    inst._zod.processJSONSchema = (ctx, json, params) => processors.symbolProcessor(inst, ctx, json, params);\n});\nexport function symbol(params) {\n    return core._symbol(ZodSymbol, params);\n}\nexport const ZodUndefined = /*@__PURE__*/ core.$constructor(\"ZodUndefined\", (inst, def) => {\n    core.$ZodUndefined.init(inst, def);\n    ZodType.init(inst, def);\n    inst._zod.processJSONSchema = (ctx, json, params) => processors.undefinedProcessor(inst, ctx, json, params);\n});\nfunction _undefined(params) {\n    return core._undefined(ZodUndefined, params);\n}\nexport { _undefined as undefined };\nexport const ZodNull = /*@__PURE__*/ core.$constructor(\"ZodNull\", (inst, def) => {\n    core.$ZodNull.init(inst, def);\n    ZodType.init(inst, def);\n    inst._zod.processJSONSchema = (ctx, json, params) => processors.nullProcessor(inst, ctx, json, params);\n});\nfunction _null(params) {\n    return core._null(ZodNull, params);\n}\nexport { _null as null };\nexport const ZodAny = /*@__PURE__*/ core.$constructor(\"ZodAny\", (inst, def) => {\n    core.$ZodAny.init(inst, def);\n    ZodType.init(inst, def);\n    inst._zod.processJSONSchema = (ctx, json, params) => processors.anyProcessor(inst, ctx, json, params);\n});\nexport function any() {\n    return core._any(ZodAny);\n}\nexport const ZodUnknown = /*@__PURE__*/ core.$constructor(\"ZodUnknown\", (inst, def) => {\n    core.$ZodUnknown.init(inst, def);\n    ZodType.init(inst, def);\n    inst._zod.processJSONSchema = (ctx, json, params) => processors.unknownProcessor(inst, ctx, json, params);\n});\nexport function unknown() {\n    return core._unknown(ZodUnknown);\n}\nexport const ZodNever = /*@__PURE__*/ core.$constructor(\"ZodNever\", (inst, def) => {\n    core.$ZodNever.init(inst, def);\n    ZodType.init(inst, def);\n    inst._zod.processJSONSchema = (ctx, json, params) => processors.neverProcessor(inst, ctx, json, params);\n});\nexport function never(params) {\n    return core._never(ZodNever, params);\n}\nexport const ZodVoid = /*@__PURE__*/ core.$constructor(\"ZodVoid\", (inst, def) => {\n    core.$ZodVoid.init(inst, def);\n    ZodType.init(inst, def);\n    inst._zod.processJSONSchema = (ctx, json, params) => processors.voidProcessor(inst, ctx, json, params);\n});\nfunction _void(params) {\n    return core._void(ZodVoid, params);\n}\nexport { _void as void };\nexport const ZodDate = /*@__PURE__*/ core.$constructor(\"ZodDate\", (inst, def) => {\n    core.$ZodDate.init(inst, def);\n    ZodType.init(inst, def);\n    inst._zod.processJSONSchema = (ctx, json, params) => processors.dateProcessor(inst, ctx, json, params);\n    inst.min = (value, params) => inst.check(checks.gte(value, params));\n    inst.max = (value, params) => inst.check(checks.lte(value, params));\n}, \n/*@__PURE__*/ util.derived({\n    minDate: (inst) => {\n        const { minimum } = processors.aggregateChecks(inst);\n        return minimum ? new Date(minimum) : null;\n    },\n    maxDate: (inst) => {\n        const { maximum } = processors.aggregateChecks(inst);\n        return maximum ? new Date(maximum) : null;\n    },\n}, {}));\nexport function date(params) {\n    return core._date(ZodDate, params);\n}\nexport const ZodArray = /*@__PURE__*/ core.$constructor(\"ZodArray\", (inst, def) => {\n    _ensureDefaultMemoizer();\n    core.$ZodArray.init(inst, def);\n    ZodType.init(inst, def);\n    inst._zod.processJSONSchema = (ctx, json, params) => processors.arrayProcessor(inst, ctx, json, params);\n    inst.element = def.element;\n}, {\n    min(n, params) {\n        return this.check(checks.minLength(n, params));\n    },\n    nonempty(params) {\n        return this.check(checks.minLength(1, params));\n    },\n    max(n, params) {\n        return this.check(checks.maxLength(n, params));\n    },\n    length(n, params) {\n        return this.check(checks.length(n, params));\n    },\n    unwrap() {\n        return this.element;\n    },\n});\nexport function array(element, params) {\n    return core._array(ZodArray, element, params);\n}\n// .keyof\nexport function keyof(schema) {\n    const shape = schema._zod.def.shape;\n    return _enum(Object.keys(shape));\n}\nexport const ZodObject = /*@__PURE__*/ core.$constructor(\"ZodObject\", (inst, def) => {\n    _ensureDefaultMemoizer();\n    core.$ZodObjectJIT.init(inst, def);\n    ZodType.init(inst, def);\n    inst._zod.processJSONSchema = (ctx, json, params) => processors.objectProcessor(inst, ctx, json, params);\n    util.installLazyProp(inst, \"shape\", (self) => self._zod.def.shape, false);\n}, {\n    keyof() {\n        return _enum(Object.keys(this._zod.def.shape));\n    },\n    catchall(catchall) {\n        // `mergeDefs` rather than a spread: spreading reads `shape`, and resolving it can mint a whole fresh subtree\n        return this.clone(util.mergeDefs(this._zod.def, { catchall: catchall }));\n    },\n    passthrough() {\n        return this.clone(util.mergeDefs(this._zod.def, { catchall: unknown() }));\n    },\n    loose() {\n        return this.clone(util.mergeDefs(this._zod.def, { catchall: unknown() }));\n    },\n    strict() {\n        return this.clone(util.mergeDefs(this._zod.def, { catchall: never() }));\n    },\n    strip() {\n        return this.clone(util.mergeDefs(this._zod.def, { catchall: undefined }));\n    },\n    extend(incoming) {\n        return util.extend(this, incoming);\n    },\n    safeExtend(incoming) {\n        return util.safeExtend(this, incoming);\n    },\n    merge(other) {\n        return util.merge(this, other);\n    },\n    pick(mask) {\n        return util.pick(this, mask);\n    },\n    omit(mask) {\n        return util.omit(this, mask);\n    },\n    partial(...args) {\n        return util.partial(ZodOptional, this, args[0]);\n    },\n    exactPartial(...args) {\n        return util.partial(ZodExactOptional, this, args[0], \"exactPartial\");\n    },\n    required(...args) {\n        return util.required(ZodNonOptional, this, args[0]);\n    },\n});\nexport function object(shape, params) {\n    const def = {\n        type: \"object\",\n        shape: shape ?? {},\n        ...util.normalizeParams(params),\n    };\n    return new ZodObject(def);\n}\n// strictObject\nexport function strictObject(shape, params) {\n    return new ZodObject({\n        type: \"object\",\n        shape,\n        catchall: never(),\n        ...util.normalizeParams(params),\n    });\n}\n// looseObject\nexport function looseObject(shape, params) {\n    return new ZodObject({\n        type: \"object\",\n        shape,\n        catchall: unknown(),\n        ...util.normalizeParams(params),\n    });\n}\nexport const ZodUnion = /*@__PURE__*/ core.$constructor(\"ZodUnion\", (inst, def) => {\n    core.$ZodUnion.init(inst, def);\n    ZodType.init(inst, def);\n    inst._zod.processJSONSchema = (ctx, json, params) => processors.unionProcessor(inst, ctx, json, params);\n    inst.options = def.options;\n});\nexport function union(options, params) {\n    return new ZodUnion({\n        type: \"union\",\n        options: options,\n        ...util.normalizeParams(params),\n    });\n}\nexport const ZodXor = /*@__PURE__*/ core.$constructor(\"ZodXor\", (inst, def) => {\n    ZodUnion.init(inst, def);\n    core.$ZodXor.init(inst, def);\n    inst._zod.processJSONSchema = (ctx, json, params) => processors.unionProcessor(inst, ctx, json, params);\n    inst.options = def.options;\n});\n/** Creates an exclusive union (XOR) where exactly one option must match.\n * Unlike regular unions that succeed when any option matches, xor fails if\n * zero or more than one option matches the input. */\nexport function xor(options, params) {\n    return new ZodXor({\n        type: \"union\",\n        options: options,\n        inclusive: false,\n        ...util.normalizeParams(params),\n    });\n}\nexport const ZodDiscriminatedUnion = /*@__PURE__*/ core.$constructor(\"ZodDiscriminatedUnion\", (inst, def) => {\n    ZodUnion.init(inst, def);\n    core.$ZodDiscriminatedUnion.init(inst, def);\n});\nexport function discriminatedUnion(discriminator, options, params) {\n    // const [options, params] = args;\n    return new ZodDiscriminatedUnion({\n        type: \"union\",\n        options: options,\n        discriminator,\n        ...util.normalizeParams(params),\n    });\n}\nexport const ZodIntersection = /*@__PURE__*/ core.$constructor(\"ZodIntersection\", (inst, def) => {\n    core.$ZodIntersection.init(inst, def);\n    ZodType.init(inst, def);\n    inst._zod.processJSONSchema = (ctx, json, params) => processors.intersectionProcessor(inst, ctx, json, params);\n});\nexport function intersection(left, right) {\n    return new ZodIntersection({\n        type: \"intersection\",\n        left: left,\n        right: right,\n    });\n}\nexport const ZodTuple = /*@__PURE__*/ core.$constructor(\"ZodTuple\", (inst, def) => {\n    _ensureDefaultMemoizer();\n    core.$ZodTuple.init(inst, def);\n    ZodType.init(inst, def);\n    inst._zod.processJSONSchema = (ctx, json, params) => processors.tupleProcessor(inst, ctx, json, params);\n}, {\n    rest(rest) {\n        return this.clone({\n            ...this._zod.def,\n            rest: rest,\n        });\n    },\n    partial() {\n        const def = this._zod.def;\n        // a refinement was authored against the full arity; partialing would run it on a shorter array\n        if (def.checks?.length)\n            throw new Error(\".partial() cannot be used on tuple schemas containing refinements\");\n        return this.clone({\n            ...def,\n            items: def.items.map((item) => new ZodOptional({ type: \"optional\", innerType: item })),\n        });\n    },\n});\nexport function tuple(items, _paramsOrRest, _params) {\n    const hasRest = _paramsOrRest instanceof core.$ZodType;\n    const params = hasRest ? _params : _paramsOrRest;\n    const rest = hasRest ? _paramsOrRest : null;\n    return new ZodTuple({\n        type: \"tuple\",\n        items: items,\n        rest,\n        ...util.normalizeParams(params),\n    });\n}\nexport const ZodRecord = /*@__PURE__*/ core.$constructor(\"ZodRecord\", (inst, def) => {\n    _ensureDefaultMemoizer();\n    core.$ZodRecord.init(inst, def);\n    ZodType.init(inst, def);\n    inst._zod.processJSONSchema = (ctx, json, params) => processors.recordProcessor(inst, ctx, json, params);\n    inst.keyType = def.keyType;\n    inst.valueType = def.valueType;\n});\nexport function record(keyType, valueType, params) {\n    // v3-compat: z.record(valueType, params?) — defaults keyType to z.string()\n    if (!valueType || !valueType._zod) {\n        return new ZodRecord({\n            type: \"record\",\n            keyType: string(),\n            valueType: keyType,\n            ...util.normalizeParams(valueType),\n        });\n    }\n    return new ZodRecord({\n        type: \"record\",\n        keyType,\n        valueType: valueType,\n        ...util.normalizeParams(params),\n    });\n}\n// type alksjf = core.output<core.$ZodRecordKey>;\nexport function partialRecord(keyType, valueType, params) {\n    return new ZodRecord({\n        type: \"record\",\n        keyType,\n        valueType: valueType,\n        ...util.normalizeParams(params),\n        partial: true,\n    });\n}\nexport function looseRecord(keyType, valueType, params) {\n    return new ZodRecord({\n        type: \"record\",\n        keyType,\n        valueType: valueType,\n        mode: \"loose\",\n        ...util.normalizeParams(params),\n    });\n}\nexport const ZodMap = /*@__PURE__*/ core.$constructor(\"ZodMap\", (inst, def) => {\n    _ensureDefaultMemoizer();\n    core.$ZodMap.init(inst, def);\n    ZodType.init(inst, def);\n    inst._zod.processJSONSchema = (ctx, json, params) => processors.mapProcessor(inst, ctx, json, params);\n    inst.keyType = def.keyType;\n    inst.valueType = def.valueType;\n    inst.min = (...args) => inst.check(core._minSize(...args));\n    inst.nonempty = (params) => inst.check(core._minSize(1, params));\n    inst.max = (...args) => inst.check(core._maxSize(...args));\n    inst.size = (...args) => inst.check(core._size(...args));\n});\nexport function map(keyType, valueType, params) {\n    return new ZodMap({\n        type: \"map\",\n        keyType: keyType,\n        valueType: valueType,\n        ...util.normalizeParams(params),\n    });\n}\nexport const ZodSet = /*@__PURE__*/ core.$constructor(\"ZodSet\", (inst, def) => {\n    _ensureDefaultMemoizer();\n    core.$ZodSet.init(inst, def);\n    ZodType.init(inst, def);\n    inst._zod.processJSONSchema = (ctx, json, params) => processors.setProcessor(inst, ctx, json, params);\n    inst.min = (...args) => inst.check(core._minSize(...args));\n    inst.nonempty = (params) => inst.check(core._minSize(1, params));\n    inst.max = (...args) => inst.check(core._maxSize(...args));\n    inst.size = (...args) => inst.check(core._size(...args));\n});\nexport function set(valueType, params) {\n    return new ZodSet({\n        type: \"set\",\n        valueType: valueType,\n        ...util.normalizeParams(params),\n    });\n}\nexport const ZodEnum = /*@__PURE__*/ core.$constructor(\"ZodEnum\", (inst, def) => {\n    core.$ZodEnum.init(inst, def);\n    ZodType.init(inst, def);\n    inst._zod.processJSONSchema = (ctx, json, params) => processors.enumProcessor(inst, ctx, json, params);\n    inst.enum = def.entries;\n    // reuse the parsed value set so a numeric TS enum's reverse-mapping keys stay out\n    inst.options = [...inst._zod.values];\n    const keys = new Set(Object.keys(def.entries));\n    inst.extract = (values, params) => {\n        const newEntries = {};\n        for (const value of values) {\n            if (keys.has(value)) {\n                newEntries[value] = def.entries[value];\n            }\n            else\n                throw new Error(`Key ${value} not found in enum`);\n        }\n        return new ZodEnum({\n            ...def,\n            checks: [],\n            ...util.normalizeParams(params),\n            entries: newEntries,\n        });\n    };\n    inst.exclude = (values, params) => {\n        const newEntries = { ...def.entries };\n        for (const value of values) {\n            if (keys.has(value)) {\n                delete newEntries[value];\n            }\n            else\n                throw new Error(`Key ${value} not found in enum`);\n        }\n        return new ZodEnum({\n            ...def,\n            checks: [],\n            ...util.normalizeParams(params),\n            entries: newEntries,\n        });\n    };\n});\nfunction _enum(values, params) {\n    const entries = Array.isArray(values) ? Object.fromEntries(values.map((v) => [v, v])) : values;\n    return new ZodEnum({\n        type: \"enum\",\n        entries,\n        ...util.normalizeParams(params),\n    });\n}\nexport { _enum as enum };\n/** @deprecated This API has been merged into `z.enum()`. Use `z.enum()` instead.\n *\n * ```ts\n * enum Colors { red, green, blue }\n * z.enum(Colors);\n * ```\n */\nexport function nativeEnum(entries, params) {\n    return new ZodEnum({\n        type: \"enum\",\n        entries,\n        ...util.normalizeParams(params),\n    });\n}\nexport const ZodLiteral = /*@__PURE__*/ core.$constructor(\"ZodLiteral\", (inst, def) => {\n    core.$ZodLiteral.init(inst, def);\n    ZodType.init(inst, def);\n    inst._zod.processJSONSchema = (ctx, json, params) => processors.literalProcessor(inst, ctx, json, params);\n    inst.values = new Set(def.values);\n    Object.defineProperty(inst, \"value\", {\n        get() {\n            if (def.values.length > 1) {\n                throw new Error(\"This schema contains multiple valid literal values. Use `.values` instead.\");\n            }\n            return def.values[0];\n        },\n    });\n});\nexport function literal(value, params) {\n    return new ZodLiteral({\n        type: \"literal\",\n        values: Array.isArray(value) ? value : [value],\n        ...util.normalizeParams(params),\n    });\n}\nexport const ZodFile = /*@__PURE__*/ core.$constructor(\"ZodFile\", (inst, def) => {\n    core.$ZodFile.init(inst, def);\n    ZodType.init(inst, def);\n    inst._zod.processJSONSchema = (ctx, json, params) => processors.fileProcessor(inst, ctx, json, params);\n    inst.min = (size, params) => inst.check(core._minSize(size, params));\n    inst.max = (size, params) => inst.check(core._maxSize(size, params));\n    inst.mime = (types, params) => inst.check(core._mime(Array.isArray(types) ? types : [types], params));\n});\nexport function file(params) {\n    return core._file(ZodFile, params);\n}\nexport const ZodTransform = /*@__PURE__*/ core.$constructor(\"ZodTransform\", (inst, def) => {\n    _ensureDefaultMemoizer();\n    core.$ZodTransform.init(inst, def);\n    ZodType.init(inst, def);\n    inst._zod.processJSONSchema = (ctx, json, params) => processors.transformProcessor(inst, ctx, json, params);\n    inst._zod.parse = (payload, _ctx) => {\n        if (_ctx.direction === \"backward\") {\n            throw new core.$ZodEncodeError(inst.constructor.name);\n        }\n        payload.addIssue = (issue) => {\n            if (typeof issue === \"string\") {\n                payload.issues.push(util.issue(issue, payload.value, def));\n            }\n            else {\n                // for Zod 3 backwards compatibility\n                const _issue = issue;\n                if (_issue.fatal)\n                    _issue.continue = false;\n                _issue.code ?? (_issue.code = \"custom\");\n                if (!(\"input\" in _issue))\n                    _issue.input = payload.value;\n                _issue.inst ?? (_issue.inst = inst);\n                // _issue.continue ??= true;\n                payload.issues.push(util.issue(_issue));\n            }\n        };\n        const output = def.transform(payload.value, payload);\n        if (output instanceof Promise) {\n            return output.then((output) => {\n                payload.value = output;\n                return payload;\n            });\n        }\n        payload.value = output;\n        return payload;\n    };\n});\nexport function transform(fn) {\n    return new ZodTransform({\n        type: \"transform\",\n        transform: fn,\n    });\n}\nexport const ZodOptional = /*@__PURE__*/ core.$constructor(\"ZodOptional\", (inst, def) => {\n    core.$ZodOptional.init(inst, def);\n    ZodType.init(inst, def);\n    inst._zod.processJSONSchema = (ctx, json, params) => processors.optionalProcessor(inst, ctx, json, params);\n    inst.unwrap = () => inst._zod.def.innerType;\n});\nexport function optional(innerType) {\n    return new ZodOptional({\n        type: \"optional\",\n        innerType: innerType,\n    });\n}\nexport const ZodExactOptional = /*@__PURE__*/ core.$constructor(\"ZodExactOptional\", (inst, def) => {\n    core.$ZodExactOptional.init(inst, def);\n    ZodType.init(inst, def);\n    inst._zod.processJSONSchema = (ctx, json, params) => processors.optionalProcessor(inst, ctx, json, params);\n    inst.unwrap = () => inst._zod.def.innerType;\n});\nexport function exactOptional(innerType) {\n    return new ZodExactOptional({\n        type: \"optional\",\n        innerType: innerType,\n    });\n}\nexport const ZodNullable = /*@__PURE__*/ core.$constructor(\"ZodNullable\", (inst, def) => {\n    core.$ZodNullable.init(inst, def);\n    ZodType.init(inst, def);\n    inst._zod.processJSONSchema = (ctx, json, params) => processors.nullableProcessor(inst, ctx, json, params);\n    inst.unwrap = () => inst._zod.def.innerType;\n});\nexport function nullable(innerType) {\n    return new ZodNullable({\n        type: \"nullable\",\n        innerType: innerType,\n    });\n}\n// nullish\nexport function nullish(innerType) {\n    return optional(nullable(innerType));\n}\nexport const ZodDefault = /*@__PURE__*/ core.$constructor(\"ZodDefault\", (inst, def) => {\n    core.$ZodDefault.init(inst, def);\n    ZodType.init(inst, def);\n    inst._zod.processJSONSchema = (ctx, json, params) => processors.defaultProcessor(inst, ctx, json, params);\n    inst.unwrap = () => inst._zod.def.innerType;\n    inst.removeDefault = inst.unwrap;\n});\nexport function _default(innerType, defaultValue) {\n    return new ZodDefault({\n        type: \"default\",\n        innerType: innerType,\n        get defaultValue() {\n            return typeof defaultValue === \"function\" ? defaultValue() : util.shallowClone(defaultValue);\n        },\n    });\n}\nexport const ZodPrefault = /*@__PURE__*/ core.$constructor(\"ZodPrefault\", (inst, def) => {\n    core.$ZodPrefault.init(inst, def);\n    ZodType.init(inst, def);\n    inst._zod.processJSONSchema = (ctx, json, params) => processors.prefaultProcessor(inst, ctx, json, params);\n    inst.unwrap = () => inst._zod.def.innerType;\n});\nexport function prefault(innerType, defaultValue) {\n    return new ZodPrefault({\n        type: \"prefault\",\n        innerType: innerType,\n        get defaultValue() {\n            return typeof defaultValue === \"function\" ? defaultValue() : util.shallowClone(defaultValue);\n        },\n    });\n}\nexport const ZodNonOptional = /*@__PURE__*/ core.$constructor(\"ZodNonOptional\", (inst, def) => {\n    core.$ZodNonOptional.init(inst, def);\n    ZodType.init(inst, def);\n    inst._zod.processJSONSchema = (ctx, json, params) => processors.nonoptionalProcessor(inst, ctx, json, params);\n    inst.unwrap = () => inst._zod.def.innerType;\n});\nexport function nonoptional(innerType, params) {\n    return new ZodNonOptional({\n        type: \"nonoptional\",\n        innerType: innerType,\n        ...util.normalizeParams(params),\n    });\n}\nexport const ZodSuccess = /*@__PURE__*/ core.$constructor(\"ZodSuccess\", (inst, def) => {\n    core.$ZodSuccess.init(inst, def);\n    ZodType.init(inst, def);\n    inst._zod.processJSONSchema = (ctx, json, params) => processors.successProcessor(inst, ctx, json, params);\n    inst.unwrap = () => inst._zod.def.innerType;\n});\nexport function success(innerType) {\n    return new ZodSuccess({\n        type: \"success\",\n        innerType: innerType,\n    });\n}\nexport const ZodCatch = /*@__PURE__*/ core.$constructor(\"ZodCatch\", (inst, def) => {\n    core.$ZodCatch.init(inst, def);\n    ZodType.init(inst, def);\n    inst._zod.processJSONSchema = (ctx, json, params) => processors.catchProcessor(inst, ctx, json, params);\n    inst.unwrap = () => inst._zod.def.innerType;\n    inst.removeCatch = inst.unwrap;\n});\nfunction _catch(innerType, catchValue) {\n    return new ZodCatch({\n        type: \"catch\",\n        innerType: innerType,\n        catchValue: (typeof catchValue === \"function\" ? catchValue : core.util.constantCatch(catchValue)),\n    });\n}\nexport { _catch as catch };\nexport const ZodNaN = /*@__PURE__*/ core.$constructor(\"ZodNaN\", (inst, def) => {\n    core.$ZodNaN.init(inst, def);\n    ZodType.init(inst, def);\n    inst._zod.processJSONSchema = (ctx, json, params) => processors.nanProcessor(inst, ctx, json, params);\n});\nexport function nan(params) {\n    return core._nan(ZodNaN, params);\n}\nexport const ZodPipe = /*@__PURE__*/ core.$constructor(\"ZodPipe\", (inst, def) => {\n    core.$ZodPipe.init(inst, def);\n    ZodType.init(inst, def);\n    inst._zod.processJSONSchema = (ctx, json, params) => processors.pipeProcessor(inst, ctx, json, params);\n    inst.in = def.in;\n    inst.out = def.out;\n});\nexport function pipe(in_, out) {\n    return new ZodPipe({\n        type: \"pipe\",\n        in: in_,\n        out: out,\n        // ...util.normalizeParams(params),\n    });\n}\nexport const ZodCodec = /*@__PURE__*/ core.$constructor(\"ZodCodec\", (inst, def) => {\n    ZodPipe.init(inst, def);\n    core.$ZodCodec.init(inst, def);\n});\nexport function codec(in_, out, params) {\n    return new ZodCodec({\n        type: \"pipe\",\n        in: in_,\n        out: out,\n        transform: params.decode,\n        reverseTransform: params.encode,\n    });\n}\nexport function invertCodec(codec) {\n    const def = codec._zod.def;\n    return new ZodCodec({\n        type: \"pipe\",\n        in: def.out,\n        out: def.in,\n        transform: def.reverseTransform,\n        reverseTransform: def.transform,\n    });\n}\nexport const ZodPreprocess = /*@__PURE__*/ core.$constructor(\"ZodPreprocess\", (inst, def) => {\n    ZodPipe.init(inst, def);\n    core.$ZodPreprocess.init(inst, def);\n});\nexport const ZodReadonly = /*@__PURE__*/ core.$constructor(\"ZodReadonly\", (inst, def) => {\n    core.$ZodReadonly.init(inst, def);\n    ZodType.init(inst, def);\n    inst._zod.processJSONSchema = (ctx, json, params) => processors.readonlyProcessor(inst, ctx, json, params);\n    inst.unwrap = () => inst._zod.def.innerType;\n});\nexport function readonly(innerType) {\n    return new ZodReadonly({\n        type: \"readonly\",\n        innerType: innerType,\n    });\n}\nexport const ZodTemplateLiteral = /*@__PURE__*/ core.$constructor(\"ZodTemplateLiteral\", (inst, def) => {\n    core.$ZodTemplateLiteral.init(inst, def);\n    ZodType.init(inst, def);\n    inst._zod.processJSONSchema = (ctx, json, params) => processors.templateLiteralProcessor(inst, ctx, json, params);\n});\nexport function templateLiteral(parts, params) {\n    return new ZodTemplateLiteral({\n        type: \"template_literal\",\n        parts,\n        ...util.normalizeParams(params),\n    });\n}\nexport const ZodLazy = /*@__PURE__*/ core.$constructor(\"ZodLazy\", (inst, def) => {\n    core.$ZodLazy.init(inst, def);\n    ZodType.init(inst, def);\n    inst._zod.processJSONSchema = (ctx, json, params) => processors.lazyProcessor(inst, ctx, json, params);\n    inst.unwrap = () => inst._zod.def.getter();\n});\nexport function lazy(getter) {\n    return new ZodLazy({\n        type: \"lazy\",\n        getter: getter,\n    });\n}\nexport const ZodPromise = /*@__PURE__*/ core.$constructor(\"ZodPromise\", (inst, def) => {\n    core.$ZodPromise.init(inst, def);\n    ZodType.init(inst, def);\n    inst._zod.processJSONSchema = (ctx, json, params) => processors.promiseProcessor(inst, ctx, json, params);\n    inst.unwrap = () => inst._zod.def.innerType;\n});\nexport function promise(innerType) {\n    return new ZodPromise({\n        type: \"promise\",\n        innerType: innerType,\n    });\n}\nexport const ZodFunction = /*@__PURE__*/ core.$constructor(\"ZodFunction\", (inst, def) => {\n    core.$ZodFunction.init(inst, def);\n    ZodType.init(inst, def);\n    inst._zod.processJSONSchema = (ctx, json, params) => processors.functionProcessor(inst, ctx, json, params);\n});\nexport function _function(params) {\n    return new ZodFunction({\n        type: \"function\",\n        input: Array.isArray(params?.input) ? tuple(params?.input) : (params?.input ?? array(unknown())),\n        output: params?.output ?? unknown(),\n    });\n}\nexport { _function as function };\nexport const ZodCustom = /*@__PURE__*/ core.$constructor(\"ZodCustom\", (inst, def) => {\n    core.$ZodCustom.init(inst, def);\n    ZodType.init(inst, def);\n    inst._zod.processJSONSchema = (ctx, json, params) => processors.customProcessor(inst, ctx, json, params);\n});\n// custom checks\nexport function check(fn) {\n    const ch = new core.$ZodCheck({\n        check: \"custom\",\n        // ...util.normalizeParams(params),\n    });\n    ch._zod.check = fn;\n    return ch;\n}\nexport function custom(fn, _params) {\n    return core._custom(ZodCustom, fn ?? (() => true), _params);\n}\nexport function refine(fn, _params = {}) {\n    return core._refine(ZodCustom, fn, _params);\n}\n// superRefine\nexport function superRefine(fn, params) {\n    return core._superRefine(fn, params);\n}\n// Re-export describe and meta from core\nexport const describe = core.describe;\nexport const meta = core.meta;\nexport const ZodInstanceOf = /*@__PURE__*/ core.$constructor(\"ZodInstanceOf\", (inst, def) => {\n    ZodCustom.init(inst, def);\n}, {\n    properties(shape, params) {\n        // asserts in place, so the narrowed output type is truthful without a wrapper\n        return this.check(core._properties(shape, params));\n    },\n});\nfunction _instanceof(cls, params = {}) {\n    const inst = new ZodInstanceOf({\n        type: \"custom\",\n        check: \"custom\",\n        fn: (data) => data instanceof cls,\n        abort: true,\n        ...util.normalizeParams(params),\n    });\n    inst._zod.bag.Class = cls;\n    // Override check to emit invalid_type instead of custom\n    inst._zod.check = (payload) => {\n        if (!(payload.value instanceof cls)) {\n            payload.issues.push({\n                code: \"invalid_type\",\n                expected: cls.name,\n                input: payload.value,\n                inst,\n                path: [...(inst._zod.def.path ?? [])],\n            });\n        }\n    };\n    return inst;\n}\nexport { _instanceof as instanceof };\n// stringbool\nexport const stringbool = (...args) => core._stringbool({\n    Codec: ZodCodec,\n    Boolean: ZodBoolean,\n    String: ZodString,\n}, ...args);\nexport function json(params) {\n    const jsonSchema = lazy(() => {\n        return union([string(params), number(), boolean(), _null(), array(jsonSchema), record(string(), jsonSchema)]);\n    });\n    return jsonSchema;\n}\n// preprocess\nexport function preprocess(fn, schema) {\n    return new ZodPreprocess({\n        type: \"pipe\",\n        in: transform(fn),\n        out: schema,\n    });\n}\n","// Zod 3 compat layer\nimport * as core from \"../core/index.js\";\n/** @deprecated Use the raw string literal codes instead, e.g. \"invalid_type\". */\nexport const ZodIssueCode = {\n    invalid_type: \"invalid_type\",\n    too_big: \"too_big\",\n    too_small: \"too_small\",\n    invalid_format: \"invalid_format\",\n    not_multiple_of: \"not_multiple_of\",\n    unrecognized_keys: \"unrecognized_keys\",\n    invalid_union: \"invalid_union\",\n    invalid_key: \"invalid_key\",\n    invalid_element: \"invalid_element\",\n    invalid_value: \"invalid_value\",\n    custom: \"custom\",\n};\nexport { $brand, config } from \"../core/index.js\";\n/** @deprecated Use `z.config(params)` instead. */\nexport function setErrorMap(map) {\n    core.config({\n        customError: map,\n    });\n}\n/** @deprecated Use `z.config()` instead. */\nexport function getErrorMap() {\n    return core.config().customError;\n}\n/** @deprecated Do not use. Stub definition, only included for zod-to-json-schema compatibility. */\nexport var ZodFirstPartyTypeKind;\n(function (ZodFirstPartyTypeKind) {\n})(ZodFirstPartyTypeKind || (ZodFirstPartyTypeKind = {}));\n","import * as core from \"../core/index.js\";\nimport { ZodISODate, ZodISODateTime, ZodISODuration, ZodISOTime } from \"./schemas.js\";\nexport { ZodISODate, ZodISODateTime, ZodISODuration, ZodISOTime } from \"./schemas.js\";\nexport function datetime(params) {\n    return core._isoDateTime(ZodISODateTime, params);\n}\nexport function date(params) {\n    return core._isoDate(ZodISODate, params);\n}\nexport function time(params) {\n    return core._isoTime(ZodISOTime, params);\n}\nexport function duration(params) {\n    return core._isoDuration(ZodISODuration, params);\n}\n","import * as core from \"../core/index.js\";\nimport * as schemas from \"./schemas.js\";\nexport function string(params) {\n    return core._coercedString(schemas.ZodString, params);\n}\nexport function number(params) {\n    return core._coercedNumber(schemas.ZodNumber, params);\n}\nexport function boolean(params) {\n    return core._coercedBoolean(schemas.ZodBoolean, params);\n}\nexport function bigint(params) {\n    return core._coercedBigint(schemas.ZodBigInt, params);\n}\nexport function date(params) {\n    return core._coercedDate(schemas.ZodDate, params);\n}\n","export * as core from \"../core/index.js\";\nexport * from \"./schemas.js\";\nexport * from \"./checks.js\";\nexport * from \"./errors.js\";\nexport * from \"./parse.js\";\nexport * from \"./compat.js\";\nexport { globalRegistry, registry, config, memoizer, $output, $input, $brand, clone, regexes, treeifyError, prettifyError, formatError, flattenError, TimePrecision, util, NEVER, INVALID, toZod, compile, withParser, ZodCompileAsyncError, ZodCompileUnsupportedError, getDiscriminatedOption, } from \"../core/index.js\";\nexport { toJSONSchema } from \"../core/json-schema-processors.js\";\nexport { fromJSONSchema } from \"./from-json-schema.js\";\nexport { deepPartial } from \"./deep-partial.js\";\n// Types and values both, from one module — re-exporting the types from core would collide.\nexport { input, output } from \"./in-out.js\";\nexport * as locales from \"../locales/index.js\";\n// iso must be exported from top-level https://github.com/colinhacks/zod/issues/4491\nexport { ZodISODateTime, ZodISODate, ZodISOTime, ZodISODuration } from \"./iso.js\";\nexport * as iso from \"./iso.js\";\nexport * as coerce from \"./coerce.js\";\n","import * as z from \"./external.js\";\nexport * from \"./external.js\";\n// See the note in `src/index.ts` — aliasing keeps the default export shakable.\nexport { z, z as default };\n","import * as z4 from \"./classic/external.js\";\nexport * from \"./classic/index.js\";\n// See the note in `src/index.ts` — aliasing keeps the default export shakable. Aliased from the namespace, not from `./classic/index.js`'s default, so both the tsc and Babel CJS outputs stay a plain `exports.default =` rather than a getter.\nexport { z4 as default };\n","export const LATEST_PROTOCOL_VERSION = '2025-11-25';\nexport const DEFAULT_NEGOTIATED_PROTOCOL_VERSION = '2025-03-26';\nexport const SUPPORTED_PROTOCOL_VERSIONS = [LATEST_PROTOCOL_VERSION, '2025-06-18', '2025-03-26', '2024-11-05', '2024-10-07'];\n\n/**\n * `_meta` key associating a message with a 2025-11-25 task.\n *\n * @deprecated 2025-11-25 wire vocabulary with no SDK runtime; kept importable for interoperability only.\n */\nexport const RELATED_TASK_META_KEY = 'io.modelcontextprotocol/related-task';\n\n/* Reserved `_meta` keys for the per-request envelope (protocol revision 2026-07-28) */\n\n/**\n * `_meta` key carrying the MCP protocol version governing a request.\n *\n * For the HTTP transport, the value must match the `MCP-Protocol-Version` header.\n */\nexport const PROTOCOL_VERSION_META_KEY = 'io.modelcontextprotocol/protocolVersion';\n\n/**\n * `_meta` key identifying the client software making a request.\n *\n * Clients SHOULD include it on every request; the value is self-reported and\n * intended for display, logging, and debugging — servers should not rely on\n * it for behavior or security decisions.\n */\nexport const CLIENT_INFO_META_KEY = 'io.modelcontextprotocol/clientInfo';\n\n/**\n * `_meta` key identifying the server software producing a response.\n *\n * Servers SHOULD include it on every response; the value is self-reported and\n * intended for display, logging, and debugging — clients should not rely on\n * it for behavior or security decisions.\n */\nexport const SERVER_INFO_META_KEY = 'io.modelcontextprotocol/serverInfo';\n\n/**\n * `_meta` key carrying the client's capabilities for a request.\n *\n * Capabilities are declared per request rather than once at initialization;\n * servers must not infer capabilities from prior requests.\n */\nexport const CLIENT_CAPABILITIES_META_KEY = 'io.modelcontextprotocol/clientCapabilities';\n\n/**\n * `_meta` key carrying the JSON-RPC ID of the `subscriptions/listen` request\n * that opened the stream a notification was delivered on.\n *\n * Stamped by the server on every notification delivered via a\n * `subscriptions/listen` stream (including the leading\n * `notifications/subscriptions/acknowledged`); on stdio, where all messages\n * share one channel, clients use it to correlate notifications with their\n * originating subscription. The value is the listen request's JSON-RPC ID\n * verbatim.\n */\nexport const SUBSCRIPTION_ID_META_KEY = 'io.modelcontextprotocol/subscriptionId';\n\n/**\n * `_meta` key carrying the desired log level for a request.\n *\n * When absent, the server must not send `notifications/message` notifications\n * for the request.\n *\n * @deprecated Deprecated as of protocol version 2026-07-28 (SEP-2577); remains\n * in the specification for at least twelve months.\n */\nexport const LOG_LEVEL_META_KEY = 'io.modelcontextprotocol/logLevel';\n\n/*\n * Reserved `_meta` keys for distributed trace context propagation (SEP-414).\n *\n * These unprefixed keys are reserved by the MCP specification as an explicit\n * exception to the `_meta` key prefix rule. The SDK does not interpret them;\n * they pass through `_meta` untouched for OpenTelemetry-style propagation.\n */\n\n/**\n * `_meta` key carrying W3C Trace Context for distributed tracing (SEP-414).\n *\n * When present, the value MUST follow the W3C `traceparent` header format,\n * e.g. `00-4bf92f3577b34da6a3ce929d0e0e4736-00f067aa0ba902b7-01`.\n *\n * @see https://www.w3.org/TR/trace-context/#traceparent-header\n */\nexport const TRACEPARENT_META_KEY = 'traceparent';\n\n/**\n * `_meta` key carrying vendor-specific trace state for distributed tracing (SEP-414).\n *\n * When present, the value MUST follow the W3C `tracestate` header format,\n * e.g. `vendor1=value1,vendor2=value2`.\n *\n * @see https://www.w3.org/TR/trace-context/#tracestate-header\n */\nexport const TRACESTATE_META_KEY = 'tracestate';\n\n/**\n * `_meta` key carrying cross-cutting propagation values for distributed tracing (SEP-414).\n *\n * When present, the value MUST follow the W3C Baggage header format,\n * e.g. `userId=alice,serverRegion=us-east-1`.\n *\n * @see https://www.w3.org/TR/baggage/\n */\nexport const BAGGAGE_META_KEY = 'baggage';\n\n/* JSON-RPC types */\nexport const JSONRPC_VERSION = '2.0';\n\n/* Standard JSON-RPC error code constants */\nexport const PARSE_ERROR = -32_700;\nexport const INVALID_REQUEST = -32_600;\nexport const METHOD_NOT_FOUND = -32_601;\nexport const INVALID_PARAMS = -32_602;\nexport const INTERNAL_ERROR = -32_603;\n","import * as z from 'zod/v4';\n\nimport { JSONRPC_VERSION, RELATED_TASK_META_KEY, SERVER_INFO_META_KEY, SUBSCRIPTION_ID_META_KEY } from './constants';\nimport type { JSONArray, JSONObject, JSONValue } from './types';\n\nexport const JSONValueSchema: z.ZodType<JSONValue, JSONValue> = z.lazy(() =>\n    z.union([z.string(), z.number(), z.boolean(), z.null(), z.record(z.string(), JSONValueSchema), z.array(JSONValueSchema)])\n);\nexport const JSONObjectSchema: z.ZodType<JSONObject, JSONObject> = z.record(z.string(), JSONValueSchema);\nexport const JSONArraySchema: z.ZodType<JSONArray, JSONArray> = z.array(JSONValueSchema);\n/**\n * A progress token, used to associate progress notifications with the original request.\n */\nexport const ProgressTokenSchema = z.union([z.string(), z.number().int()]);\n\n/**\n * An opaque token used to represent a cursor for pagination.\n */\nexport const CursorSchema = z.string();\n\n/** @deprecated 2025-11-25 wire vocabulary with no SDK runtime; kept importable for interoperability only. */\nexport const TaskMetadataSchema = z.object({\n    ttl: z.number().optional()\n});\n\n/**\n * Metadata for associating messages with a task.\n * Include this in the `_meta` field under the key `io.modelcontextprotocol/related-task`.\n *\n * @deprecated 2025-11-25 wire vocabulary with no SDK runtime; kept importable for interoperability only.\n */\nexport const RelatedTaskMetadataSchema = z.object({\n    taskId: z.string()\n});\n\nexport const RequestMetaSchema = z.looseObject({\n    /**\n     * If specified, the caller is requesting out-of-band progress notifications for this request (as represented by notifications/progress). The value of this parameter is an opaque token that will be attached to any subsequent notifications. The receiver is not obligated to provide these notifications.\n     */\n    progressToken: ProgressTokenSchema.optional(),\n    /**\n     * If specified, this request is related to the provided task.\n     */\n    [RELATED_TASK_META_KEY]: RelatedTaskMetadataSchema.optional()\n});\n\n/**\n * Common params for any request.\n */\nexport const BaseRequestParamsSchema = z.object({\n    /**\n     * See [General fields: `_meta`](https://modelcontextprotocol.io/specification/2026-07-28/basic/index#meta) for notes on `_meta` usage.\n     */\n    _meta: RequestMetaSchema.optional()\n});\n\n/**\n * Common params for any task-augmented request.\n *\n * @deprecated 2025-11-25 wire vocabulary with no SDK runtime; kept importable for interoperability only.\n */\nexport const TaskAugmentedRequestParamsSchema = BaseRequestParamsSchema.extend({\n    /**\n     * If specified, the caller is requesting task-augmented execution for this request.\n     * The request will return a `CreateTaskResult` immediately, and the actual result can be\n     * retrieved later via `tasks/result`.\n     *\n     * Task augmentation is subject to capability negotiation - receivers MUST declare support\n     * for task augmentation of specific request types in their capabilities.\n     */\n    task: TaskMetadataSchema.optional()\n});\n\nexport const RequestSchema = z.object({\n    method: z.string(),\n    params: BaseRequestParamsSchema.loose().optional()\n});\n\nexport const NotificationsParamsSchema = z.object({\n    /**\n     * See [MCP specification](https://modelcontextprotocol.io/specification/2026-07-28/basic/index#general-fields)\n     * for notes on `_meta` usage.\n     */\n    _meta: RequestMetaSchema.optional()\n});\n\nexport const NotificationSchema = z.object({\n    method: z.string(),\n    params: NotificationsParamsSchema.loose().optional()\n});\n\n/**\n * The contents of a result's `_meta` field (the 2026-07-28 `ResultMetaObject`).\n * Loose — implementation-specific keys pass through.\n *\n * The serverInfo key identifies the server software producing the response\n * (servers SHOULD include it on every response; the value is self-reported\n * and intended for display, logging, and debugging). The getter defers the\n * `ImplementationSchema` reference, which is declared later in this file.\n */\nexport const ResultMetaObjectSchema = z.looseObject({\n    get [SERVER_INFO_META_KEY]() {\n        // Malformed drops to absent, matching the wire layer: the value \"is\n        // not verified by the protocol\" and clients \"SHOULD NOT use it to\n        // change their behavior\". Load-bearing beyond leniency — this schema\n        // sits inside JSONRPCResultResponseSchema, whose guard classifies\n        // every inbound message, so a strict key here would drop whole\n        // responses over a bad display-only stamp.\n        // eslint-disable-next-line unicorn/prefer-top-level-await -- Zod `.catch()`, not a Promise\n        return ImplementationSchema.optional().catch(undefined);\n    }\n});\n\nexport const ResultSchema = z.looseObject({\n    /**\n     * See [MCP specification](https://modelcontextprotocol.io/specification/2026-07-28/basic/index#general-fields)\n     * for notes on `_meta` usage.\n     */\n    _meta: ResultMetaObjectSchema.optional()\n    // `resultType` is wire-only vocabulary (protocol revision 2026-07-28) and\n    // is deliberately NOT modeled here: the neutral result schemas carry no\n    // slot for it. It exists only inside the 2026-era wire codec, which\n    // consumes it on decode and stamps it on encode. (Q1 increment 2 - the\n    // former optional member here was the masking surface that let modern\n    // vocabulary leak through every legacy-leg parse.)\n});\n\n/**\n * A uniquely identifying ID for a request in JSON-RPC.\n */\nexport const RequestIdSchema = z.union([z.string(), z.number().int()]);\n\n/**\n * A request that expects a response.\n */\nexport const JSONRPCRequestSchema = z\n    .object({\n        jsonrpc: z.literal(JSONRPC_VERSION),\n        id: RequestIdSchema,\n        ...RequestSchema.shape\n    })\n    .strict();\n\n/**\n * A notification which does not expect a response.\n */\nexport const JSONRPCNotificationSchema = z\n    .object({\n        jsonrpc: z.literal(JSONRPC_VERSION),\n        ...NotificationSchema.shape\n    })\n    .strict();\n\n/**\n * A successful (non-error) response to a request.\n */\nexport const JSONRPCResultResponseSchema = z\n    .object({\n        jsonrpc: z.literal(JSONRPC_VERSION),\n        id: RequestIdSchema,\n        result: ResultSchema\n    })\n    .strict();\n\n/**\n * A response to a request that indicates an error occurred.\n */\nexport const JSONRPCErrorResponseSchema = z\n    .object({\n        jsonrpc: z.literal(JSONRPC_VERSION),\n        id: RequestIdSchema.optional(),\n        error: z.object({\n            /**\n             * The error type that occurred.\n             */\n            code: z.number().int(),\n            /**\n             * A short description of the error. The message SHOULD be limited to a concise single sentence.\n             */\n            message: z.string(),\n            /**\n             * Additional information about the error. The value of this member is defined by the sender (e.g. detailed error information, nested errors etc.).\n             */\n            data: z.unknown().optional()\n        })\n    })\n    .strict();\n\nexport const JSONRPCMessageSchema = z.union([\n    JSONRPCRequestSchema,\n    JSONRPCNotificationSchema,\n    JSONRPCResultResponseSchema,\n    JSONRPCErrorResponseSchema\n]);\n\nexport const JSONRPCResponseSchema = z.union([JSONRPCResultResponseSchema, JSONRPCErrorResponseSchema]);\n\n/* Empty result */\n/**\n * A response that indicates success but carries no data.\n */\nexport const EmptyResultSchema = ResultSchema.strict();\n\nexport const CancelledNotificationParamsSchema = NotificationsParamsSchema.extend({\n    /**\n     * The ID of the request to cancel.\n     *\n     * This MUST correspond to the ID of a request previously issued in the same direction.\n     */\n    requestId: RequestIdSchema.optional(),\n    /**\n     * An optional string describing the reason for the cancellation. This MAY be logged or presented to the user.\n     */\n    reason: z.string().optional()\n});\n/* Cancellation */\n/**\n * This notification can be sent by either side to indicate that it is cancelling a previously-issued request.\n *\n * 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.\n *\n * This notification indicates that the result will be unused, so any associated processing SHOULD cease.\n *\n * A client MUST NOT attempt to cancel its {@linkcode InitializeRequest | initialize} request.\n */\nexport const CancelledNotificationSchema = NotificationSchema.extend({\n    method: z.literal('notifications/cancelled'),\n    params: CancelledNotificationParamsSchema\n});\n\n/* Base Metadata */\n/**\n * Icon schema for use in {@link Tool | tools}, {@link Prompt | prompts}, {@link Resource | resources}, and {@link Implementation | implementations}.\n */\nexport const IconSchema = z.object({\n    /**\n     * URL or data URI for the icon.\n     */\n    src: z.string(),\n    /**\n     * Optional MIME type for the icon.\n     */\n    mimeType: z.string().optional(),\n    /**\n     * Optional array of strings that specify sizes at which the icon can be used.\n     * Each string should be in WxH format (e.g., `\"48x48\"`, `\"96x96\"`) or `\"any\"` for scalable formats like SVG.\n     *\n     * If not provided, the client should assume that the icon can be used at any size.\n     */\n    sizes: z.array(z.string()).optional(),\n    /**\n     * Optional specifier for the theme this icon is designed for. `light` indicates\n     * the icon is designed to be used with a light background, and `dark` indicates\n     * the icon is designed to be used with a dark background.\n     *\n     * If not provided, the client should assume the icon can be used with any theme.\n     */\n    theme: z.enum(['light', 'dark']).optional()\n});\n\n/**\n * Base schema to add `icons` property.\n *\n */\nexport const IconsSchema = z.object({\n    /**\n     * Optional set of sized icons that the client can display in a user interface.\n     *\n     * Clients that support rendering icons MUST support at least the following MIME types:\n     * - `image/png` - PNG images (safe, universal compatibility)\n     * - `image/jpeg` (and `image/jpg`) - JPEG images (safe, universal compatibility)\n     *\n     * Clients that support rendering icons SHOULD also support:\n     * - `image/svg+xml` - SVG images (scalable but requires security precautions)\n     * - `image/webp` - WebP images (modern, efficient format)\n     */\n    icons: z.array(IconSchema).optional()\n});\n\n/**\n * Base metadata interface for common properties across {@link Resource | resources}, {@link Tool | tools}, {@link Prompt | prompts}, and {@link Implementation | implementations}.\n */\nexport const BaseMetadataSchema = z.object({\n    /** Intended for programmatic or logical use, but used as a display name in past specs or fallback */\n    name: z.string(),\n    /**\n     * Intended for UI and end-user contexts — optimized to be human-readable and easily understood,\n     * even by those unfamiliar with domain-specific terminology.\n     *\n     * If not provided, the `name` should be used for display (except for `Tool`,\n     * where `annotations.title` should be given precedence over using `name`,\n     * if present).\n     */\n    title: z.string().optional()\n});\n\n/* Initialization */\n/**\n * Describes the name and version of an MCP implementation.\n */\nexport const ImplementationSchema = BaseMetadataSchema.extend({\n    ...BaseMetadataSchema.shape,\n    ...IconsSchema.shape,\n    version: z.string(),\n    /**\n     * An optional URL of the website for this implementation.\n     */\n    websiteUrl: z.string().optional(),\n\n    /**\n     * An optional human-readable description of what this implementation does.\n     *\n     * This can be used by clients or servers to provide context about their purpose\n     * and capabilities. For example, a server might describe the types of resources\n     * or tools it provides, while a client might describe its intended use case.\n     */\n    description: z.string().optional()\n});\n\nconst FormElicitationCapabilitySchema = z.intersection(\n    z.object({\n        applyDefaults: z.boolean().optional()\n    }),\n    JSONObjectSchema\n);\n\nconst ElicitationCapabilitySchema = z.preprocess(\n    value => {\n        if (value && typeof value === 'object' && !Array.isArray(value) && Object.keys(value as Record<string, unknown>).length === 0) {\n            return { form: {} };\n        }\n        return value;\n    },\n    z.intersection(\n        z.object({\n            form: FormElicitationCapabilitySchema.optional(),\n            url: JSONObjectSchema.optional()\n        }),\n        JSONObjectSchema.optional()\n    )\n);\n\n/**\n * Task capabilities for clients, indicating which request types support task creation.\n *\n * @deprecated 2025-11-25 wire vocabulary with no SDK runtime; kept importable for interoperability only.\n */\nexport const ClientTasksCapabilitySchema = z.looseObject({\n    /**\n     * Present if the client supports listing tasks.\n     */\n    list: JSONObjectSchema.optional(),\n    /**\n     * Present if the client supports cancelling tasks.\n     */\n    cancel: JSONObjectSchema.optional(),\n    /**\n     * Capabilities for task creation on specific request types.\n     */\n    requests: z\n        .looseObject({\n            /**\n             * Task support for sampling requests.\n             */\n            sampling: z\n                .looseObject({\n                    createMessage: JSONObjectSchema.optional()\n                })\n                .optional(),\n            /**\n             * Task support for elicitation requests.\n             */\n            elicitation: z\n                .looseObject({\n                    create: JSONObjectSchema.optional()\n                })\n                .optional()\n        })\n        .optional()\n});\n\n/**\n * Task capabilities for servers, indicating which request types support task creation.\n *\n * @deprecated 2025-11-25 wire vocabulary with no SDK runtime; kept importable for interoperability only.\n */\nexport const ServerTasksCapabilitySchema = z.looseObject({\n    /**\n     * Present if the server supports listing tasks.\n     */\n    list: JSONObjectSchema.optional(),\n    /**\n     * Present if the server supports cancelling tasks.\n     */\n    cancel: JSONObjectSchema.optional(),\n    /**\n     * Capabilities for task creation on specific request types.\n     */\n    requests: z\n        .looseObject({\n            /**\n             * Task support for tool requests.\n             */\n            tools: z\n                .looseObject({\n                    call: JSONObjectSchema.optional()\n                })\n                .optional()\n        })\n        .optional()\n});\n\n/**\n * 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.\n */\nexport const ClientCapabilitiesSchema = z.object({\n    /**\n     * Experimental, non-standard capabilities that the client supports.\n     */\n    experimental: z.record(z.string(), JSONObjectSchema).optional(),\n    /**\n     * Present if the client supports sampling from an LLM.\n     *\n     * @deprecated Deprecated as of protocol version 2026-07-28 (SEP-2577); remains\n     * in the specification for at least twelve months. Migrate to calling LLM\n     * provider APIs directly.\n     */\n    sampling: z\n        .object({\n            /**\n             * Present if the client supports context inclusion via `includeContext` parameter.\n             * If not declared, servers SHOULD only use `includeContext: \"none\"` (or omit it).\n             */\n            context: JSONObjectSchema.optional(),\n            /**\n             * Present if the client supports tool use via `tools` and `toolChoice` parameters.\n             */\n            tools: JSONObjectSchema.optional()\n        })\n        .optional(),\n    /**\n     * Present if the client supports eliciting user input.\n     */\n    elicitation: ElicitationCapabilitySchema.optional(),\n    /**\n     * Present if the client supports listing roots.\n     *\n     * @deprecated Deprecated as of protocol version 2026-07-28 (SEP-2577); remains\n     * in the specification for at least twelve months. Migrate to passing paths via\n     * tool parameters, resource URIs, or configuration.\n     */\n    roots: z\n        .object({\n            /**\n             * Whether the client supports issuing notifications for changes to the roots list.\n             */\n            listChanged: z.boolean().optional()\n        })\n        .optional(),\n    /**\n     * Present if the client supports task creation.\n     *\n     * @deprecated 2025-11-25 wire vocabulary with no SDK runtime; parsed for interoperability only — servers built on this SDK never advertise it.\n     */\n    tasks: ClientTasksCapabilitySchema.optional(),\n    /**\n     * Extensions that the client supports. Keys are extension identifiers (vendor-prefix/extension-name).\n     */\n    extensions: z.record(z.string(), JSONObjectSchema).optional()\n});\n\nexport const InitializeRequestParamsSchema = BaseRequestParamsSchema.extend({\n    /**\n     * The latest version of the Model Context Protocol that the client supports. The client MAY decide to support older versions as well.\n     */\n    protocolVersion: z.string(),\n    capabilities: ClientCapabilitiesSchema,\n    clientInfo: ImplementationSchema\n});\n/**\n * This request is sent from the client to the server when it first connects, asking it to begin initialization.\n */\nexport const InitializeRequestSchema = RequestSchema.extend({\n    method: z.literal('initialize'),\n    params: InitializeRequestParamsSchema\n});\n\n/**\n * 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.\n */\nexport const ServerCapabilitiesSchema = z.object({\n    /**\n     * Experimental, non-standard capabilities that the server supports.\n     */\n    experimental: z.record(z.string(), JSONObjectSchema).optional(),\n    /**\n     * Present if the server supports sending log messages to the client.\n     *\n     * @deprecated Deprecated as of protocol version 2026-07-28 (SEP-2577); remains\n     * in the specification for at least twelve months. Migrate to stderr logging\n     * (STDIO servers) or OpenTelemetry.\n     */\n    logging: JSONObjectSchema.optional(),\n    /**\n     * Present if the server supports sending completions to the client.\n     */\n    completions: JSONObjectSchema.optional(),\n    /**\n     * Present if the server offers any prompt templates.\n     */\n    prompts: z\n        .object({\n            /**\n             * Whether this server supports issuing notifications for changes to the prompt list.\n             */\n            listChanged: z.boolean().optional()\n        })\n        .optional(),\n    /**\n     * Present if the server offers any resources to read.\n     */\n    resources: z\n        .object({\n            /**\n             * Whether this server supports clients subscribing to resource updates.\n             */\n            subscribe: z.boolean().optional(),\n\n            /**\n             * Whether this server supports issuing notifications for changes to the resource list.\n             */\n            listChanged: z.boolean().optional()\n        })\n        .optional(),\n    /**\n     * Present if the server offers any tools to call.\n     */\n    tools: z\n        .object({\n            /**\n             * Whether this server supports issuing notifications for changes to the tool list.\n             */\n            listChanged: z.boolean().optional()\n        })\n        .optional(),\n    /**\n     * Present if the server supports task creation.\n     *\n     * @deprecated 2025-11-25 wire vocabulary with no SDK runtime; parsed for interoperability only — servers built on this SDK never advertise it.\n     */\n    tasks: ServerTasksCapabilitySchema.optional(),\n    /**\n     * Extensions that the server supports. Keys are extension identifiers (vendor-prefix/extension-name).\n     */\n    extensions: z.record(z.string(), JSONObjectSchema).optional()\n});\n\n/**\n * After receiving an initialize request from the client, the server sends this response.\n */\nexport const InitializeResultSchema = ResultSchema.extend({\n    /**\n     * The version of the Model Context Protocol that the server wants to use. This may not match the version that the client requested. If the client cannot support this version, it MUST disconnect.\n     */\n    protocolVersion: z.string(),\n    capabilities: ServerCapabilitiesSchema,\n    serverInfo: ImplementationSchema,\n    /**\n     * Instructions describing how to use the server and its features.\n     *\n     * This can be used by clients to improve the LLM's understanding of available tools, resources, etc. It can be thought of like a \"hint\" to the model. For example, this information MAY be added to the system prompt.\n     */\n    instructions: z.string().optional()\n});\n\n/**\n * This notification is sent from the client to the server after initialization has finished.\n */\nexport const InitializedNotificationSchema = NotificationSchema.extend({\n    method: z.literal('notifications/initialized'),\n    params: NotificationsParamsSchema.optional()\n});\n\n/* Discovery */\n/**\n * A request from the client asking the server to advertise its supported protocol\n * versions, capabilities, and other metadata (protocol revision 2026-07-28). Servers\n * MUST implement `server/discover`. Clients MAY call it but are not required to —\n * version negotiation can also happen inline via the per-request `_meta` envelope.\n */\nexport const DiscoverRequestSchema = RequestSchema.extend({\n    method: z.literal('server/discover'),\n    params: BaseRequestParamsSchema.optional()\n});\n\n/**\n * The result returned by the server for a `server/discover` request.\n */\nexport const DiscoverResultSchema = ResultSchema.extend({\n    /**\n     * MCP protocol versions this server supports. The client should choose a\n     * version from this list for use in subsequent requests.\n     */\n    supportedVersions: z.array(z.string()),\n    /**\n     * The capabilities of the server.\n     */\n    capabilities: ServerCapabilitiesSchema,\n    /**\n     * Instructions describing how to use the server and its features.\n     *\n     * This can be used by clients to improve the LLM's understanding of available tools, resources, etc. It can be thought of like a \"hint\" to the model. For example, this information MAY be added to the system prompt.\n     *\n     * Server identity is not a body field: it travels in\n     * `_meta['io.modelcontextprotocol/serverInfo']` (spec PR #3002).\n     */\n    instructions: z.string().optional()\n});\n\n/* Ping */\n/**\n * 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.\n */\nexport const PingRequestSchema = RequestSchema.extend({\n    method: z.literal('ping'),\n    params: BaseRequestParamsSchema.optional()\n});\n\n/* Progress notifications */\nexport const ProgressSchema = z.object({\n    /**\n     * The progress thus far. This should increase every time progress is made, even if the total is unknown.\n     */\n    progress: z.number(),\n    /**\n     * Total number of items to process (or total progress required), if known.\n     */\n    total: z.optional(z.number()),\n    /**\n     * An optional message describing the current progress.\n     */\n    message: z.optional(z.string())\n});\n\nexport const ProgressNotificationParamsSchema = z.object({\n    ...NotificationsParamsSchema.shape,\n    ...ProgressSchema.shape,\n    /**\n     * The progress token which was given in the initial request, used to associate this notification with the request that is proceeding.\n     */\n    progressToken: ProgressTokenSchema\n});\n/**\n * An out-of-band notification used to inform the receiver of a progress update for a long-running request.\n *\n * @category notifications/progress\n */\nexport const ProgressNotificationSchema = NotificationSchema.extend({\n    method: z.literal('notifications/progress'),\n    params: ProgressNotificationParamsSchema\n});\n\nexport const PaginatedRequestParamsSchema = BaseRequestParamsSchema.extend({\n    /**\n     * An opaque token representing the current pagination position.\n     * If provided, the server should return results starting after this cursor.\n     */\n    cursor: CursorSchema.optional()\n});\n\n/* Pagination */\nexport const PaginatedRequestSchema = RequestSchema.extend({\n    params: PaginatedRequestParamsSchema.optional()\n});\n\nexport const PaginatedResultSchema = ResultSchema.extend({\n    /**\n     * An opaque token representing the pagination position after the last returned result.\n     * If present, there may be more results available.\n     */\n    nextCursor: CursorSchema.optional()\n});\n\n/* Resources */\n/**\n * The contents of a specific resource or sub-resource.\n */\nexport const ResourceContentsSchema = z.object({\n    /**\n     * The URI of this resource.\n     */\n    uri: z.string(),\n    /**\n     * The MIME type of this resource, if known.\n     */\n    mimeType: z.optional(z.string()),\n    /**\n     * See [MCP specification](https://modelcontextprotocol.io/specification/2026-07-28/basic/index#general-fields)\n     * for notes on `_meta` usage.\n     */\n    _meta: z.record(z.string(), z.unknown()).optional()\n});\n\nexport const TextResourceContentsSchema = ResourceContentsSchema.extend({\n    /**\n     * The text of the item. This must only be set if the item can actually be represented as text (not binary data).\n     */\n    text: z.string()\n});\n\n/**\n * A Zod schema for validating Base64 strings that is more performant and\n * robust for very large inputs than the default regex-based check. It avoids\n * stack overflows by using the native `atob` function for validation.\n */\nconst Base64Schema = z.string().refine(\n    val => {\n        try {\n            // atob throws a DOMException if the string contains characters\n            // that are not part of the Base64 character set.\n            atob(val);\n            return true;\n        } catch {\n            return false;\n        }\n    },\n    { message: 'Invalid Base64 string' }\n);\n\nexport const BlobResourceContentsSchema = ResourceContentsSchema.extend({\n    /**\n     * A base64-encoded string representing the binary data of the item.\n     */\n    blob: Base64Schema\n});\n\n/**\n * The sender or recipient of messages and data in a conversation.\n */\nexport const RoleSchema = z.enum(['user', 'assistant']);\n\n/**\n * Optional annotations providing clients additional context about a resource.\n */\nexport const AnnotationsSchema = z.object({\n    /**\n     * Intended audience(s) for the resource.\n     */\n    audience: z.array(RoleSchema).optional(),\n\n    /**\n     * Importance hint for the resource, from 0 (least) to 1 (most).\n     */\n    priority: z.number().min(0).max(1).optional(),\n\n    /**\n     * ISO 8601 timestamp for the most recent modification.\n     */\n    lastModified: z.iso.datetime({ offset: true }).optional()\n});\n\n/**\n * A known resource that the server is capable of reading.\n */\nexport const ResourceSchema = z.object({\n    ...BaseMetadataSchema.shape,\n    ...IconsSchema.shape,\n    /**\n     * The URI of this resource.\n     */\n    uri: z.string(),\n\n    /**\n     * A description of what this resource represents.\n     *\n     * This can be used by clients to improve the LLM's understanding of available resources. It can be thought of like a \"hint\" to the model.\n     */\n    description: z.optional(z.string()),\n\n    /**\n     * The MIME type of this resource, if known.\n     */\n    mimeType: z.optional(z.string()),\n\n    /**\n     * The size of the raw resource content, in bytes (i.e., before base64 encoding or any tokenization), if known.\n     *\n     * This can be used by Hosts to display file sizes and estimate context window usage.\n     */\n    size: z.optional(z.number()),\n\n    /**\n     * Optional annotations for the client.\n     */\n    annotations: AnnotationsSchema.optional(),\n\n    /**\n     * See [MCP specification](https://modelcontextprotocol.io/specification/2026-07-28/basic/index#general-fields)\n     * for notes on `_meta` usage.\n     */\n    _meta: z.optional(z.looseObject({}))\n});\n\n/**\n * A template description for resources available on the server.\n */\nexport const ResourceTemplateSchema = z.object({\n    ...BaseMetadataSchema.shape,\n    ...IconsSchema.shape,\n    /**\n     * A URI template (according to RFC 6570) that can be used to construct resource URIs.\n     */\n    uriTemplate: z.string(),\n\n    /**\n     * A description of what this template is for.\n     *\n     * This can be used by clients to improve the LLM's understanding of available resources. It can be thought of like a \"hint\" to the model.\n     */\n    description: z.optional(z.string()),\n\n    /**\n     * The MIME type for all resources that match this template. This should only be included if all resources matching this template have the same type.\n     */\n    mimeType: z.optional(z.string()),\n\n    /**\n     * Optional annotations for the client.\n     */\n    annotations: AnnotationsSchema.optional(),\n\n    /**\n     * See [MCP specification](https://modelcontextprotocol.io/specification/2026-07-28/basic/index#general-fields)\n     * for notes on `_meta` usage.\n     */\n    _meta: z.optional(z.looseObject({}))\n});\n\n/**\n * Sent from the client to request a list of resources the server has.\n */\nexport const ListResourcesRequestSchema = PaginatedRequestSchema.extend({\n    method: z.literal('resources/list')\n});\n\n/**\n * The server's response to a {@linkcode ListResourcesRequest | resources/list} request from the client.\n */\nexport const ListResourcesResultSchema = PaginatedResultSchema.extend({\n    resources: z.array(ResourceSchema)\n});\n\n/**\n * Sent from the client to request a list of resource templates the server has.\n */\nexport const ListResourceTemplatesRequestSchema = PaginatedRequestSchema.extend({\n    method: z.literal('resources/templates/list')\n});\n\n/**\n * The server's response to a {@linkcode ListResourceTemplatesRequest | resources/templates/list} request from the client.\n */\nexport const ListResourceTemplatesResultSchema = PaginatedResultSchema.extend({\n    resourceTemplates: z.array(ResourceTemplateSchema)\n});\n\nexport const ResourceRequestParamsSchema = BaseRequestParamsSchema.extend({\n    /**\n     * The URI of the resource to read. The URI can use any protocol; it is up to the server how to interpret it.\n     *\n     * @format uri\n     */\n    uri: z.string()\n});\n\n/**\n * Parameters for a {@linkcode ReadResourceRequest | resources/read} request.\n */\nexport const ReadResourceRequestParamsSchema = ResourceRequestParamsSchema;\n\n/**\n * Sent from the client to the server, to read a specific resource URI.\n */\nexport const ReadResourceRequestSchema = RequestSchema.extend({\n    method: z.literal('resources/read'),\n    params: ReadResourceRequestParamsSchema\n});\n\n/**\n * The server's response to a {@linkcode ReadResourceRequest | resources/read} request from the client.\n */\nexport const ReadResourceResultSchema = ResultSchema.extend({\n    contents: z.array(z.union([TextResourceContentsSchema, BlobResourceContentsSchema]))\n});\n\n/**\n * 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.\n */\nexport const ResourceListChangedNotificationSchema = NotificationSchema.extend({\n    method: z.literal('notifications/resources/list_changed'),\n    params: NotificationsParamsSchema.optional()\n});\n\nexport const SubscribeRequestParamsSchema = ResourceRequestParamsSchema;\n/**\n * Sent from the client to request `resources/updated` notifications from the server whenever a particular resource changes.\n */\nexport const SubscribeRequestSchema = RequestSchema.extend({\n    method: z.literal('resources/subscribe'),\n    params: SubscribeRequestParamsSchema\n});\n\nexport const UnsubscribeRequestParamsSchema = ResourceRequestParamsSchema;\n/**\n * 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.\n */\nexport const UnsubscribeRequestSchema = RequestSchema.extend({\n    method: z.literal('resources/unsubscribe'),\n    params: UnsubscribeRequestParamsSchema\n});\n\n/* Subscriptions (protocol revision 2026-07-28) */\n/**\n * The set of notification types a client opts in to on a `subscriptions/listen`\n * request. Each type is opt-in; the server MUST NOT send a notification type\n * the client has not explicitly requested here.\n */\nexport const SubscriptionFilterSchema = z.object({\n    /**\n     * If true, receive `notifications/tools/list_changed`.\n     */\n    toolsListChanged: z.boolean().optional(),\n    /**\n     * If true, receive `notifications/prompts/list_changed`.\n     */\n    promptsListChanged: z.boolean().optional(),\n    /**\n     * If true, receive `notifications/resources/list_changed`.\n     */\n    resourcesListChanged: z.boolean().optional(),\n    /**\n     * Subscribe to `notifications/resources/updated` for these resource URIs.\n     * Replaces the former `resources/subscribe` RPC on the 2026-07-28 revision.\n     */\n    resourceSubscriptions: z.array(z.string()).optional()\n});\n\nexport const SubscriptionsListenRequestParamsSchema = BaseRequestParamsSchema.extend({\n    /**\n     * The notifications the client opts in to on this stream. The server MUST\n     * NOT send notification types the client has not explicitly requested.\n     */\n    notifications: SubscriptionFilterSchema\n});\n\n/**\n * Sent from the client to open a long-lived channel for receiving notifications\n * outside the context of a specific request (protocol revision 2026-07-28).\n * Replaces the previous HTTP GET endpoint and `resources/subscribe`.\n */\nexport const SubscriptionsListenRequestSchema = RequestSchema.extend({\n    method: z.literal('subscriptions/listen'),\n    params: SubscriptionsListenRequestParamsSchema\n});\n\nexport const SubscriptionsAcknowledgedNotificationParamsSchema = NotificationsParamsSchema.extend({\n    /**\n     * The subset of requested notification types the server agreed to honor.\n     */\n    notifications: SubscriptionFilterSchema\n});\n\n/**\n * Sent by the server as the first message on a `subscriptions/listen` stream\n * to acknowledge that the subscription has been established and report which\n * notification types it agreed to honor (protocol revision 2026-07-28).\n */\nexport const SubscriptionsAcknowledgedNotificationSchema = NotificationSchema.extend({\n    method: z.literal('notifications/subscriptions/acknowledged'),\n    params: SubscriptionsAcknowledgedNotificationParamsSchema\n});\n\n/**\n * `_meta` for a {@linkcode SubscriptionsListenResult}: the listen request's\n * JSON-RPC ID under the canonical subscription-id key (mirroring the same key\n * on every notification delivered on the stream). Extends\n * {@linkcode ResultMetaObjectSchema}, so the optional serverInfo key is typed\n * here too.\n */\nexport const SubscriptionsListenResultMetaSchema = ResultMetaObjectSchema.extend({\n    [SUBSCRIPTION_ID_META_KEY]: RequestIdSchema\n});\n\n/**\n * The response to a `subscriptions/listen` request, signalling that the\n * subscription has ended gracefully (for example, during server shutdown).\n * Because the listen stream is long-lived, this result is sent only when the\n * server tears the subscription down; an abrupt transport close carries no\n * response. The result body is otherwise empty.\n */\nexport const SubscriptionsListenResultSchema = ResultSchema.extend({\n    _meta: SubscriptionsListenResultMetaSchema\n});\n\n/**\n * Parameters for a {@linkcode ResourceUpdatedNotification | notifications/resources/updated} notification.\n */\nexport const ResourceUpdatedNotificationParamsSchema = NotificationsParamsSchema.extend({\n    /**\n     * The URI of the resource that has been updated. This might be a sub-resource of the one that the client actually subscribed to.\n     */\n    uri: z.string()\n});\n\n/**\n * 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.\n */\nexport const ResourceUpdatedNotificationSchema = NotificationSchema.extend({\n    method: z.literal('notifications/resources/updated'),\n    params: ResourceUpdatedNotificationParamsSchema\n});\n\n/* Prompts */\n/**\n * Describes an argument that a prompt can accept.\n */\nexport const PromptArgumentSchema = z.object({\n    /**\n     * The name of the argument.\n     */\n    name: z.string(),\n    /**\n     * A human-readable description of the argument.\n     */\n    description: z.optional(z.string()),\n    /**\n     * Whether this argument must be provided.\n     */\n    required: z.optional(z.boolean())\n});\n\n/**\n * A prompt or prompt template that the server offers.\n */\nexport const PromptSchema = z.object({\n    ...BaseMetadataSchema.shape,\n    ...IconsSchema.shape,\n    /**\n     * An optional description of what this prompt provides\n     */\n    description: z.optional(z.string()),\n    /**\n     * A list of arguments to use for templating the prompt.\n     */\n    arguments: z.optional(z.array(PromptArgumentSchema)),\n    /**\n     * See [MCP specification](https://modelcontextprotocol.io/specification/2026-07-28/basic/index#general-fields)\n     * for notes on `_meta` usage.\n     */\n    _meta: z.optional(z.looseObject({}))\n});\n\n/**\n * Sent from the client to request a list of prompts and prompt templates the server has.\n */\nexport const ListPromptsRequestSchema = PaginatedRequestSchema.extend({\n    method: z.literal('prompts/list')\n});\n\n/**\n * The server's response to a {@linkcode ListPromptsRequest | prompts/list} request from the client.\n */\nexport const ListPromptsResultSchema = PaginatedResultSchema.extend({\n    prompts: z.array(PromptSchema)\n});\n\n/**\n * Parameters for a {@linkcode GetPromptRequest | prompts/get} request.\n */\nexport const GetPromptRequestParamsSchema = BaseRequestParamsSchema.extend({\n    /**\n     * The name of the prompt or prompt template.\n     */\n    name: z.string(),\n    /**\n     * Arguments to use for templating the prompt.\n     */\n    arguments: z.record(z.string(), z.string()).optional()\n});\n/**\n * Used by the client to get a prompt provided by the server.\n */\nexport const GetPromptRequestSchema = RequestSchema.extend({\n    method: z.literal('prompts/get'),\n    params: GetPromptRequestParamsSchema\n});\n\n/**\n * Text provided to or from an LLM.\n */\nexport const TextContentSchema = z.object({\n    type: z.literal('text'),\n    /**\n     * The text content of the message.\n     */\n    text: z.string(),\n\n    /**\n     * Optional annotations for the client.\n     */\n    annotations: AnnotationsSchema.optional(),\n\n    /**\n     * See [MCP specification](https://modelcontextprotocol.io/specification/2026-07-28/basic/index#general-fields)\n     * for notes on `_meta` usage.\n     */\n    _meta: z.record(z.string(), z.unknown()).optional()\n});\n\n/**\n * An image provided to or from an LLM.\n */\nexport const ImageContentSchema = z.object({\n    type: z.literal('image'),\n    /**\n     * The base64-encoded image data.\n     */\n    data: Base64Schema,\n    /**\n     * The MIME type of the image. Different providers may support different image types.\n     */\n    mimeType: z.string(),\n\n    /**\n     * Optional annotations for the client.\n     */\n    annotations: AnnotationsSchema.optional(),\n\n    /**\n     * See [MCP specification](https://modelcontextprotocol.io/specification/2026-07-28/basic/index#general-fields)\n     * for notes on `_meta` usage.\n     */\n    _meta: z.record(z.string(), z.unknown()).optional()\n});\n\n/**\n * Audio content provided to or from an LLM.\n */\nexport const AudioContentSchema = z.object({\n    type: z.literal('audio'),\n    /**\n     * The base64-encoded audio data.\n     */\n    data: Base64Schema,\n    /**\n     * The MIME type of the audio. Different providers may support different audio types.\n     */\n    mimeType: z.string(),\n\n    /**\n     * Optional annotations for the client.\n     */\n    annotations: AnnotationsSchema.optional(),\n\n    /**\n     * See [MCP specification](https://modelcontextprotocol.io/specification/2026-07-28/basic/index#general-fields)\n     * for notes on `_meta` usage.\n     */\n    _meta: z.record(z.string(), z.unknown()).optional()\n});\n\n/**\n * A tool call request from an assistant (LLM).\n * Represents the assistant's request to use a tool.\n *\n * @deprecated Deprecated as of protocol version 2026-07-28 (SEP-2577); remains\n * in the specification for at least twelve months. Migrate to calling LLM\n * provider APIs directly.\n */\nexport const ToolUseContentSchema = z.object({\n    type: z.literal('tool_use'),\n    /**\n     * The name of the tool to invoke.\n     * Must match a tool name from the request's tools array.\n     */\n    name: z.string(),\n    /**\n     * Unique identifier for this tool call.\n     * Used to correlate with `ToolResultContent` in subsequent messages.\n     */\n    id: z.string(),\n    /**\n     * Arguments to pass to the tool.\n     * Must conform to the tool's `inputSchema`.\n     */\n    input: z.record(z.string(), z.unknown()),\n    /**\n     * See [MCP specification](https://modelcontextprotocol.io/specification/2026-07-28/basic/index#general-fields)\n     * for notes on `_meta` usage.\n     */\n    _meta: z.record(z.string(), z.unknown()).optional()\n});\n\n/**\n * The contents of a resource, embedded into a prompt or tool call result.\n */\nexport const EmbeddedResourceSchema = z.object({\n    type: z.literal('resource'),\n    resource: z.union([TextResourceContentsSchema, BlobResourceContentsSchema]),\n    /**\n     * Optional annotations for the client.\n     */\n    annotations: AnnotationsSchema.optional(),\n    /**\n     * See [MCP specification](https://modelcontextprotocol.io/specification/2026-07-28/basic/index#general-fields)\n     * for notes on `_meta` usage.\n     */\n    _meta: z.record(z.string(), z.unknown()).optional()\n});\n\n/**\n * A resource that the server is capable of reading, included in a prompt or tool call result.\n *\n * Note: resource links returned by tools are not guaranteed to appear in the results of {@linkcode ListResourcesRequest | resources/list} requests.\n */\nexport const ResourceLinkSchema = ResourceSchema.extend({\n    type: z.literal('resource_link')\n});\n\n/**\n * A content block that can be used in prompts and tool results.\n */\nexport const ContentBlockSchema = z.union([\n    TextContentSchema,\n    ImageContentSchema,\n    AudioContentSchema,\n    ResourceLinkSchema,\n    EmbeddedResourceSchema\n]);\n\n/**\n * Describes a message returned as part of a prompt.\n */\nexport const PromptMessageSchema = z.object({\n    role: RoleSchema,\n    content: ContentBlockSchema\n});\n\n/**\n * The server's response to a {@linkcode GetPromptRequest | prompts/get} request from the client.\n */\nexport const GetPromptResultSchema = ResultSchema.extend({\n    /**\n     * An optional description for the prompt.\n     */\n    description: z.string().optional(),\n    messages: z.array(PromptMessageSchema)\n});\n\n/**\n * 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.\n */\nexport const PromptListChangedNotificationSchema = NotificationSchema.extend({\n    method: z.literal('notifications/prompts/list_changed'),\n    params: NotificationsParamsSchema.optional()\n});\n\n/* Tools */\n/**\n * Additional properties describing a `Tool` to clients.\n *\n * NOTE: all properties in {@linkcode ToolAnnotations} are **hints**.\n * They are not guaranteed to provide a faithful description of\n * tool behavior (including descriptive properties like `title`).\n *\n * Clients should never make tool use decisions based on `ToolAnnotations`\n * received from untrusted servers.\n */\nexport const ToolAnnotationsSchema = z.object({\n    /**\n     * A human-readable title for the tool.\n     */\n    title: z.string().optional(),\n\n    /**\n     * If `true`, the tool does not modify its environment.\n     *\n     * Default: `false`\n     */\n    readOnlyHint: z.boolean().optional(),\n\n    /**\n     * If `true`, the tool may perform destructive updates to its environment.\n     * If `false`, the tool performs only additive updates.\n     *\n     * (This property is meaningful only when `readOnlyHint == false`)\n     *\n     * Default: `true`\n     */\n    destructiveHint: z.boolean().optional(),\n\n    /**\n     * If `true`, calling the tool repeatedly with the same arguments\n     * will have no additional effect on its environment.\n     *\n     * (This property is meaningful only when `readOnlyHint == false`)\n     *\n     * Default: `false`\n     */\n    idempotentHint: z.boolean().optional(),\n\n    /**\n     * If `true`, this tool may interact with an \"open world\" of external\n     * entities. If `false`, the tool's domain of interaction is closed.\n     * For example, the world of a web search tool is open, whereas that\n     * of a memory tool is not.\n     *\n     * Default: `true`\n     */\n    openWorldHint: z.boolean().optional()\n});\n\n/**\n * Execution-related properties for a tool.\n */\nexport const ToolExecutionSchema = z.object({\n    /**\n     * Indicates the tool's preference for task-augmented execution.\n     * - `\"required\"`: Clients MUST invoke the tool as a task\n     * - `\"optional\"`: Clients MAY invoke the tool as a task or normal request\n     * - `\"forbidden\"`: Clients MUST NOT attempt to invoke the tool as a task\n     *\n     * If not present, defaults to `\"forbidden\"`.\n     */\n    taskSupport: z.enum(['required', 'optional', 'forbidden']).optional()\n});\n\n/**\n * Definition for a tool the client can call.\n */\nexport const ToolSchema = z.object({\n    ...BaseMetadataSchema.shape,\n    ...IconsSchema.shape,\n    /**\n     * A human-readable description of the tool.\n     */\n    description: z.string().optional(),\n    /**\n     * A JSON Schema 2020-12 object defining the expected parameters for the tool.\n     * Must have `type: 'object'` at the root level per MCP spec.\n     */\n    inputSchema: z\n        .object({\n            type: z.literal('object'),\n            properties: z.record(z.string(), JSONValueSchema).optional(),\n            required: z.array(z.string()).optional()\n        })\n        .catchall(z.unknown()),\n    /**\n     * An optional JSON Schema 2020-12 document describing the structure of the tool's output\n     * returned in the `structuredContent` field of a `CallToolResult`.\n     *\n     * SEP-2106: any JSON Schema root is permitted (e.g. `type:'array'`, `oneOf`, `$ref`).\n     * The 2025-11-25 wire parse retains the `type:'object'` constraint via the frozen schema in\n     * `wire/rev2025-11-25/schemas.ts`; this neutral/public schema widens.\n     */\n    outputSchema: z.looseObject({ $schema: z.string().optional() }).optional(),\n    /**\n     * Optional additional tool information.\n     */\n    annotations: ToolAnnotationsSchema.optional(),\n    /**\n     * Execution-related properties for this tool.\n     */\n    execution: ToolExecutionSchema.optional(),\n\n    /**\n     * See [MCP specification](https://modelcontextprotocol.io/specification/2026-07-28/basic/index#general-fields)\n     * for notes on `_meta` usage.\n     */\n    _meta: z.record(z.string(), z.unknown()).optional()\n});\n\n/**\n * Sent from the client to request a list of tools the server has.\n */\nexport const ListToolsRequestSchema = PaginatedRequestSchema.extend({\n    method: z.literal('tools/list')\n});\n\n/**\n * The server's response to a {@linkcode ListToolsRequest | tools/list} request from the client.\n */\nexport const ListToolsResultSchema = PaginatedResultSchema.extend({\n    tools: z.array(ToolSchema)\n});\n\n/**\n * The server's response to a tool call.\n */\nexport const CallToolResultSchema = ResultSchema.extend({\n    /**\n     * A list of content objects that represent the result of the tool call.\n     *\n     * If the `Tool` does not define an outputSchema, this field MUST be present in the result.\n     * Required on the wire per the specification (it may be an empty array).\n     *\n     * Parse-tolerant: absent `content` defaults to `[]` (v1 parity — deployed\n     * servers omit it alongside `structuredContent`).\n     */\n    content: z.array(ContentBlockSchema).default([]),\n\n    /**\n     * Structured tool output.\n     *\n     * If the `Tool` defines an `outputSchema`, this field MUST be present in the result and\n     * contain a JSON value that matches the schema.\n     *\n     * SEP-2106: any JSON value is permitted (arrays, primitives, `null`). Narrow before property\n     * access. The 2025-11-25 wire parse retains the object-only constraint via the frozen schema\n     * in `wire/rev2025-11-25/schemas.ts`; this neutral/public schema widens.\n     */\n    structuredContent: z.unknown().optional(),\n\n    /**\n     * Whether the tool call ended in an error.\n     *\n     * If not set, this is assumed to be `false` (the call was successful).\n     *\n     * Any errors that originate from the tool SHOULD be reported inside the result\n     * object, with `isError` set to `true`, _not_ as an MCP protocol-level error\n     * response. Otherwise, the LLM would not be able to see that an error occurred\n     * and self-correct.\n     *\n     * However, any errors in _finding_ the tool, an error indicating that the\n     * server does not support tool calls, or any other exceptional conditions,\n     * should be reported as an MCP error response.\n     */\n    isError: z.boolean().optional()\n});\n\n/**\n * {@linkcode CallToolResultSchema} extended with backwards compatibility to protocol version 2024-10-07.\n */\nexport const CompatibilityCallToolResultSchema = CallToolResultSchema.or(\n    ResultSchema.extend({\n        toolResult: z.unknown()\n    })\n);\n\n/**\n * Parameters for a `tools/call` request.\n */\nexport const CallToolRequestParamsSchema = TaskAugmentedRequestParamsSchema.extend({\n    /**\n     * The name of the tool to call.\n     */\n    name: z.string(),\n    /**\n     * Arguments to pass to the tool.\n     */\n    arguments: z.record(z.string(), z.unknown()).optional()\n});\n\n/**\n * Used by the client to invoke a tool provided by the server.\n */\nexport const CallToolRequestSchema = RequestSchema.extend({\n    method: z.literal('tools/call'),\n    params: CallToolRequestParamsSchema\n});\n\n/**\n * 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.\n */\nexport const ToolListChangedNotificationSchema = NotificationSchema.extend({\n    method: z.literal('notifications/tools/list_changed'),\n    params: NotificationsParamsSchema.optional()\n});\n\n/**\n * Base schema for list changed subscription options (without callback).\n * Used internally for Zod validation of `autoRefresh` and `debounceMs`.\n */\nexport const ListChangedOptionsBaseSchema = z.object({\n    /**\n     * If `true`, the list will be refreshed automatically when a list changed notification is received.\n     * The callback will be called with the updated list.\n     *\n     * If `false`, the callback will be called with `null` items, allowing manual refresh.\n     *\n     * @default true\n     */\n    autoRefresh: z.boolean().default(true),\n    /**\n     * Debounce time in milliseconds for list changed notification processing.\n     *\n     * Multiple notifications received within this timeframe will only trigger one refresh.\n     * Set to `0` to disable debouncing.\n     *\n     * @default 300\n     */\n    debounceMs: z.number().int().nonnegative().default(300)\n});\n\n/* Logging */\n/**\n * The severity of a log message.\n *\n * @deprecated Deprecated as of protocol version 2026-07-28 (SEP-2577); remains\n * in the specification for at least twelve months. Migrate to stderr logging\n * (STDIO servers) or OpenTelemetry.\n */\nexport const LoggingLevelSchema = z.enum(['debug', 'info', 'notice', 'warning', 'error', 'critical', 'alert', 'emergency']);\n\n/**\n * Parameters for a `logging/setLevel` request.\n *\n * @deprecated Deprecated as of protocol version 2026-07-28 (SEP-2577); remains\n * in the specification for at least twelve months. Migrate to stderr logging\n * (STDIO servers) or OpenTelemetry.\n */\nexport const SetLevelRequestParamsSchema = BaseRequestParamsSchema.extend({\n    /**\n     * The level of logging that the client wants to receive from the server. The server should send all logs at this level and higher (i.e., more severe) to the client as `notifications/logging/message`.\n     */\n    level: LoggingLevelSchema\n});\n/**\n * A request from the client to the server, to enable or adjust logging.\n *\n * @deprecated Deprecated as of protocol version 2026-07-28 (SEP-2577); remains\n * in the specification for at least twelve months. Migrate to stderr logging\n * (STDIO servers) or OpenTelemetry.\n */\nexport const SetLevelRequestSchema = RequestSchema.extend({\n    method: z.literal('logging/setLevel'),\n    params: SetLevelRequestParamsSchema\n});\n\n/**\n * Parameters for a `notifications/message` notification.\n *\n * @deprecated Deprecated as of protocol version 2026-07-28 (SEP-2577); remains\n * in the specification for at least twelve months. Migrate to stderr logging\n * (STDIO servers) or OpenTelemetry.\n */\nexport const LoggingMessageNotificationParamsSchema = NotificationsParamsSchema.extend({\n    /**\n     * The severity of this log message.\n     */\n    level: LoggingLevelSchema,\n    /**\n     * An optional name of the logger issuing this message.\n     */\n    logger: z.string().optional(),\n    /**\n     * The data to be logged, such as a string message or an object. Any JSON serializable type is allowed here.\n     */\n    data: z.unknown()\n});\n/**\n * 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.\n *\n * @deprecated Deprecated as of protocol version 2026-07-28 (SEP-2577); remains\n * in the specification for at least twelve months. Migrate to stderr logging\n * (STDIO servers) or OpenTelemetry.\n */\nexport const LoggingMessageNotificationSchema = NotificationSchema.extend({\n    method: z.literal('notifications/message'),\n    params: LoggingMessageNotificationParamsSchema\n});\n\n/* Sampling */\n/**\n * Hints to use for model selection.\n *\n * @deprecated Deprecated as of protocol version 2026-07-28 (SEP-2577); remains\n * in the specification for at least twelve months. Migrate to calling LLM\n * provider APIs directly.\n */\nexport const ModelHintSchema = z.object({\n    /**\n     * A hint for a model name.\n     */\n    name: z.string().optional()\n});\n\n/**\n * The server's preferences for model selection, requested of the client during sampling.\n *\n * @deprecated Deprecated as of protocol version 2026-07-28 (SEP-2577); remains\n * in the specification for at least twelve months. Migrate to calling LLM\n * provider APIs directly.\n */\nexport const ModelPreferencesSchema = z.object({\n    /**\n     * Optional hints to use for model selection.\n     */\n    hints: z.array(ModelHintSchema).optional(),\n    /**\n     * How much to prioritize cost when selecting a model.\n     */\n    costPriority: z.number().min(0).max(1).optional(),\n    /**\n     * How much to prioritize sampling speed (latency) when selecting a model.\n     */\n    speedPriority: z.number().min(0).max(1).optional(),\n    /**\n     * How much to prioritize intelligence and capabilities when selecting a model.\n     */\n    intelligencePriority: z.number().min(0).max(1).optional()\n});\n\n/**\n * Controls tool usage behavior in sampling requests.\n *\n * @deprecated Deprecated as of protocol version 2026-07-28 (SEP-2577); remains\n * in the specification for at least twelve months. Migrate to calling LLM\n * provider APIs directly.\n */\nexport const ToolChoiceSchema = z.object({\n    /**\n     * Controls when tools are used:\n     * - `\"auto\"`: Model decides whether to use tools (default)\n     * - `\"required\"`: Model MUST use at least one tool before completing\n     * - `\"none\"`: Model MUST NOT use any tools\n     */\n    mode: z.enum(['auto', 'required', 'none']).optional()\n});\n\n/**\n * The result of a tool execution, provided by the user (server).\n * Represents the outcome of invoking a tool requested via `ToolUseContent`.\n *\n * @deprecated Deprecated as of protocol version 2026-07-28 (SEP-2577); remains\n * in the specification for at least twelve months. Migrate to calling LLM\n * provider APIs directly.\n */\nexport const ToolResultContentSchema = z.object({\n    type: z.literal('tool_result'),\n    toolUseId: z.string().describe('The unique identifier for the corresponding tool call.'),\n    content: z.array(ContentBlockSchema),\n    /**\n     * SEP-2106: any JSON value is permitted. The 2025-11-25 wire parse retains the object-only\n     * constraint via the frozen schema in `wire/rev2025-11-25/schemas.ts`.\n     */\n    structuredContent: z.unknown().optional(),\n    isError: z.boolean().optional(),\n\n    /**\n     * See [MCP specification](https://modelcontextprotocol.io/specification/2026-07-28/basic/index#general-fields)\n     * for notes on `_meta` usage.\n     */\n    _meta: z.record(z.string(), z.unknown()).optional()\n});\n\n/**\n * Basic content types for sampling responses (without tool use).\n * Used for backwards-compatible {@linkcode CreateMessageResult} when tools are not used.\n *\n * @deprecated Deprecated as of protocol version 2026-07-28 (SEP-2577); remains\n * in the specification for at least twelve months. Migrate to calling LLM\n * provider APIs directly.\n */\nexport const SamplingContentSchema = z.discriminatedUnion('type', [TextContentSchema, ImageContentSchema, AudioContentSchema]);\n\n/**\n * Content block types allowed in sampling messages.\n * This includes text, image, audio, tool use requests, and tool results.\n *\n * @deprecated Deprecated as of protocol version 2026-07-28 (SEP-2577); remains\n * in the specification for at least twelve months. Migrate to calling LLM\n * provider APIs directly.\n */\nexport const SamplingMessageContentBlockSchema = z.discriminatedUnion('type', [\n    TextContentSchema,\n    ImageContentSchema,\n    AudioContentSchema,\n    ToolUseContentSchema,\n    ToolResultContentSchema\n]);\n\n/**\n * Describes a message issued to or received from an LLM API.\n *\n * @deprecated Deprecated as of protocol version 2026-07-28 (SEP-2577); remains\n * in the specification for at least twelve months. Migrate to calling LLM\n * provider APIs directly.\n */\nexport const SamplingMessageSchema = z.object({\n    role: RoleSchema,\n    content: z.union([SamplingMessageContentBlockSchema, z.array(SamplingMessageContentBlockSchema)]),\n    /**\n     * See [MCP specification](https://modelcontextprotocol.io/specification/2026-07-28/basic/index#general-fields)\n     * for notes on `_meta` usage.\n     */\n    _meta: z.record(z.string(), z.unknown()).optional()\n});\n\n/**\n * Parameters for a `sampling/createMessage` request.\n *\n * @deprecated Deprecated as of protocol version 2026-07-28 (SEP-2577); remains\n * in the specification for at least twelve months. Migrate to calling LLM\n * provider APIs directly.\n */\nexport const CreateMessageRequestParamsSchema = TaskAugmentedRequestParamsSchema.extend({\n    messages: z.array(SamplingMessageSchema),\n    /**\n     * The server's preferences for which model to select. The client MAY modify or omit this request.\n     */\n    modelPreferences: ModelPreferencesSchema.optional(),\n    /**\n     * An optional system prompt the server wants to use for sampling. The client MAY modify or omit this prompt.\n     */\n    systemPrompt: z.string().optional(),\n    /**\n     * A request to include context from one or more MCP servers (including the caller), to be attached to the prompt.\n     * The client MAY ignore this request.\n     *\n     * Default is `\"none\"`. The values `\"thisServer\"` and `\"allServers\"` are deprecated (SEP-2596): servers SHOULD\n     * omit this field or use `\"none\"`, and SHOULD only use the deprecated values if the client declares\n     * `ClientCapabilities`.`sampling.context`.\n     *\n     * @deprecated The `\"thisServer\"` and `\"allServers\"` values are deprecated as of protocol version 2025-11-25\n     * (SEP-2596) and will be removed no later than the Sampling feature itself (SEP-2577). Omit this field or use `\"none\"`.\n     */\n    includeContext: z.enum(['none', 'thisServer', 'allServers']).optional(),\n    temperature: z.number().optional(),\n    /**\n     * The requested maximum number of tokens to sample (to prevent runaway completions).\n     *\n     * The client MAY choose to sample fewer tokens than the requested maximum.\n     */\n    maxTokens: z.number().int(),\n    stopSequences: z.array(z.string()).optional(),\n    /**\n     * Optional metadata to pass through to the LLM provider. The format of this metadata is provider-specific.\n     */\n    metadata: JSONObjectSchema.optional(),\n    /**\n     * Tools that the model may use during generation.\n     * The client MUST return an error if this field is provided but `ClientCapabilities`.`sampling.tools` is not declared.\n     */\n    tools: z.array(ToolSchema).optional(),\n    /**\n     * Controls how the model uses tools.\n     * The client MUST return an error if this field is provided but `ClientCapabilities`.`sampling.tools` is not declared.\n     * Default is `{ mode: \"auto\" }`.\n     */\n    toolChoice: ToolChoiceSchema.optional()\n});\n/**\n * 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.\n *\n * @deprecated Deprecated as of protocol version 2026-07-28 (SEP-2577); remains\n * in the specification for at least twelve months. Migrate to calling LLM\n * provider APIs directly.\n */\nexport const CreateMessageRequestSchema = RequestSchema.extend({\n    method: z.literal('sampling/createMessage'),\n    params: CreateMessageRequestParamsSchema\n});\n\n/**\n * The client's response to a `sampling/create_message` request from the server.\n * This is the backwards-compatible version that returns single content (no arrays).\n * Used when the request does not include tools.\n *\n * @deprecated Deprecated as of protocol version 2026-07-28 (SEP-2577); remains\n * in the specification for at least twelve months. Migrate to calling LLM\n * provider APIs directly.\n */\nexport const CreateMessageResultSchema = ResultSchema.extend({\n    /**\n     * The name of the model that generated the message.\n     */\n    model: z.string(),\n    /**\n     * The reason why sampling stopped, if known.\n     *\n     * Standard values:\n     * - `\"endTurn\"`: Natural end of the assistant's turn\n     * - `\"stopSequence\"`: A stop sequence was encountered\n     * - `\"maxTokens\"`: Maximum token limit was reached\n     *\n     * This field is an open string to allow for provider-specific stop reasons.\n     */\n    stopReason: z.optional(z.enum(['endTurn', 'stopSequence', 'maxTokens']).or(z.string())),\n    role: RoleSchema,\n    /**\n     * Response content. Single content block (text, image, or audio).\n     */\n    content: SamplingContentSchema\n});\n\n/**\n * The client's response to a `sampling/create_message` request when tools were provided.\n * This version supports array content for tool use flows.\n *\n * @deprecated Deprecated as of protocol version 2026-07-28 (SEP-2577); remains\n * in the specification for at least twelve months. Migrate to calling LLM\n * provider APIs directly.\n */\nexport const CreateMessageResultWithToolsSchema = ResultSchema.extend({\n    /**\n     * The name of the model that generated the message.\n     */\n    model: z.string(),\n    /**\n     * The reason why sampling stopped, if known.\n     *\n     * Standard values:\n     * - `\"endTurn\"`: Natural end of the assistant's turn\n     * - `\"stopSequence\"`: A stop sequence was encountered\n     * - `\"maxTokens\"`: Maximum token limit was reached\n     * - `\"toolUse\"`: The model wants to use one or more tools\n     *\n     * This field is an open string to allow for provider-specific stop reasons.\n     */\n    stopReason: z.optional(z.enum(['endTurn', 'stopSequence', 'maxTokens', 'toolUse']).or(z.string())),\n    role: RoleSchema,\n    /**\n     * Response content. May be a single block or array. May include `ToolUseContent` if `stopReason` is `\"toolUse\"`.\n     */\n    content: z.union([SamplingMessageContentBlockSchema, z.array(SamplingMessageContentBlockSchema)])\n});\n\n/* Elicitation */\n/**\n * Primitive schema definition for boolean fields.\n */\nexport const BooleanSchemaSchema = z.object({\n    type: z.literal('boolean'),\n    title: z.string().optional(),\n    description: z.string().optional(),\n    default: z.boolean().optional()\n});\n\n/**\n * Primitive schema definition for string fields.\n */\nexport const StringSchemaSchema = z.object({\n    type: z.literal('string'),\n    title: z.string().optional(),\n    description: z.string().optional(),\n    minLength: z.number().optional(),\n    maxLength: z.number().optional(),\n    format: z.enum(['email', 'uri', 'date', 'date-time']).optional(),\n    default: z.string().optional()\n});\n\n/**\n * Primitive schema definition for number fields.\n */\nexport const NumberSchemaSchema = z.object({\n    type: z.enum(['number', 'integer']),\n    title: z.string().optional(),\n    description: z.string().optional(),\n    minimum: z.number().optional(),\n    maximum: z.number().optional(),\n    default: z.number().optional()\n});\n\n/**\n * Schema for single-selection enumeration without display titles for options.\n */\nexport const UntitledSingleSelectEnumSchemaSchema = z.object({\n    type: z.literal('string'),\n    title: z.string().optional(),\n    description: z.string().optional(),\n    enum: z.array(z.string()),\n    default: z.string().optional()\n});\n\n/**\n * Schema for single-selection enumeration with display titles for each option.\n */\nexport const TitledSingleSelectEnumSchemaSchema = z.object({\n    type: z.literal('string'),\n    title: z.string().optional(),\n    description: z.string().optional(),\n    oneOf: z.array(\n        z.object({\n            const: z.string(),\n            title: z.string()\n        })\n    ),\n    default: z.string().optional()\n});\n\n/**\n * Use {@linkcode TitledSingleSelectEnumSchema} instead.\n * This interface will be removed in a future version.\n */\nexport const LegacyTitledEnumSchemaSchema = z.object({\n    type: z.literal('string'),\n    title: z.string().optional(),\n    description: z.string().optional(),\n    enum: z.array(z.string()),\n    enumNames: z.array(z.string()).optional(),\n    default: z.string().optional()\n});\n\n// Combined single selection enumeration\nexport const SingleSelectEnumSchemaSchema = z.union([UntitledSingleSelectEnumSchemaSchema, TitledSingleSelectEnumSchemaSchema]);\n\n/**\n * Schema for multiple-selection enumeration without display titles for options.\n */\nexport const UntitledMultiSelectEnumSchemaSchema = z.object({\n    type: z.literal('array'),\n    title: z.string().optional(),\n    description: z.string().optional(),\n    minItems: z.number().optional(),\n    maxItems: z.number().optional(),\n    items: z.object({\n        type: z.literal('string'),\n        enum: z.array(z.string())\n    }),\n    default: z.array(z.string()).optional()\n});\n\n/**\n * Schema for multiple-selection enumeration with display titles for each option.\n */\nexport const TitledMultiSelectEnumSchemaSchema = z.object({\n    type: z.literal('array'),\n    title: z.string().optional(),\n    description: z.string().optional(),\n    minItems: z.number().optional(),\n    maxItems: z.number().optional(),\n    items: z.object({\n        anyOf: z.array(\n            z.object({\n                const: z.string(),\n                title: z.string()\n            })\n        )\n    }),\n    default: z.array(z.string()).optional()\n});\n\n/**\n * Combined schema for multiple-selection enumeration\n */\nexport const MultiSelectEnumSchemaSchema = z.union([UntitledMultiSelectEnumSchemaSchema, TitledMultiSelectEnumSchemaSchema]);\n\n/**\n * Primitive schema definition for enum fields.\n */\nexport const EnumSchemaSchema = z.union([LegacyTitledEnumSchemaSchema, SingleSelectEnumSchemaSchema, MultiSelectEnumSchemaSchema]);\n\n/**\n * Union of all primitive schema definitions.\n */\nexport const PrimitiveSchemaDefinitionSchema = z.union([EnumSchemaSchema, BooleanSchemaSchema, StringSchemaSchema, NumberSchemaSchema]);\n\n/**\n * Parameters for an `elicitation/create` request for form-based elicitation.\n */\nexport const ElicitRequestFormParamsSchema = TaskAugmentedRequestParamsSchema.extend({\n    /**\n     * The elicitation mode.\n     *\n     * Optional for backward compatibility. Clients MUST treat missing `mode` as `\"form\"`.\n     */\n    mode: z.literal('form').optional(),\n    /**\n     * The message to present to the user describing what information is being requested.\n     */\n    message: z.string(),\n    /**\n     * A restricted subset of JSON Schema.\n     * Only top-level properties are allowed, without nesting.\n     */\n    requestedSchema: z\n        .object({\n            type: z.literal('object'),\n            properties: z.record(z.string(), PrimitiveSchemaDefinitionSchema),\n            required: z.array(z.string()).optional()\n        })\n        .catchall(z.unknown())\n});\n\n/**\n * Parameters for an {@linkcode ElicitRequest | elicitation/create} request for URL-based elicitation.\n */\nexport const ElicitRequestURLParamsSchema = TaskAugmentedRequestParamsSchema.extend({\n    /**\n     * The elicitation mode.\n     */\n    mode: z.literal('url'),\n    /**\n     * The message to present to the user explaining why the interaction is needed.\n     */\n    message: z.string(),\n    /**\n     * The ID of the elicitation, which must be unique within the context of the server.\n     * The client MUST treat this ID as an opaque value.\n     *\n     * @deprecated Removed from the spec by #2891 (2026-07-28). The client learns the\n     * outcome of an out-of-band interaction by retrying the original request; no\n     * server-initiated completion signal exists in the 2026-07-28 revision. Kept here\n     * for the 2025-era URL-mode flow only.\n     */\n    elicitationId: z.string(),\n    /**\n     * The URL that the user should navigate to.\n     */\n    url: z.string().url()\n});\n\n/**\n * The parameters for a request to elicit additional information from the user via the client.\n */\nexport const ElicitRequestParamsSchema = z.union([ElicitRequestFormParamsSchema, ElicitRequestURLParamsSchema]);\n\n/**\n * A request from the server to elicit user input via the client.\n * The client should present the message and form fields to the user (form mode)\n * or navigate to a URL (URL mode).\n */\nexport const ElicitRequestSchema = RequestSchema.extend({\n    method: z.literal('elicitation/create'),\n    params: ElicitRequestParamsSchema\n});\n\n/**\n * Parameters for a {@linkcode ElicitationCompleteNotification | notifications/elicitation/complete} notification.\n *\n * @deprecated Removed from the spec by #2891 (2026-07-28). The client learns the outcome\n * of an out-of-band interaction by retrying the original request; no server-initiated\n * completion signal exists in the 2026-07-28 revision. Kept here for the 2025-era flow\n * only. The 2026-07-28 wire codec excludes this notification.\n * @category notifications/elicitation/complete\n */\nexport const ElicitationCompleteNotificationParamsSchema = NotificationsParamsSchema.extend({\n    /**\n     * The ID of the elicitation that completed.\n     *\n     * @deprecated See {@linkcode ElicitationCompleteNotificationParamsSchema}.\n     */\n    elicitationId: z.string()\n});\n\n/**\n * A notification from the server to the client, informing it of a completion of an out-of-band elicitation request.\n *\n * @deprecated Removed from the spec by #2891 (2026-07-28). The client learns the outcome\n * of an out-of-band interaction by retrying the original request; no server-initiated\n * completion signal exists in the 2026-07-28 revision. Kept here for the 2025-era flow\n * only. The 2026-07-28 wire codec excludes this notification.\n * @category notifications/elicitation/complete\n */\nexport const ElicitationCompleteNotificationSchema = NotificationSchema.extend({\n    method: z.literal('notifications/elicitation/complete'),\n    params: ElicitationCompleteNotificationParamsSchema\n});\n\n/**\n * The client's response to an {@linkcode ElicitRequest | elicitation/create} request from the server.\n */\nexport const ElicitResultSchema = ResultSchema.extend({\n    /**\n     * The user action in response to the elicitation.\n     * - `\"accept\"`: User submitted the form/confirmed the action\n     * - `\"decline\"`: User explicitly declined the action\n     * - `\"cancel\"`: User dismissed without making an explicit choice\n     */\n    action: z.enum(['accept', 'decline', 'cancel']),\n    /**\n     * The submitted form data, only present when action is `\"accept\"`.\n     * Contains values matching the requested schema.\n     * Per MCP spec, content is \"typically omitted\" for decline/cancel actions.\n     * We normalize `null` to `undefined` for leniency while maintaining type compatibility.\n     */\n    content: z.preprocess(\n        val => (val === null ? undefined : val),\n        z.record(z.string(), z.union([z.string(), z.number(), z.boolean(), z.array(z.string())])).optional()\n    )\n});\n\n/* Autocomplete */\n/**\n * A reference to a resource or resource template definition.\n */\nexport const ResourceTemplateReferenceSchema = z.object({\n    type: z.literal('ref/resource'),\n    /**\n     * The URI or URI template of the resource.\n     */\n    uri: z.string()\n});\n\n/**\n * Identifies a prompt.\n */\nexport const PromptReferenceSchema = z.object({\n    type: z.literal('ref/prompt'),\n    /**\n     * The name of the prompt or prompt template\n     */\n    name: z.string()\n});\n\n/**\n * Parameters for a {@linkcode CompleteRequest | completion/complete} request.\n */\nexport const CompleteRequestParamsSchema = BaseRequestParamsSchema.extend({\n    ref: z.union([PromptReferenceSchema, ResourceTemplateReferenceSchema]),\n    /**\n     * The argument's information\n     */\n    argument: z.object({\n        /**\n         * The name of the argument\n         */\n        name: z.string(),\n        /**\n         * The value of the argument to use for completion matching.\n         */\n        value: z.string()\n    }),\n    context: z\n        .object({\n            /**\n             * Previously-resolved variables in a URI template or prompt.\n             */\n            arguments: z.record(z.string(), z.string()).optional()\n        })\n        .optional()\n});\n/**\n * A request from the client to the server, to ask for completion options.\n */\nexport const CompleteRequestSchema = RequestSchema.extend({\n    method: z.literal('completion/complete'),\n    params: CompleteRequestParamsSchema\n});\n\n/**\n * The server's response to a {@linkcode CompleteRequest | completion/complete} request\n */\nexport const CompleteResultSchema = ResultSchema.extend({\n    completion: z.looseObject({\n        /**\n         * An array of completion values. Must not exceed 100 items.\n         */\n        values: z.array(z.string()).max(100),\n        /**\n         * The total number of completion options available. This can exceed the number of values actually sent in the response.\n         */\n        total: z.optional(z.number().int()),\n        /**\n         * Indicates whether there are additional completion options beyond those provided in the current response, even if the exact total is unknown.\n         */\n        hasMore: z.optional(z.boolean())\n    })\n});\n\n/* Roots */\n/**\n * Represents a root directory or file that the server can operate on.\n *\n * @deprecated Deprecated as of protocol version 2026-07-28 (SEP-2577); remains\n * in the specification for at least twelve months. Migrate to passing paths via\n * tool parameters, resource URIs, or configuration.\n */\nexport const RootSchema = z.object({\n    /**\n     * The URI identifying the root. This *must* start with `file://` for now.\n     */\n    uri: z.string().startsWith('file://'),\n    /**\n     * An optional name for the root.\n     */\n    name: z.string().optional(),\n\n    /**\n     * See [MCP specification](https://modelcontextprotocol.io/specification/2026-07-28/basic/index#general-fields)\n     * for notes on `_meta` usage.\n     */\n    _meta: z.record(z.string(), z.unknown()).optional()\n});\n\n/**\n * Sent from the server to request a list of root URIs from the client.\n *\n * @deprecated Deprecated as of protocol version 2026-07-28 (SEP-2577); remains\n * in the specification for at least twelve months. Migrate to passing paths via\n * tool parameters, resource URIs, or configuration.\n */\nexport const ListRootsRequestSchema = RequestSchema.extend({\n    method: z.literal('roots/list'),\n    params: BaseRequestParamsSchema.optional()\n});\n\n/**\n * The client's response to a `roots/list` request from the server.\n *\n * @deprecated Deprecated as of protocol version 2026-07-28 (SEP-2577); remains\n * in the specification for at least twelve months. Migrate to passing paths via\n * tool parameters, resource URIs, or configuration.\n */\nexport const ListRootsResultSchema = ResultSchema.extend({\n    roots: z.array(RootSchema)\n});\n\n/**\n * A notification from the client to the server, informing it that the list of roots has changed.\n *\n * @deprecated Deprecated as of protocol version 2026-07-28 (SEP-2577); remains\n * in the specification for at least twelve months. Migrate to passing paths via\n * tool parameters, resource URIs, or configuration.\n */\nexport const RootsListChangedNotificationSchema = NotificationSchema.extend({\n    method: z.literal('notifications/roots/list_changed'),\n    params: NotificationsParamsSchema.optional()\n});\n\n/* ───────────────────────────────────────────────────────────────────────────\n * Tasks (2025-11-25 wire vocabulary, DEPRECATED)\n *\n * The task message surface defined by the 2025-11-25 protocol revision. These\n * schemas are kept in the neutral layer so the public Task* types stay\n * nameable without a cross-layer import into wire/rev*; the wire-parse\n * contract for them is the FROZEN copy in wire/rev2025-11-25/schemas.ts.\n *\n * They appear in NO role aggregate below and no API signature — nameable-only\n * vocabulary for interop with task-capable 2025 peers (#2248). Removable at\n * the major version that drops 2025-era support.\n * ─────────────────────────────────────────────────────────────────────────── */\n\n/**\n * Task creation parameters, used to ask that the server create a task to represent a request.\n *\n * @deprecated 2025-11-25 wire vocabulary with no SDK runtime; kept importable for interoperability only.\n */\nexport const TaskCreationParamsSchema = z.looseObject({\n    /**\n     * Requested duration in milliseconds to retain task from creation.\n     */\n    ttl: z.number().optional(),\n\n    /**\n     * Time in milliseconds to wait between task status requests.\n     */\n    pollInterval: z.number().optional()\n});\n\n/**\n * The status of a task.\n *\n * @deprecated 2025-11-25 wire vocabulary with no SDK runtime; kept importable for interoperability only.\n */\nexport const TaskStatusSchema = z.enum(['working', 'input_required', 'completed', 'failed', 'cancelled']);\n\n/**\n * A pollable state object associated with a request.\n *\n * @deprecated 2025-11-25 wire vocabulary with no SDK runtime; kept importable for interoperability only.\n */\nexport const TaskSchema = z.object({\n    taskId: z.string(),\n    status: TaskStatusSchema,\n    /**\n     * Time in milliseconds to keep task results available after completion.\n     * If `null`, the task has unlimited lifetime until manually cleaned up.\n     */\n    ttl: z.union([z.number(), z.null()]),\n    /**\n     * ISO 8601 timestamp when the task was created.\n     */\n    createdAt: z.string(),\n    /**\n     * ISO 8601 timestamp when the task was last updated.\n     */\n    lastUpdatedAt: z.string(),\n    pollInterval: z.optional(z.number()),\n    /**\n     * Optional diagnostic message for failed tasks or other status information.\n     */\n    statusMessage: z.optional(z.string())\n});\n\n/**\n * Result returned when a task is created, containing the task data wrapped in a `task` field.\n *\n * @deprecated 2025-11-25 wire vocabulary with no SDK runtime; kept importable for interoperability only.\n */\nexport const CreateTaskResultSchema = ResultSchema.extend({\n    task: TaskSchema\n});\n\n/**\n * Parameters for task status notification.\n *\n * @deprecated 2025-11-25 wire vocabulary with no SDK runtime; kept importable for interoperability only.\n */\nexport const TaskStatusNotificationParamsSchema = NotificationsParamsSchema.merge(TaskSchema);\n\n/**\n * A notification sent when a task's status changes.\n *\n * @deprecated 2025-11-25 wire vocabulary with no SDK runtime; kept importable for interoperability only.\n */\nexport const TaskStatusNotificationSchema = NotificationSchema.extend({\n    method: z.literal('notifications/tasks/status'),\n    params: TaskStatusNotificationParamsSchema\n});\n\n/**\n * A request to get the state of a specific task.\n *\n * @deprecated 2025-11-25 wire vocabulary with no SDK runtime; kept importable for interoperability only.\n */\nexport const GetTaskRequestSchema = RequestSchema.extend({\n    method: z.literal('tasks/get'),\n    params: BaseRequestParamsSchema.extend({\n        taskId: z.string()\n    })\n});\n\n/**\n * The response to a {@linkcode GetTaskRequest | tasks/get} request.\n *\n * @deprecated 2025-11-25 wire vocabulary with no SDK runtime; kept importable for interoperability only.\n */\nexport const GetTaskResultSchema = ResultSchema.merge(TaskSchema);\n\n/**\n * A request to get the result of a specific task.\n *\n * @deprecated 2025-11-25 wire vocabulary with no SDK runtime; kept importable for interoperability only.\n */\nexport const GetTaskPayloadRequestSchema = RequestSchema.extend({\n    method: z.literal('tasks/result'),\n    params: BaseRequestParamsSchema.extend({\n        taskId: z.string()\n    })\n});\n\n/**\n * The response to a `tasks/result` request.\n * The structure matches the result type of the original request.\n * For example, a {@linkcode CallToolRequest | tools/call} task would return the `CallToolResult` structure.\n *\n *\n * @deprecated 2025-11-25 wire vocabulary with no SDK runtime; kept importable for interoperability only.\n */\nexport const GetTaskPayloadResultSchema = ResultSchema.loose();\n\n/**\n * A request to list tasks.\n *\n * @deprecated 2025-11-25 wire vocabulary with no SDK runtime; kept importable for interoperability only.\n */\nexport const ListTasksRequestSchema = PaginatedRequestSchema.extend({\n    method: z.literal('tasks/list')\n});\n\n/**\n * The response to a {@linkcode ListTasksRequest | tasks/list} request.\n *\n * @deprecated 2025-11-25 wire vocabulary with no SDK runtime; kept importable for interoperability only.\n */\nexport const ListTasksResultSchema = PaginatedResultSchema.extend({\n    tasks: z.array(TaskSchema)\n});\n\n/**\n * A request to cancel a specific task.\n *\n * @deprecated 2025-11-25 wire vocabulary with no SDK runtime; kept importable for interoperability only.\n */\nexport const CancelTaskRequestSchema = RequestSchema.extend({\n    method: z.literal('tasks/cancel'),\n    params: BaseRequestParamsSchema.extend({\n        taskId: z.string()\n    })\n});\n\n/**\n * The response to a {@linkcode CancelTaskRequest | tasks/cancel} request.\n *\n * @deprecated 2025-11-25 wire vocabulary with no SDK runtime; kept importable for interoperability only.\n */\nexport const CancelTaskResultSchema = ResultSchema.merge(TaskSchema);\n\n/* Client messages */\n// NOTE (Q1 increment 2): the role unions below are the NEUTRAL message sets.\n// The 2025-era task vocabulary (tasks/* methods, task results, the task\n// status notification) is 2025-only WIRE vocabulary; the deprecated Task*\n// schemas above are nameable-only and appear in NO role aggregate and no API\n// signature. The era's full wire role unions live in\n// `wire/rev2025-11-25/schemas.ts`.\nexport const ClientRequestSchema = z.union([\n    PingRequestSchema,\n    InitializeRequestSchema,\n    DiscoverRequestSchema,\n    CompleteRequestSchema,\n    SetLevelRequestSchema,\n    GetPromptRequestSchema,\n    ListPromptsRequestSchema,\n    ListResourcesRequestSchema,\n    ListResourceTemplatesRequestSchema,\n    ReadResourceRequestSchema,\n    SubscribeRequestSchema,\n    UnsubscribeRequestSchema,\n    SubscriptionsListenRequestSchema,\n    CallToolRequestSchema,\n    ListToolsRequestSchema\n]);\n\nexport const ClientNotificationSchema = z.union([\n    CancelledNotificationSchema,\n    ProgressNotificationSchema,\n    InitializedNotificationSchema,\n    RootsListChangedNotificationSchema\n]);\n\nexport const ClientResultSchema = z.union([\n    EmptyResultSchema,\n    CreateMessageResultSchema,\n    CreateMessageResultWithToolsSchema,\n    ElicitResultSchema,\n    ListRootsResultSchema\n]);\n\n/* Server messages */\nexport const ServerRequestSchema = z.union([PingRequestSchema, CreateMessageRequestSchema, ElicitRequestSchema, ListRootsRequestSchema]);\n\nexport const ServerNotificationSchema = z.union([\n    CancelledNotificationSchema,\n    ProgressNotificationSchema,\n    LoggingMessageNotificationSchema,\n    ResourceUpdatedNotificationSchema,\n    ResourceListChangedNotificationSchema,\n    ToolListChangedNotificationSchema,\n    PromptListChangedNotificationSchema,\n    SubscriptionsAcknowledgedNotificationSchema,\n    ElicitationCompleteNotificationSchema\n]);\n\nexport const ServerResultSchema = z.union([\n    EmptyResultSchema,\n    InitializeResultSchema,\n    DiscoverResultSchema,\n    CompleteResultSchema,\n    GetPromptResultSchema,\n    ListPromptsResultSchema,\n    ListResourcesResultSchema,\n    ListResourceTemplatesResultSchema,\n    ReadResourceResultSchema,\n    CallToolResultSchema,\n    ListToolsResultSchema,\n    SubscriptionsListenResultSchema\n]);\n","import * as z from 'zod/v4';\n\n/**\n * Reusable URL validation that disallows `javascript:` scheme\n */\nexport const SafeUrlSchema = z\n    .url()\n    .superRefine((val, ctx) => {\n        if (!URL.canParse(val)) {\n            ctx.addIssue({\n                code: z.ZodIssueCode.custom,\n                message: 'URL must be parseable',\n                fatal: true\n            });\n\n            return z.NEVER;\n        }\n    })\n    .refine(\n        url => {\n            const u = new URL(url);\n            return u.protocol !== 'javascript:' && u.protocol !== 'data:' && u.protocol !== 'vbscript:';\n        },\n        { message: 'URL cannot use javascript:, data:, or vbscript: scheme' }\n    );\n\n/**\n * RFC 9728 OAuth Protected Resource Metadata\n */\nexport const OAuthProtectedResourceMetadataSchema = z.looseObject({\n    resource: z.string().url(),\n    authorization_servers: z.array(SafeUrlSchema).optional(),\n    jwks_uri: z.string().url().optional(),\n    scopes_supported: z.array(z.string()).optional(),\n    bearer_methods_supported: z.array(z.string()).optional(),\n    resource_signing_alg_values_supported: z.array(z.string()).optional(),\n    resource_name: z.string().optional(),\n    resource_documentation: z.string().optional(),\n    resource_policy_uri: z.string().url().optional(),\n    resource_tos_uri: z.string().url().optional(),\n    tls_client_certificate_bound_access_tokens: z.boolean().optional(),\n    authorization_details_types_supported: z.array(z.string()).optional(),\n    dpop_signing_alg_values_supported: z.array(z.string()).optional(),\n    dpop_bound_access_tokens_required: z.boolean().optional()\n});\n\n/**\n * RFC 8414 OAuth 2.0 Authorization Server Metadata\n */\nexport const OAuthMetadataSchema = z.looseObject({\n    issuer: z.string(),\n    authorization_endpoint: SafeUrlSchema,\n    token_endpoint: SafeUrlSchema,\n    registration_endpoint: SafeUrlSchema.optional(),\n    scopes_supported: z.array(z.string()).optional(),\n    response_types_supported: z.array(z.string()),\n    response_modes_supported: z.array(z.string()).optional(),\n    grant_types_supported: z.array(z.string()).optional(),\n    token_endpoint_auth_methods_supported: z.array(z.string()).optional(),\n    token_endpoint_auth_signing_alg_values_supported: z.array(z.string()).optional(),\n    service_documentation: SafeUrlSchema.optional(),\n    revocation_endpoint: SafeUrlSchema.optional(),\n    revocation_endpoint_auth_methods_supported: z.array(z.string()).optional(),\n    revocation_endpoint_auth_signing_alg_values_supported: z.array(z.string()).optional(),\n    introspection_endpoint: z.string().optional(),\n    introspection_endpoint_auth_methods_supported: z.array(z.string()).optional(),\n    introspection_endpoint_auth_signing_alg_values_supported: z.array(z.string()).optional(),\n    code_challenge_methods_supported: z.array(z.string()).optional(),\n    client_id_metadata_document_supported: z.boolean().optional(),\n    // eslint-disable-next-line unicorn/prefer-top-level-await -- Zod .catch(), not a Promise chain\n    authorization_response_iss_parameter_supported: z.boolean().optional().catch(undefined),\n    /**\n     * RFC 9449 §5.1 (DPoP, SEP-1932): the JWS `alg` values this authorization server accepts for\n     * DPoP proofs at the token endpoint. A server supporting DPoP MUST publish this field.\n     */\n    dpop_signing_alg_values_supported: z.array(z.string()).optional()\n});\n\n/**\n * OpenID Connect Discovery 1.0 Provider Metadata\n *\n * @see https://openid.net/specs/openid-connect-discovery-1_0.html#ProviderMetadata\n */\nexport const OpenIdProviderMetadataSchema = z.looseObject({\n    issuer: z.string(),\n    authorization_endpoint: SafeUrlSchema,\n    token_endpoint: SafeUrlSchema,\n    userinfo_endpoint: SafeUrlSchema.optional(),\n    jwks_uri: SafeUrlSchema,\n    registration_endpoint: SafeUrlSchema.optional(),\n    scopes_supported: z.array(z.string()).optional(),\n    response_types_supported: z.array(z.string()),\n    response_modes_supported: z.array(z.string()).optional(),\n    grant_types_supported: z.array(z.string()).optional(),\n    acr_values_supported: z.array(z.string()).optional(),\n    subject_types_supported: z.array(z.string()),\n    id_token_signing_alg_values_supported: z.array(z.string()),\n    id_token_encryption_alg_values_supported: z.array(z.string()).optional(),\n    id_token_encryption_enc_values_supported: z.array(z.string()).optional(),\n    userinfo_signing_alg_values_supported: z.array(z.string()).optional(),\n    userinfo_encryption_alg_values_supported: z.array(z.string()).optional(),\n    userinfo_encryption_enc_values_supported: z.array(z.string()).optional(),\n    request_object_signing_alg_values_supported: z.array(z.string()).optional(),\n    request_object_encryption_alg_values_supported: z.array(z.string()).optional(),\n    request_object_encryption_enc_values_supported: z.array(z.string()).optional(),\n    token_endpoint_auth_methods_supported: z.array(z.string()).optional(),\n    token_endpoint_auth_signing_alg_values_supported: z.array(z.string()).optional(),\n    display_values_supported: z.array(z.string()).optional(),\n    claim_types_supported: z.array(z.string()).optional(),\n    claims_supported: z.array(z.string()).optional(),\n    service_documentation: z.string().optional(),\n    claims_locales_supported: z.array(z.string()).optional(),\n    ui_locales_supported: z.array(z.string()).optional(),\n    claims_parameter_supported: z.boolean().optional(),\n    request_parameter_supported: z.boolean().optional(),\n    request_uri_parameter_supported: z.boolean().optional(),\n    require_request_uri_registration: z.boolean().optional(),\n    op_policy_uri: SafeUrlSchema.optional(),\n    op_tos_uri: SafeUrlSchema.optional(),\n    client_id_metadata_document_supported: z.boolean().optional(),\n    // eslint-disable-next-line unicorn/prefer-top-level-await -- Zod .catch(), not a Promise chain\n    authorization_response_iss_parameter_supported: z.boolean().optional().catch(undefined)\n});\n\n/**\n * OpenID Connect Discovery metadata that may include OAuth 2.0 fields\n * This schema represents the real-world scenario where OIDC providers\n * return a mix of OpenID Connect and OAuth 2.0 metadata fields\n */\nexport const OpenIdProviderDiscoveryMetadataSchema = z.object({\n    ...OpenIdProviderMetadataSchema.shape,\n    ...OAuthMetadataSchema.pick({\n        code_challenge_methods_supported: true\n    }).shape\n});\n\n/**\n * OAuth 2.1 token response\n */\nexport const OAuthTokensSchema = z\n    .object({\n        access_token: z.string(),\n        id_token: z.string().optional(), // Optional for OAuth 2.1, but necessary in OpenID Connect\n        token_type: z.string(),\n        expires_in: z.coerce.number().optional(),\n        scope: z.string().optional(),\n        refresh_token: z.string().optional(),\n        /**\n         * Not part of the wire format: the authorization server this value was obtained from, added by\n         * the client's `auth()` before it is stored and compared when it is read back (SEP-2352).\n         */\n        // eslint-disable-next-line unicorn/prefer-top-level-await -- Zod .catch(), not a Promise chain\n        issuer: z.string().optional().catch(undefined)\n    })\n    .strip();\n\n/**\n * RFC 8693 §2.2.1 Token Exchange response for ID-JAG tokens.\n *\n * `token_type` is intentionally optional: per RFC 8693 §2.2.1 it is informational when\n * the issued token is not an access token, and per RFC 6749 §5.1 it is case-insensitive,\n * so strict checking rejects conformant IdPs.\n */\nexport const IdJagTokenExchangeResponseSchema = z\n    .object({\n        issued_token_type: z.literal('urn:ietf:params:oauth:token-type:id-jag'),\n        access_token: z.string(),\n        token_type: z.string().optional(),\n        expires_in: z.number().optional(),\n        scope: z.string().optional()\n    })\n    .strip();\n\nexport type IdJagTokenExchangeResponse = z.infer<typeof IdJagTokenExchangeResponseSchema>;\n\n/**\n * OAuth 2.1 error response\n */\nexport const OAuthErrorResponseSchema = z.object({\n    error: z.string(),\n    error_description: z.string().optional(),\n    error_uri: z.string().optional()\n});\n\n/**\n * Optional version of {@linkcode SafeUrlSchema} that allows empty string for backward compatibility on `tos_uri` and `logo_uri`\n */\n// eslint-disable-next-line unicorn/no-useless-undefined\nexport const OptionalSafeUrlSchema = SafeUrlSchema.optional().or(z.literal('').transform(() => undefined));\n\n/**\n * RFC 7591 OAuth 2.0 Dynamic Client Registration metadata\n */\nexport const OAuthClientMetadataSchema = z\n    .object({\n        redirect_uris: z.array(SafeUrlSchema),\n        token_endpoint_auth_method: z.string().optional(),\n        grant_types: z.array(z.string()).optional(),\n        response_types: z.array(z.string()).optional(),\n        /**\n         * OIDC Dynamic Client Registration `application_type`. MCP clients MUST set\n         * this to `'native'` or `'web'` when registering (SEP-837); the SDK defaults\n         * it from `redirect_uris` when omitted. Typed as `string` (not an enum) so\n         * that parsing an authorization server's registration response — which under\n         * RFC 7591 may echo extension values — never rejects the document on this\n         * field alone.\n         */\n        application_type: z.string().optional(),\n        client_name: z.string().optional(),\n        client_uri: SafeUrlSchema.optional(),\n        logo_uri: OptionalSafeUrlSchema,\n        scope: z.string().optional(),\n        contacts: z.array(z.string()).optional(),\n        tos_uri: OptionalSafeUrlSchema,\n        policy_uri: z.string().optional(),\n        jwks_uri: SafeUrlSchema.optional(),\n        jwks: z.any().optional(),\n        software_id: z.string().optional(),\n        software_version: z.string().optional(),\n        software_statement: z.string().optional()\n    })\n    .strip();\n\n/**\n * RFC 7591 OAuth 2.0 Dynamic Client Registration client information\n */\nexport const OAuthClientInformationSchema = z\n    .object({\n        client_id: z.string(),\n        client_secret: z.string().optional(),\n        client_id_issued_at: z.number().optional(),\n        client_secret_expires_at: z.number().optional(),\n        /**\n         * Not part of the wire format: the authorization server this value was obtained from, added by\n         * the client's `auth()` before it is stored and compared when it is read back (SEP-2352).\n         */\n        // eslint-disable-next-line unicorn/prefer-top-level-await -- Zod .catch(), not a Promise chain\n        issuer: z.string().optional().catch(undefined)\n    })\n    .strip();\n\n/**\n * RFC 7591 OAuth 2.0 Dynamic Client Registration full response (client information plus metadata)\n */\nexport const OAuthClientInformationFullSchema = OAuthClientMetadataSchema.merge(OAuthClientInformationSchema);\n\n/**\n * RFC 7591 OAuth 2.0 Dynamic Client Registration error response\n */\nexport const OAuthClientRegistrationErrorSchema = z\n    .object({\n        error: z.string(),\n        error_description: z.string().optional()\n    })\n    .strip();\n\n/**\n * RFC 7009 OAuth 2.0 Token Revocation request\n */\nexport const OAuthTokenRevocationRequestSchema = z\n    .object({\n        token: z.string(),\n        token_type_hint: z.string().optional()\n    })\n    .strip();\n\nexport type OAuthMetadata = z.infer<typeof OAuthMetadataSchema>;\nexport type OpenIdProviderMetadata = z.infer<typeof OpenIdProviderMetadataSchema>;\nexport type OpenIdProviderDiscoveryMetadata = z.infer<typeof OpenIdProviderDiscoveryMetadataSchema>;\n\nexport type OAuthTokens = z.infer<typeof OAuthTokensSchema>;\nexport type OAuthErrorResponse = z.infer<typeof OAuthErrorResponseSchema>;\nexport type OAuthClientMetadata = z.infer<typeof OAuthClientMetadataSchema>;\nexport type OAuthClientInformation = z.infer<typeof OAuthClientInformationSchema>;\nexport type OAuthClientInformationFull = z.infer<typeof OAuthClientInformationFullSchema>;\nexport type OAuthClientInformationMixed = OAuthClientInformation | OAuthClientInformationFull;\n\n/**\n * {@linkcode OAuthTokens} as persisted by an `OAuthClientProvider`. Adds an\n * SDK-stamped authorization-server `issuer` identifier so stored tokens are\n * bound to the AS that issued them. The `issuer` field is **not** part of the\n * RFC 6749 wire response; the client SDK writes it before calling `saveTokens`.\n */\nexport type StoredOAuthTokens = OAuthTokens & { issuer?: string | undefined };\n\n/**\n * {@linkcode OAuthClientInformationMixed} as persisted by an\n * `OAuthClientProvider`. Adds an SDK-stamped authorization-server `issuer`\n * identifier so stored client credentials are bound to the AS that issued them.\n * The `issuer` field is **not** part of the RFC 7591 wire response; the client SDK\n * writes it before calling `saveClientInformation`.\n */\nexport type StoredOAuthClientInformation = OAuthClientInformationMixed & { issuer?: string | undefined };\n\nexport type OAuthClientRegistrationError = z.infer<typeof OAuthClientRegistrationErrorSchema>;\nexport type OAuthTokenRevocationRequest = z.infer<typeof OAuthTokenRevocationRequestSchema>;\nexport type OAuthProtectedResourceMetadata = z.infer<typeof OAuthProtectedResourceMetadataSchema>;\n\n// Unified type for authorization server metadata\nexport type AuthorizationServerMetadata = OAuthMetadata | OpenIdProviderDiscoveryMetadata;\n","import { $ as InitializeRequestParamsSchema, $n as ToolSchema, $t as RequestIdSchema, A as DiscoverRequestSchema, An as SubscriptionFilterSchema, At as ModelPreferencesSchema, B as EmptyResultSchema, Bn as TaskSchema, Bt as ProgressNotificationParamsSchema, C as ContentBlockSchema, Cn as ServerTasksCapabilitySchema, Cr as TRACESTATE_META_KEY, Ct as ListTasksResultSchema, D as CreateMessageResultWithToolsSchema, Dn as StringSchemaSchema, Dt as LoggingMessageNotificationParamsSchema, E as CreateMessageResultSchema, En as SingleSelectEnumSchemaSchema, Et as LoggingLevelSchema, F as ElicitRequestURLParamsSchema, Fn as SubscriptionsListenResultMetaSchema, Ft as PaginatedRequestParamsSchema, G as GetTaskPayloadRequestSchema, Gn as TextResourceContentsSchema, Gt as PromptListChangedNotificationSchema, H as GetPromptRequestParamsSchema, Hn as TaskStatusNotificationSchema, Ht as ProgressSchema, I as ElicitResultSchema, In as SubscriptionsListenResultSchema, It as PaginatedRequestSchema, J as GetTaskResultSchema, Jn as ToolAnnotationsSchema, Jt as PromptSchema, K as GetTaskPayloadResultSchema, Kn as TitledMultiSelectEnumSchemaSchema, Kt as PromptMessageSchema, L as ElicitationCompleteNotificationParamsSchema, Ln as TaskAugmentedRequestParamsSchema, Lt as PaginatedResultSchema, M as ElicitRequestFormParamsSchema, Mn as SubscriptionsAcknowledgedNotificationSchema, Mt as NotificationSchema, N as ElicitRequestParamsSchema, Nn as SubscriptionsListenRequestParamsSchema, Nt as NotificationsParamsSchema, O as CreateTaskResultSchema, On as SubscribeRequestParamsSchema, Ot as LoggingMessageNotificationSchema, P as ElicitRequestSchema, Pn as SubscriptionsListenRequestSchema, Pt as NumberSchemaSchema, Q as ImplementationSchema, Qn as ToolResultContentSchema, Qt as RelatedTaskMetadataSchema, R as ElicitationCompleteNotificationSchema, Rn as TaskCreationParamsSchema, Rt as PingRequestSchema, S as CompleteResultSchema, Sn as ServerResultSchema, Sr as TRACEPARENT_META_KEY, St as ListTasksRequestSchema, T as CreateMessageRequestSchema, Tn as SetLevelRequestSchema, Tt as ListToolsResultSchema, U as GetPromptRequestSchema, Un as TaskStatusSchema, Ut as ProgressTokenSchema, V as EnumSchemaSchema, Vn as TaskStatusNotificationParamsSchema, Vt as ProgressNotificationSchema, W as GetPromptResultSchema, Wn as TextContentSchema, Wt as PromptArgumentSchema, X as IconsSchema, Xn as ToolExecutionSchema, Xt as ReadResourceRequestSchema, Y as IconSchema, Yn as ToolChoiceSchema, Yt as ReadResourceRequestParamsSchema, Z as ImageContentSchema, Zn as ToolListChangedNotificationSchema, Zt as ReadResourceResultSchema, _ as ClientResultSchema, _n as SamplingMessageContentBlockSchema, _r as PROTOCOL_VERSION_META_KEY, _t as ListResourceTemplatesResultSchema, a as BlobResourceContentsSchema, an as ResourceRequestParamsSchema, ar as BAGGAGE_META_KEY, at as JSONRPCErrorResponseSchema, b as CompleteRequestParamsSchema, bn as ServerNotificationSchema, br as SUBSCRIPTION_ID_META_KEY, bt as ListRootsRequestSchema, c as CallToolRequestSchema, cn as ResourceTemplateSchema, cr as DEFAULT_NEGOTIATED_PROTOCOL_VERSION, ct as JSONRPCRequestSchema, d as CancelTaskResultSchema, dn as ResultMetaObjectSchema, dr as INVALID_REQUEST, dt as JSONValueSchema, en as RequestMetaSchema, er as ToolUseContentSchema, et as InitializeRequestSchema, f as CancelledNotificationParamsSchema, fn as ResultSchema, fr as JSONRPC_VERSION, ft as LegacyTitledEnumSchemaSchema, g as ClientRequestSchema, gn as SamplingContentSchema, gr as PARSE_ERROR, gt as ListResourceTemplatesRequestSchema, h as ClientNotificationSchema, hn as RootsListChangedNotificationSchema, hr as METHOD_NOT_FOUND, ht as ListPromptsResultSchema, i as BaseRequestParamsSchema, in as ResourceListChangedNotificationSchema, ir as UntitledSingleSelectEnumSchemaSchema, it as JSONObjectSchema, j as DiscoverResultSchema, jn as SubscriptionsAcknowledgedNotificationParamsSchema, jt as MultiSelectEnumSchemaSchema, k as CursorSchema, kn as SubscribeRequestSchema, kt as ModelHintSchema, l as CallToolResultSchema, ln as ResourceUpdatedNotificationParamsSchema, lr as INTERNAL_ERROR, lt as JSONRPCResponseSchema, m as ClientCapabilitiesSchema, mn as RootSchema, mr as LOG_LEVEL_META_KEY, mt as ListPromptsRequestSchema, n as AudioContentSchema, nn as ResourceContentsSchema, nr as UnsubscribeRequestSchema, nt as InitializedNotificationSchema, o as BooleanSchemaSchema, on as ResourceSchema, or as CLIENT_CAPABILITIES_META_KEY, ot as JSONRPCMessageSchema, p as CancelledNotificationSchema, pn as RoleSchema, pr as LATEST_PROTOCOL_VERSION, pt as ListChangedOptionsBaseSchema, q as GetTaskRequestSchema, qn as TitledSingleSelectEnumSchemaSchema, qt as PromptReferenceSchema, r as BaseMetadataSchema, rn as ResourceLinkSchema, rr as UntitledMultiSelectEnumSchemaSchema, rt as JSONArraySchema, s as CallToolRequestParamsSchema, sn as ResourceTemplateReferenceSchema, sr as CLIENT_INFO_META_KEY, st as JSONRPCNotificationSchema, t as AnnotationsSchema, tn as RequestSchema, tr as UnsubscribeRequestParamsSchema, tt as InitializeResultSchema, u as CancelTaskRequestSchema, un as ResourceUpdatedNotificationSchema, ur as INVALID_PARAMS, ut as JSONRPCResultResponseSchema, v as ClientTasksCapabilitySchema, vn as SamplingMessageSchema, vr as RELATED_TASK_META_KEY, vt as ListResourcesRequestSchema, w as CreateMessageRequestParamsSchema, wn as SetLevelRequestParamsSchema, wt as ListToolsRequestSchema, x as CompleteRequestSchema, xn as ServerRequestSchema, xr as SUPPORTED_PROTOCOL_VERSIONS, xt as ListRootsResultSchema, y as CompatibilityCallToolResultSchema, yn as ServerCapabilitiesSchema, yr as SERVER_INFO_META_KEY, yt as ListResourcesResultSchema, z as EmbeddedResourceSchema, zn as TaskMetadataSchema, zt as PrimitiveSchemaDefinitionSchema } from \"./schemas-DscsoNZN.mjs\";\nimport { a as OAuthClientRegistrationErrorSchema, c as OAuthProtectedResourceMetadataSchema, d as OpenIdProviderDiscoveryMetadataSchema, f as OpenIdProviderMetadataSchema, i as OAuthClientMetadataSchema, l as OAuthTokenRevocationRequestSchema, m as SafeUrlSchema, n as OAuthClientInformationFullSchema, o as OAuthErrorResponseSchema, p as OptionalSafeUrlSchema, r as OAuthClientInformationSchema, s as OAuthMetadataSchema, t as IdJagTokenExchangeResponseSchema, u as OAuthTokensSchema } from \"./auth-UMQCo-ad.mjs\";\n\nexport { AnnotationsSchema, AudioContentSchema, BAGGAGE_META_KEY, BaseMetadataSchema, BaseRequestParamsSchema, BlobResourceContentsSchema, BooleanSchemaSchema, CLIENT_CAPABILITIES_META_KEY, CLIENT_INFO_META_KEY, CallToolRequestParamsSchema, CallToolRequestSchema, CallToolResultSchema, CancelTaskRequestSchema, CancelTaskResultSchema, CancelledNotificationParamsSchema, CancelledNotificationSchema, ClientCapabilitiesSchema, ClientNotificationSchema, ClientRequestSchema, ClientResultSchema, ClientTasksCapabilitySchema, CompatibilityCallToolResultSchema, CompleteRequestParamsSchema, CompleteRequestSchema, CompleteResultSchema, ContentBlockSchema, CreateMessageRequestParamsSchema, CreateMessageRequestSchema, CreateMessageResultSchema, CreateMessageResultWithToolsSchema, CreateTaskResultSchema, CursorSchema, DEFAULT_NEGOTIATED_PROTOCOL_VERSION, DiscoverRequestSchema, DiscoverResultSchema, ElicitRequestFormParamsSchema, ElicitRequestParamsSchema, ElicitRequestSchema, ElicitRequestURLParamsSchema, ElicitResultSchema, ElicitationCompleteNotificationParamsSchema, ElicitationCompleteNotificationSchema, EmbeddedResourceSchema, EmptyResultSchema, EnumSchemaSchema, GetPromptRequestParamsSchema, GetPromptRequestSchema, GetPromptResultSchema, GetTaskPayloadRequestSchema, GetTaskPayloadResultSchema, GetTaskRequestSchema, GetTaskResultSchema, INTERNAL_ERROR, INVALID_PARAMS, INVALID_REQUEST, IconSchema, IconsSchema, IdJagTokenExchangeResponseSchema, ImageContentSchema, ImplementationSchema, InitializeRequestParamsSchema, InitializeRequestSchema, InitializeResultSchema, InitializedNotificationSchema, JSONArraySchema, JSONObjectSchema, JSONRPCErrorResponseSchema, JSONRPCMessageSchema, JSONRPCNotificationSchema, JSONRPCRequestSchema, JSONRPCResponseSchema, JSONRPCResultResponseSchema, JSONRPC_VERSION, JSONValueSchema, LATEST_PROTOCOL_VERSION, LOG_LEVEL_META_KEY, LegacyTitledEnumSchemaSchema, ListChangedOptionsBaseSchema, ListPromptsRequestSchema, ListPromptsResultSchema, ListResourceTemplatesRequestSchema, ListResourceTemplatesResultSchema, ListResourcesRequestSchema, ListResourcesResultSchema, ListRootsRequestSchema, ListRootsResultSchema, ListTasksRequestSchema, ListTasksResultSchema, ListToolsRequestSchema, ListToolsResultSchema, LoggingLevelSchema, LoggingMessageNotificationParamsSchema, LoggingMessageNotificationSchema, METHOD_NOT_FOUND, ModelHintSchema, ModelPreferencesSchema, MultiSelectEnumSchemaSchema, NotificationSchema, NotificationsParamsSchema, NumberSchemaSchema, OAuthClientInformationFullSchema, OAuthClientInformationSchema, OAuthClientMetadataSchema, OAuthClientRegistrationErrorSchema, OAuthErrorResponseSchema, OAuthMetadataSchema, OAuthProtectedResourceMetadataSchema, OAuthTokenRevocationRequestSchema, OAuthTokensSchema, OpenIdProviderDiscoveryMetadataSchema, OpenIdProviderMetadataSchema, OptionalSafeUrlSchema, PARSE_ERROR, PROTOCOL_VERSION_META_KEY, PaginatedRequestParamsSchema, PaginatedRequestSchema, PaginatedResultSchema, PingRequestSchema, PrimitiveSchemaDefinitionSchema, ProgressNotificationParamsSchema, ProgressNotificationSchema, ProgressSchema, ProgressTokenSchema, PromptArgumentSchema, PromptListChangedNotificationSchema, PromptMessageSchema, PromptReferenceSchema, PromptSchema, RELATED_TASK_META_KEY, ReadResourceRequestParamsSchema, ReadResourceRequestSchema, ReadResourceResultSchema, RelatedTaskMetadataSchema, RequestIdSchema, RequestMetaSchema, RequestSchema, ResourceContentsSchema, ResourceLinkSchema, ResourceListChangedNotificationSchema, ResourceRequestParamsSchema, ResourceSchema, ResourceTemplateReferenceSchema, ResourceTemplateSchema, ResourceUpdatedNotificationParamsSchema, ResourceUpdatedNotificationSchema, ResultMetaObjectSchema, ResultSchema, RoleSchema, RootSchema, RootsListChangedNotificationSchema, SERVER_INFO_META_KEY, SUBSCRIPTION_ID_META_KEY, SUPPORTED_PROTOCOL_VERSIONS, SafeUrlSchema, SamplingContentSchema, SamplingMessageContentBlockSchema, SamplingMessageSchema, ServerCapabilitiesSchema, ServerNotificationSchema, ServerRequestSchema, ServerResultSchema, ServerTasksCapabilitySchema, SetLevelRequestParamsSchema, SetLevelRequestSchema, SingleSelectEnumSchemaSchema, StringSchemaSchema, SubscribeRequestParamsSchema, SubscribeRequestSchema, SubscriptionFilterSchema, SubscriptionsAcknowledgedNotificationParamsSchema, SubscriptionsAcknowledgedNotificationSchema, SubscriptionsListenRequestParamsSchema, SubscriptionsListenRequestSchema, SubscriptionsListenResultMetaSchema, SubscriptionsListenResultSchema, TRACEPARENT_META_KEY, TRACESTATE_META_KEY, TaskAugmentedRequestParamsSchema, TaskCreationParamsSchema, TaskMetadataSchema, TaskSchema, TaskStatusNotificationParamsSchema, TaskStatusNotificationSchema, TaskStatusSchema, TextContentSchema, TextResourceContentsSchema, TitledMultiSelectEnumSchemaSchema, TitledSingleSelectEnumSchemaSchema, ToolAnnotationsSchema, ToolChoiceSchema, ToolExecutionSchema, ToolListChangedNotificationSchema, ToolResultContentSchema, ToolSchema, ToolUseContentSchema, UnsubscribeRequestParamsSchema, UnsubscribeRequestSchema, UntitledMultiSelectEnumSchemaSchema, UntitledSingleSelectEnumSchemaSchema };","/**\n * Cross-bundle `instanceof` support for the SDK error classes.\n *\n * `@modelcontextprotocol/client` and `@modelcontextprotocol/server` each bundle their\n * own copy of `core-internal`, so an error constructed by one package fails a\n * prototype-identity `instanceof` against the same class re-exported by the other —\n * exactly the check a dual-role process (gateway, host, in-process test) writes.\n *\n * Instead of prototype identity, branded classes stamp every instance with the brand\n * strings of its class chain under a registry symbol (`Symbol.for`, shared across\n * bundles and realms), and resolve `instanceof` via `Symbol.hasInstance` against the\n * brand set. Ordinary prototype-based `instanceof` is kept as a fallback so behavior\n * is unchanged for anything unbranded.\n *\n * A class participates by defining an **own** `mcpBrand` static (via a `static {}`\n * block, so nothing reaches the declaration files — a declared `protected static`\n * field would make the constructor types nominally incompatible across the bundled\n * copies) and (for hierarchy roots) installing {@linkcode brandedHasInstance} as\n * `Symbol.hasInstance`. User-defined subclasses that do not declare their own brand\n * keep plain prototype semantics — a foreign base-class instance never satisfies\n * `instanceof UserSubclass`.\n *\n * Prior art — the same stamp-and-hook shape ships at scale elsewhere: Node core\n * (stream.Writable since 2017, Console via a marker symbol, diagnostics_channel),\n * undici's whole error hierarchy (vendored into Node as fetch), googleapis/gaxios\n * (GaxiosError, Symbol.for marker), AWS SDK v3's ServiceException (which pairs a\n * Symbol.hasInstance override with a static isInstance guard, as we do), and zod v4\n * (Symbol.hasInstance on every schema class for cross-version interop).\n *\n * Contract notes:\n * - Participation criterion: **every error class exported from a public package that\n *   callers are documented to `instanceof` must be branded.** The per-package\n *   errorBrandConformance tests walk the export surfaces and fail naming any\n *   exported Error subclass that has not opted in.\n * - Brands assert **identity, not shape**: brand strings are version-less, so an\n *   instance from one SDK version matches the class of another. Members added to a\n *   branded class in a later version may be absent on a matched instance — read\n *   fields defensively, and treat branded classes as additive-only. The escape\n *   hatch when a release must break a branded class's read contract: change that\n *   class's brand string in the same release, which cleanly severs cross-version\n *   matching for that class. The per-package brand pins make the rename\n *   deliberate: errorSurfacePins.test.ts owns the core-internal brands, and each\n *   package's errorBrandConformance test pins its package-local ones.\n * - Cross-bundle matching requires **both** copies to be at or after the release\n *   that introduced branding; against an older copy, behavior degrades to plain\n *   prototype `instanceof` in both directions.\n * - A consumer re-bundling the SDK with property mangling (`mangle.props`) would\n *   break the brand statics; default esbuild/webpack/terser settings do not.\n */\n\n/** Registry symbol — identical across bundled copies and realms. */\nconst BRANDS: unique symbol = Symbol.for('mcp.sdk.errorBrands') as never;\n\ninterface BrandCarrier {\n    [BRANDS]?: { has(brand: string): boolean };\n}\n\ninterface BrandedConstructor {\n    mcpBrand?: string;\n}\n\n/**\n * Stamp `instance` with the brand of every class in `ctor`'s chain that declares an\n * own `mcpBrand`. Call once from the hierarchy root's constructor with `new.target` —\n * subclasses inherit the stamping without touching their constructors.\n *\n * Constructor-time only: never stamp arbitrary objects. A stamped non-instance would\n * satisfy `instanceof` while lacking the prototype members (getters like `.status`)\n * that callers reach for after the check.\n */\nexport function stampErrorBrands(instance: object, ctor: unknown): void {\n    const brands = new Set<string>();\n    let current: unknown = ctor;\n    while (typeof current === 'function') {\n        const brand = (current as BrandedConstructor).mcpBrand;\n        if (Object.prototype.hasOwnProperty.call(current, 'mcpBrand') && typeof brand === 'string') {\n            brands.add(brand);\n        }\n        current = Object.getPrototypeOf(current);\n    }\n    if (brands.size === 0) return;\n    // configurable so userland instrumentation that clones/replaces error objects\n    // (e.g. wrapping via Object.defineProperties) is not broken by a frozen stamp;\n    // deleting the stamp merely degrades that instance to prototype `instanceof`.\n    Object.defineProperty(instance, BRANDS, { value: brands, enumerable: false, configurable: true });\n}\n\n/**\n * `Symbol.hasInstance` implementation for branded hierarchy roots. Matches when the\n * value carries the **own** brand of the class being tested against (cross-bundle\n * path), falling back to ordinary prototype-based `instanceof` otherwise.\n */\nexport function brandedHasInstance(cls: object, value: unknown): boolean {\n    try {\n        if (\n            typeof value === 'object' &&\n            value !== null &&\n            Object.prototype.hasOwnProperty.call(cls, 'mcpBrand') &&\n            typeof (cls as BrandedConstructor).mcpBrand === 'string' &&\n            // Own-property only: a brand inherited via the prototype chain is never\n            // honored, so polluting Object.prototype with the registry symbol cannot\n            // make arbitrary objects satisfy instanceof (real instances are stamped\n            // with an own property by stampErrorBrands).\n            Object.prototype.hasOwnProperty.call(value, BRANDS)\n        ) {\n            const carried = (value as BrandCarrier)[BRANDS];\n            if (carried && typeof carried.has === 'function' && carried.has((cls as BrandedConstructor).mcpBrand!)) {\n                return true;\n            }\n        }\n    } catch {\n        // A hostile Proxy trap or throwing accessor must not make `instanceof`\n        // throw where it previously returned false — fall through to the\n        // ordinary prototype check.\n    }\n    return Function.prototype[Symbol.hasInstance].call(cls, value);\n}\n","import { brandedHasInstance, stampErrorBrands } from '../errors/crossBundleBrand';\nimport type { OAuthErrorResponse } from '../shared/auth';\n\n/**\n * OAuth error codes as defined by {@link https://datatracker.ietf.org/doc/html/rfc6749#section-5.2 | RFC 6749}\n * and extensions.\n */\nexport enum OAuthErrorCode {\n    /**\n     * The request is missing a required parameter, includes an invalid parameter value,\n     * includes a parameter more than once, or is otherwise malformed.\n     */\n    InvalidRequest = 'invalid_request',\n\n    /**\n     * Client authentication failed (e.g., unknown client, no client authentication included,\n     * or unsupported authentication method).\n     */\n    InvalidClient = 'invalid_client',\n\n    /**\n     * The provided authorization grant or refresh token is invalid, expired, revoked,\n     * does not match the redirection URI used in the authorization request, or was issued to another client.\n     */\n    InvalidGrant = 'invalid_grant',\n\n    /**\n     * The authenticated client is not authorized to use this authorization grant type.\n     */\n    UnauthorizedClient = 'unauthorized_client',\n\n    /**\n     * The authorization grant type is not supported by the authorization server.\n     */\n    UnsupportedGrantType = 'unsupported_grant_type',\n\n    /**\n     * The requested scope is invalid, unknown, malformed, or exceeds the scope granted by the resource owner.\n     */\n    InvalidScope = 'invalid_scope',\n\n    /**\n     * The resource owner or authorization server denied the request.\n     */\n    AccessDenied = 'access_denied',\n\n    /**\n     * The authorization server encountered an unexpected condition that prevented it from fulfilling the request.\n     */\n    ServerError = 'server_error',\n\n    /**\n     * The authorization server is currently unable to handle the request due to temporary overloading or maintenance.\n     */\n    TemporarilyUnavailable = 'temporarily_unavailable',\n\n    /**\n     * The authorization server does not support obtaining an authorization code using this method.\n     */\n    UnsupportedResponseType = 'unsupported_response_type',\n\n    /**\n     * The authorization server does not support the requested token type.\n     */\n    UnsupportedTokenType = 'unsupported_token_type',\n\n    /**\n     * The access token provided is expired, revoked, malformed, or invalid for other reasons.\n     */\n    InvalidToken = 'invalid_token',\n\n    /**\n     * The HTTP method used is not allowed for this endpoint. (Custom, non-standard error)\n     */\n    MethodNotAllowed = 'method_not_allowed',\n\n    /**\n     * Rate limit exceeded. (Custom, non-standard error based on RFC 6585)\n     */\n    TooManyRequests = 'too_many_requests',\n\n    /**\n     * The client metadata is invalid. (Custom error for dynamic client registration - RFC 7591)\n     */\n    InvalidClientMetadata = 'invalid_client_metadata',\n\n    /**\n     * The value of one or more redirection URIs is invalid. (Dynamic client registration - RFC 7591 §3.2.2)\n     */\n    InvalidRedirectUri = 'invalid_redirect_uri',\n\n    /**\n     * The request requires higher privileges than provided by the access token.\n     */\n    InsufficientScope = 'insufficient_scope',\n\n    /**\n     * The requested resource is invalid, missing, unknown, or malformed. (Custom error for resource indicators - RFC 8707)\n     */\n    InvalidTarget = 'invalid_target',\n\n    /**\n     * The DPoP proof accompanying the request is invalid, or does not match the key the grant\n     * (e.g. a refresh token) is bound to. (RFC 9449 §5 / §7.1)\n     */\n    InvalidDpopProof = 'invalid_dpop_proof',\n\n    /**\n     * The server requires a server-supplied nonce in the DPoP proof; retry with the `DPoP-Nonce`\n     * it returned. (RFC 9449 §8 / §9)\n     */\n    UseDpopNonce = 'use_dpop_nonce'\n}\n\n/**\n * OAuth error class for all OAuth-related errors.\n */\nexport class OAuthError extends Error {\n    static {\n        Object.defineProperty(this, 'mcpBrand', { value: 'mcp.OAuthError' });\n    }\n\n    static override [Symbol.hasInstance](value: unknown): boolean {\n        return brandedHasInstance(this, value);\n    }\n\n    /**\n     * Brand-based type guard: equivalent to `value instanceof this`, as an\n     * explicit static predicate (the axios/AWS-SDK `isInstance` style). Reads\n     * the caller's own brand via `this`, so every branded subclass gets a\n     * correctly-scoped guard by inheritance. Must be invoked on the class —\n     * in callback position write `v => SdkError.isInstance(v)`, not\n     * `.filter(SdkError.isInstance)` (detached calls throw rather than\n     * silently matching nothing).\n     */\n    static isInstance<T extends abstract new (...args: never[]) => unknown>(this: T, value: unknown): value is InstanceType<T> {\n        if (typeof this !== 'function') {\n            throw new TypeError(\n                'isInstance must be called on the class (e.g. `SdkError.isInstance(value)`); for callbacks use `v => SdkError.isInstance(v)`'\n            );\n        }\n        return brandedHasInstance(this, value);\n    }\n\n    constructor(\n        public readonly code: OAuthErrorCode | string,\n        message: string,\n        public readonly errorUri?: string\n    ) {\n        super(message);\n        this.name = 'OAuthError';\n        stampErrorBrands(this, new.target);\n    }\n\n    /**\n     * Converts the error to a standard OAuth error response object.\n     */\n    toResponseObject(): OAuthErrorResponse {\n        const response: OAuthErrorResponse = {\n            error: this.code,\n            error_description: this.message\n        };\n\n        if (this.errorUri) {\n            response.error_uri = this.errorUri;\n        }\n\n        return response;\n    }\n\n    /**\n     * Creates an {@linkcode OAuthError} from an OAuth error response.\n     */\n    static fromResponse(response: OAuthErrorResponse): OAuthError {\n        return new OAuthError(response.error as OAuthErrorCode, response.error_description ?? response.error, response.error_uri);\n    }\n}\n","import { brandedHasInstance, stampErrorBrands } from './crossBundleBrand';\n\n/**\n * Error codes for SDK errors (local errors that never cross the wire).\n * Unlike {@linkcode ProtocolErrorCode} which uses numeric JSON-RPC codes, `SdkErrorCode` uses\n * descriptive string values for better developer experience.\n *\n * These errors are thrown locally by the SDK and are never serialized as\n * JSON-RPC error responses.\n */\nexport enum SdkErrorCode {\n    // State errors\n    /** Transport is not connected */\n    NotConnected = 'NOT_CONNECTED',\n    /** Transport is already connected */\n    AlreadyConnected = 'ALREADY_CONNECTED',\n    /** Protocol is not initialized */\n    NotInitialized = 'NOT_INITIALIZED',\n\n    // Capability errors\n    /** Required capability is not supported by the remote side */\n    CapabilityNotSupported = 'CAPABILITY_NOT_SUPPORTED',\n\n    // Transport errors\n    /** Request timed out waiting for response */\n    RequestTimeout = 'REQUEST_TIMEOUT',\n    /** Connection was closed */\n    ConnectionClosed = 'CONNECTION_CLOSED',\n    /** Failed to send message */\n    SendFailed = 'SEND_FAILED',\n    /** Response result failed local schema validation */\n    InvalidResult = 'INVALID_RESULT',\n    /**\n     * The response carried a `resultType` discriminator (protocol revision\n     * 2026-07-28) naming a result kind this client cannot consume yet, e.g.\n     * `input_required`. The kind is carried in `data.resultType`.\n     */\n    UnsupportedResultType = 'UNSUPPORTED_RESULT_TYPE',\n    /**\n     * The multi-round-trip auto-fulfilment driver exhausted its round cap\n     * (`inputRequired.maxRounds`) without the server returning a complete\n     * result. `data.rounds` carries the cap that was hit and\n     * `data.lastResult` carries the last `input_required` payload received\n     * (`{ inputRequests, requestState? }`), so callers can inspect or resume\n     * the flow manually.\n     */\n    InputRequiredRoundsExceeded = 'INPUT_REQUIRED_ROUNDS_EXCEEDED',\n    /**\n     * The auto-aggregating no-`cursor` `listTools()` / `listPrompts()` /\n     * `listResources()` / `listResourceTemplates()` walk hit the\n     * `ClientOptions.listMaxPages` cap without the server's pagination\n     * converging. `data.method` carries the list verb and\n     * `data.listMaxPages` the cap that was hit; raise the cap or fall back to\n     * explicit per-page `{ cursor }` calls.\n     */\n    ListPaginationExceeded = 'LIST_PAGINATION_EXCEEDED',\n    /**\n     * The spec method being sent does not exist on the negotiated protocol\n     * version's wire era (e.g. `tasks/get` toward a 2026-07-28 peer, or\n     * `server/discover` toward a 2025-era peer). Raised locally, before\n     * anything reaches the transport. The method and era are carried in\n     * `data.method` / `data.era`.\n     */\n    MethodNotSupportedByProtocolVersion = 'METHOD_NOT_SUPPORTED_BY_PROTOCOL_VERSION',\n    /**\n     * Protocol-era negotiation at connect time failed without producing either a\n     * usable modern (2026-07-28+) era or a definitive legacy fallback signal —\n     * e.g. the negotiation mode forbids falling back (`pin`), the probe hit a\n     * network failure, or the server answered the probe with a 5xx (a typed\n     * connect error, never an era verdict).\n     *\n     * Negotiation-phase only: this code is never used once an era is\n     * established. Auth walls never carry it: a 401/403 rejecting the probe\n     * uses {@linkcode ClientHttpAuthentication} / {@linkcode ClientHttpForbidden}\n     * instead, so era-recovery flows keyed on this code (e.g. cached-verdict\n     * gateways) can never persist a verdict for an unauthorized exchange.\n     */\n    EraNegotiationFailed = 'ERA_NEGOTIATION_FAILED',\n\n    // Transport errors\n    ClientHttpNotImplemented = 'CLIENT_HTTP_NOT_IMPLEMENTED',\n    /**\n     * HTTP 401 authentication failure: the transport's re-auth retry still got\n     * 401 (`Server returned 401 after re-authentication`), or the version\n     * negotiation probe was rejected 401 with no `authProvider` configured\n     * (`Version negotiation failed: the server requires authorization (HTTP 401)`).\n     * Carried on an {@linkcode SdkHttpError} with `status: 401`.\n     */\n    ClientHttpAuthentication = 'CLIENT_HTTP_AUTHENTICATION',\n    /**\n     * HTTP 403 denial: the step-up re-authorization retry limit was reached,\n     * or the version negotiation probe was rejected 403\n     * (`Version negotiation failed: the server denied access (HTTP 403)`).\n     * Carried on an {@linkcode SdkHttpError} with `status: 403`.\n     */\n    ClientHttpForbidden = 'CLIENT_HTTP_FORBIDDEN',\n    ClientHttpUnexpectedContent = 'CLIENT_HTTP_UNEXPECTED_CONTENT',\n    ClientHttpFailedToOpenStream = 'CLIENT_HTTP_FAILED_TO_OPEN_STREAM',\n    ClientHttpFailedToTerminateSession = 'CLIENT_HTTP_FAILED_TO_TERMINATE_SESSION'\n}\n\n/**\n * SDK errors are local errors that never cross the wire.\n * They are distinct from {@linkcode ProtocolError} which represents JSON-RPC protocol errors\n * that are serialized and sent as error responses.\n *\n * @example\n * ```ts source=\"./sdkErrors.examples.ts#SdkError_basicUsage\"\n * try {\n *     // Throwing an SDK error\n *     throw new SdkError(SdkErrorCode.NotConnected, 'Transport is not connected');\n * } catch (error) {\n *     // Checking error type by code\n *     if (error instanceof SdkError && error.code === SdkErrorCode.RequestTimeout) {\n *         // Handle timeout\n *     }\n * }\n * ```\n */\nexport class SdkError extends Error {\n    static {\n        Object.defineProperty(this, 'mcpBrand', { value: 'mcp.SdkError' });\n    }\n\n    static override [Symbol.hasInstance](value: unknown): boolean {\n        return brandedHasInstance(this, value);\n    }\n\n    /**\n     * Brand-based type guard: equivalent to `value instanceof this`, as an\n     * explicit static predicate (the axios/AWS-SDK `isInstance` style). Reads\n     * the caller's own brand via `this`, so every branded subclass gets a\n     * correctly-scoped guard by inheritance. Must be invoked on the class —\n     * in callback position write `v => SdkError.isInstance(v)`, not\n     * `.filter(SdkError.isInstance)` (detached calls throw rather than\n     * silently matching nothing).\n     */\n    static isInstance<T extends abstract new (...args: never[]) => unknown>(this: T, value: unknown): value is InstanceType<T> {\n        if (typeof this !== 'function') {\n            throw new TypeError(\n                'isInstance must be called on the class (e.g. `SdkError.isInstance(value)`); for callbacks use `v => SdkError.isInstance(v)`'\n            );\n        }\n        return brandedHasInstance(this, value);\n    }\n\n    /**\n     * @param code - Stable string code identifying the failure ({@linkcode SdkErrorCode}).\n     * @param message - Human-readable description.\n     * @param data - Optional structured payload (for example the HTTP status carried by\n     * {@linkcode SdkHttpError}). Opaque to the SDK: a `cause` key inside `data` is not\n     * promoted to `Error.cause`.\n     * @param options - Standard `ErrorOptions`, forwarded to `Error`. Pass the underlying\n     * failure as `{ cause }` so it is reachable through the `Error.cause` chain that\n     * loggers and error trackers walk.\n     */\n    constructor(\n        public readonly code: SdkErrorCode,\n        message: string,\n        public readonly data?: unknown,\n        options?: ErrorOptions\n    ) {\n        super(message, options);\n        this.name = 'SdkError';\n        stampErrorBrands(this, new.target);\n    }\n}\n\n/**\n * Typed shape for HTTP error data carried by {@linkcode SdkHttpError}.\n */\nexport interface SdkHttpErrorData {\n    status: number;\n    statusText?: string;\n    [key: string]: unknown;\n}\n\n/**\n * An {@linkcode SdkError} subclass for HTTP transport failures.\n *\n * Thrown by the streamable HTTP transport when the server responds with a\n * non-OK status code. Narrows {@linkcode SdkError.data | data} to\n * {@linkcode SdkHttpErrorData} so consumers can inspect the HTTP status\n * without unsafe casting.\n *\n * @example\n * ```ts source=\"./sdkErrors.examples.ts#SdkHttpError_basicUsage\"\n * if (error instanceof SdkHttpError) {\n *     console.log(error.status); // number\n *     console.log(error.statusText); // string | undefined\n * }\n * ```\n */\nexport class SdkHttpError extends SdkError {\n    static {\n        Object.defineProperty(this, 'mcpBrand', { value: 'mcp.SdkHttpError' });\n    }\n\n    declare readonly data: SdkHttpErrorData;\n\n    /**\n     * @param options - Standard `ErrorOptions`, forwarded to `Error` (see {@linkcode SdkError}).\n     */\n    constructor(code: SdkErrorCode, message: string, data: SdkHttpErrorData, options?: ErrorOptions) {\n        super(code, message, data, options);\n        this.name = 'SdkHttpError';\n    }\n\n    get status(): number {\n        return this.data.status;\n    }\n\n    get statusText(): string | undefined {\n        return this.data.statusText;\n    }\n}\n","/**\n * Utilities for handling OAuth resource URIs.\n */\n\n/**\n * Converts a server URL to a resource URL by removing the fragment.\n * {@link https://datatracker.ietf.org/doc/html/rfc8707#section-2 | RFC 8707 section 2}\n * states that resource URIs \"MUST NOT include a fragment component\".\n * Keeps everything else unchanged (scheme, domain, port, path, query).\n */\nexport function resourceUrlFromServerUrl(url: URL | string): URL {\n    const resourceURL = typeof url === 'string' ? new URL(url) : new URL(url.href);\n    resourceURL.hash = ''; // Remove fragment\n    return resourceURL;\n}\n\n/** Returns an authorization-server response body without `issuer`, which only the client sets, when it stores a value (SEP-2352). */\nexport function withoutIssuer(body: unknown): unknown {\n    if (typeof body !== 'object' || body === null || Array.isArray(body)) return body;\n    const copy: Record<string, unknown> = { ...body };\n    delete copy.issuer;\n    return copy;\n}\n\n/**\n * Checks if a requested resource URL matches a configured resource URL.\n * A requested resource matches if it has the same scheme, domain, port,\n * and its path starts with the configured resource's path.\n *\n * @param options - The options object\n * @param options.requestedResource - The resource URL being requested\n * @param options.configuredResource - The resource URL that has been configured\n * @returns true if the requested resource matches the configured resource, false otherwise\n */\nexport function checkResourceAllowed({\n    requestedResource,\n    configuredResource\n}: {\n    requestedResource: URL | string;\n    configuredResource: URL | string;\n}): boolean {\n    const requested = typeof requestedResource === 'string' ? new URL(requestedResource) : new URL(requestedResource.href);\n    const configured = typeof configuredResource === 'string' ? new URL(configuredResource) : new URL(configuredResource.href);\n\n    // Compare the origin (scheme, domain, and port)\n    if (requested.origin !== configured.origin) {\n        return false;\n    }\n\n    // Handle cases like requested=/foo and configured=/foo/\n    if (requested.pathname.length < configured.pathname.length) {\n        return false;\n    }\n\n    // Check if the requested path starts with the configured path\n    // Ensure both paths end with / for proper comparison\n    // This ensures that if we have paths like \"/api\" and \"/api/users\",\n    // we properly detect that \"/api/users\" is a subpath of \"/api\"\n    // By adding a trailing slash if missing, we avoid false positives\n    // where paths like \"/api123\" would incorrectly match \"/api\"\n    const requestedPath = requested.pathname.endsWith('/') ? requested.pathname : requested.pathname + '/';\n    const configuredPath = configured.pathname.endsWith('/') ? configured.pathname : configured.pathname + '/';\n\n    return requestedPath.startsWith(configuredPath);\n}\n","/**\n * Protocol-era helpers (pure module). The MCP wire protocol splits into two eras:\n * legacy (the 2025-11-25 family and earlier; the version is negotiated via the\n * `initialize` handshake) and modern (2026-07-28 and later; no `initialize` —\n * servers advertise versions via `server/discover` and every request carries a\n * `_meta` envelope).\n *\n * An operation that belongs to one era must only ever consult that era's subset\n * of a supported-versions list: `initialize` never accepts or counter-offers a\n * modern revision, and the `server/discover` advertisement only ever contains\n * modern revisions.\n */\n\n/**\n * The protocol era of a connection: `'legacy'` for the 2025-11-25 family and\n * earlier (negotiated via `initialize`), `'modern'` for 2026-07-28 and later\n * (negotiated via `server/discover`; every request carries a `_meta` envelope).\n */\nexport type ProtocolEra = 'legacy' | 'modern';\n\n/**\n * The first protocol revision of the modern (2026-07-28) era. Revision identifiers\n * are ISO dates, so lexicographic comparison orders them chronologically.\n */\nexport const FIRST_MODERN_PROTOCOL_VERSION = '2026-07-28';\n\n/**\n * Modern-era protocol revisions this SDK can negotiate via `server/discover`.\n * Deliberately separate from {@linkcode SUPPORTED_PROTOCOL_VERSIONS} (the legacy\n * `initialize` list), so adding a revision here can never leak a modern version\n * string into a 2025-era handshake. Internal — not part of the public API surface.\n */\nexport const SUPPORTED_MODERN_PROTOCOL_VERSIONS = [FIRST_MODERN_PROTOCOL_VERSION];\n\n/** Whether the given protocol revision belongs to the modern (2026-07-28+) era. */\nexport function isModernProtocolVersion(version: string): boolean {\n    return version >= FIRST_MODERN_PROTOCOL_VERSION;\n}\n\n/** The legacy-era (pre-2026-07-28) subset of a supported-versions list, in the list's own preference order. */\nexport function legacyProtocolVersions(versions: readonly string[]): string[] {\n    return versions.filter(version => !isModernProtocolVersion(version));\n}\n\n/** The modern-era (2026-07-28+) subset of a supported-versions list, in the list's own preference order. */\nexport function modernProtocolVersions(versions: readonly string[]): string[] {\n    return versions.filter(version => isModernProtocolVersion(version));\n}\n","import type { CallToolResult } from '../types/types';\n\n/**\n * SEP-2106 §4.3 TextContent auto-append, era-agnostic, called from BOTH\n * codecs' {@link WireCodec.projectCallToolResult}: when `structuredContent`\n * is a non-object value (array/primitive/`null`) and the handler authored no\n * `type:'text'` block, append `{type:'text', text: JSON.stringify(value)}`.\n * Object-shaped (or absent) `structuredContent` returns the same reference.\n *\n * Leaf module: imported by both era codec modules, so it must NOT import from\n * `./codec.js` (which value-imports the rev codecs at top level — that would\n * make a runtime cycle and a TDZ hazard for entries that evaluate a rev codec\n * module first).\n */\nexport function appendTextFallbackForNonObject(result: CallToolResult): CallToolResult {\n    const sc = result.structuredContent;\n    if (sc === undefined) return result;\n    const isNonObjectValue = typeof sc !== 'object' || sc === null || Array.isArray(sc);\n    if (!isNonObjectValue) return result;\n    const hasTextContent = result.content?.some(c => c.type === 'text') ?? false;\n    if (hasTextContent) return result;\n    return { ...result, content: [...(result.content ?? []), { type: 'text' as const, text: JSON.stringify(sc) }] };\n}\n","/**\n * Result-family keys that must never default into a `{content: []}` tools/call\n * success. Shared by the 2025 wire-seam schema and server normalization.\n * Leaf module (like `textFallback.ts`): imported by registry/server paths, so\n * it must NOT import from `./codec.js` — that would close a runtime cycle.\n */\nexport const TOOL_RESULT_FOREIGN_FAMILY_KEYS = ['task', 'inputRequests', 'requestState'] as const;\n\n/**\n * Single owner of the v1-parity ruling: a plain-object tool result without `content` (and\n * without foreign-family keys) gains `content: []`. Shared by the 2025 wire seam and server-side handler normalization.\n */\nexport function normalizeContentlessToolResult(value: unknown): unknown {\n    if (\n        value === null ||\n        typeof value !== 'object' ||\n        Array.isArray(value) ||\n        (value as { content?: unknown }).content !== undefined ||\n        TOOL_RESULT_FOREIGN_FAMILY_KEYS.some(key => key in value)\n    ) {\n        return value;\n    }\n    return { ...value, content: [] };\n}\n","/**\n * Complete frozen 2025-11-25 wire schemas. Self-contained — no imports from\n * the public/neutral types/schemas.ts. The neutral layer is the public-API\n * superset and is free to evolve (e.g., SEP-2106 widening); this file is the\n * 2025 wire-parse contract (Q10-L2 byte-identity) and is BEHAVIOR-FROZEN.\n *\n * This is the era's complete frozen wire-parse contract — both the 2025-only\n * delta (the deprecated task family, the era role unions) AND frozen copies of\n * every era-shared shape (Tool, CallToolResult, Initialize*, ContentBlock,\n * prompts/resources/completion/elicitation, …). The 2026-era codec\n * (`wire/rev2026-07-28/`) is symmetrically self-contained in the same way.\n *\n * The 2025-only delta (the task message surface, restored types-only by #2248\n * for interop with task-capable 2025 peers) is parsed ONLY through this era's\n * registry; the deprecated Task* schemas also live (marked `@deprecated`) in\n * the neutral schema layer so the public types stay nameable without a\n * cross-layer import — nameability is constant, runtime availability is\n * version-keyed — but appear in no API signature. Q1 increment 2 — deletions\n * are physical: the\n * 2026-era REGISTRY has no Task* methods (its frozen building-block copies do\n * carry the deprecated Task* sub-schemas by composition — soft contamination,\n * tracked for anchor-exactness adjudication).\n *\n * The only cross-layer dependency is `import type { JSONObject, JSONValue }`\n * from the neutral types barrel — pure structural type aliases with no parse\n * behavior. No runtime schema is shared with the neutral layer.\n */\nimport * as z from 'zod/v4';\n\nimport type { JSONObject, JSONValue } from '../../types/types';\nimport { normalizeContentlessToolResult, TOOL_RESULT_FOREIGN_FAMILY_KEYS } from '../resultFamilies';\n\nfunction build() {\n    /* ───────────────────────────────────────────────────────────────────────────\n     * Building blocks\n     * ─────────────────────────────────────────────────────────────────────────── */\n\n    const JSONValueSchema: z.ZodType<JSONValue, JSONValue> = z.lazy(() =>\n        z.union([z.string(), z.number(), z.boolean(), z.null(), z.record(z.string(), JSONValueSchema), z.array(JSONValueSchema)])\n    );\n    const JSONObjectSchema: z.ZodType<JSONObject, JSONObject> = z.record(z.string(), JSONValueSchema);\n\n    /**\n     * A progress token, used to associate progress notifications with the original request.\n     */\n    const ProgressTokenSchema = z.union([z.string(), z.number().int()]);\n\n    /**\n     * An opaque token used to represent a cursor for pagination.\n     */\n    const CursorSchema = z.string();\n\n    /** @deprecated 2025-11-25 wire vocabulary with no SDK runtime; kept importable for interoperability only. */\n    const TaskMetadataSchema = z.object({\n        ttl: z.number().optional()\n    });\n\n    /**\n     * Metadata for associating messages with a task.\n     * Include this in the `_meta` field under the key `io.modelcontextprotocol/related-task`.\n     *\n     * @deprecated 2025-11-25 wire vocabulary with no SDK runtime; kept importable for interoperability only.\n     */\n    const RelatedTaskMetadataSchema = z.object({\n        taskId: z.string()\n    });\n\n    const RequestMetaSchema = z.looseObject({\n        /**\n         * If specified, the caller is requesting out-of-band progress notifications for this request (as represented by notifications/progress). The value of this parameter is an opaque token that will be attached to any subsequent notifications. The receiver is not obligated to provide these notifications.\n         */\n        progressToken: ProgressTokenSchema.optional(),\n        /**\n         * If specified, this request is related to the provided task.\n         */\n        'io.modelcontextprotocol/related-task': RelatedTaskMetadataSchema.optional()\n    });\n\n    /**\n     * Common params for any request.\n     */\n    const BaseRequestParamsSchema = z.object({\n        /**\n         * See [General fields: `_meta`](/specification/draft/basic/index#meta) for notes on `_meta` usage.\n         */\n        _meta: RequestMetaSchema.optional()\n    });\n\n    /**\n     * Common params for any task-augmented request.\n     *\n     * @deprecated 2025-11-25 wire vocabulary with no SDK runtime; kept importable for interoperability only.\n     */\n    const TaskAugmentedRequestParamsSchema = BaseRequestParamsSchema.extend({\n        /**\n         * If specified, the caller is requesting task-augmented execution for this request.\n         * The request will return a `CreateTaskResult` immediately, and the actual result can be\n         * retrieved later via `tasks/result`.\n         *\n         * Task augmentation is subject to capability negotiation - receivers MUST declare support\n         * for task augmentation of specific request types in their capabilities.\n         */\n        task: TaskMetadataSchema.optional()\n    });\n\n    const RequestSchema = z.object({\n        method: z.string(),\n        params: BaseRequestParamsSchema.loose().optional()\n    });\n\n    const NotificationsParamsSchema = z.object({\n        /**\n         * See [MCP specification](https://github.com/modelcontextprotocol/modelcontextprotocol/blob/47339c03c143bb4ec01a26e721a1b8fe66634ebe/docs/specification/draft/basic/index.mdx#general-fields)\n         * for notes on `_meta` usage.\n         */\n        _meta: RequestMetaSchema.optional()\n    });\n\n    const NotificationSchema = z.object({\n        method: z.string(),\n        params: NotificationsParamsSchema.loose().optional()\n    });\n\n    const ResultSchema = z.looseObject({\n        /**\n         * See [MCP specification](https://github.com/modelcontextprotocol/modelcontextprotocol/blob/47339c03c143bb4ec01a26e721a1b8fe66634ebe/docs/specification/draft/basic/index.mdx#general-fields)\n         * for notes on `_meta` usage.\n         */\n        _meta: RequestMetaSchema.optional()\n    });\n\n    /**\n     * A uniquely identifying ID for a request in JSON-RPC.\n     */\n    const RequestIdSchema = z.union([z.string(), z.number().int()]);\n\n    /* Empty result */\n    /**\n     * A response that indicates success but carries no data.\n     */\n    const EmptyResultSchema = ResultSchema.strict();\n\n    const CancelledNotificationParamsSchema = NotificationsParamsSchema.extend({\n        /**\n         * The ID of the request to cancel.\n         *\n         * This MUST correspond to the ID of a request previously issued in the same direction.\n         */\n        requestId: RequestIdSchema.optional(),\n        /**\n         * An optional string describing the reason for the cancellation. This MAY be logged or presented to the user.\n         */\n        reason: z.string().optional()\n    });\n    /* Cancellation */\n    /**\n     * This notification can be sent by either side to indicate that it is cancelling a previously-issued request.\n     *\n     * 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.\n     *\n     * This notification indicates that the result will be unused, so any associated processing SHOULD cease.\n     *\n     * A client MUST NOT attempt to cancel its {@linkcode InitializeRequest | initialize} request.\n     */\n    const CancelledNotificationSchema = NotificationSchema.extend({\n        method: z.literal('notifications/cancelled'),\n        params: CancelledNotificationParamsSchema\n    });\n\n    /* Base Metadata */\n    /**\n     * Icon schema for use in {@link Tool | tools}, {@link Prompt | prompts}, {@link Resource | resources}, and {@link Implementation | implementations}.\n     */\n    const IconSchema = z.object({\n        /**\n         * URL or data URI for the icon.\n         */\n        src: z.string(),\n        /**\n         * Optional MIME type for the icon.\n         */\n        mimeType: z.string().optional(),\n        /**\n         * Optional array of strings that specify sizes at which the icon can be used.\n         * Each string should be in WxH format (e.g., `\"48x48\"`, `\"96x96\"`) or `\"any\"` for scalable formats like SVG.\n         *\n         * If not provided, the client should assume that the icon can be used at any size.\n         */\n        sizes: z.array(z.string()).optional(),\n        /**\n         * Optional specifier for the theme this icon is designed for. `light` indicates\n         * the icon is designed to be used with a light background, and `dark` indicates\n         * the icon is designed to be used with a dark background.\n         *\n         * If not provided, the client should assume the icon can be used with any theme.\n         */\n        theme: z.enum(['light', 'dark']).optional()\n    });\n\n    /**\n     * Base schema to add `icons` property.\n     *\n     */\n    const IconsSchema = z.object({\n        /**\n         * Optional set of sized icons that the client can display in a user interface.\n         *\n         * Clients that support rendering icons MUST support at least the following MIME types:\n         * - `image/png` - PNG images (safe, universal compatibility)\n         * - `image/jpeg` (and `image/jpg`) - JPEG images (safe, universal compatibility)\n         *\n         * Clients that support rendering icons SHOULD also support:\n         * - `image/svg+xml` - SVG images (scalable but requires security precautions)\n         * - `image/webp` - WebP images (modern, efficient format)\n         */\n        icons: z.array(IconSchema).optional()\n    });\n\n    /**\n     * Base metadata interface for common properties across {@link Resource | resources}, {@link Tool | tools}, {@link Prompt | prompts}, and {@link Implementation | implementations}.\n     */\n    const BaseMetadataSchema = z.object({\n        /** Intended for programmatic or logical use, but used as a display name in past specs or fallback */\n        name: z.string(),\n        /**\n         * Intended for UI and end-user contexts — optimized to be human-readable and easily understood,\n         * even by those unfamiliar with domain-specific terminology.\n         *\n         * If not provided, the `name` should be used for display (except for `Tool`,\n         * where `annotations.title` should be given precedence over using `name`,\n         * if present).\n         */\n        title: z.string().optional()\n    });\n\n    /* Initialization */\n    /**\n     * Describes the name and version of an MCP implementation.\n     */\n    const ImplementationSchema = BaseMetadataSchema.extend({\n        ...BaseMetadataSchema.shape,\n        ...IconsSchema.shape,\n        version: z.string(),\n        /**\n         * An optional URL of the website for this implementation.\n         */\n        websiteUrl: z.string().optional(),\n\n        /**\n         * An optional human-readable description of what this implementation does.\n         *\n         * This can be used by clients or servers to provide context about their purpose\n         * and capabilities. For example, a server might describe the types of resources\n         * or tools it provides, while a client might describe its intended use case.\n         */\n        description: z.string().optional()\n    });\n\n    const FormElicitationCapabilitySchema = z.intersection(\n        z.object({\n            applyDefaults: z.boolean().optional()\n        }),\n        JSONObjectSchema\n    );\n\n    const ElicitationCapabilitySchema = z.preprocess(\n        value => {\n            if (value && typeof value === 'object' && !Array.isArray(value) && Object.keys(value as Record<string, unknown>).length === 0) {\n                return { form: {} };\n            }\n            return value;\n        },\n        z.intersection(\n            z.object({\n                form: FormElicitationCapabilitySchema.optional(),\n                url: JSONObjectSchema.optional()\n            }),\n            JSONObjectSchema.optional()\n        )\n    );\n\n    /**\n     * Task capabilities for clients, indicating which request types support task creation.\n     *\n     * @deprecated 2025-11-25 wire vocabulary with no SDK runtime; kept importable for interoperability only.\n     */\n    const ClientTasksCapabilitySchema = z.looseObject({\n        /**\n         * Present if the client supports listing tasks.\n         */\n        list: JSONObjectSchema.optional(),\n        /**\n         * Present if the client supports cancelling tasks.\n         */\n        cancel: JSONObjectSchema.optional(),\n        /**\n         * Capabilities for task creation on specific request types.\n         */\n        requests: z\n            .looseObject({\n                /**\n                 * Task support for sampling requests.\n                 */\n                sampling: z\n                    .looseObject({\n                        createMessage: JSONObjectSchema.optional()\n                    })\n                    .optional(),\n                /**\n                 * Task support for elicitation requests.\n                 */\n                elicitation: z\n                    .looseObject({\n                        create: JSONObjectSchema.optional()\n                    })\n                    .optional()\n            })\n            .optional()\n    });\n\n    /**\n     * Task capabilities for servers, indicating which request types support task creation.\n     *\n     * @deprecated 2025-11-25 wire vocabulary with no SDK runtime; kept importable for interoperability only.\n     */\n    const ServerTasksCapabilitySchema = z.looseObject({\n        /**\n         * Present if the server supports listing tasks.\n         */\n        list: JSONObjectSchema.optional(),\n        /**\n         * Present if the server supports cancelling tasks.\n         */\n        cancel: JSONObjectSchema.optional(),\n        /**\n         * Capabilities for task creation on specific request types.\n         */\n        requests: z\n            .looseObject({\n                /**\n                 * Task support for tool requests.\n                 */\n                tools: z\n                    .looseObject({\n                        call: JSONObjectSchema.optional()\n                    })\n                    .optional()\n            })\n            .optional()\n    });\n\n    /**\n     * 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.\n     */\n    const ClientCapabilitiesSchema = z.object({\n        /**\n         * Experimental, non-standard capabilities that the client supports.\n         */\n        experimental: z.record(z.string(), JSONObjectSchema).optional(),\n        /**\n         * Present if the client supports sampling from an LLM.\n         *\n         * @deprecated Deprecated as of protocol version 2026-07-28 (SEP-2577); remains\n         * in the specification for at least twelve months. Migrate to calling LLM\n         * provider APIs directly.\n         */\n        sampling: z\n            .object({\n                /**\n                 * Present if the client supports context inclusion via `includeContext` parameter.\n                 * If not declared, servers SHOULD only use `includeContext: \"none\"` (or omit it).\n                 */\n                context: JSONObjectSchema.optional(),\n                /**\n                 * Present if the client supports tool use via `tools` and `toolChoice` parameters.\n                 */\n                tools: JSONObjectSchema.optional()\n            })\n            .optional(),\n        /**\n         * Present if the client supports eliciting user input.\n         */\n        elicitation: ElicitationCapabilitySchema.optional(),\n        /**\n         * Present if the client supports listing roots.\n         *\n         * @deprecated Deprecated as of protocol version 2026-07-28 (SEP-2577); remains\n         * in the specification for at least twelve months. Migrate to passing paths via\n         * tool parameters, resource URIs, or configuration.\n         */\n        roots: z\n            .object({\n                /**\n                 * Whether the client supports issuing notifications for changes to the roots list.\n                 */\n                listChanged: z.boolean().optional()\n            })\n            .optional(),\n        /**\n         * Present if the client supports task creation.\n         *\n         * @deprecated 2025-11-25 wire vocabulary with no SDK runtime; parsed for interoperability only — servers built on this SDK never advertise it.\n         */\n        tasks: ClientTasksCapabilitySchema.optional(),\n        /**\n         * Extensions that the client supports. Keys are extension identifiers (vendor-prefix/extension-name).\n         */\n        extensions: z.record(z.string(), JSONObjectSchema).optional()\n    });\n\n    const InitializeRequestParamsSchema = BaseRequestParamsSchema.extend({\n        /**\n         * The latest version of the Model Context Protocol that the client supports. The client MAY decide to support older versions as well.\n         */\n        protocolVersion: z.string(),\n        capabilities: ClientCapabilitiesSchema,\n        clientInfo: ImplementationSchema\n    });\n    /**\n     * This request is sent from the client to the server when it first connects, asking it to begin initialization.\n     */\n    const InitializeRequestSchema = RequestSchema.extend({\n        method: z.literal('initialize'),\n        params: InitializeRequestParamsSchema\n    });\n\n    /**\n     * 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.\n     */\n    const ServerCapabilitiesSchema = z.object({\n        /**\n         * Experimental, non-standard capabilities that the server supports.\n         */\n        experimental: z.record(z.string(), JSONObjectSchema).optional(),\n        /**\n         * Present if the server supports sending log messages to the client.\n         *\n         * @deprecated Deprecated as of protocol version 2026-07-28 (SEP-2577); remains\n         * in the specification for at least twelve months. Migrate to stderr logging\n         * (STDIO servers) or OpenTelemetry.\n         */\n        logging: JSONObjectSchema.optional(),\n        /**\n         * Present if the server supports sending completions to the client.\n         */\n        completions: JSONObjectSchema.optional(),\n        /**\n         * Present if the server offers any prompt templates.\n         */\n        prompts: z\n            .object({\n                /**\n                 * Whether this server supports issuing notifications for changes to the prompt list.\n                 */\n                listChanged: z.boolean().optional()\n            })\n            .optional(),\n        /**\n         * Present if the server offers any resources to read.\n         */\n        resources: z\n            .object({\n                /**\n                 * Whether this server supports clients subscribing to resource updates.\n                 */\n                subscribe: z.boolean().optional(),\n\n                /**\n                 * Whether this server supports issuing notifications for changes to the resource list.\n                 */\n                listChanged: z.boolean().optional()\n            })\n            .optional(),\n        /**\n         * Present if the server offers any tools to call.\n         */\n        tools: z\n            .object({\n                /**\n                 * Whether this server supports issuing notifications for changes to the tool list.\n                 */\n                listChanged: z.boolean().optional()\n            })\n            .optional(),\n        /**\n         * Present if the server supports task creation.\n         *\n         * @deprecated 2025-11-25 wire vocabulary with no SDK runtime; parsed for interoperability only — servers built on this SDK never advertise it.\n         */\n        tasks: ServerTasksCapabilitySchema.optional(),\n        /**\n         * Extensions that the server supports. Keys are extension identifiers (vendor-prefix/extension-name).\n         */\n        extensions: z.record(z.string(), JSONObjectSchema).optional()\n    });\n\n    /**\n     * After receiving an initialize request from the client, the server sends this response.\n     */\n    const InitializeResultSchema = ResultSchema.extend({\n        /**\n         * The version of the Model Context Protocol that the server wants to use. This may not match the version that the client requested. If the client cannot support this version, it MUST disconnect.\n         */\n        protocolVersion: z.string(),\n        capabilities: ServerCapabilitiesSchema,\n        serverInfo: ImplementationSchema,\n        /**\n         * Instructions describing how to use the server and its features.\n         *\n         * This can be used by clients to improve the LLM's understanding of available tools, resources, etc. It can be thought of like a \"hint\" to the model. For example, this information MAY be added to the system prompt.\n         */\n        instructions: z.string().optional()\n    });\n\n    /**\n     * This notification is sent from the client to the server after initialization has finished.\n     */\n    const InitializedNotificationSchema = NotificationSchema.extend({\n        method: z.literal('notifications/initialized'),\n        params: NotificationsParamsSchema.optional()\n    });\n\n    /* Ping */\n    /**\n     * 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.\n     */\n    const PingRequestSchema = RequestSchema.extend({\n        method: z.literal('ping'),\n        params: BaseRequestParamsSchema.optional()\n    });\n\n    /* Progress notifications */\n    const ProgressSchema = z.object({\n        /**\n         * The progress thus far. This should increase every time progress is made, even if the total is unknown.\n         */\n        progress: z.number(),\n        /**\n         * Total number of items to process (or total progress required), if known.\n         */\n        total: z.optional(z.number()),\n        /**\n         * An optional message describing the current progress.\n         */\n        message: z.optional(z.string())\n    });\n\n    const ProgressNotificationParamsSchema = z.object({\n        ...NotificationsParamsSchema.shape,\n        ...ProgressSchema.shape,\n        /**\n         * The progress token which was given in the initial request, used to associate this notification with the request that is proceeding.\n         */\n        progressToken: ProgressTokenSchema\n    });\n    /**\n     * An out-of-band notification used to inform the receiver of a progress update for a long-running request.\n     *\n     * @category notifications/progress\n     */\n    const ProgressNotificationSchema = NotificationSchema.extend({\n        method: z.literal('notifications/progress'),\n        params: ProgressNotificationParamsSchema\n    });\n\n    const PaginatedRequestParamsSchema = BaseRequestParamsSchema.extend({\n        /**\n         * An opaque token representing the current pagination position.\n         * If provided, the server should return results starting after this cursor.\n         */\n        cursor: CursorSchema.optional()\n    });\n\n    /* Pagination */\n    const PaginatedRequestSchema = RequestSchema.extend({\n        params: PaginatedRequestParamsSchema.optional()\n    });\n\n    const PaginatedResultSchema = ResultSchema.extend({\n        /**\n         * An opaque token representing the pagination position after the last returned result.\n         * If present, there may be more results available.\n         */\n        nextCursor: CursorSchema.optional()\n    });\n\n    /* Resources */\n    /**\n     * The contents of a specific resource or sub-resource.\n     */\n    const ResourceContentsSchema = z.object({\n        /**\n         * The URI of this resource.\n         */\n        uri: z.string(),\n        /**\n         * The MIME type of this resource, if known.\n         */\n        mimeType: z.optional(z.string()),\n        /**\n         * See [MCP specification](https://github.com/modelcontextprotocol/modelcontextprotocol/blob/47339c03c143bb4ec01a26e721a1b8fe66634ebe/docs/specification/draft/basic/index.mdx#general-fields)\n         * for notes on `_meta` usage.\n         */\n        _meta: z.record(z.string(), z.unknown()).optional()\n    });\n\n    const TextResourceContentsSchema = ResourceContentsSchema.extend({\n        /**\n         * The text of the item. This must only be set if the item can actually be represented as text (not binary data).\n         */\n        text: z.string()\n    });\n\n    /**\n     * A Zod schema for validating Base64 strings that is more performant and\n     * robust for very large inputs than the default regex-based check. It avoids\n     * stack overflows by using the native `atob` function for validation.\n     */\n    const Base64Schema = z.string().refine(\n        val => {\n            try {\n                // atob throws a DOMException if the string contains characters\n                // that are not part of the Base64 character set.\n                atob(val);\n                return true;\n            } catch {\n                return false;\n            }\n        },\n        { message: 'Invalid Base64 string' }\n    );\n\n    const BlobResourceContentsSchema = ResourceContentsSchema.extend({\n        /**\n         * A base64-encoded string representing the binary data of the item.\n         */\n        blob: Base64Schema\n    });\n\n    /**\n     * The sender or recipient of messages and data in a conversation.\n     */\n    const RoleSchema = z.enum(['user', 'assistant']);\n\n    /**\n     * Optional annotations providing clients additional context about a resource.\n     */\n    const AnnotationsSchema = z.object({\n        /**\n         * Intended audience(s) for the resource.\n         */\n        audience: z.array(RoleSchema).optional(),\n\n        /**\n         * Importance hint for the resource, from 0 (least) to 1 (most).\n         */\n        priority: z.number().min(0).max(1).optional(),\n\n        /**\n         * ISO 8601 timestamp for the most recent modification.\n         */\n        lastModified: z.iso.datetime({ offset: true }).optional()\n    });\n\n    /**\n     * A known resource that the server is capable of reading.\n     */\n    const ResourceSchema = z.object({\n        ...BaseMetadataSchema.shape,\n        ...IconsSchema.shape,\n        /**\n         * The URI of this resource.\n         */\n        uri: z.string(),\n\n        /**\n         * A description of what this resource represents.\n         *\n         * This can be used by clients to improve the LLM's understanding of available resources. It can be thought of like a \"hint\" to the model.\n         */\n        description: z.optional(z.string()),\n\n        /**\n         * The MIME type of this resource, if known.\n         */\n        mimeType: z.optional(z.string()),\n\n        /**\n         * The size of the raw resource content, in bytes (i.e., before base64 encoding or any tokenization), if known.\n         *\n         * This can be used by Hosts to display file sizes and estimate context window usage.\n         */\n        size: z.optional(z.number()),\n\n        /**\n         * Optional annotations for the client.\n         */\n        annotations: AnnotationsSchema.optional(),\n\n        /**\n         * See [MCP specification](https://github.com/modelcontextprotocol/modelcontextprotocol/blob/47339c03c143bb4ec01a26e721a1b8fe66634ebe/docs/specification/draft/basic/index.mdx#general-fields)\n         * for notes on `_meta` usage.\n         */\n        _meta: z.optional(z.looseObject({}))\n    });\n\n    /**\n     * A template description for resources available on the server.\n     */\n    const ResourceTemplateSchema = z.object({\n        ...BaseMetadataSchema.shape,\n        ...IconsSchema.shape,\n        /**\n         * A URI template (according to RFC 6570) that can be used to construct resource URIs.\n         */\n        uriTemplate: z.string(),\n\n        /**\n         * A description of what this template is for.\n         *\n         * This can be used by clients to improve the LLM's understanding of available resources. It can be thought of like a \"hint\" to the model.\n         */\n        description: z.optional(z.string()),\n\n        /**\n         * The MIME type for all resources that match this template. This should only be included if all resources matching this template have the same type.\n         */\n        mimeType: z.optional(z.string()),\n\n        /**\n         * Optional annotations for the client.\n         */\n        annotations: AnnotationsSchema.optional(),\n\n        /**\n         * See [MCP specification](https://github.com/modelcontextprotocol/modelcontextprotocol/blob/47339c03c143bb4ec01a26e721a1b8fe66634ebe/docs/specification/draft/basic/index.mdx#general-fields)\n         * for notes on `_meta` usage.\n         */\n        _meta: z.optional(z.looseObject({}))\n    });\n\n    /**\n     * Sent from the client to request a list of resources the server has.\n     */\n    const ListResourcesRequestSchema = PaginatedRequestSchema.extend({\n        method: z.literal('resources/list')\n    });\n\n    /**\n     * The server's response to a {@linkcode ListResourcesRequest | resources/list} request from the client.\n     */\n    const ListResourcesResultSchema = PaginatedResultSchema.extend({\n        resources: z.array(ResourceSchema)\n    });\n\n    /**\n     * Sent from the client to request a list of resource templates the server has.\n     */\n    const ListResourceTemplatesRequestSchema = PaginatedRequestSchema.extend({\n        method: z.literal('resources/templates/list')\n    });\n\n    /**\n     * The server's response to a {@linkcode ListResourceTemplatesRequest | resources/templates/list} request from the client.\n     */\n    const ListResourceTemplatesResultSchema = PaginatedResultSchema.extend({\n        resourceTemplates: z.array(ResourceTemplateSchema)\n    });\n\n    const ResourceRequestParamsSchema = BaseRequestParamsSchema.extend({\n        /**\n         * The URI of the resource to read. The URI can use any protocol; it is up to the server how to interpret it.\n         *\n         * @format uri\n         */\n        uri: z.string()\n    });\n\n    /**\n     * Parameters for a {@linkcode ReadResourceRequest | resources/read} request.\n     */\n    const ReadResourceRequestParamsSchema = ResourceRequestParamsSchema;\n\n    /**\n     * Sent from the client to the server, to read a specific resource URI.\n     */\n    const ReadResourceRequestSchema = RequestSchema.extend({\n        method: z.literal('resources/read'),\n        params: ReadResourceRequestParamsSchema\n    });\n\n    /**\n     * The server's response to a {@linkcode ReadResourceRequest | resources/read} request from the client.\n     */\n    const ReadResourceResultSchema = ResultSchema.extend({\n        contents: z.array(z.union([TextResourceContentsSchema, BlobResourceContentsSchema]))\n    });\n\n    /**\n     * 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.\n     */\n    const ResourceListChangedNotificationSchema = NotificationSchema.extend({\n        method: z.literal('notifications/resources/list_changed'),\n        params: NotificationsParamsSchema.optional()\n    });\n\n    const SubscribeRequestParamsSchema = ResourceRequestParamsSchema;\n    /**\n     * Sent from the client to request `resources/updated` notifications from the server whenever a particular resource changes.\n     */\n    const SubscribeRequestSchema = RequestSchema.extend({\n        method: z.literal('resources/subscribe'),\n        params: SubscribeRequestParamsSchema\n    });\n\n    const UnsubscribeRequestParamsSchema = ResourceRequestParamsSchema;\n    /**\n     * 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.\n     */\n    const UnsubscribeRequestSchema = RequestSchema.extend({\n        method: z.literal('resources/unsubscribe'),\n        params: UnsubscribeRequestParamsSchema\n    });\n\n    /**\n     * Parameters for a {@linkcode ResourceUpdatedNotification | notifications/resources/updated} notification.\n     */\n    const ResourceUpdatedNotificationParamsSchema = NotificationsParamsSchema.extend({\n        /**\n         * The URI of the resource that has been updated. This might be a sub-resource of the one that the client actually subscribed to.\n         */\n        uri: z.string()\n    });\n\n    /**\n     * 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.\n     */\n    const ResourceUpdatedNotificationSchema = NotificationSchema.extend({\n        method: z.literal('notifications/resources/updated'),\n        params: ResourceUpdatedNotificationParamsSchema\n    });\n\n    /* Prompts */\n    /**\n     * Describes an argument that a prompt can accept.\n     */\n    const PromptArgumentSchema = z.object({\n        /**\n         * The name of the argument.\n         */\n        name: z.string(),\n        /**\n         * A human-readable description of the argument.\n         */\n        description: z.optional(z.string()),\n        /**\n         * Whether this argument must be provided.\n         */\n        required: z.optional(z.boolean())\n    });\n\n    /**\n     * A prompt or prompt template that the server offers.\n     */\n    const PromptSchema = z.object({\n        ...BaseMetadataSchema.shape,\n        ...IconsSchema.shape,\n        /**\n         * An optional description of what this prompt provides\n         */\n        description: z.optional(z.string()),\n        /**\n         * A list of arguments to use for templating the prompt.\n         */\n        arguments: z.optional(z.array(PromptArgumentSchema)),\n        /**\n         * See [MCP specification](https://github.com/modelcontextprotocol/modelcontextprotocol/blob/47339c03c143bb4ec01a26e721a1b8fe66634ebe/docs/specification/draft/basic/index.mdx#general-fields)\n         * for notes on `_meta` usage.\n         */\n        _meta: z.optional(z.looseObject({}))\n    });\n\n    /**\n     * Sent from the client to request a list of prompts and prompt templates the server has.\n     */\n    const ListPromptsRequestSchema = PaginatedRequestSchema.extend({\n        method: z.literal('prompts/list')\n    });\n\n    /**\n     * The server's response to a {@linkcode ListPromptsRequest | prompts/list} request from the client.\n     */\n    const ListPromptsResultSchema = PaginatedResultSchema.extend({\n        prompts: z.array(PromptSchema)\n    });\n\n    /**\n     * Parameters for a {@linkcode GetPromptRequest | prompts/get} request.\n     */\n    const GetPromptRequestParamsSchema = BaseRequestParamsSchema.extend({\n        /**\n         * The name of the prompt or prompt template.\n         */\n        name: z.string(),\n        /**\n         * Arguments to use for templating the prompt.\n         */\n        arguments: z.record(z.string(), z.string()).optional()\n    });\n    /**\n     * Used by the client to get a prompt provided by the server.\n     */\n    const GetPromptRequestSchema = RequestSchema.extend({\n        method: z.literal('prompts/get'),\n        params: GetPromptRequestParamsSchema\n    });\n\n    /**\n     * Text provided to or from an LLM.\n     */\n    const TextContentSchema = z.object({\n        type: z.literal('text'),\n        /**\n         * The text content of the message.\n         */\n        text: z.string(),\n\n        /**\n         * Optional annotations for the client.\n         */\n        annotations: AnnotationsSchema.optional(),\n\n        /**\n         * See [MCP specification](https://github.com/modelcontextprotocol/modelcontextprotocol/blob/47339c03c143bb4ec01a26e721a1b8fe66634ebe/docs/specification/draft/basic/index.mdx#general-fields)\n         * for notes on `_meta` usage.\n         */\n        _meta: z.record(z.string(), z.unknown()).optional()\n    });\n\n    /**\n     * An image provided to or from an LLM.\n     */\n    const ImageContentSchema = z.object({\n        type: z.literal('image'),\n        /**\n         * The base64-encoded image data.\n         */\n        data: Base64Schema,\n        /**\n         * The MIME type of the image. Different providers may support different image types.\n         */\n        mimeType: z.string(),\n\n        /**\n         * Optional annotations for the client.\n         */\n        annotations: AnnotationsSchema.optional(),\n\n        /**\n         * See [MCP specification](https://github.com/modelcontextprotocol/modelcontextprotocol/blob/47339c03c143bb4ec01a26e721a1b8fe66634ebe/docs/specification/draft/basic/index.mdx#general-fields)\n         * for notes on `_meta` usage.\n         */\n        _meta: z.record(z.string(), z.unknown()).optional()\n    });\n\n    /**\n     * Audio content provided to or from an LLM.\n     */\n    const AudioContentSchema = z.object({\n        type: z.literal('audio'),\n        /**\n         * The base64-encoded audio data.\n         */\n        data: Base64Schema,\n        /**\n         * The MIME type of the audio. Different providers may support different audio types.\n         */\n        mimeType: z.string(),\n\n        /**\n         * Optional annotations for the client.\n         */\n        annotations: AnnotationsSchema.optional(),\n\n        /**\n         * See [MCP specification](https://github.com/modelcontextprotocol/modelcontextprotocol/blob/47339c03c143bb4ec01a26e721a1b8fe66634ebe/docs/specification/draft/basic/index.mdx#general-fields)\n         * for notes on `_meta` usage.\n         */\n        _meta: z.record(z.string(), z.unknown()).optional()\n    });\n\n    /**\n     * A tool call request from an assistant (LLM).\n     * Represents the assistant's request to use a tool.\n     *\n     * @deprecated Deprecated as of protocol version 2026-07-28 (SEP-2577); remains\n     * in the specification for at least twelve months. Migrate to calling LLM\n     * provider APIs directly.\n     */\n    const ToolUseContentSchema = z.object({\n        type: z.literal('tool_use'),\n        /**\n         * The name of the tool to invoke.\n         * Must match a tool name from the request's tools array.\n         */\n        name: z.string(),\n        /**\n         * Unique identifier for this tool call.\n         * Used to correlate with `ToolResultContent` in subsequent messages.\n         */\n        id: z.string(),\n        /**\n         * Arguments to pass to the tool.\n         * Must conform to the tool's `inputSchema`.\n         */\n        input: z.record(z.string(), z.unknown()),\n        /**\n         * See [MCP specification](https://github.com/modelcontextprotocol/modelcontextprotocol/blob/47339c03c143bb4ec01a26e721a1b8fe66634ebe/docs/specification/draft/basic/index.mdx#general-fields)\n         * for notes on `_meta` usage.\n         */\n        _meta: z.record(z.string(), z.unknown()).optional()\n    });\n\n    /**\n     * The contents of a resource, embedded into a prompt or tool call result.\n     */\n    const EmbeddedResourceSchema = z.object({\n        type: z.literal('resource'),\n        resource: z.union([TextResourceContentsSchema, BlobResourceContentsSchema]),\n        /**\n         * Optional annotations for the client.\n         */\n        annotations: AnnotationsSchema.optional(),\n        /**\n         * See [MCP specification](https://github.com/modelcontextprotocol/modelcontextprotocol/blob/47339c03c143bb4ec01a26e721a1b8fe66634ebe/docs/specification/draft/basic/index.mdx#general-fields)\n         * for notes on `_meta` usage.\n         */\n        _meta: z.record(z.string(), z.unknown()).optional()\n    });\n\n    /**\n     * A resource that the server is capable of reading, included in a prompt or tool call result.\n     *\n     * Note: resource links returned by tools are not guaranteed to appear in the results of {@linkcode ListResourcesRequest | resources/list} requests.\n     */\n    const ResourceLinkSchema = ResourceSchema.extend({\n        type: z.literal('resource_link')\n    });\n\n    /**\n     * A content block that can be used in prompts and tool results.\n     */\n    const ContentBlockSchema = z.union([\n        TextContentSchema,\n        ImageContentSchema,\n        AudioContentSchema,\n        ResourceLinkSchema,\n        EmbeddedResourceSchema\n    ]);\n\n    /**\n     * Describes a message returned as part of a prompt.\n     */\n    const PromptMessageSchema = z.object({\n        role: RoleSchema,\n        content: ContentBlockSchema\n    });\n\n    /**\n     * The server's response to a {@linkcode GetPromptRequest | prompts/get} request from the client.\n     */\n    const GetPromptResultSchema = ResultSchema.extend({\n        /**\n         * An optional description for the prompt.\n         */\n        description: z.string().optional(),\n        messages: z.array(PromptMessageSchema)\n    });\n\n    /**\n     * 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.\n     */\n    const PromptListChangedNotificationSchema = NotificationSchema.extend({\n        method: z.literal('notifications/prompts/list_changed'),\n        params: NotificationsParamsSchema.optional()\n    });\n\n    /* Tools */\n    /**\n     * Additional properties describing a `Tool` to clients.\n     *\n     * NOTE: all properties in {@linkcode ToolAnnotations} are **hints**.\n     * They are not guaranteed to provide a faithful description of\n     * tool behavior (including descriptive properties like `title`).\n     *\n     * Clients should never make tool use decisions based on `ToolAnnotations`\n     * received from untrusted servers.\n     */\n    const ToolAnnotationsSchema = z.object({\n        /**\n         * A human-readable title for the tool.\n         */\n        title: z.string().optional(),\n\n        /**\n         * If `true`, the tool does not modify its environment.\n         *\n         * Default: `false`\n         */\n        readOnlyHint: z.boolean().optional(),\n\n        /**\n         * If `true`, the tool may perform destructive updates to its environment.\n         * If `false`, the tool performs only additive updates.\n         *\n         * (This property is meaningful only when `readOnlyHint == false`)\n         *\n         * Default: `true`\n         */\n        destructiveHint: z.boolean().optional(),\n\n        /**\n         * If `true`, calling the tool repeatedly with the same arguments\n         * will have no additional effect on its environment.\n         *\n         * (This property is meaningful only when `readOnlyHint == false`)\n         *\n         * Default: `false`\n         */\n        idempotentHint: z.boolean().optional(),\n\n        /**\n         * If `true`, this tool may interact with an \"open world\" of external\n         * entities. If `false`, the tool's domain of interaction is closed.\n         * For example, the world of a web search tool is open, whereas that\n         * of a memory tool is not.\n         *\n         * Default: `true`\n         */\n        openWorldHint: z.boolean().optional()\n    });\n\n    /**\n     * Execution-related properties for a tool.\n     */\n    const ToolExecutionSchema = z.object({\n        /**\n         * Indicates the tool's preference for task-augmented execution.\n         * - `\"required\"`: Clients MUST invoke the tool as a task\n         * - `\"optional\"`: Clients MAY invoke the tool as a task or normal request\n         * - `\"forbidden\"`: Clients MUST NOT attempt to invoke the tool as a task\n         *\n         * If not present, defaults to `\"forbidden\"`.\n         */\n        taskSupport: z.enum(['required', 'optional', 'forbidden']).optional()\n    });\n\n    /**\n     * Definition for a tool the client can call.\n     */\n    const ToolSchema = z.object({\n        ...BaseMetadataSchema.shape,\n        ...IconsSchema.shape,\n        /**\n         * A human-readable description of the tool.\n         */\n        description: z.string().optional(),\n        /**\n         * A JSON Schema 2020-12 object defining the expected parameters for the tool.\n         * Must have `type: 'object'` at the root level per MCP spec.\n         */\n        inputSchema: z\n            .object({\n                type: z.literal('object'),\n                properties: z.record(z.string(), JSONValueSchema).optional(),\n                required: z.array(z.string()).optional()\n            })\n            .catchall(z.unknown()),\n        /**\n         * An optional JSON Schema 2020-12 object defining the structure of the tool's output\n         * returned in the `structuredContent` field of a `CallToolResult`.\n         * Must have `type: 'object'` at the root level per MCP spec.\n         */\n        outputSchema: z\n            .object({\n                type: z.literal('object'),\n                properties: z.record(z.string(), JSONValueSchema).optional(),\n                required: z.array(z.string()).optional()\n            })\n            .catchall(z.unknown())\n            .optional(),\n        /**\n         * Optional additional tool information.\n         */\n        annotations: ToolAnnotationsSchema.optional(),\n        /**\n         * Execution-related properties for this tool.\n         */\n        execution: ToolExecutionSchema.optional(),\n\n        /**\n         * See [MCP specification](https://github.com/modelcontextprotocol/modelcontextprotocol/blob/47339c03c143bb4ec01a26e721a1b8fe66634ebe/docs/specification/draft/basic/index.mdx#general-fields)\n         * for notes on `_meta` usage.\n         */\n        _meta: z.record(z.string(), z.unknown()).optional()\n    });\n\n    /**\n     * Sent from the client to request a list of tools the server has.\n     */\n    const ListToolsRequestSchema = PaginatedRequestSchema.extend({\n        method: z.literal('tools/list')\n    });\n\n    /**\n     * The server's response to a {@linkcode ListToolsRequest | tools/list} request from the client.\n     */\n    const ListToolsResultSchema = PaginatedResultSchema.extend({\n        tools: z.array(ToolSchema)\n    });\n\n    /**\n     * The server's response to a tool call.\n     */\n    const CallToolResultSchema = ResultSchema.extend({\n        /**\n         * A list of content objects that represent the result of the tool call.\n         *\n         * If the `Tool` does not define an outputSchema, this field MUST be present in the result.\n         * Required on the wire per the specification (it may be an empty array).\n         */\n        content: z.array(ContentBlockSchema),\n\n        /**\n         * An object containing structured tool output.\n         *\n         * If the `Tool` defines an outputSchema, this field MUST be present in the result, and contain a JSON object that matches the schema.\n         */\n        structuredContent: z.record(z.string(), z.unknown()).optional(),\n\n        /**\n         * Whether the tool call ended in an error.\n         *\n         * If not set, this is assumed to be `false` (the call was successful).\n         *\n         * Any errors that originate from the tool SHOULD be reported inside the result\n         * object, with `isError` set to `true`, _not_ as an MCP protocol-level error\n         * response. Otherwise, the LLM would not be able to see that an error occurred\n         * and self-correct.\n         *\n         * However, any errors in _finding_ the tool, an error indicating that the\n         * server does not support tool calls, or any other exceptional conditions,\n         * should be reported as an MCP error response.\n         */\n        isError: z.boolean().optional()\n    });\n\n    /**\n     * Parameters for a `tools/call` request.\n     */\n    const CallToolRequestParamsSchema = TaskAugmentedRequestParamsSchema.extend({\n        /**\n         * The name of the tool to call.\n         */\n        name: z.string(),\n        /**\n         * Arguments to pass to the tool.\n         */\n        arguments: z.record(z.string(), z.unknown()).optional()\n    });\n\n    /**\n     * Used by the client to invoke a tool provided by the server.\n     */\n    const CallToolRequestSchema = RequestSchema.extend({\n        method: z.literal('tools/call'),\n        params: CallToolRequestParamsSchema\n    });\n\n    /**\n     * 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.\n     */\n    const ToolListChangedNotificationSchema = NotificationSchema.extend({\n        method: z.literal('notifications/tools/list_changed'),\n        params: NotificationsParamsSchema.optional()\n    });\n\n    /* Logging */\n    /**\n     * The severity of a log message.\n     *\n     * @deprecated Deprecated as of protocol version 2026-07-28 (SEP-2577); remains\n     * in the specification for at least twelve months. Migrate to stderr logging\n     * (STDIO servers) or OpenTelemetry.\n     */\n    const LoggingLevelSchema = z.enum(['debug', 'info', 'notice', 'warning', 'error', 'critical', 'alert', 'emergency']);\n\n    /**\n     * Parameters for a `logging/setLevel` request.\n     *\n     * @deprecated Deprecated as of protocol version 2026-07-28 (SEP-2577); remains\n     * in the specification for at least twelve months. Migrate to stderr logging\n     * (STDIO servers) or OpenTelemetry.\n     */\n    const SetLevelRequestParamsSchema = BaseRequestParamsSchema.extend({\n        /**\n         * The level of logging that the client wants to receive from the server. The server should send all logs at this level and higher (i.e., more severe) to the client as `notifications/logging/message`.\n         */\n        level: LoggingLevelSchema\n    });\n    /**\n     * A request from the client to the server, to enable or adjust logging.\n     *\n     * @deprecated Deprecated as of protocol version 2026-07-28 (SEP-2577); remains\n     * in the specification for at least twelve months. Migrate to stderr logging\n     * (STDIO servers) or OpenTelemetry.\n     */\n    const SetLevelRequestSchema = RequestSchema.extend({\n        method: z.literal('logging/setLevel'),\n        params: SetLevelRequestParamsSchema\n    });\n\n    /**\n     * Parameters for a `notifications/message` notification.\n     *\n     * @deprecated Deprecated as of protocol version 2026-07-28 (SEP-2577); remains\n     * in the specification for at least twelve months. Migrate to stderr logging\n     * (STDIO servers) or OpenTelemetry.\n     */\n    const LoggingMessageNotificationParamsSchema = NotificationsParamsSchema.extend({\n        /**\n         * The severity of this log message.\n         */\n        level: LoggingLevelSchema,\n        /**\n         * An optional name of the logger issuing this message.\n         */\n        logger: z.string().optional(),\n        /**\n         * The data to be logged, such as a string message or an object. Any JSON serializable type is allowed here.\n         */\n        data: z.unknown()\n    });\n    /**\n     * 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.\n     *\n     * @deprecated Deprecated as of protocol version 2026-07-28 (SEP-2577); remains\n     * in the specification for at least twelve months. Migrate to stderr logging\n     * (STDIO servers) or OpenTelemetry.\n     */\n    const LoggingMessageNotificationSchema = NotificationSchema.extend({\n        method: z.literal('notifications/message'),\n        params: LoggingMessageNotificationParamsSchema\n    });\n\n    /* Sampling */\n    /**\n     * Hints to use for model selection.\n     *\n     * @deprecated Deprecated as of protocol version 2026-07-28 (SEP-2577); remains\n     * in the specification for at least twelve months. Migrate to calling LLM\n     * provider APIs directly.\n     */\n    const ModelHintSchema = z.object({\n        /**\n         * A hint for a model name.\n         */\n        name: z.string().optional()\n    });\n\n    /**\n     * The server's preferences for model selection, requested of the client during sampling.\n     *\n     * @deprecated Deprecated as of protocol version 2026-07-28 (SEP-2577); remains\n     * in the specification for at least twelve months. Migrate to calling LLM\n     * provider APIs directly.\n     */\n    const ModelPreferencesSchema = z.object({\n        /**\n         * Optional hints to use for model selection.\n         */\n        hints: z.array(ModelHintSchema).optional(),\n        /**\n         * How much to prioritize cost when selecting a model.\n         */\n        costPriority: z.number().min(0).max(1).optional(),\n        /**\n         * How much to prioritize sampling speed (latency) when selecting a model.\n         */\n        speedPriority: z.number().min(0).max(1).optional(),\n        /**\n         * How much to prioritize intelligence and capabilities when selecting a model.\n         */\n        intelligencePriority: z.number().min(0).max(1).optional()\n    });\n\n    /**\n     * Controls tool usage behavior in sampling requests.\n     *\n     * @deprecated Deprecated as of protocol version 2026-07-28 (SEP-2577); remains\n     * in the specification for at least twelve months. Migrate to calling LLM\n     * provider APIs directly.\n     */\n    const ToolChoiceSchema = z.object({\n        /**\n         * Controls when tools are used:\n         * - `\"auto\"`: Model decides whether to use tools (default)\n         * - `\"required\"`: Model MUST use at least one tool before completing\n         * - `\"none\"`: Model MUST NOT use any tools\n         */\n        mode: z.enum(['auto', 'required', 'none']).optional()\n    });\n\n    /**\n     * The result of a tool execution, provided by the user (server).\n     * Represents the outcome of invoking a tool requested via `ToolUseContent`.\n     *\n     * @deprecated Deprecated as of protocol version 2026-07-28 (SEP-2577); remains\n     * in the specification for at least twelve months. Migrate to calling LLM\n     * provider APIs directly.\n     */\n    const ToolResultContentSchema = z.object({\n        type: z.literal('tool_result'),\n        toolUseId: z.string().describe('The unique identifier for the corresponding tool call.'),\n        content: z.array(ContentBlockSchema),\n        structuredContent: z.object({}).loose().optional(),\n        isError: z.boolean().optional(),\n\n        /**\n         * See [MCP specification](https://github.com/modelcontextprotocol/modelcontextprotocol/blob/47339c03c143bb4ec01a26e721a1b8fe66634ebe/docs/specification/draft/basic/index.mdx#general-fields)\n         * for notes on `_meta` usage.\n         */\n        _meta: z.record(z.string(), z.unknown()).optional()\n    });\n\n    /**\n     * Basic content types for sampling responses (without tool use).\n     * Used for backwards-compatible {@linkcode CreateMessageResult} when tools are not used.\n     *\n     * @deprecated Deprecated as of protocol version 2026-07-28 (SEP-2577); remains\n     * in the specification for at least twelve months. Migrate to calling LLM\n     * provider APIs directly.\n     */\n    const SamplingContentSchema = z.discriminatedUnion('type', [TextContentSchema, ImageContentSchema, AudioContentSchema]);\n\n    /**\n     * Content block types allowed in sampling messages.\n     * This includes text, image, audio, tool use requests, and tool results.\n     *\n     * @deprecated Deprecated as of protocol version 2026-07-28 (SEP-2577); remains\n     * in the specification for at least twelve months. Migrate to calling LLM\n     * provider APIs directly.\n     */\n    const SamplingMessageContentBlockSchema = z.discriminatedUnion('type', [\n        TextContentSchema,\n        ImageContentSchema,\n        AudioContentSchema,\n        ToolUseContentSchema,\n        ToolResultContentSchema\n    ]);\n\n    /**\n     * Describes a message issued to or received from an LLM API.\n     *\n     * @deprecated Deprecated as of protocol version 2026-07-28 (SEP-2577); remains\n     * in the specification for at least twelve months. Migrate to calling LLM\n     * provider APIs directly.\n     */\n    const SamplingMessageSchema = z.object({\n        role: RoleSchema,\n        content: z.union([SamplingMessageContentBlockSchema, z.array(SamplingMessageContentBlockSchema)]),\n        /**\n         * See [MCP specification](https://github.com/modelcontextprotocol/modelcontextprotocol/blob/47339c03c143bb4ec01a26e721a1b8fe66634ebe/docs/specification/draft/basic/index.mdx#general-fields)\n         * for notes on `_meta` usage.\n         */\n        _meta: z.record(z.string(), z.unknown()).optional()\n    });\n\n    /**\n     * Parameters for a `sampling/createMessage` request.\n     *\n     * @deprecated Deprecated as of protocol version 2026-07-28 (SEP-2577); remains\n     * in the specification for at least twelve months. Migrate to calling LLM\n     * provider APIs directly.\n     */\n    const CreateMessageRequestParamsSchema = TaskAugmentedRequestParamsSchema.extend({\n        messages: z.array(SamplingMessageSchema),\n        /**\n         * The server's preferences for which model to select. The client MAY modify or omit this request.\n         */\n        modelPreferences: ModelPreferencesSchema.optional(),\n        /**\n         * An optional system prompt the server wants to use for sampling. The client MAY modify or omit this prompt.\n         */\n        systemPrompt: z.string().optional(),\n        /**\n         * A request to include context from one or more MCP servers (including the caller), to be attached to the prompt.\n         * The client MAY ignore this request.\n         *\n         * Default is `\"none\"`. The values `\"thisServer\"` and `\"allServers\"` are deprecated (SEP-2596): servers SHOULD\n         * omit this field or use `\"none\"`, and SHOULD only use the deprecated values if the client declares\n         * `ClientCapabilities`.`sampling.context`.\n         *\n         * @deprecated The `\"thisServer\"` and `\"allServers\"` values are deprecated as of protocol version 2025-11-25\n         * (SEP-2596) and will be removed no later than the Sampling feature itself (SEP-2577). Omit this field or use `\"none\"`.\n         */\n        includeContext: z.enum(['none', 'thisServer', 'allServers']).optional(),\n        temperature: z.number().optional(),\n        /**\n         * The requested maximum number of tokens to sample (to prevent runaway completions).\n         *\n         * The client MAY choose to sample fewer tokens than the requested maximum.\n         */\n        maxTokens: z.number().int(),\n        stopSequences: z.array(z.string()).optional(),\n        /**\n         * Optional metadata to pass through to the LLM provider. The format of this metadata is provider-specific.\n         */\n        metadata: JSONObjectSchema.optional(),\n        /**\n         * Tools that the model may use during generation.\n         * The client MUST return an error if this field is provided but `ClientCapabilities`.`sampling.tools` is not declared.\n         */\n        tools: z.array(ToolSchema).optional(),\n        /**\n         * Controls how the model uses tools.\n         * The client MUST return an error if this field is provided but `ClientCapabilities`.`sampling.tools` is not declared.\n         * Default is `{ mode: \"auto\" }`.\n         */\n        toolChoice: ToolChoiceSchema.optional()\n    });\n    /**\n     * 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.\n     *\n     * @deprecated Deprecated as of protocol version 2026-07-28 (SEP-2577); remains\n     * in the specification for at least twelve months. Migrate to calling LLM\n     * provider APIs directly.\n     */\n    const CreateMessageRequestSchema = RequestSchema.extend({\n        method: z.literal('sampling/createMessage'),\n        params: CreateMessageRequestParamsSchema\n    });\n\n    /**\n     * The client's response to a `sampling/create_message` request from the server.\n     * This is the backwards-compatible version that returns single content (no arrays).\n     * Used when the request does not include tools.\n     *\n     * @deprecated Deprecated as of protocol version 2026-07-28 (SEP-2577); remains\n     * in the specification for at least twelve months. Migrate to calling LLM\n     * provider APIs directly.\n     */\n    const CreateMessageResultSchema = ResultSchema.extend({\n        /**\n         * The name of the model that generated the message.\n         */\n        model: z.string(),\n        /**\n         * The reason why sampling stopped, if known.\n         *\n         * Standard values:\n         * - `\"endTurn\"`: Natural end of the assistant's turn\n         * - `\"stopSequence\"`: A stop sequence was encountered\n         * - `\"maxTokens\"`: Maximum token limit was reached\n         *\n         * This field is an open string to allow for provider-specific stop reasons.\n         */\n        stopReason: z.optional(z.enum(['endTurn', 'stopSequence', 'maxTokens']).or(z.string())),\n        role: RoleSchema,\n        /**\n         * Response content. Single content block (text, image, or audio).\n         */\n        content: SamplingContentSchema\n    });\n\n    /**\n     * The client's response to a `sampling/create_message` request when tools were provided.\n     * This version supports array content for tool use flows.\n     *\n     * @deprecated Deprecated as of protocol version 2026-07-28 (SEP-2577); remains\n     * in the specification for at least twelve months. Migrate to calling LLM\n     * provider APIs directly.\n     */\n    const CreateMessageResultWithToolsSchema = ResultSchema.extend({\n        /**\n         * The name of the model that generated the message.\n         */\n        model: z.string(),\n        /**\n         * The reason why sampling stopped, if known.\n         *\n         * Standard values:\n         * - `\"endTurn\"`: Natural end of the assistant's turn\n         * - `\"stopSequence\"`: A stop sequence was encountered\n         * - `\"maxTokens\"`: Maximum token limit was reached\n         * - `\"toolUse\"`: The model wants to use one or more tools\n         *\n         * This field is an open string to allow for provider-specific stop reasons.\n         */\n        stopReason: z.optional(z.enum(['endTurn', 'stopSequence', 'maxTokens', 'toolUse']).or(z.string())),\n        role: RoleSchema,\n        /**\n         * Response content. May be a single block or array. May include `ToolUseContent` if `stopReason` is `\"toolUse\"`.\n         */\n        content: z.union([SamplingMessageContentBlockSchema, z.array(SamplingMessageContentBlockSchema)])\n    });\n\n    /* Elicitation */\n    /**\n     * Primitive schema definition for boolean fields.\n     */\n    const BooleanSchemaSchema = z.object({\n        type: z.literal('boolean'),\n        title: z.string().optional(),\n        description: z.string().optional(),\n        default: z.boolean().optional()\n    });\n\n    /**\n     * Primitive schema definition for string fields.\n     */\n    const StringSchemaSchema = z.object({\n        type: z.literal('string'),\n        title: z.string().optional(),\n        description: z.string().optional(),\n        minLength: z.number().optional(),\n        maxLength: z.number().optional(),\n        format: z.enum(['email', 'uri', 'date', 'date-time']).optional(),\n        default: z.string().optional()\n    });\n\n    /**\n     * Primitive schema definition for number fields.\n     */\n    const NumberSchemaSchema = z.object({\n        type: z.enum(['number', 'integer']),\n        title: z.string().optional(),\n        description: z.string().optional(),\n        minimum: z.number().optional(),\n        maximum: z.number().optional(),\n        default: z.number().optional()\n    });\n\n    /**\n     * Schema for single-selection enumeration without display titles for options.\n     */\n    const UntitledSingleSelectEnumSchemaSchema = z.object({\n        type: z.literal('string'),\n        title: z.string().optional(),\n        description: z.string().optional(),\n        enum: z.array(z.string()),\n        default: z.string().optional()\n    });\n\n    /**\n     * Schema for single-selection enumeration with display titles for each option.\n     */\n    const TitledSingleSelectEnumSchemaSchema = z.object({\n        type: z.literal('string'),\n        title: z.string().optional(),\n        description: z.string().optional(),\n        oneOf: z.array(\n            z.object({\n                const: z.string(),\n                title: z.string()\n            })\n        ),\n        default: z.string().optional()\n    });\n\n    /**\n     * Use {@linkcode TitledSingleSelectEnumSchema} instead.\n     * This interface will be removed in a future version.\n     */\n    const LegacyTitledEnumSchemaSchema = z.object({\n        type: z.literal('string'),\n        title: z.string().optional(),\n        description: z.string().optional(),\n        enum: z.array(z.string()),\n        enumNames: z.array(z.string()).optional(),\n        default: z.string().optional()\n    });\n\n    // Combined single selection enumeration\n    const SingleSelectEnumSchemaSchema = z.union([UntitledSingleSelectEnumSchemaSchema, TitledSingleSelectEnumSchemaSchema]);\n\n    /**\n     * Schema for multiple-selection enumeration without display titles for options.\n     */\n    const UntitledMultiSelectEnumSchemaSchema = z.object({\n        type: z.literal('array'),\n        title: z.string().optional(),\n        description: z.string().optional(),\n        minItems: z.number().optional(),\n        maxItems: z.number().optional(),\n        items: z.object({\n            type: z.literal('string'),\n            enum: z.array(z.string())\n        }),\n        default: z.array(z.string()).optional()\n    });\n\n    /**\n     * Schema for multiple-selection enumeration with display titles for each option.\n     */\n    const TitledMultiSelectEnumSchemaSchema = z.object({\n        type: z.literal('array'),\n        title: z.string().optional(),\n        description: z.string().optional(),\n        minItems: z.number().optional(),\n        maxItems: z.number().optional(),\n        items: z.object({\n            anyOf: z.array(\n                z.object({\n                    const: z.string(),\n                    title: z.string()\n                })\n            )\n        }),\n        default: z.array(z.string()).optional()\n    });\n\n    /**\n     * Combined schema for multiple-selection enumeration\n     */\n    const MultiSelectEnumSchemaSchema = z.union([UntitledMultiSelectEnumSchemaSchema, TitledMultiSelectEnumSchemaSchema]);\n\n    /**\n     * Primitive schema definition for enum fields.\n     */\n    const EnumSchemaSchema = z.union([LegacyTitledEnumSchemaSchema, SingleSelectEnumSchemaSchema, MultiSelectEnumSchemaSchema]);\n\n    /**\n     * Union of all primitive schema definitions.\n     */\n    const PrimitiveSchemaDefinitionSchema = z.union([EnumSchemaSchema, BooleanSchemaSchema, StringSchemaSchema, NumberSchemaSchema]);\n\n    /**\n     * Parameters for an `elicitation/create` request for form-based elicitation.\n     */\n    const ElicitRequestFormParamsSchema = TaskAugmentedRequestParamsSchema.extend({\n        /**\n         * The elicitation mode.\n         *\n         * Optional for backward compatibility. Clients MUST treat missing `mode` as `\"form\"`.\n         */\n        mode: z.literal('form').optional(),\n        /**\n         * The message to present to the user describing what information is being requested.\n         */\n        message: z.string(),\n        /**\n         * A restricted subset of JSON Schema.\n         * Only top-level properties are allowed, without nesting.\n         */\n        requestedSchema: z\n            .object({\n                type: z.literal('object'),\n                properties: z.record(z.string(), PrimitiveSchemaDefinitionSchema),\n                required: z.array(z.string()).optional()\n            })\n            .catchall(z.unknown())\n    });\n\n    /**\n     * Parameters for an {@linkcode ElicitRequest | elicitation/create} request for URL-based elicitation.\n     */\n    const ElicitRequestURLParamsSchema = TaskAugmentedRequestParamsSchema.extend({\n        /**\n         * The elicitation mode.\n         */\n        mode: z.literal('url'),\n        /**\n         * The message to present to the user explaining why the interaction is needed.\n         */\n        message: z.string(),\n        /**\n         * The ID of the elicitation, which must be unique within the context of the server.\n         * The client MUST treat this ID as an opaque value.\n         */\n        elicitationId: z.string(),\n        /**\n         * The URL that the user should navigate to.\n         */\n        url: z.string().url()\n    });\n\n    /**\n     * The parameters for a request to elicit additional information from the user via the client.\n     */\n    const ElicitRequestParamsSchema = z.union([ElicitRequestFormParamsSchema, ElicitRequestURLParamsSchema]);\n\n    /**\n     * A request from the server to elicit user input via the client.\n     * The client should present the message and form fields to the user (form mode)\n     * or navigate to a URL (URL mode).\n     */\n    const ElicitRequestSchema = RequestSchema.extend({\n        method: z.literal('elicitation/create'),\n        params: ElicitRequestParamsSchema\n    });\n\n    /**\n     * Parameters for a {@linkcode ElicitationCompleteNotification | notifications/elicitation/complete} notification.\n     *\n     * @category notifications/elicitation/complete\n     */\n    const ElicitationCompleteNotificationParamsSchema = NotificationsParamsSchema.extend({\n        /**\n         * The ID of the elicitation that completed.\n         */\n        elicitationId: z.string()\n    });\n\n    /**\n     * A notification from the server to the client, informing it of a completion of an out-of-band elicitation request.\n     *\n     * @category notifications/elicitation/complete\n     */\n    const ElicitationCompleteNotificationSchema = NotificationSchema.extend({\n        method: z.literal('notifications/elicitation/complete'),\n        params: ElicitationCompleteNotificationParamsSchema\n    });\n\n    /**\n     * The client's response to an {@linkcode ElicitRequest | elicitation/create} request from the server.\n     */\n    const ElicitResultSchema = ResultSchema.extend({\n        /**\n         * The user action in response to the elicitation.\n         * - `\"accept\"`: User submitted the form/confirmed the action\n         * - `\"decline\"`: User explicitly declined the action\n         * - `\"cancel\"`: User dismissed without making an explicit choice\n         */\n        action: z.enum(['accept', 'decline', 'cancel']),\n        /**\n         * The submitted form data, only present when action is `\"accept\"`.\n         * Contains values matching the requested schema.\n         * Per MCP spec, content is \"typically omitted\" for decline/cancel actions.\n         * We normalize `null` to `undefined` for leniency while maintaining type compatibility.\n         */\n        content: z.preprocess(\n            val => (val === null ? undefined : val),\n            z.record(z.string(), z.union([z.string(), z.number(), z.boolean(), z.array(z.string())])).optional()\n        )\n    });\n\n    /* Autocomplete */\n    /**\n     * A reference to a resource or resource template definition.\n     */\n    const ResourceTemplateReferenceSchema = z.object({\n        type: z.literal('ref/resource'),\n        /**\n         * The URI or URI template of the resource.\n         */\n        uri: z.string()\n    });\n\n    /**\n     * Identifies a prompt.\n     */\n    const PromptReferenceSchema = z.object({\n        type: z.literal('ref/prompt'),\n        /**\n         * The name of the prompt or prompt template\n         */\n        name: z.string()\n    });\n\n    /**\n     * Parameters for a {@linkcode CompleteRequest | completion/complete} request.\n     */\n    const CompleteRequestParamsSchema = BaseRequestParamsSchema.extend({\n        ref: z.union([PromptReferenceSchema, ResourceTemplateReferenceSchema]),\n        /**\n         * The argument's information\n         */\n        argument: z.object({\n            /**\n             * The name of the argument\n             */\n            name: z.string(),\n            /**\n             * The value of the argument to use for completion matching.\n             */\n            value: z.string()\n        }),\n        context: z\n            .object({\n                /**\n                 * Previously-resolved variables in a URI template or prompt.\n                 */\n                arguments: z.record(z.string(), z.string()).optional()\n            })\n            .optional()\n    });\n    /**\n     * A request from the client to the server, to ask for completion options.\n     */\n    const CompleteRequestSchema = RequestSchema.extend({\n        method: z.literal('completion/complete'),\n        params: CompleteRequestParamsSchema\n    });\n\n    /**\n     * The server's response to a {@linkcode CompleteRequest | completion/complete} request\n     */\n    const CompleteResultSchema = ResultSchema.extend({\n        completion: z.looseObject({\n            /**\n             * An array of completion values. Must not exceed 100 items.\n             */\n            values: z.array(z.string()).max(100),\n            /**\n             * The total number of completion options available. This can exceed the number of values actually sent in the response.\n             */\n            total: z.optional(z.number().int()),\n            /**\n             * Indicates whether there are additional completion options beyond those provided in the current response, even if the exact total is unknown.\n             */\n            hasMore: z.optional(z.boolean())\n        })\n    });\n\n    /* Roots */\n    /**\n     * Represents a root directory or file that the server can operate on.\n     *\n     * @deprecated Deprecated as of protocol version 2026-07-28 (SEP-2577); remains\n     * in the specification for at least twelve months. Migrate to passing paths via\n     * tool parameters, resource URIs, or configuration.\n     */\n    const RootSchema = z.object({\n        /**\n         * The URI identifying the root. This *must* start with `file://` for now.\n         */\n        uri: z.string().startsWith('file://'),\n        /**\n         * An optional name for the root.\n         */\n        name: z.string().optional(),\n\n        /**\n         * See [MCP specification](https://github.com/modelcontextprotocol/modelcontextprotocol/blob/47339c03c143bb4ec01a26e721a1b8fe66634ebe/docs/specification/draft/basic/index.mdx#general-fields)\n         * for notes on `_meta` usage.\n         */\n        _meta: z.record(z.string(), z.unknown()).optional()\n    });\n\n    /**\n     * Sent from the server to request a list of root URIs from the client.\n     *\n     * @deprecated Deprecated as of protocol version 2026-07-28 (SEP-2577); remains\n     * in the specification for at least twelve months. Migrate to passing paths via\n     * tool parameters, resource URIs, or configuration.\n     */\n    const ListRootsRequestSchema = RequestSchema.extend({\n        method: z.literal('roots/list'),\n        params: BaseRequestParamsSchema.optional()\n    });\n\n    /**\n     * The client's response to a `roots/list` request from the server.\n     *\n     * @deprecated Deprecated as of protocol version 2026-07-28 (SEP-2577); remains\n     * in the specification for at least twelve months. Migrate to passing paths via\n     * tool parameters, resource URIs, or configuration.\n     */\n    const ListRootsResultSchema = ResultSchema.extend({\n        roots: z.array(RootSchema)\n    });\n\n    /**\n     * A notification from the client to the server, informing it that the list of roots has changed.\n     *\n     * @deprecated Deprecated as of protocol version 2026-07-28 (SEP-2577); remains\n     * in the specification for at least twelve months. Migrate to passing paths via\n     * tool parameters, resource URIs, or configuration.\n     */\n    const RootsListChangedNotificationSchema = NotificationSchema.extend({\n        method: z.literal('notifications/roots/list_changed'),\n        params: NotificationsParamsSchema.optional()\n    });\n\n    /* ───────────────────────────────────────────────────────────────────────────\n     * Tasks (2025-11-25 wire vocabulary; restored types-only by #2248 for interop\n     * with task-capable 2025 peers — parsed ONLY through this era's registry).\n     * ─────────────────────────────────────────────────────────────────────────── */\n\n    /**\n     * Task creation parameters, used to ask that the server create a task to represent a request.\n     *\n     * @deprecated 2025-11-25 wire vocabulary with no SDK runtime; kept importable for interoperability only.\n     */\n    const TaskCreationParamsSchema = z.looseObject({\n        /**\n         * Requested duration in milliseconds to retain task from creation.\n         */\n        ttl: z.number().optional(),\n\n        /**\n         * Time in milliseconds to wait between task status requests.\n         */\n        pollInterval: z.number().optional()\n    });\n\n    /**\n     * The status of a task.\n     *\n     * @deprecated 2025-11-25 wire vocabulary with no SDK runtime; kept importable for interoperability only.\n     */\n    const TaskStatusSchema = z.enum(['working', 'input_required', 'completed', 'failed', 'cancelled']);\n\n    /**\n     * A pollable state object associated with a request.\n     *\n     * @deprecated 2025-11-25 wire vocabulary with no SDK runtime; kept importable for interoperability only.\n     */\n    const TaskSchema = z.object({\n        taskId: z.string(),\n        status: TaskStatusSchema,\n        /**\n         * Time in milliseconds to keep task results available after completion.\n         * If `null`, the task has unlimited lifetime until manually cleaned up.\n         */\n        ttl: z.union([z.number(), z.null()]),\n        /**\n         * ISO 8601 timestamp when the task was created.\n         */\n        createdAt: z.string(),\n        /**\n         * ISO 8601 timestamp when the task was last updated.\n         */\n        lastUpdatedAt: z.string(),\n        pollInterval: z.optional(z.number()),\n        /**\n         * Optional diagnostic message for failed tasks or other status information.\n         */\n        statusMessage: z.optional(z.string())\n    });\n\n    /**\n     * Result returned when a task is created, containing the task data wrapped in a `task` field.\n     *\n     * @deprecated 2025-11-25 wire vocabulary with no SDK runtime; kept importable for interoperability only.\n     */\n    const CreateTaskResultSchema = ResultSchema.extend({\n        task: TaskSchema\n    });\n\n    /**\n     * Parameters for task status notification.\n     *\n     * @deprecated 2025-11-25 wire vocabulary with no SDK runtime; kept importable for interoperability only.\n     */\n    const TaskStatusNotificationParamsSchema = NotificationsParamsSchema.merge(TaskSchema);\n\n    /**\n     * A notification sent when a task's status changes.\n     *\n     * @deprecated 2025-11-25 wire vocabulary with no SDK runtime; kept importable for interoperability only.\n     */\n    const TaskStatusNotificationSchema = NotificationSchema.extend({\n        method: z.literal('notifications/tasks/status'),\n        params: TaskStatusNotificationParamsSchema\n    });\n\n    /**\n     * A request to get the state of a specific task.\n     *\n     * @deprecated 2025-11-25 wire vocabulary with no SDK runtime; kept importable for interoperability only.\n     */\n    const GetTaskRequestSchema = RequestSchema.extend({\n        method: z.literal('tasks/get'),\n        params: BaseRequestParamsSchema.extend({\n            taskId: z.string()\n        })\n    });\n\n    /**\n     * The response to a {@linkcode GetTaskRequest | tasks/get} request.\n     *\n     * @deprecated 2025-11-25 wire vocabulary with no SDK runtime; kept importable for interoperability only.\n     */\n    const GetTaskResultSchema = ResultSchema.merge(TaskSchema);\n\n    /**\n     * A request to get the result of a specific task.\n     *\n     * @deprecated 2025-11-25 wire vocabulary with no SDK runtime; kept importable for interoperability only.\n     */\n    const GetTaskPayloadRequestSchema = RequestSchema.extend({\n        method: z.literal('tasks/result'),\n        params: BaseRequestParamsSchema.extend({\n            taskId: z.string()\n        })\n    });\n\n    /**\n     * The response to a `tasks/result` request.\n     * The structure matches the result type of the original request.\n     * For example, a {@linkcode CallToolRequest | tools/call} task would return the `CallToolResult` structure.\n     *\n     *\n     * @deprecated 2025-11-25 wire vocabulary with no SDK runtime; kept importable for interoperability only.\n     */\n    const GetTaskPayloadResultSchema = ResultSchema.loose();\n\n    /**\n     * A request to list tasks.\n     *\n     * @deprecated 2025-11-25 wire vocabulary with no SDK runtime; kept importable for interoperability only.\n     */\n    const ListTasksRequestSchema = PaginatedRequestSchema.extend({\n        method: z.literal('tasks/list')\n    });\n\n    /**\n     * The response to a {@linkcode ListTasksRequest | tasks/list} request.\n     *\n     * @deprecated 2025-11-25 wire vocabulary with no SDK runtime; kept importable for interoperability only.\n     */\n    const ListTasksResultSchema = PaginatedResultSchema.extend({\n        tasks: z.array(TaskSchema)\n    });\n\n    /**\n     * A request to cancel a specific task.\n     *\n     * @deprecated 2025-11-25 wire vocabulary with no SDK runtime; kept importable for interoperability only.\n     */\n    const CancelTaskRequestSchema = RequestSchema.extend({\n        method: z.literal('tasks/cancel'),\n        params: BaseRequestParamsSchema.extend({\n            taskId: z.string()\n        })\n    });\n\n    /**\n     * The response to a {@linkcode CancelTaskRequest | tasks/cancel} request.\n     *\n     * @deprecated 2025-11-25 wire vocabulary with no SDK runtime; kept importable for interoperability only.\n     */\n    const CancelTaskResultSchema = ResultSchema.merge(TaskSchema);\n\n    /* ───────────────────────────────────────────────────────────────────────────\n     * The 2025-era wire role unions: the era-faithful aggregates (what a\n     * 2025-11-25 peer may legally put on the wire, per role) and the source the\n     * era registry is built from. Member order preserves the pre-split unions\n     * (task members last for requests/results; notification members are\n     * method-discriminated, so ordering is not observable).\n     * ─────────────────────────────────────────────────────────────────────────── */\n\n    const ClientRequestSchema = z.union([\n        PingRequestSchema,\n        InitializeRequestSchema,\n        CompleteRequestSchema,\n        SetLevelRequestSchema,\n        GetPromptRequestSchema,\n        ListPromptsRequestSchema,\n        ListResourcesRequestSchema,\n        ListResourceTemplatesRequestSchema,\n        ReadResourceRequestSchema,\n        SubscribeRequestSchema,\n        UnsubscribeRequestSchema,\n        CallToolRequestSchema,\n        ListToolsRequestSchema,\n        GetTaskRequestSchema,\n        GetTaskPayloadRequestSchema,\n        ListTasksRequestSchema,\n        CancelTaskRequestSchema\n    ]);\n\n    const ClientNotificationSchema = z.union([\n        CancelledNotificationSchema,\n        ProgressNotificationSchema,\n        InitializedNotificationSchema,\n        RootsListChangedNotificationSchema,\n        TaskStatusNotificationSchema\n    ]);\n\n    const ClientResultSchema = z.union([\n        EmptyResultSchema,\n        CreateMessageResultSchema,\n        CreateMessageResultWithToolsSchema,\n        ElicitResultSchema,\n        ListRootsResultSchema,\n        GetTaskResultSchema,\n        ListTasksResultSchema,\n        CreateTaskResultSchema\n    ]);\n\n    const ServerRequestSchema = z.union([\n        PingRequestSchema,\n        CreateMessageRequestSchema,\n        ElicitRequestSchema,\n        ListRootsRequestSchema,\n        GetTaskRequestSchema,\n        GetTaskPayloadRequestSchema,\n        ListTasksRequestSchema,\n        CancelTaskRequestSchema\n    ]);\n\n    const ServerNotificationSchema = z.union([\n        CancelledNotificationSchema,\n        ProgressNotificationSchema,\n        LoggingMessageNotificationSchema,\n        ResourceUpdatedNotificationSchema,\n        ResourceListChangedNotificationSchema,\n        ToolListChangedNotificationSchema,\n        PromptListChangedNotificationSchema,\n        TaskStatusNotificationSchema,\n        ElicitationCompleteNotificationSchema\n    ]);\n\n    const ServerResultSchema = z.union([\n        EmptyResultSchema,\n        InitializeResultSchema,\n        CompleteResultSchema,\n        GetPromptResultSchema,\n        ListPromptsResultSchema,\n        ListResourcesResultSchema,\n        ListResourceTemplatesResultSchema,\n        ReadResourceResultSchema,\n        CallToolResultSchema,\n        ListToolsResultSchema,\n        GetTaskResultSchema,\n        ListTasksResultSchema,\n        CreateTaskResultSchema\n    ]);\n\n    /**\n     * Wire seam: owns both halves of the v1-parity ruling — the guard (a content-less body\n     * carrying another result family's keys fails loudly; the era is frozen so the key list is\n     * complete) and the tolerance (`content` defaults to `[]`). The era file stays twin-conformant.\n     * Definition verbatim from the pre-lazy registry.ts; it lives with the era schemas so the\n     * registry's lazy result map and the eager shim serve the SAME object through the memo.\n     */\n    const CallToolResultWireSchema = z\n        .unknown()\n        .superRefine((value, ctx) => {\n            // content === undefined covers both an absent key and an explicit\n            // undefined from server-side authoring objects.\n            if (\n                typeof value !== 'object' ||\n                value === null ||\n                Array.isArray(value) ||\n                (value as Record<string, unknown>).content !== undefined\n            )\n                return;\n            for (const key of TOOL_RESULT_FOREIGN_FAMILY_KEYS) {\n                if (key in value) {\n                    ctx.addIssue({\n                        code: 'custom',\n                        message: `content is required when the body carries '${key}' — another result family cannot default into an empty tools/call success`\n                    });\n                    return;\n                }\n            }\n        })\n        .transform(normalizeContentlessToolResult)\n        .pipe(CallToolResultSchema);\n\n    return {\n        JSONValueSchema,\n        JSONObjectSchema,\n        ProgressTokenSchema,\n        CursorSchema,\n        TaskMetadataSchema,\n        RelatedTaskMetadataSchema,\n        RequestMetaSchema,\n        BaseRequestParamsSchema,\n        TaskAugmentedRequestParamsSchema,\n        RequestSchema,\n        NotificationsParamsSchema,\n        NotificationSchema,\n        ResultSchema,\n        RequestIdSchema,\n        EmptyResultSchema,\n        CancelledNotificationParamsSchema,\n        CancelledNotificationSchema,\n        IconSchema,\n        IconsSchema,\n        BaseMetadataSchema,\n        ImplementationSchema,\n        ClientTasksCapabilitySchema,\n        ServerTasksCapabilitySchema,\n        ClientCapabilitiesSchema,\n        InitializeRequestParamsSchema,\n        InitializeRequestSchema,\n        ServerCapabilitiesSchema,\n        InitializeResultSchema,\n        InitializedNotificationSchema,\n        PingRequestSchema,\n        ProgressSchema,\n        ProgressNotificationParamsSchema,\n        ProgressNotificationSchema,\n        PaginatedRequestParamsSchema,\n        PaginatedRequestSchema,\n        PaginatedResultSchema,\n        ResourceContentsSchema,\n        TextResourceContentsSchema,\n        BlobResourceContentsSchema,\n        RoleSchema,\n        AnnotationsSchema,\n        ResourceSchema,\n        ResourceTemplateSchema,\n        ListResourcesRequestSchema,\n        ListResourcesResultSchema,\n        ListResourceTemplatesRequestSchema,\n        ListResourceTemplatesResultSchema,\n        ResourceRequestParamsSchema,\n        ReadResourceRequestParamsSchema,\n        ReadResourceRequestSchema,\n        ReadResourceResultSchema,\n        ResourceListChangedNotificationSchema,\n        SubscribeRequestParamsSchema,\n        SubscribeRequestSchema,\n        UnsubscribeRequestParamsSchema,\n        UnsubscribeRequestSchema,\n        ResourceUpdatedNotificationParamsSchema,\n        ResourceUpdatedNotificationSchema,\n        PromptArgumentSchema,\n        PromptSchema,\n        ListPromptsRequestSchema,\n        ListPromptsResultSchema,\n        GetPromptRequestParamsSchema,\n        GetPromptRequestSchema,\n        TextContentSchema,\n        ImageContentSchema,\n        AudioContentSchema,\n        ToolUseContentSchema,\n        EmbeddedResourceSchema,\n        ResourceLinkSchema,\n        ContentBlockSchema,\n        PromptMessageSchema,\n        GetPromptResultSchema,\n        PromptListChangedNotificationSchema,\n        ToolAnnotationsSchema,\n        ToolExecutionSchema,\n        ToolSchema,\n        ListToolsRequestSchema,\n        ListToolsResultSchema,\n        CallToolResultSchema,\n        CallToolRequestParamsSchema,\n        CallToolRequestSchema,\n        ToolListChangedNotificationSchema,\n        LoggingLevelSchema,\n        SetLevelRequestParamsSchema,\n        SetLevelRequestSchema,\n        LoggingMessageNotificationParamsSchema,\n        LoggingMessageNotificationSchema,\n        ModelHintSchema,\n        ModelPreferencesSchema,\n        ToolChoiceSchema,\n        ToolResultContentSchema,\n        SamplingContentSchema,\n        SamplingMessageContentBlockSchema,\n        SamplingMessageSchema,\n        CreateMessageRequestParamsSchema,\n        CreateMessageRequestSchema,\n        CreateMessageResultSchema,\n        CreateMessageResultWithToolsSchema,\n        BooleanSchemaSchema,\n        StringSchemaSchema,\n        NumberSchemaSchema,\n        UntitledSingleSelectEnumSchemaSchema,\n        TitledSingleSelectEnumSchemaSchema,\n        LegacyTitledEnumSchemaSchema,\n        SingleSelectEnumSchemaSchema,\n        UntitledMultiSelectEnumSchemaSchema,\n        TitledMultiSelectEnumSchemaSchema,\n        MultiSelectEnumSchemaSchema,\n        EnumSchemaSchema,\n        PrimitiveSchemaDefinitionSchema,\n        ElicitRequestFormParamsSchema,\n        ElicitRequestURLParamsSchema,\n        ElicitRequestParamsSchema,\n        ElicitRequestSchema,\n        ElicitationCompleteNotificationParamsSchema,\n        ElicitationCompleteNotificationSchema,\n        ElicitResultSchema,\n        ResourceTemplateReferenceSchema,\n        PromptReferenceSchema,\n        CompleteRequestParamsSchema,\n        CompleteRequestSchema,\n        CompleteResultSchema,\n        RootSchema,\n        ListRootsRequestSchema,\n        ListRootsResultSchema,\n        RootsListChangedNotificationSchema,\n        TaskCreationParamsSchema,\n        TaskStatusSchema,\n        TaskSchema,\n        CreateTaskResultSchema,\n        TaskStatusNotificationParamsSchema,\n        TaskStatusNotificationSchema,\n        GetTaskRequestSchema,\n        GetTaskResultSchema,\n        GetTaskPayloadRequestSchema,\n        GetTaskPayloadResultSchema,\n        ListTasksRequestSchema,\n        ListTasksResultSchema,\n        CancelTaskRequestSchema,\n        CancelTaskResultSchema,\n        ClientRequestSchema,\n        ClientNotificationSchema,\n        ClientResultSchema,\n        ServerRequestSchema,\n        ServerNotificationSchema,\n        ServerResultSchema,\n        CallToolResultWireSchema\n    };\n}\n\n/** The full set of frozen 2025-11-25 wire schemas, as one built object (the memo target). */\nexport type Rev2025WireSchemas = ReturnType<typeof build>;\n\nlet memo: Rev2025WireSchemas | undefined;\n\n/**\n * Builds the era wire-schema set on first call and returns the same object\n * thereafter. Module evaluation stays construction-free so importing the\n * era codec/registry costs nothing until the first validation actually\n * needs a schema; the registry, the codec, and the eager `schemas.ts`\n * shim all pull through this memo, so reference identity holds across\n * every consumer.\n */\nexport function buildSchemas2025(): Rev2025WireSchemas {\n    return (memo ??= build());\n}\n","/**\n * SEP-2106 legacy `outputSchema` wrap helpers (2025-era projection only).\n *\n * The neutral / 2026-07-28 model lets a tool's `outputSchema` carry any JSON\n * Schema root. The 2025-11-25 wire shape requires `type:'object'` at the root,\n * so when an era-blind handler advertises a non-object root, the 2025 codec's\n * `encodeResult('tools/list', …)` projects it down to\n * `{type:'object', properties:{result:<natural>}, required:['result']}`, and\n * `projectCallToolResult` wraps the matching `structuredContent` as\n * `{result:<value>}`. The 2026 codec's projections are the identity.\n *\n * These helpers are wire-layer property — they exist so the projection can\n * live behind {@link WireCodec.encodeResult} / {@link WireCodec.projectCallToolResult}\n * and never be re-derived in shared/ or server-side code.\n */\n\nimport { declares2019Dialect } from '../../validators/dialects';\n\n/**\n * Whether a JSON Schema's root is non-object: either an explicit non-object\n * `type`, or a typeless root such as `{anyOf:[…]}`. Object-shaped typeless\n * roots that the schema-conversion layer can prove are objects are stamped\n * `type:'object'` upstream, so they reach this predicate as object roots.\n */\nexport function isNonObjectJsonSchemaRoot(json: Readonly<Record<string, unknown>>): boolean {\n    return json['type'] !== 'object';\n}\n\n/**\n * Keyword-position keys whose values are instance data (not subschemas). A\n * `{$ref:…}` appearing inside one is a literal value, not a JSON Pointer to\n * rewrite. Only consulted when the current object is in keyword position —\n * a PROPERTY named `default`/`const` (under `properties`/`$defs`/…) is a name\n * position whose value IS a subschema and is recursed into.\n */\nconst REF_REWRITE_DATA_POSITION_KEYS: ReadonlySet<string> = new Set(['const', 'enum', 'default', 'examples']);\n\n/**\n * Keyword-position keys whose value is a name→subschema map. Entries inside\n * such a map are in NAME position: their keys are author-chosen property\n * names (which may collide with JSON Schema keywords), their values are\n * subschemas to recurse into.\n */\nconst REF_REWRITE_NAME_MAP_KEYS: ReadonlySet<string> = new Set([\n    'properties',\n    'patternProperties',\n    '$defs',\n    'definitions',\n    'dependentSchemas',\n    // draft-07's dependentSchemas predecessor; its array-of-strings form is\n    // unaffected (string arrays contain no refs).\n    'dependencies'\n]);\n\n/**\n * Whether a subtree's `$id` establishes a new resolution base. A fragment-only\n * `$id` (`\"#item\"`, the draft-07/06 spelling of 2020-12's `$anchor`) does not\n * change the RFC 3986 base URI — same-document pointers inside still resolve\n * against the document root and must be rewritten.\n */\nfunction establishesNewBase(id: unknown): boolean {\n    return id !== undefined && !(typeof id === 'string' && id.startsWith('#'));\n}\n\n/*\n * Reference/base-affecting keyword coverage across the four supported dialects\n * (2020-12, 2019-09, draft-07, draft-06). Every entry is rewritten, position-guarded,\n * or N/A with the reason; legacyWrap.test.ts pins each handled row:\n * - `$ref` (all dialects): JSON-Pointer forms `#`/`#/…` rewritten; other values untouched.\n * - `$dynamicRef` (2020-12): pointer forms rewritten like `$ref`; plain-name form (`#name`)\n *   untouched — see `$anchor`.\n * - `$dynamicAnchor` (2020-12): N/A — location-independent plain name; the envelope adds no\n *   anchors and the natural schema moves whole, so dynamic resolution is unchanged.\n * - `$anchor` (2019-09/2020-12): N/A — same as `$dynamicAnchor`; `#name` refs are fragments,\n *   not pointers, and are never rewritten.\n * - `$recursiveRef` (2019-09): handled only in documents whose DECLARED dialect is 2019-09.\n *   Elsewhere it is off-spec input copied verbatim — KNOWN LIMITATION: the engines already\n *   disagree on it there (only classic Ajv ignores it; Ajv2020 and @cfworker enforce it in\n *   every draft mode), so no consistent wrap behavior exists — the verbatim `#` mis-resolves\n *   to the envelope on the enforcing legs, while converting would manufacture a constraint\n *   on the classic-Ajv leg. Inherent to envelope relocation plus engine disagreement; the\n *   escape is the 2026 era or authoring the schema with a proper 2019-09 stamp. Within\n *   2019-09: value restricted to `#`, and per core §8.2.4.2.1 a root-base ref is dynamic\n *   only when the DOCUMENT ROOT carries `$recursiveAnchor: true` (a non-root anchor can\n *   never be the initial target and is inert). Root-anchor-less documents: converted to the\n *   statically equivalent `$ref: '#/properties/result'`; when `$ref` co-occurs (legal,\n *   conjunctive in 2019-09) the conversion joins as an `allOf` entry instead. Documents\n *   whose root carries `$recursiveAnchor: true`: left verbatim — KNOWN LIMITATION:\n *   relocation cannot preserve dynamic re-resolution (a static rewrite would freeze it and\n *   the envelope root carries no anchor), so root-anchored recursion still mis-resolves on\n *   the 2025 projection.\n * - `$recursiveAnchor` (2019-09): boolean, not a location — only the ROOT occurrence gates the\n *   conversion above; nested occurrences are copied verbatim and stay inert.\n * - `$id`, URI form (all dialects): establishes a new base — subtree skipped (root and nested).\n * - `$id`, fragment form (draft-07/06 anchor spelling; illegal in 2019-09/2020-12): does not\n *   change the base — descended into.\n * - `$schema`: hoisted to the wrapper root so dialect dispatch and the graceful\n *   unsupported-dialect rejection see it.\n * - `$vocabulary` (2019-09/2020-12): N/A — meta-schema-only keyword, inert in tool schemas.\n * - Name→subschema maps (`properties`, `patternProperties`, `$defs`, `definitions`,\n *   `dependentSchemas`, draft-07/06 `dependencies`): entries are name positions; their keys\n *   are never treated as keywords.\n * - Data-position keywords (`const`/`enum`/`default`/`examples`): values are instance data,\n *   never descended into.\n */\n/**\n * Wrap a non-object output schema in the 2025-era envelope:\n * `{type:'object', properties:{result:<natural>}, required:['result']}`.\n *\n * Same-document `$ref` / `$dynamicRef` JSON Pointers inside the natural schema\n * (e.g. `#/properties/foo` produced by zod for de-duplicated/recursive types)\n * are rewritten to account for the new `#/properties/result` root: bare `#` →\n * `#/properties/result`, `#/…` → `#/properties/result/…`. Cross-document refs\n * (anything not starting with `#`) are left untouched.\n *\n * The rewrite is position-aware: data-valued keywords\n * (`const`/`enum`/`default`/`examples`) in keyword position are NOT descended\n * into; the same names appearing as property names under\n * `properties`/`patternProperties`/`$defs`/`definitions`/`dependentSchemas`/\n * `dependencies` ARE descended into (they're subschemas). The rewrite is also\n * `$id`-scoped: if the natural root carries a base-establishing `$id` no\n * pointer is rewritten (same-document refs inside resolve against the embedded\n * `$id` base, not the wrapper root), and any subtree that establishes its own\n * `$id` is left untouched for the same reason. Fragment-only `$id` (`\"#item\"`,\n * draft-07's anchor spelling) does not establish a base and IS descended into.\n */\nexport function wrapOutputSchemaForLegacy(natural: Readonly<Record<string, unknown>>): Record<string, unknown> {\n    // A root `$schema` is hoisted to the wrapper root: it's a document-level\n    // dialect declaration and the built-in providers' dialect dispatch only\n    // inspects the root, so leaving it under `properties.result` would make\n    // the wrapper compile under the default 2020-12 engine (an opaque Ajv2020\n    // compile error on draft-07 tuple-form `items` instead of the classic\n    // engine's tuple semantics) while the same tool dispatches to the declared\n    // dialect on the 2026 era — and hide an unsupported dialect from the\n    // graceful rejection.\n    const $schema = typeof natural['$schema'] === 'string' ? natural['$schema'] : undefined;\n    // A base-establishing `$id` at the natural root: every same-document `#/…`\n    // ref inside resolves against that base URI, not against the wrapper root —\n    // skip the rewrite. Fragment-only `$id` keeps the document-root base.\n    if (establishesNewBase(natural['$id'])) {\n        return { ...($schema !== undefined && { $schema }), type: 'object', properties: { result: natural }, required: ['result'] };\n    }\n    // `$recursiveRef` is a 2019-09-only keyword: the conversion applies solely to documents\n    // whose DECLARED dialect is 2019-09 (one document-level check). Elsewhere it is copied\n    // verbatim — converting would manufacture a constraint on the classic-Ajv leg, which\n    // ignores the member; the legs that enforce it are a KNOWN LIMITATION (coverage block).\n    // Within 2019-09, a root-base `$recursiveRef: '#'` is dynamic only when the DOCUMENT\n    // ROOT carries `$recursiveAnchor: true` (core §8.2.4.2.1); otherwise it is statically\n    // `$ref: '#'`-equivalent and is converted. See the coverage block above.\n    const convertRecursiveRefs = declares2019Dialect(natural['$schema']) && natural['$recursiveAnchor'] !== true;\n    const rewriteRefs = (node: unknown, parentIsNameMap: boolean): unknown => {\n        if (Array.isArray(node)) return node.map(item => rewriteRefs(item, false));\n        if (node === null || typeof node !== 'object') return node;\n        // A nested base-establishing `$id` owns resolution for the subtree —\n        // same-document refs inside are no longer relative to the wrapper root.\n        // Only applies in keyword position (a property NAMED `$id` is just a name).\n        if (!parentIsNameMap && establishesNewBase((node as Record<string, unknown>)['$id'])) return node;\n        const out: Record<string, unknown> = {};\n        let convertedRecursion = false;\n        for (const [k, v] of Object.entries(node)) {\n            if (parentIsNameMap) {\n                // Name position: `k` is an author-chosen property/def name, `v` is a\n                // subschema in keyword position. Never treat `k` as a keyword here.\n                out[k] = rewriteRefs(v, false);\n            } else if ((k === '$ref' || k === '$dynamicRef') && typeof v === 'string') {\n                out[k] = v === '#' ? '#/properties/result' : v.startsWith('#/') ? `#/properties/result${v.slice(1)}` : v;\n            } else if (k === '$recursiveRef' && v === '#' && convertRecursiveRefs) {\n                // Emitted after the loop: plain `$ref` when free, `allOf` join when `$ref`\n                // co-occurs ($ref and $recursiveRef are conjunctive in-place applicators).\n                convertedRecursion = true;\n            } else if (REF_REWRITE_DATA_POSITION_KEYS.has(k)) {\n                out[k] = v;\n            } else if (REF_REWRITE_NAME_MAP_KEYS.has(k)) {\n                out[k] = rewriteRefs(v, true);\n            } else {\n                out[k] = rewriteRefs(v, false);\n            }\n        }\n        if (convertedRecursion) {\n            if ('$ref' in out) {\n                out['allOf'] = [...(Array.isArray(out['allOf']) ? out['allOf'] : []), { $ref: '#/properties/result' }];\n            } else {\n                out['$ref'] = '#/properties/result';\n            }\n        }\n        return out;\n    };\n    return {\n        ...($schema !== undefined && { $schema }),\n        type: 'object',\n        properties: { result: rewriteRefs(natural, false) },\n        required: ['result']\n    };\n}\n","/**\n * The 2025-era method registries — re-homed verbatim from\n * `types/schemas.ts` (Q1 increment-2 step 1: mechanical relocation behind the\n * codec interface; the registry CONTENT is byte-identical to the pre-split\n * maps and is pinned by reference in `test/types/registryPins.test.ts`).\n *\n * This era serves all five legacy protocol versions (2024-10-07 …\n * 2025-11-25), exactly as the single schema set did before the split. It is\n * BEHAVIOR-FROZEN behind the Q10-L2 byte-identity suite: the request and\n * notification maps carry the full deliberate 2025-11-25 wire vocabulary,\n * including the task family (the #2248 wire-interop restore). The RESULT map\n * is the runtime/typed ALIGNED map (PR #2293 review): keyed by this era's\n * subset of the typed `RequestMethod` set so it cannot drift from the typed\n * `ResultTypeMap` — no\n * task-result union members and no `tasks/*` entries; a task-capable 2025\n * peer's `CreateTaskResult` answer fails the plain per-method schema as a\n * typed invalid-result error, and callers needing task interop pass an\n * explicit result schema (see `test/shared/typedMapAlignment.test.ts`).\n *\n * 2026-only vocabulary (`server/discover`, `subscriptions/listen`, the MRTR\n * shells, `resultType`, the `_meta` envelope) has NO entry and NO code path\n * here — the inverse-leak guarantee is physical absence, not discipline.\n *\n * LAZY SCHEMA CONSTRUCTION: method membership and the exported method lists\n * are static (null-valued key objects below — the mapped-type keying keeps\n * the both-direction drift guard), while the schema VALUES are pulled through\n * the era's memoized `buildSchemas2025()` factory on first lookup. Importing\n * this module therefore constructs no zod schemas; the first validation does,\n * once, and every consumer (registry, codec, the eager `schemas.ts` shim)\n * sees the same objects, so the by-reference pins keep holding.\n */\nimport type * as z from 'zod/v4';\n\nimport type { NotificationMethod, NotificationTypeMap, RequestMethod, RequestTypeMap, ResultTypeMap } from '../../types/types';\nimport type { Rev2025WireSchemas } from './buildSchemas';\nimport { buildSchemas2025 } from './buildSchemas';\n\n/* The era's wire vocabulary, derived from the wire role unions in\n * `./buildSchemas.ts` (the same unions the registries used to be built from\n * at runtime). Keying the maps by these derived unions makes drift a compile\n * error in BOTH directions: a union member without a map entry, a map entry\n * the unions do not know, and an entry pointing at a different method's\n * schema all fail to typecheck. */\ntype WireRequest = z.output<Rev2025WireSchemas['ClientRequestSchema']> | z.output<Rev2025WireSchemas['ServerRequestSchema']>;\ntype WireNotification = z.output<Rev2025WireSchemas['ClientNotificationSchema']> | z.output<Rev2025WireSchemas['ServerNotificationSchema']>;\n\n/** Every request method in the 2025-era wire vocabulary (the typed `RequestMethod` surface plus the task family). */\nexport type Rev2025RequestMethod = WireRequest['method'];\n/** Every notification method in the 2025-era wire vocabulary. */\nexport type Rev2025NotificationMethod = WireNotification['method'];\n\n/**\n * The typed-method surface this era serves: the typed `RequestMethod` set\n * minus methods whose wire vocabulary does not exist on this era (e.g.\n * `server/discover`, which the typed maps carry but only the 2026-era\n * registry serves). Deriving the subset from the era's own wire role unions\n * keeps the both-direction drift guard: a typed 2025-era method without a map\n * entry, or a map entry the era's wire vocabulary does not know, is a compile\n * error.\n */\ntype Rev2025TypedRequestMethod = Extract<RequestMethod, Rev2025RequestMethod>;\n\n/* Static method membership — the schema-free half of the registry.\n *\n * These null-valued objects carry ONLY the method keys, in the same order the\n * eager schema maps used to declare them (so the exported method lists stay\n * byte-identical to the pre-lazy builder). The mapped-type keying preserves\n * the both-direction drift guard: a union member without a key, or a key the\n * union does not know, is a compile error. Membership checks and the exported\n * lists read these objects and never touch the schema memo. */\nconst requestMethodKeys: { readonly [M in Rev2025RequestMethod]: null } = {\n    ping: null,\n    initialize: null,\n    'completion/complete': null,\n    'logging/setLevel': null,\n    'prompts/get': null,\n    'prompts/list': null,\n    'resources/list': null,\n    'resources/templates/list': null,\n    'resources/read': null,\n    'resources/subscribe': null,\n    'resources/unsubscribe': null,\n    'tools/call': null,\n    'tools/list': null,\n    'tasks/get': null,\n    'tasks/result': null,\n    'tasks/list': null,\n    'tasks/cancel': null,\n    'sampling/createMessage': null,\n    'elicitation/create': null,\n    'roots/list': null\n};\n\nconst notificationMethodKeys: { readonly [M in Rev2025NotificationMethod]: null } = {\n    'notifications/cancelled': null,\n    'notifications/progress': null,\n    'notifications/initialized': null,\n    'notifications/roots/list_changed': null,\n    'notifications/tasks/status': null,\n    'notifications/message': null,\n    'notifications/resources/updated': null,\n    'notifications/resources/list_changed': null,\n    'notifications/tools/list_changed': null,\n    'notifications/prompts/list_changed': null,\n    'notifications/elicitation/complete': null\n};\n\nconst resultMethodKeys: { readonly [M in Rev2025TypedRequestMethod]: null } = {\n    ping: null,\n    initialize: null,\n    'completion/complete': null,\n    'logging/setLevel': null,\n    'prompts/get': null,\n    'prompts/list': null,\n    'resources/list': null,\n    'resources/templates/list': null,\n    'resources/read': null,\n    'resources/subscribe': null,\n    'resources/unsubscribe': null,\n    'tools/call': null,\n    'tools/list': null,\n    'sampling/createMessage': null,\n    'elicitation/create': null,\n    'roots/list': null\n};\n\n/* Lazy schema maps — built once, on the first schema lookup, from the era's\n * memoized schema factory. The entries are the SAME schema objects the wire\n * role unions are built from (reference identity is pinned by\n * `test/types/registryPins.test.ts`), and the key order preserves the\n * pre-split union iteration order. The mapped types below are unchanged from\n * the eager maps, so the drift guards still apply entry by entry. */\ninterface RegistryMaps {\n    /* Runtime schema lookup — request and notification schemas by method. */\n    readonly requestSchemas: { readonly [M in Rev2025RequestMethod]: z.ZodType<Extract<WireRequest, { method: M }>> };\n    readonly notificationSchemas: { readonly [M in Rev2025NotificationMethod]: z.ZodType<Extract<WireNotification, { method: M }>> };\n    /* Runtime schema lookup — result schemas by method.\n     *\n     * Keyed by the era's typed-method subset and valued by\n     * `z.ZodType<ResultTypeMap[M]>` so the runtime map and the typed\n     * `ResultTypeMap` cannot drift: a missing entry, an extra key, or an entry\n     * that does not parse to the typed map's result type is a compile error. No\n     * entry may be looser than the typed map (no task-result union members) and\n     * no key may fall outside it (no `tasks/*` entries — the task methods are\n     * 2025-11-25 wire vocabulary with no SDK runtime; callers needing task\n     * interop pass an explicit schema). The `tools/call` entry is the wire-seam\n     * wrapper `CallToolResultWireSchema` (content-default guard + tolerance),\n     * which lives with the era schemas in `./buildSchemas.ts`. */\n    readonly resultSchemas: { readonly [M in Rev2025TypedRequestMethod]: z.ZodType<ResultTypeMap[M]> };\n}\n\nlet maps: RegistryMaps | undefined;\n\nfunction registryMaps(): RegistryMaps {\n    if (maps) return maps;\n    const s = buildSchemas2025();\n    maps = {\n        requestSchemas: {\n            ping: s.PingRequestSchema,\n            initialize: s.InitializeRequestSchema,\n            'completion/complete': s.CompleteRequestSchema,\n            'logging/setLevel': s.SetLevelRequestSchema,\n            'prompts/get': s.GetPromptRequestSchema,\n            'prompts/list': s.ListPromptsRequestSchema,\n            'resources/list': s.ListResourcesRequestSchema,\n            'resources/templates/list': s.ListResourceTemplatesRequestSchema,\n            'resources/read': s.ReadResourceRequestSchema,\n            'resources/subscribe': s.SubscribeRequestSchema,\n            'resources/unsubscribe': s.UnsubscribeRequestSchema,\n            'tools/call': s.CallToolRequestSchema,\n            'tools/list': s.ListToolsRequestSchema,\n            'tasks/get': s.GetTaskRequestSchema,\n            'tasks/result': s.GetTaskPayloadRequestSchema,\n            'tasks/list': s.ListTasksRequestSchema,\n            'tasks/cancel': s.CancelTaskRequestSchema,\n            'sampling/createMessage': s.CreateMessageRequestSchema,\n            'elicitation/create': s.ElicitRequestSchema,\n            'roots/list': s.ListRootsRequestSchema\n        },\n        notificationSchemas: {\n            'notifications/cancelled': s.CancelledNotificationSchema,\n            'notifications/progress': s.ProgressNotificationSchema,\n            'notifications/initialized': s.InitializedNotificationSchema,\n            'notifications/roots/list_changed': s.RootsListChangedNotificationSchema,\n            'notifications/tasks/status': s.TaskStatusNotificationSchema,\n            'notifications/message': s.LoggingMessageNotificationSchema,\n            'notifications/resources/updated': s.ResourceUpdatedNotificationSchema,\n            'notifications/resources/list_changed': s.ResourceListChangedNotificationSchema,\n            'notifications/tools/list_changed': s.ToolListChangedNotificationSchema,\n            'notifications/prompts/list_changed': s.PromptListChangedNotificationSchema,\n            'notifications/elicitation/complete': s.ElicitationCompleteNotificationSchema\n        },\n        resultSchemas: {\n            ping: s.EmptyResultSchema,\n            initialize: s.InitializeResultSchema,\n            'completion/complete': s.CompleteResultSchema,\n            'logging/setLevel': s.EmptyResultSchema,\n            'prompts/get': s.GetPromptResultSchema,\n            'prompts/list': s.ListPromptsResultSchema,\n            'resources/list': s.ListResourcesResultSchema,\n            'resources/templates/list': s.ListResourceTemplatesResultSchema,\n            'resources/read': s.ReadResourceResultSchema,\n            'resources/subscribe': s.EmptyResultSchema,\n            'resources/unsubscribe': s.EmptyResultSchema,\n            'tools/call': s.CallToolResultWireSchema,\n            'tools/list': s.ListToolsResultSchema,\n            'sampling/createMessage': s.CreateMessageResultWithToolsSchema,\n            'elicitation/create': s.ElicitResultSchema,\n            'roots/list': s.ListRootsResultSchema\n        }\n    };\n    return maps;\n}\n\n/**\n * Forces the lazy registry maps (and, through them, the era's schema memo).\n * Warm-up hook for `preloadSchemas()` — no-op once the maps exist.\n */\nexport function warmRegistryMaps2025(): void {\n    registryMaps();\n}\n\n/** The 2025-era request-method set (registry membership = the deletion story). */\nexport function hasRequestMethod2025(method: string): method is Rev2025RequestMethod {\n    return Object.prototype.hasOwnProperty.call(requestMethodKeys, method);\n}\n\n/** The 2025-era notification-method set. */\nexport function hasNotificationMethod2025(method: string): method is Rev2025NotificationMethod {\n    return Object.prototype.hasOwnProperty.call(notificationMethodKeys, method);\n}\n\n/** Result-map membership: exactly the era's typed-method subset (no task entries, no 2026-only methods). */\nfunction hasResultMethod(method: string): method is Rev2025TypedRequestMethod {\n    return Object.prototype.hasOwnProperty.call(resultMethodKeys, method);\n}\n\n/**\n * Gets the Zod schema for validating results of a given request method.\n * Returns `undefined` for non-spec methods and 2026-only methods.\n * The typed overload is backed by the map's own typing (`z.ZodType<ResultTypeMap[M]>`\n * per entry), so callers with a statically known 2025-era method can use the\n * parsed value without a type assertion.\n */\nexport function getResultSchema<M extends Rev2025TypedRequestMethod>(method: M): z.ZodType<ResultTypeMap[M]>;\nexport function getResultSchema(method: string): z.ZodType | undefined;\nexport function getResultSchema(method: string): z.ZodType | undefined {\n    return hasResultMethod(method) ? registryMaps().resultSchemas[method] : undefined;\n}\n\n/**\n * Gets the Zod schema for a given request method.\n * Returns `undefined` for non-spec methods and 2026-only methods.\n * The typed overload returns a ZodType that parses to `RequestTypeMap[M]`,\n * allowing callers to use `schema.parse()` without additional type assertions.\n */\nexport function getRequestSchema<M extends Rev2025TypedRequestMethod>(method: M): z.ZodType<RequestTypeMap[M]>;\nexport function getRequestSchema(method: string): z.ZodType | undefined;\nexport function getRequestSchema(method: string): z.ZodType | undefined {\n    return hasRequestMethod2025(method) ? registryMaps().requestSchemas[method] : undefined;\n}\n\n/**\n * Gets the Zod schema for a given notification method.\n * Returns `undefined` for non-spec methods.\n * @see getRequestSchema for the typed-overload contract.\n */\nexport function getNotificationSchema<M extends NotificationMethod>(method: M): z.ZodType<NotificationTypeMap[M]>;\nexport function getNotificationSchema(method: string): z.ZodType | undefined;\nexport function getNotificationSchema(method: string): z.ZodType | undefined {\n    return hasNotificationMethod2025(method) ? registryMaps().notificationSchemas[method] : undefined;\n}\n\n/** Registry method lists (for the spec-method universe and the CI registry-diff oracle). */\nexport const rev2025RequestMethods: readonly string[] = Object.keys(requestMethodKeys);\nexport const rev2025NotificationMethods: readonly string[] = Object.keys(notificationMethodKeys);\n","/**\n * The 2025-era wire codec: decode/encode ≈ identity.\n *\n * This codec serves every legacy protocol version (2024-10-07 … 2025-11-25).\n * It is BEHAVIOR-FROZEN behind the Q10-L2 byte-identity suite — its schemas\n * are today's schemas, its registry is today's method map, and its encode\n * path is the identity.\n *\n * Never-stamp guarantee: this module NEVER WRITES 2026 vocabulary\n * (`resultType`, `ttlMs`, `cacheScope`, the `_meta` envelope keys) — there is\n * no code path that can. `encodeResult` is the identity for every result\n * EXCEPT the SEP-2106 `tools/list` projection: when a tool's neutral\n * `outputSchema` has a non-object root, the 2025 wire shape requires\n * `type:'object'` there, so the codec PROJECTS the public superset down by\n * wrapping the advertised schema as `{type:'object',\n * properties:{result:<natural>}, required:['result']}`. That projection\n * narrows neutral→2025-wire; it never adds 2026 vocabulary.\n *\n * One deliberate exception to \"no 2026 code path\" (Q1-SD3 ii, amending the\n * V-2 'no code path at all' design claim): `decodeResult` STRIPS a foreign\n * `resultType` key from inbound results before validation (strip-on-lift).\n * `resultType` is not 2025 vocabulary — a 2025 peer that sends it is\n * misbehaving — and the ruled posture is tolerate-and-drop so the foreign key\n * can neither surface to consumers (the neutral types have no slot for it)\n * nor leak through the retained loose-object passthrough. This is the ONLY\n * 2026-vocabulary code path in the 2025 codec, it exists on the decode side\n * only, and it deletes — never reads, maps, or emits — the foreign value.\n */\nimport type * as z from 'zod/v4';\n\nimport type { CallToolResult, Result } from '../../types/types';\nimport type { DecodedResult, EnvelopeIssue, LiftedWireMaterial, OutboundEnvelopeMaterial, ValidateOutcome, WireCodec } from '../codec';\nimport { appendTextFallbackForNonObject } from '../textFallback';\nimport { buildSchemas2025 } from './buildSchemas';\nimport { isNonObjectJsonSchemaRoot, wrapOutputSchemaForLegacy } from './legacyWrap';\nimport { getNotificationSchema, getRequestSchema, getResultSchema, hasNotificationMethod2025, hasRequestMethod2025 } from './registry';\n\nfunction isPlainObject(value: unknown): value is Record<string, unknown> {\n    return value !== null && typeof value === 'object' && !Array.isArray(value);\n}\n\n/** Tri-state wrap of an optional Zod schema lookup (the function-only contract). */\nfunction triState<T>(schema: z.ZodType<T> | undefined, raw: unknown): ValidateOutcome<T> {\n    if (schema === undefined) return { ok: false, reason: 'not-in-era' };\n    const parsed = schema.safeParse(raw);\n    return parsed.success ? { ok: true, value: parsed.data } : { ok: false, reason: 'invalid', message: String(parsed.error) };\n}\n\nconst NOT_IN_ERA: ValidateOutcome<never> = { ok: false, reason: 'not-in-era' };\n\n/** Whether a `tools/list` entry advertises a non-object `outputSchema` root that needs the SEP-2106 legacy wrap. */\nfunction toolNeedsLegacyWrap(t: unknown): t is { outputSchema: Record<string, unknown> } {\n    return isPlainObject(t) && isPlainObject(t['outputSchema']) && isNonObjectJsonSchemaRoot(t['outputSchema']);\n}\n\n/** The wire→neutral trust boundary: a decoded 2025-era wire result is adopted as the neutral `Result` here (the module's single deliberate assertion). */\nfunction toNeutralResult(value: unknown): Result {\n    return value as Result;\n}\n\nexport const rev2025Codec: WireCodec = {\n    era: '2025-11-25',\n\n    hasRequestMethod: hasRequestMethod2025,\n    hasNotificationMethod: hasNotificationMethod2025,\n\n    // ── Function-only validation surface ──\n    validateRequest: (method: string, raw: unknown) => triState(getRequestSchema(method), raw),\n    validateResult: (method: string, raw: unknown) => triState(getResultSchema(method), raw),\n    validateNotification: (method: string, raw: unknown) => triState(getNotificationSchema(method), raw),\n    // No in-band input-request vocabulary on this era: elicitation, sampling\n    // and roots are real wire request methods here (see the registry).\n    hasInputRequestMethod: (): boolean => false,\n    validateInputRequest: (): ValidateOutcome<never> => NOT_IN_ERA,\n    validateInputResponse: (): ValidateOutcome<never> => NOT_IN_ERA,\n\n    // Arrow literals can't carry overload signatures; the cast is sound (the\n    // boolean dispatches to exactly the schema each overload names). The\n    // schemas are pulled through the era's memo so the codec module itself\n    // stays construction-free at import time.\n    samplingResultVariant: ((hasTools: boolean, raw: unknown) => {\n        const s = buildSchemas2025();\n        return triState(hasTools ? s.CreateMessageResultWithToolsSchema : s.CreateMessageResultSchema, raw);\n    }) as WireCodec['samplingResultVariant'],\n\n    // The 2025 era carries no per-request `_meta` envelope — legacy wire\n    // bytes stay identical (the never-stamp guarantee, outbound-request half).\n    outboundEnvelope: (_material: OutboundEnvelopeMaterial): undefined => undefined,\n    validateEnvelopeMeta: (_meta: Readonly<Record<string, unknown>>): EnvelopeIssue[] => [],\n\n    projectCallToolResult(result: CallToolResult, advertisedOutputSchema): CallToolResult {\n        // Era-agnostic SEP-2106 §4.3 TextContent auto-append first (value-shape-based).\n        const withText = appendTextFallbackForNonObject(result);\n        const sc = withText.structuredContent;\n        if (sc === undefined) return withText;\n        // SEP-2106 result-side projection. Wrap as `{result:<sc>}` when EITHER:\n        //  - the value is non-object (array/primitive/`null`) — REGARDLESS of\n        //    advertised schema, because the 2025 wire shape requires\n        //    `structuredContent` to be an object (a schema-less tool returning\n        //    `[1,2,3]` would otherwise ship wire-illegal bytes), or\n        //  - the advertised `outputSchema` has a non-object root — so the\n        //    result satisfies the wrapped schema this codec's\n        //    `encodeResult('tools/list', …)` advertised for the same tool.\n        const valueIsNonObject = typeof sc !== 'object' || sc === null || Array.isArray(sc);\n        const schemaWrapped = advertisedOutputSchema !== undefined && isNonObjectJsonSchemaRoot(advertisedOutputSchema);\n        if (!valueIsNonObject && !schemaWrapped) return withText;\n        return { ...withText, structuredContent: { result: sc } };\n    },\n\n    decodeResult(_method: string, raw: unknown): DecodedResult {\n        // Strip-on-lift (Q1-SD3 ii): a foreign `resultType` on the 2025 leg is\n        // dropped before validation, whatever its value. Validation judges the\n        // husk — the registry wire-seam schema on the plain path, the caller's\n        // schema on the explicit path (task interop).\n        if (isPlainObject(raw) && 'resultType' in raw) {\n            const stripped = { ...raw };\n            delete stripped['resultType'];\n            return { kind: 'complete', result: toNeutralResult(stripped) };\n        }\n        return { kind: 'complete', result: toNeutralResult(raw) };\n    },\n\n    // The never-stamp guarantee: never writes 2026 vocabulary. Identity for\n    // every result EXCEPT the SEP-2106 `tools/list` projection (see header).\n    // Copy-on-write: a listing with no non-object outputSchema roots returns\n    // the same reference (the byte-identity suite pins this).\n    encodeResult(method: string, result: Result): Result {\n        if (method !== 'tools/list') return result;\n        const tools = (result as { tools?: unknown }).tools;\n        if (!Array.isArray(tools) || !tools.some(t => toolNeedsLegacyWrap(t))) return result;\n        return {\n            ...result,\n            tools: tools.map(t => (toolNeedsLegacyWrap(t) ? { ...t, outputSchema: wrapOutputSchemaForLegacy(t.outputSchema) } : t))\n        } as Result;\n    },\n\n    // The −32002 resource-not-found domain code maps to −32602 on the wire on\n    // this era too (matching what the deployed v1.x SDK already emits — this\n    // is not a behavior change for v1.x peers). There is deliberately no era\n    // branch that preserves −32002.\n    encodeErrorCode: (code: number): number => (code === -32_002 ? -32_602 : code),\n\n    // The 2025 era never requires a per-request envelope.\n    checkInboundEnvelope: (_material: LiftedWireMaterial): string | undefined => undefined\n};\n","/**\n * 2026-era wire schemas (protocol revision 2026-07-28).\n *\n * Fully self-contained — no runtime imports from types/schemas.ts. The\n * neutral types/schemas.ts layer is the public-API superset and is free to\n * evolve; this file is the 2026 wire-parse contract and is BEHAVIOR-FROZEN\n * against the 2026-07-28 anchor. Every era-shared building block (content\n * blocks, resources, prompts, capabilities, notifications, …) that the wire\n * shapes compose is a frozen LOCAL copy — verbatim from the neutral layer at\n * the point this revision was sealed, dependencies first. The only cross-layer\n * dependency is `import type { JSONObject, JSONValue }` from the neutral types\n * barrel — pure structural type aliases with no parse behavior.\n *\n * This module is the only place the per-request `_meta` envelope is modeled.\n * The envelope is wire-only vocabulary: the protocol layer lifts it off\n * inbound requests before any handler runs and surfaces it at\n * `ctx.mcpReq.envelope`; the 2026-era codec enforces its requiredness at\n * dispatch time (`checkInboundEnvelope`) - the former neutral-schema JSDoc\n * deferral (\"enforced per request at dispatch time, not here\") is now\n * discharged by that codec step.\n *\n * No 2025-era traffic ever touches this module, so requiredness here is\n * bare and spec-exact (the shared-schema `.catch` hazards do not apply).\n *\n * SPEC-CURRENCY RE-SEAL (2026-07-17): the 2026-07-28 revision was re-sealed\n * upstream by spec PR #3002 (commit 71e30695, merged 2026-07-15 — after the\n * previous anchor pin f68d864a): the envelope's `clientInfo` demoted from\n * required to SHOULD, and `DiscoverResult.serverInfo` moved from the result\n * body to the new `ResultMetaObject` key\n * `_meta['io.modelcontextprotocol/serverInfo']` (optional on every result).\n * The shapes below are the re-sealed anchor, exactly — no pre-#3002 shape is\n * modeled anywhere (per ruling: the final revision is the only 2026-07-28).\n */\nimport * as z from 'zod/v4';\n\nimport {\n    CLIENT_CAPABILITIES_META_KEY,\n    CLIENT_INFO_META_KEY,\n    LOG_LEVEL_META_KEY,\n    PROTOCOL_VERSION_META_KEY,\n    SERVER_INFO_META_KEY\n} from '../../types/constants';\nimport type { JSONObject, JSONValue } from '../../types/types';\n\n/**\n * The 2026-era request-method set — the hand-registry seed (see registry.ts\n * for the seed decisions). The dispatch maps below are mapped types over this\n * union, so a missing entry, an extra entry, or an entry pointing at another\n * method's schema is a compile error; the CI registry-diff oracle pins the\n * same set against the anchor at runtime.\n */\nexport type Rev2026RequestMethod =\n    | 'tools/call'\n    | 'tools/list'\n    | 'prompts/get'\n    | 'prompts/list'\n    | 'resources/list'\n    | 'resources/templates/list'\n    | 'resources/read'\n    | 'completion/complete'\n    | 'server/discover'\n    | 'subscriptions/listen';\n\n/** The 2026-era notification-method set (the hand-registry seed; see the deletion list above). */\nexport type Rev2026NotificationMethod =\n    | 'notifications/cancelled'\n    | 'notifications/progress'\n    | 'notifications/message'\n    | 'notifications/resources/updated'\n    | 'notifications/resources/list_changed'\n    | 'notifications/tools/list_changed'\n    | 'notifications/prompts/list_changed'\n    | 'notifications/subscriptions/acknowledged';\n\nfunction build() {\n    /* ════════════════════════════════════════════════════════════════════════════\n     * Frozen neutral-layer building blocks\n     *\n     * Everything from this point until the next ═-banner is a verbatim frozen\n     * copy of a schema that, at the time this revision was sealed, lived in the\n     * neutral types/schemas.ts. They are copied dependencies-first so no forward\n     * references exist. They are NOT re-derived from the public layer at runtime —\n     * a widening or tightening landed on types/schemas.ts has no effect here until\n     * a deliberate per-revision re-freeze.\n     * ════════════════════════════════════════════════════════════════════════════ */\n\n    const JSONValueSchema: z.ZodType<JSONValue, JSONValue> = z.lazy(() =>\n        z.union([z.string(), z.number(), z.boolean(), z.null(), z.record(z.string(), JSONValueSchema), z.array(JSONValueSchema)])\n    );\n    const JSONObjectSchema: z.ZodType<JSONObject, JSONObject> = z.record(z.string(), JSONValueSchema);\n\n    /**\n     * A progress token, used to associate progress notifications with the original request.\n     */\n    const ProgressTokenSchema = z.union([z.string(), z.number().int()]);\n\n    /**\n     * An opaque token used to represent a cursor for pagination.\n     */\n    const CursorSchema = z.string();\n\n    /**\n     * A uniquely identifying ID for a request in JSON-RPC.\n     */\n    const RequestIdSchema = z.union([z.string(), z.number().int()]);\n\n    /**\n     * The sender or recipient of messages and data in a conversation.\n     */\n    const RoleSchema = z.enum(['user', 'assistant']);\n\n    /**\n     * The severity of a log message.\n     */\n    const LoggingLevelSchema = z.enum(['debug', 'info', 'notice', 'warning', 'error', 'critical', 'alert', 'emergency']);\n\n    /**\n     * A Zod schema for validating Base64 strings that is more performant and\n     * robust for very large inputs than the default regex-based check. It avoids\n     * stack overflows by using the native `atob` function for validation.\n     */\n    const Base64Schema = z.string().refine(\n        val => {\n            try {\n                atob(val);\n                return true;\n            } catch {\n                return false;\n            }\n        },\n        { message: 'Invalid Base64 string' }\n    );\n\n    /* ─── Request/notification meta and base params ─── */\n\n    /** @deprecated 2025-11-25 wire vocabulary with no SDK runtime; kept importable for interoperability only. */\n    const TaskMetadataSchema = z.object({\n        ttl: z.number().optional()\n    });\n\n    /** @deprecated 2025-11-25 wire vocabulary with no SDK runtime; kept importable for interoperability only. */\n    const RelatedTaskMetadataSchema = z.object({\n        taskId: z.string()\n    });\n\n    const RequestMetaSchema = z.looseObject({\n        /**\n         * If specified, the caller is requesting out-of-band progress notifications for this request (as represented by notifications/progress). The value of this parameter is an opaque token that will be attached to any subsequent notifications. The receiver is not obligated to provide these notifications.\n         */\n        progressToken: ProgressTokenSchema.optional(),\n        /**\n         * If specified, this request is related to the provided task.\n         */\n        'io.modelcontextprotocol/related-task': RelatedTaskMetadataSchema.optional()\n    });\n\n    const BaseRequestParamsSchema = z.object({\n        _meta: RequestMetaSchema.optional()\n    });\n\n    /** @deprecated 2025-11-25 wire vocabulary with no SDK runtime; kept importable for interoperability only. */\n    const TaskAugmentedRequestParamsSchema = BaseRequestParamsSchema.extend({\n        task: TaskMetadataSchema.optional()\n    });\n\n    const NotificationsParamsSchema = z.object({\n        _meta: RequestMetaSchema.optional()\n    });\n\n    const NotificationSchema = z.object({\n        method: z.string(),\n        params: NotificationsParamsSchema.loose().optional()\n    });\n\n    /* ─── Icons / base metadata / implementation ─── */\n\n    const IconSchema = z.object({\n        src: z.string(),\n        mimeType: z.string().optional(),\n        sizes: z.array(z.string()).optional(),\n        theme: z.enum(['light', 'dark']).optional()\n    });\n\n    const IconsSchema = z.object({\n        icons: z.array(IconSchema).optional()\n    });\n\n    const BaseMetadataSchema = z.object({\n        name: z.string(),\n        title: z.string().optional()\n    });\n\n    const ImplementationSchema = BaseMetadataSchema.extend({\n        ...BaseMetadataSchema.shape,\n        ...IconsSchema.shape,\n        version: z.string(),\n        websiteUrl: z.string().optional(),\n        description: z.string().optional()\n    });\n\n    /* ─── Capability schemas ─── */\n\n    const FormElicitationCapabilitySchema = z.intersection(\n        z.object({\n            applyDefaults: z.boolean().optional()\n        }),\n        JSONObjectSchema\n    );\n\n    const ElicitationCapabilitySchema = z.preprocess(\n        value => {\n            if (value && typeof value === 'object' && !Array.isArray(value) && Object.keys(value as Record<string, unknown>).length === 0) {\n                return { form: {} };\n            }\n            return value;\n        },\n        z.intersection(\n            z.object({\n                form: FormElicitationCapabilitySchema.optional(),\n                url: JSONObjectSchema.optional()\n            }),\n            JSONObjectSchema.optional()\n        )\n    );\n\n    /** @deprecated 2025-11-25 wire vocabulary with no SDK runtime; kept importable for interoperability only. */\n    const ClientTasksCapabilitySchema = z.looseObject({\n        list: JSONObjectSchema.optional(),\n        cancel: JSONObjectSchema.optional(),\n        requests: z\n            .looseObject({\n                sampling: z\n                    .looseObject({\n                        createMessage: JSONObjectSchema.optional()\n                    })\n                    .optional(),\n                elicitation: z\n                    .looseObject({\n                        create: JSONObjectSchema.optional()\n                    })\n                    .optional()\n            })\n            .optional()\n    });\n\n    /** @deprecated 2025-11-25 wire vocabulary with no SDK runtime; kept importable for interoperability only. */\n    const ServerTasksCapabilitySchema = z.looseObject({\n        list: JSONObjectSchema.optional(),\n        cancel: JSONObjectSchema.optional(),\n        requests: z\n            .looseObject({\n                tools: z\n                    .looseObject({\n                        call: JSONObjectSchema.optional()\n                    })\n                    .optional()\n            })\n            .optional()\n    });\n\n    const ClientCapabilitiesSchema = z.object({\n        experimental: z.record(z.string(), JSONObjectSchema).optional(),\n        sampling: z\n            .object({\n                context: JSONObjectSchema.optional(),\n                tools: JSONObjectSchema.optional()\n            })\n            .optional(),\n        elicitation: ElicitationCapabilitySchema.optional(),\n        roots: z\n            .object({\n                listChanged: z.boolean().optional()\n            })\n            .optional(),\n        tasks: ClientTasksCapabilitySchema.optional(),\n        extensions: z.record(z.string(), JSONObjectSchema).optional()\n    });\n\n    const ServerCapabilitiesSchema = z.object({\n        experimental: z.record(z.string(), JSONObjectSchema).optional(),\n        logging: JSONObjectSchema.optional(),\n        completions: JSONObjectSchema.optional(),\n        prompts: z\n            .object({\n                listChanged: z.boolean().optional()\n            })\n            .optional(),\n        resources: z\n            .object({\n                subscribe: z.boolean().optional(),\n                listChanged: z.boolean().optional()\n            })\n            .optional(),\n        tools: z\n            .object({\n                listChanged: z.boolean().optional()\n            })\n            .optional(),\n        tasks: ServerTasksCapabilitySchema.optional(),\n        extensions: z.record(z.string(), JSONObjectSchema).optional()\n    });\n\n    /* ─── Progress / logging notifications ─── */\n\n    const ProgressSchema = z.object({\n        progress: z.number(),\n        total: z.optional(z.number()),\n        message: z.optional(z.string())\n    });\n\n    const ProgressNotificationParamsSchema = z.object({\n        ...NotificationsParamsSchema.shape,\n        ...ProgressSchema.shape,\n        progressToken: ProgressTokenSchema\n    });\n\n    const ProgressNotificationSchema = NotificationSchema.extend({\n        method: z.literal('notifications/progress'),\n        params: ProgressNotificationParamsSchema\n    });\n\n    const LoggingMessageNotificationParamsSchema = NotificationsParamsSchema.extend({\n        level: LoggingLevelSchema,\n        logger: z.string().optional(),\n        data: z.unknown()\n    });\n\n    const LoggingMessageNotificationSchema = NotificationSchema.extend({\n        method: z.literal('notifications/message'),\n        params: LoggingMessageNotificationParamsSchema\n    });\n\n    /* ─── Resource contents / annotations ─── */\n\n    const ResourceContentsSchema = z.object({\n        uri: z.string(),\n        mimeType: z.optional(z.string()),\n        _meta: z.record(z.string(), z.unknown()).optional()\n    });\n\n    const TextResourceContentsSchema = ResourceContentsSchema.extend({\n        text: z.string()\n    });\n\n    const BlobResourceContentsSchema = ResourceContentsSchema.extend({\n        blob: Base64Schema\n    });\n\n    const AnnotationsSchema = z.object({\n        audience: z.array(RoleSchema).optional(),\n        priority: z.number().min(0).max(1).optional(),\n        lastModified: z.iso.datetime({ offset: true }).optional()\n    });\n\n    /* ─── Resources / templates / list-changed notifications ─── */\n\n    const ResourceSchema = z.object({\n        ...BaseMetadataSchema.shape,\n        ...IconsSchema.shape,\n        uri: z.string(),\n        description: z.optional(z.string()),\n        mimeType: z.optional(z.string()),\n        size: z.optional(z.number()),\n        annotations: AnnotationsSchema.optional(),\n        _meta: z.optional(z.looseObject({}))\n    });\n\n    const ResourceTemplateSchema = z.object({\n        ...BaseMetadataSchema.shape,\n        ...IconsSchema.shape,\n        uriTemplate: z.string(),\n        description: z.optional(z.string()),\n        mimeType: z.optional(z.string()),\n        annotations: AnnotationsSchema.optional(),\n        _meta: z.optional(z.looseObject({}))\n    });\n\n    const ResourceListChangedNotificationSchema = NotificationSchema.extend({\n        method: z.literal('notifications/resources/list_changed'),\n        params: NotificationsParamsSchema.optional()\n    });\n\n    const ResourceUpdatedNotificationParamsSchema = NotificationsParamsSchema.extend({\n        uri: z.string()\n    });\n\n    const ResourceUpdatedNotificationSchema = NotificationSchema.extend({\n        method: z.literal('notifications/resources/updated'),\n        params: ResourceUpdatedNotificationParamsSchema\n    });\n\n    /* ─── Prompts / content blocks ─── */\n\n    const PromptArgumentSchema = z.object({\n        name: z.string(),\n        description: z.optional(z.string()),\n        required: z.optional(z.boolean())\n    });\n\n    const PromptSchema = z.object({\n        ...BaseMetadataSchema.shape,\n        ...IconsSchema.shape,\n        description: z.optional(z.string()),\n        arguments: z.optional(z.array(PromptArgumentSchema)),\n        _meta: z.optional(z.looseObject({}))\n    });\n\n    const PromptListChangedNotificationSchema = NotificationSchema.extend({\n        method: z.literal('notifications/prompts/list_changed'),\n        params: NotificationsParamsSchema.optional()\n    });\n\n    const TextContentSchema = z.object({\n        type: z.literal('text'),\n        text: z.string(),\n        annotations: AnnotationsSchema.optional(),\n        _meta: z.record(z.string(), z.unknown()).optional()\n    });\n\n    const ImageContentSchema = z.object({\n        type: z.literal('image'),\n        data: Base64Schema,\n        mimeType: z.string(),\n        annotations: AnnotationsSchema.optional(),\n        _meta: z.record(z.string(), z.unknown()).optional()\n    });\n\n    const AudioContentSchema = z.object({\n        type: z.literal('audio'),\n        data: Base64Schema,\n        mimeType: z.string(),\n        annotations: AnnotationsSchema.optional(),\n        _meta: z.record(z.string(), z.unknown()).optional()\n    });\n\n    const ToolUseContentSchema = z.object({\n        type: z.literal('tool_use'),\n        name: z.string(),\n        id: z.string(),\n        input: z.record(z.string(), z.unknown()),\n        _meta: z.record(z.string(), z.unknown()).optional()\n    });\n\n    const EmbeddedResourceSchema = z.object({\n        type: z.literal('resource'),\n        resource: z.union([TextResourceContentsSchema, BlobResourceContentsSchema]),\n        annotations: AnnotationsSchema.optional(),\n        _meta: z.record(z.string(), z.unknown()).optional()\n    });\n\n    const ResourceLinkSchema = ResourceSchema.extend({\n        type: z.literal('resource_link')\n    });\n\n    const ContentBlockSchema = z.union([\n        TextContentSchema,\n        ImageContentSchema,\n        AudioContentSchema,\n        ResourceLinkSchema,\n        EmbeddedResourceSchema\n    ]);\n\n    const PromptMessageSchema = z.object({\n        role: RoleSchema,\n        content: ContentBlockSchema\n    });\n\n    /* ─── Tool annotations / tool list-changed / sampling primitives ─── */\n\n    const ToolAnnotationsSchema = z.object({\n        title: z.string().optional(),\n        readOnlyHint: z.boolean().optional(),\n        destructiveHint: z.boolean().optional(),\n        idempotentHint: z.boolean().optional(),\n        openWorldHint: z.boolean().optional()\n    });\n\n    const ToolListChangedNotificationSchema = NotificationSchema.extend({\n        method: z.literal('notifications/tools/list_changed'),\n        params: NotificationsParamsSchema.optional()\n    });\n\n    const ModelHintSchema = z.object({\n        name: z.string().optional()\n    });\n\n    const ModelPreferencesSchema = z.object({\n        hints: z.array(ModelHintSchema).optional(),\n        costPriority: z.number().min(0).max(1).optional(),\n        speedPriority: z.number().min(0).max(1).optional(),\n        intelligencePriority: z.number().min(0).max(1).optional()\n    });\n\n    const ToolChoiceSchema = z.object({\n        mode: z.enum(['auto', 'required', 'none']).optional()\n    });\n\n    /* ─── Elicitation primitive-schema vocabulary ─── */\n\n    const BooleanSchemaSchema = z.object({\n        type: z.literal('boolean'),\n        title: z.string().optional(),\n        description: z.string().optional(),\n        default: z.boolean().optional()\n    });\n\n    const StringSchemaSchema = z.object({\n        type: z.literal('string'),\n        title: z.string().optional(),\n        description: z.string().optional(),\n        minLength: z.number().optional(),\n        maxLength: z.number().optional(),\n        format: z.enum(['email', 'uri', 'date', 'date-time']).optional(),\n        default: z.string().optional()\n    });\n\n    const NumberSchemaSchema = z.object({\n        type: z.enum(['number', 'integer']),\n        title: z.string().optional(),\n        description: z.string().optional(),\n        minimum: z.number().optional(),\n        maximum: z.number().optional(),\n        default: z.number().optional()\n    });\n\n    const UntitledSingleSelectEnumSchemaSchema = z.object({\n        type: z.literal('string'),\n        title: z.string().optional(),\n        description: z.string().optional(),\n        enum: z.array(z.string()),\n        default: z.string().optional()\n    });\n\n    const TitledSingleSelectEnumSchemaSchema = z.object({\n        type: z.literal('string'),\n        title: z.string().optional(),\n        description: z.string().optional(),\n        oneOf: z.array(\n            z.object({\n                const: z.string(),\n                title: z.string()\n            })\n        ),\n        default: z.string().optional()\n    });\n\n    const LegacyTitledEnumSchemaSchema = z.object({\n        type: z.literal('string'),\n        title: z.string().optional(),\n        description: z.string().optional(),\n        enum: z.array(z.string()),\n        enumNames: z.array(z.string()).optional(),\n        default: z.string().optional()\n    });\n\n    const SingleSelectEnumSchemaSchema = z.union([UntitledSingleSelectEnumSchemaSchema, TitledSingleSelectEnumSchemaSchema]);\n\n    const UntitledMultiSelectEnumSchemaSchema = z.object({\n        type: z.literal('array'),\n        title: z.string().optional(),\n        description: z.string().optional(),\n        minItems: z.number().optional(),\n        maxItems: z.number().optional(),\n        items: z.object({\n            type: z.literal('string'),\n            enum: z.array(z.string())\n        }),\n        default: z.array(z.string()).optional()\n    });\n\n    const TitledMultiSelectEnumSchemaSchema = z.object({\n        type: z.literal('array'),\n        title: z.string().optional(),\n        description: z.string().optional(),\n        minItems: z.number().optional(),\n        maxItems: z.number().optional(),\n        items: z.object({\n            anyOf: z.array(\n                z.object({\n                    const: z.string(),\n                    title: z.string()\n                })\n            )\n        }),\n        default: z.array(z.string()).optional()\n    });\n\n    const MultiSelectEnumSchemaSchema = z.union([UntitledMultiSelectEnumSchemaSchema, TitledMultiSelectEnumSchemaSchema]);\n\n    const EnumSchemaSchema = z.union([LegacyTitledEnumSchemaSchema, SingleSelectEnumSchemaSchema, MultiSelectEnumSchemaSchema]);\n\n    const PrimitiveSchemaDefinitionSchema = z.union([EnumSchemaSchema, BooleanSchemaSchema, StringSchemaSchema, NumberSchemaSchema]);\n\n    const ElicitRequestFormParamsSchema = TaskAugmentedRequestParamsSchema.extend({\n        mode: z.literal('form').optional(),\n        message: z.string(),\n        requestedSchema: z\n            .object({\n                type: z.literal('object'),\n                properties: z.record(z.string(), PrimitiveSchemaDefinitionSchema),\n                required: z.array(z.string()).optional()\n            })\n            .catchall(z.unknown())\n    });\n\n    /* ─── Completion references / roots ─── */\n\n    const ResourceTemplateReferenceSchema = z.object({\n        type: z.literal('ref/resource'),\n        uri: z.string()\n    });\n\n    const PromptReferenceSchema = z.object({\n        type: z.literal('ref/prompt'),\n        name: z.string()\n    });\n\n    const RootSchema = z.object({\n        uri: z.string().startsWith('file://'),\n        name: z.string().optional(),\n        _meta: z.record(z.string(), z.unknown()).optional()\n    });\n\n    /* ════════════════════════════════════════════════════════════════════════════\n     * End of frozen neutral-layer building blocks. Everything below is the\n     * 2026-07-28 wire-specific vocabulary (envelope, forks, results, requests,\n     * notifications) composed against the frozen copies above.\n     * ════════════════════════════════════════════════════════════════════════════ */\n\n    /* 2026-era capability forks (defined ahead of the envelope, which composes\n     * the client fork). The frozen shapes minus the deleted `tasks` key: `tasks`\n     * is 2025-only vocabulary with no slot on this revision, consistent with the\n     * encode-side deletion (Q1-SD3 iii).\n     *\n     * Both forks list their members EXPLICITLY (composing the frozen member\n     * schemas by reference) rather than using `.omit()`: the envelope schema\n     * below reaches the bundled package declarations, and an `.omit()` inference\n     * is a mapped type whose printed member order is unstable across dts-rollup\n     * builds (api-report flap). The explicit list doubles as the fork's deletion\n     * statement — a member added to the frozen shape must be re-adjudicated here. */\n    const sharedClientCapabilityShape = ClientCapabilitiesSchema.shape;\n    const ClientCapabilities2026Schema = z.object({\n        experimental: sharedClientCapabilityShape.experimental,\n        sampling: sharedClientCapabilityShape.sampling,\n        elicitation: sharedClientCapabilityShape.elicitation,\n        roots: sharedClientCapabilityShape.roots,\n        extensions: sharedClientCapabilityShape.extensions\n    });\n    const sharedServerCapabilityShape = ServerCapabilitiesSchema.shape;\n    const ServerCapabilities2026Schema = z.object({\n        experimental: sharedServerCapabilityShape.experimental,\n        logging: sharedServerCapabilityShape.logging,\n        completions: sharedServerCapabilityShape.completions,\n        prompts: sharedServerCapabilityShape.prompts,\n        resources: sharedServerCapabilityShape.resources,\n        tools: sharedServerCapabilityShape.tools,\n        extensions: sharedServerCapabilityShape.extensions\n    });\n\n    /* Per-request `_meta` envelope */\n    /**\n     * The per-request `_meta` envelope carried by every request under protocol revision\n     * 2026-07-28: the protocol version governing the request, the client implementation\n     * info, and the client's capabilities — declared per request rather than once at\n     * initialization — plus the optional log-level opt-in.\n     *\n     * This schema models the complete envelope on its own (loose: foreign keys\n     * pass through - the lift extracts exactly the reserved keys, so enforcement\n     * never sees extension material). Requiredness is enforced per request at\n     * dispatch time by the 2026-era codec's `checkInboundEnvelope` step.\n     */\n    const RequestMetaEnvelopeSchema = z.looseObject({\n        /**\n         * If specified, the caller is requesting out-of-band progress notifications for this request (as represented by notifications/progress). The value of this parameter is an opaque token that will be attached to any subsequent notifications. The receiver is not obligated to provide these notifications.\n         */\n        progressToken: ProgressTokenSchema.optional(),\n        /**\n         * The MCP protocol version being used for this request. For the HTTP transport,\n         * the value must match the `MCP-Protocol-Version` header.\n         */\n        [PROTOCOL_VERSION_META_KEY]: z.string(),\n        /**\n         * Identifies the client software making the request. Optional since\n         * spec PR #3002 (clients SHOULD send it; servers must not require it).\n         */\n        [CLIENT_INFO_META_KEY]: ImplementationSchema.optional(),\n        /**\n         * The client's capabilities for this specific request. An empty object means the\n         * client supports no optional capabilities. Servers must not infer capabilities\n         * from prior requests. Validated with the 2026 fork: `tasks` has no slot on\n         * this revision (deleted vocabulary), matching the server-side fork wired\n         * into `DiscoverResultSchema`.\n         */\n        [CLIENT_CAPABILITIES_META_KEY]: ClientCapabilities2026Schema,\n        /**\n         * The desired log level for this request. When absent, the server must not send\n         * `notifications/message` notifications for the request.\n         *\n         * @deprecated Deprecated as of protocol version 2026-07-28 (SEP-2577); remains\n         * in the specification for at least twelve months.\n         */\n        [LOG_LEVEL_META_KEY]: LoggingLevelSchema.optional()\n    });\n\n    /* ------------------------------------------------------------------------ *\n     * Forked payload vocabulary (shared-tier admission rule, ATK-B section 1):\n     * `Tool` and `SamplingMessage` are bidirectionally incomparable between the\n     * 2025-11-25 and 2026-07-28 anchors, so they FORK per wire module instead of\n     * sitting in the shared tier. The forks below are 2026-anchor-exact:\n     * - Tool (2026) has NO `execution` member (ToolExecution and its\n     *   `taskSupport` carrier are deleted vocabulary) — a 2026 peer's tool that\n     *   carries one is stripped on parse, and the encode side strips it from\n     *   outbound tools (Q1-SD3 iii).\n     * - SamplingMessage (2026) is composed against the 2026 anchor shape.\n     * ------------------------------------------------------------------------ */\n\n    /** 2026-era Tool: anchor-exact — no `execution` (deleted vocabulary). */\n    const ToolSchema = z.object({\n        ...BaseMetadataSchema.shape,\n        ...IconsSchema.shape,\n        description: z.string().optional(),\n        // Anchor-exact: { $schema?: string; type: 'object'; [key: string]: unknown }\n        inputSchema: z.looseObject({\n            $schema: z.string().optional(),\n            type: z.literal('object')\n        }),\n        // Anchor-exact: { $schema?: string; [key: string]: unknown }\n        outputSchema: z\n            .looseObject({\n                $schema: z.string().optional()\n            })\n            .optional(),\n        annotations: ToolAnnotationsSchema.optional(),\n        _meta: z.record(z.string(), z.unknown()).optional()\n    });\n\n    /** 2026-era ToolResultContent (anchor-exact: `structuredContent?: unknown`). */\n    const ToolResultContentSchema = z.object({\n        type: z.literal('tool_result'),\n        toolUseId: z.string(),\n        content: z.array(ContentBlockSchema),\n        structuredContent: z.unknown().optional(),\n        isError: z.boolean().optional(),\n        _meta: z.record(z.string(), z.unknown()).optional()\n    });\n\n    /** 2026-era sampling content union (composes the forked tool-result shape). */\n    const SamplingMessageContentBlockSchema = z.union([\n        TextContentSchema,\n        ImageContentSchema,\n        AudioContentSchema,\n        ToolUseContentSchema,\n        ToolResultContentSchema\n    ]);\n\n    /** 2026-era SamplingMessage (anchor-exact: single block or array). */\n    const SamplingMessageSchema = z.object({\n        role: RoleSchema,\n        content: z.union([SamplingMessageContentBlockSchema, z.array(SamplingMessageContentBlockSchema)]),\n        _meta: z.record(z.string(), z.unknown()).optional()\n    });\n\n    /* ------------------------------------------------------------------------ *\n     * Result side. `resultType` is a sender obligation (spec.types.2026-07-28\n     * Result.resultType: \"Servers implementing this protocol version MUST\n     * include this field\") and a receiver default (schema.ts:208 — clients MUST\n     * treat absent `resultType` as 'complete'). These are the WIRE-TRUE\n     * artifacts — the corpus and the parity suite parse them; `decodeResult`\n     * parses with them and then LIFTS (drops resultType) to the neutral shape.\n     * Sender-side requiredness is enforced by construction (`encodeResult`\n     * stamps it), so the parse side carries the receiver default.\n     * ------------------------------------------------------------------------ */\n\n    /** Open union per the anchor: 'complete' | 'input_required' | string. */\n    const ResultTypeSchema = z.string();\n\n    /**\n     * Result `_meta` (anchor `ResultMetaObject`, added by spec PR #3002):\n     * loose, with the serverInfo key typed when present; the outbound stamp\n     * is the encode contract's `stampServerInfoMeta` step.\n     */\n    const ResultMetaSchema = z.looseObject({\n        // Malformed drops to absent, per the spec: the value \"is not verified\n        // by the protocol\" and clients \"SHOULD NOT use it to change their behavior\".\n        // eslint-disable-next-line unicorn/prefer-top-level-await -- Zod `.catch()`, not a Promise\n        [SERVER_INFO_META_KEY]: ImplementationSchema.optional().catch(undefined)\n    });\n\n    const wireMeta = ResultMetaSchema.optional();\n\n    function wireResult<T extends z.core.$ZodLooseShape>(shape: T) {\n        return z.looseObject({\n            _meta: wireMeta,\n            /** Sender MUST set; receiver defaults absent → 'complete' (spec receiver leniency). */\n            resultType: ResultTypeSchema.default('complete'),\n            ...shape\n        });\n    }\n\n    const ResultSchema = wireResult({});\n\n    const PaginatedResultSchema = wireResult({\n        nextCursor: CursorSchema.optional()\n    });\n\n    const CallToolResultSchema = wireResult({\n        content: z.array(ContentBlockSchema),\n        structuredContent: z.unknown().optional(),\n        isError: z.boolean().optional()\n    });\n\n    const ListToolsResultSchema = wireResult({\n        ttlMs: z.number().int().min(0),\n        cacheScope: z.enum(['public', 'private']),\n        tools: z.array(ToolSchema),\n        nextCursor: CursorSchema.optional()\n    });\n\n    const ListPromptsResultSchema = wireResult({\n        ttlMs: z.number().int().min(0),\n        cacheScope: z.enum(['public', 'private']),\n        prompts: z.array(PromptSchema),\n        nextCursor: CursorSchema.optional()\n    });\n\n    const GetPromptResultSchema = wireResult({\n        description: z.string().optional(),\n        messages: z.array(PromptMessageSchema)\n    });\n\n    const ListResourcesResultSchema = wireResult({\n        ttlMs: z.number().int().min(0),\n        cacheScope: z.enum(['public', 'private']),\n        resources: z.array(ResourceSchema),\n        nextCursor: CursorSchema.optional()\n    });\n\n    const ListResourceTemplatesResultSchema = wireResult({\n        ttlMs: z.number().int().min(0),\n        cacheScope: z.enum(['public', 'private']),\n        resourceTemplates: z.array(ResourceTemplateSchema),\n        nextCursor: CursorSchema.optional()\n    });\n\n    const ReadResourceResultSchema = wireResult({\n        ttlMs: z.number().int().min(0),\n        cacheScope: z.enum(['public', 'private']),\n        contents: z.array(z.union([TextResourceContentsSchema, BlobResourceContentsSchema]))\n    });\n\n    const CompleteResultSchema = wireResult({\n        completion: z\n            .object({\n                values: z.array(z.string()).max(100),\n                total: z.number().int().optional(),\n                hasMore: z.boolean().optional()\n            })\n            .loose()\n    });\n\n    /** CacheableResult (SEP-2549): ttlMs and cacheScope REQUIRED per the anchor. */\n    const CacheableResultSchema = wireResult({\n        ttlMs: z.number().int().min(0),\n        cacheScope: z.enum(['public', 'private'])\n    });\n\n    const DiscoverResultSchema = wireResult({\n        // Receiver-side leniency per caching.mdx:56-58 — the probe classifier must\n        // accept a DiscoverResult that omits OR malforms the cache hints (spec:\n        // \"if ttlMs is negative, clients SHOULD ignore it and treat it as 0\").\n        // `.catch()` returns the fallback for both absence and parse failure;\n        // sender obligation is enforced by `encodeResult`, not by parse.\n        // eslint-disable-next-line unicorn/prefer-top-level-await -- Zod `.catch()`, not a Promise\n        ttlMs: z.number().int().min(0).catch(0),\n        // eslint-disable-next-line unicorn/prefer-top-level-await -- Zod `.catch()`, not a Promise\n        cacheScope: z.enum(['public', 'private']).catch('private'),\n        supportedVersions: z.array(z.string()),\n        capabilities: ServerCapabilities2026Schema,\n        // No body `serverInfo` (spec PR #3002) — identity lives in the result\n        // `_meta['io.modelcontextprotocol/serverInfo']`.\n        instructions: z.string().optional()\n    });\n\n    /* ------------------------------------------------------------------------ *\n     * Multi round-trip requests (SEP-2322). The in-band vocabulary of this\n     * revision: server→client interactions are carried as de-JSON-RPC'd embedded\n     * requests inside an `input_required` result, fulfilled by the client, and\n     * echoed back as embedded responses on the retry. The shapes below are\n     * anchor-exact wire artifacts (corpus + parity); the lenient dispatch-time\n     * schemas the multi-round-trip driver parses embedded requests with live in\n     * `inputRequired.ts`.\n     *\n     * The sampling shapes fork here (they compose the forked SamplingMessage /\n     * Tool payloads); the URL-mode elicitation params fork here (the draft\n     * removed `elicitationId`; the shared schema keeps it because it is required\n     * on the frozen 2025-11-25 revision); form-mode elicitation params are\n     * revision-identical and are composed by reference from the shared schema.\n     * ------------------------------------------------------------------------ */\n\n    /** 2026-era CreateMessageRequestParams (anchor-exact: forked SamplingMessage/Tool, no task augmentation). */\n    const CreateMessageRequestParamsSchema = z.object({\n        messages: z.array(SamplingMessageSchema),\n        modelPreferences: ModelPreferencesSchema.optional(),\n        systemPrompt: z.string().optional(),\n        includeContext: z.enum(['none', 'thisServer', 'allServers']).optional(),\n        temperature: z.number().optional(),\n        maxTokens: z.number().int(),\n        stopSequences: z.array(z.string()).optional(),\n        metadata: JSONObjectSchema.optional(),\n        tools: z.array(ToolSchema).optional(),\n        toolChoice: ToolChoiceSchema.optional()\n    });\n\n    /** 2026-era embedded sampling request (de-JSON-RPC'd). */\n    const CreateMessageRequestSchema = z.object({\n        method: z.literal('sampling/createMessage'),\n        params: CreateMessageRequestParamsSchema\n    });\n\n    /**\n     * 2026-era embedded roots listing request (de-JSON-RPC'd). Embedded input\n     * requests do NOT carry the per-request `_meta` envelope on this revision —\n     * the anchor declares a bare optional `_meta` on `params`.\n     */\n    const ListRootsRequestSchema = z.object({\n        method: z.literal('roots/list'),\n        params: z.object({ _meta: z.record(z.string(), z.unknown()).optional() }).optional()\n    });\n\n    /** 2026-era embedded sampling response (anchor-exact: extends the forked SamplingMessage). */\n    const CreateMessageResultSchema = z.object({\n        ...SamplingMessageSchema.shape,\n        model: z.string(),\n        stopReason: z.string().optional()\n    });\n\n    /** 2026-era embedded roots listing response (anchor-exact: bare `roots` array). */\n    const ListRootsResultSchema = z.object({\n        roots: z.array(RootSchema)\n    });\n\n    /** 2026-era embedded elicitation response (anchor-exact: bare result, restricted content value types). */\n    const ElicitResultSchema = z.object({\n        action: z.enum(['accept', 'decline', 'cancel']),\n        content: z.record(z.string(), z.union([z.string(), z.number(), z.boolean(), z.array(z.string())])).optional()\n    });\n\n    /**\n     * 2026-era URL-mode elicitation params (anchor-exact fork): the draft removed\n     * `elicitationId` (and the `notifications/elicitation/complete` channel it\n     * keyed) — the shared schema keeps the field because it is required on the\n     * frozen 2025-11-25 revision.\n     */\n    const ElicitRequestURLParamsSchema = z.object({\n        mode: z.literal('url'),\n        message: z.string(),\n        url: z.string().url()\n    });\n\n    /** 2026-era elicitation params (form mode is revision-identical; URL mode is the fork above). */\n    const ElicitRequestParamsSchema = z.union([ElicitRequestFormParamsSchema, ElicitRequestURLParamsSchema]);\n\n    /** 2026-era embedded elicitation request (de-JSON-RPC'd; see the URL-mode fork above). */\n    const ElicitRequestSchema = z.object({\n        method: z.literal('elicitation/create'),\n        params: ElicitRequestParamsSchema\n    });\n\n    /** A single embedded input request (one of the three demoted server→client requests). */\n    const InputRequestSchema = z.union([CreateMessageRequestSchema, ListRootsRequestSchema, ElicitRequestSchema]);\n\n    /** A single embedded input response — the BARE result union (never a `{method, result}` wrapper). */\n    const InputResponseSchema = z.union([CreateMessageResultSchema, ListRootsResultSchema, ElicitResultSchema]);\n\n    /** Map of embedded input requests, keyed by server-assigned identifiers. */\n    const InputRequestsSchema = z.record(z.string(), InputRequestSchema);\n\n    /** Map of embedded input responses, keyed by the corresponding request identifiers. */\n    const InputResponsesSchema = z.record(z.string(), InputResponseSchema);\n\n    /**\n     * The wire InputRequiredResult: `resultType: 'input_required'` plus at least\n     * one of `inputRequests` / `requestState` (the at-least-one rule is enforced\n     * at the server seam, not by this parse shape).\n     */\n    const InputRequiredResultSchema = wireResult({\n        inputRequests: InputRequestsSchema.optional(),\n        requestState: z.string().optional()\n    });\n\n    /** The retry-channel members carried by client-initiated requests on this revision. */\n    const retryParamsShape = {\n        inputResponses: InputResponsesSchema.optional(),\n        requestState: z.string().optional()\n    };\n\n    /** Anchor InputResponseRequestParams: the retry channel on top of the required request `_meta` envelope. */\n    const InputResponseRequestParamsSchema = z.object({\n        _meta: RequestMetaEnvelopeSchema,\n        ...retryParamsShape\n    });\n\n    /* ------------------------------------------------------------------------ *\n     * Request side. Two views per method:\n     * - WIRE-TRUE (`<Name>RequestSchema`): params `_meta` carries the REQUIRED\n     *   envelope (anchor RequestParams._meta is required). The corpus and parity\n     *   suite consume these.\n     * - DISPATCH (post-lift, internal to the registry): the protocol layer's\n     *   universal lift has already extracted the envelope, so dispatch parses a\n     *   2025-like shape with optional `_meta` (progressToken/extension keys\n     *   only) and NO 2025-only members (`task` is undeclared and strips —\n     *   payload-level deletion is physical on this leg).\n     * ------------------------------------------------------------------------ */\n\n    /** Post-lift request `_meta` (progressToken + extension keys; loose). */\n    const DispatchRequestMetaSchema = z.looseObject({\n        progressToken: ProgressTokenSchema.optional()\n    });\n\n    function wireRequest<M extends string, T extends z.core.$ZodLooseShape>(method: M, paramsShape: T) {\n        return z.object({\n            method: z.literal(method),\n            params: z.object({ _meta: RequestMetaEnvelopeSchema, ...paramsShape })\n        });\n    }\n\n    function dispatchRequest<M extends string, T extends z.core.$ZodLooseShape>(method: M, paramsShape: T) {\n        return z.object({\n            method: z.literal(method),\n            params: z.object({ _meta: DispatchRequestMetaSchema.optional(), ...paramsShape }).optional()\n        });\n    }\n\n    const callToolParamsShape = {\n        name: z.string(),\n        arguments: z.record(z.string(), z.unknown()).optional(),\n        // Multi-round-trip retry channel (the wire-true view models it; dispatch\n        // never sees it — the protocol layer lifts it before any handler runs).\n        ...retryParamsShape\n    };\n    const paginatedParamsShape = { cursor: CursorSchema.optional() };\n\n    const CallToolRequestSchema = wireRequest('tools/call', callToolParamsShape);\n    const ListToolsRequestSchema = wireRequest('tools/list', paginatedParamsShape);\n    const ListPromptsRequestSchema = wireRequest('prompts/list', paginatedParamsShape);\n    const GetPromptRequestSchema = wireRequest('prompts/get', {\n        name: z.string(),\n        arguments: z.record(z.string(), z.string()).optional(),\n        ...retryParamsShape\n    });\n    const ListResourcesRequestSchema = wireRequest('resources/list', paginatedParamsShape);\n    const ListResourceTemplatesRequestSchema = wireRequest('resources/templates/list', paginatedParamsShape);\n    const ReadResourceRequestSchema = wireRequest('resources/read', { uri: z.string(), ...retryParamsShape });\n    const completeParamsShape = {\n        ref: z.union([PromptReferenceSchema, ResourceTemplateReferenceSchema]),\n        argument: z.object({ name: z.string(), value: z.string() }),\n        context: z.object({ arguments: z.record(z.string(), z.string()).optional() }).optional()\n    };\n    const CompleteRequestSchema = wireRequest('completion/complete', completeParamsShape);\n    const DiscoverRequestSchema = wireRequest('server/discover', {});\n\n    /** Anchor SubscriptionFilter (2026-only). */\n    const SubscriptionFilterSchema = z.object({\n        toolsListChanged: z.boolean().optional(),\n        promptsListChanged: z.boolean().optional(),\n        resourcesListChanged: z.boolean().optional(),\n        resourceSubscriptions: z.array(z.string()).optional()\n    });\n    const subscriptionsListenParamsShape = { notifications: SubscriptionFilterSchema };\n    const SubscriptionsListenRequestSchema = wireRequest('subscriptions/listen', subscriptionsListenParamsShape);\n\n    /**\n     * Anchor SubscriptionsListenResultMetaObject — required subscriptionId stamp on\n     * the graceful-close result. Extends `ResultMetaObject` since spec PR\n     * #3002 (composed, so the serverInfo key and its leniency stay single-sourced).\n     */\n    const SubscriptionsListenResultMetaSchema = ResultMetaSchema.extend({\n        'io.modelcontextprotocol/subscriptionId': RequestIdSchema\n    });\n\n    /**\n     * Anchor SubscriptionsListenResult (2026-only). The empty `subscriptions/listen`\n     * response signalling that the subscription has ended gracefully (server\n     * shutdown). An abrupt transport close carries no response — the client treats\n     * stream-close-without-result as a disconnect.\n     */\n    const SubscriptionsListenResultSchema = z.looseObject({\n        /** Required `_meta` (the subscriptionId stamp); the result body is otherwise empty. */\n        _meta: SubscriptionsListenResultMetaSchema,\n        resultType: ResultTypeSchema.default('complete')\n    });\n\n    /** Dispatch (post-lift) request schemas, keyed by method — registry-internal. */\n    const dispatchRequestSchemas: { readonly [M in Rev2026RequestMethod]: z.ZodType<{ method: M }> } = {\n        'tools/call': dispatchRequest('tools/call', callToolParamsShape),\n        'tools/list': dispatchRequest('tools/list', paginatedParamsShape),\n        'prompts/get': dispatchRequest('prompts/get', {\n            name: z.string(),\n            arguments: z.record(z.string(), z.string()).optional()\n        }),\n        'prompts/list': dispatchRequest('prompts/list', paginatedParamsShape),\n        'resources/list': dispatchRequest('resources/list', paginatedParamsShape),\n        'resources/templates/list': dispatchRequest('resources/templates/list', paginatedParamsShape),\n        'resources/read': dispatchRequest('resources/read', { uri: z.string() }),\n        'completion/complete': dispatchRequest('completion/complete', completeParamsShape),\n        'server/discover': dispatchRequest('server/discover', {}),\n        'subscriptions/listen': dispatchRequest('subscriptions/listen', subscriptionsListenParamsShape)\n    };\n\n    /** Dispatch (post-lift) result schemas, keyed by method — what the funnel\n     * validates AFTER `decodeResult` consumed `resultType`. */\n    function liftedResult<T extends z.core.$ZodLooseShape>(shape: T) {\n        return z.looseObject({ _meta: wireMeta, ...shape });\n    }\n\n    const dispatchResultSchemas: { readonly [M in Rev2026RequestMethod]: z.ZodType } = {\n        'tools/call': liftedResult({\n            content: z.array(ContentBlockSchema),\n            structuredContent: z.unknown().optional(),\n            isError: z.boolean().optional()\n        }),\n        'tools/list': liftedResult({\n            ttlMs: z.number().int().min(0),\n            cacheScope: z.enum(['public', 'private']),\n            tools: z.array(ToolSchema),\n            nextCursor: CursorSchema.optional()\n        }),\n        'prompts/get': liftedResult({\n            description: z.string().optional(),\n            messages: z.array(PromptMessageSchema)\n        }),\n        'prompts/list': liftedResult({\n            ttlMs: z.number().int().min(0),\n            cacheScope: z.enum(['public', 'private']),\n            prompts: z.array(PromptSchema),\n            nextCursor: CursorSchema.optional()\n        }),\n        'resources/list': liftedResult({\n            ttlMs: z.number().int().min(0),\n            cacheScope: z.enum(['public', 'private']),\n            resources: z.array(ResourceSchema),\n            nextCursor: CursorSchema.optional()\n        }),\n        'resources/templates/list': liftedResult({\n            ttlMs: z.number().int().min(0),\n            cacheScope: z.enum(['public', 'private']),\n            resourceTemplates: z.array(ResourceTemplateSchema),\n            nextCursor: CursorSchema.optional()\n        }),\n        'resources/read': liftedResult({\n            ttlMs: z.number().int().min(0),\n            cacheScope: z.enum(['public', 'private']),\n            contents: z.array(z.union([TextResourceContentsSchema, BlobResourceContentsSchema]))\n        }),\n        'completion/complete': liftedResult({\n            completion: z\n                .object({\n                    values: z.array(z.string()).max(100),\n                    total: z.number().int().optional(),\n                    hasMore: z.boolean().optional()\n                })\n                .loose()\n        }),\n        'server/discover': liftedResult({\n            // eslint-disable-next-line unicorn/prefer-top-level-await -- Zod `.catch()`, not a Promise\n            ttlMs: z.number().int().min(0).catch(0),\n            // eslint-disable-next-line unicorn/prefer-top-level-await -- Zod `.catch()`, not a Promise\n            cacheScope: z.enum(['public', 'private']).catch('private'),\n            supportedVersions: z.array(z.string()),\n            capabilities: ServerCapabilities2026Schema,\n            // No body `serverInfo` (spec PR #3002; see DiscoverResultSchema).\n            instructions: z.string().optional()\n        }),\n        // `subscriptions/listen` receives a JSON-RPC result only on a server-side\n        // graceful close (the empty `SubscriptionsListenResult` — `_meta` carries\n        // the subscriptionId stamp). The dispatch result schema stays the lifted\n        // empty body so the mapped type is total; the listen-response demux is\n        // entry-layer (`Client._onresponse`) and never reaches `decodeResult`.\n        'subscriptions/listen': liftedResult({})\n    };\n\n    /* ------------------------------------------------------------------------ *\n     * Notifications. The 2026 notification set: cancelled, progress, message,\n     * resources/updated, resources/list_changed, tools/list_changed,\n     * prompts/list_changed. Deleted: initialized, roots/list_changed,\n     * tasks/status, elicitation/complete (removed from the draft together with\n     * URL-elicitation's elicitationId — both remain 2025-11-25 vocabulary only).\n     * The shapes are revision-identical to the shared schemas, which are\n     * composed by reference, EXCEPT cancelled (forks below: this revision\n     * requires `requestId`) and the 2026-only subscriptions/acknowledged.\n     * ------------------------------------------------------------------------ */\n\n    /**\n     * Notification `_meta` (anchor `NotificationMetaObject`): loose, with the\n     * subscriptions/listen demux key typed when present. Only the anchor-exact\n     * SHAPE is modeled here — listen delivery itself (filter gating, demux,\n     * teardown) is #14 scope and not implemented by this module.\n     */\n    const NotificationMetaSchema = z.looseObject({\n        /**\n         * The JSON-RPC ID of the `subscriptions/listen` request that opened the\n         * stream a notification was delivered on; absent on notifications not\n         * delivered via a subscription stream.\n         */\n        'io.modelcontextprotocol/subscriptionId': RequestIdSchema.optional()\n    });\n\n    /** Anchor SubscriptionsAcknowledgedNotification (2026-only). */\n    const SubscriptionsAcknowledgedNotificationSchema = z.object({\n        method: z.literal('notifications/subscriptions/acknowledged'),\n        params: z.object({\n            _meta: NotificationMetaSchema.optional(),\n            notifications: SubscriptionFilterSchema\n        })\n    });\n\n    /**\n     * 2026-era `notifications/cancelled` params (anchor-exact fork): `requestId`\n     * is REQUIRED on this revision — the shared schema keeps it optional because\n     * the frozen 2025-11-25 shape declares it optional (task cancellation goes\n     * through `tasks/cancel` there). Requiredness is bare because no 2025-era\n     * traffic touches this module.\n     */\n    const CancelledNotificationParamsSchema = z.object({\n        _meta: NotificationMetaSchema.optional(),\n        /**\n         * The ID of the request to cancel. This MUST correspond to the ID of a\n         * request the client previously issued.\n         */\n        requestId: RequestIdSchema,\n        /**\n         * An optional string describing the reason for the cancellation. This MAY\n         * be logged or presented to the user.\n         */\n        reason: z.string().optional()\n    });\n\n    /** 2026-era `notifications/cancelled` (see the params fork above). */\n    const CancelledNotificationSchema = z.object({\n        method: z.literal('notifications/cancelled'),\n        params: CancelledNotificationParamsSchema\n    });\n\n    const notificationSchemas2026: { readonly [M in Rev2026NotificationMethod]: z.ZodType<{ method: M }> } = {\n        'notifications/cancelled': CancelledNotificationSchema,\n        'notifications/progress': ProgressNotificationSchema,\n        'notifications/message': LoggingMessageNotificationSchema,\n        'notifications/resources/updated': ResourceUpdatedNotificationSchema,\n        'notifications/resources/list_changed': ResourceListChangedNotificationSchema,\n        'notifications/tools/list_changed': ToolListChangedNotificationSchema,\n        'notifications/prompts/list_changed': PromptListChangedNotificationSchema,\n        'notifications/subscriptions/acknowledged': SubscriptionsAcknowledgedNotificationSchema\n    };\n\n    /* ------------------------------------------------------------------------ *\n     * Response envelopes (wire-true; parity/corpus artifacts).\n     * ------------------------------------------------------------------------ */\n    const wireResultResponse = <T extends z.ZodType>(result: T) =>\n        z\n            .object({\n                jsonrpc: z.literal('2.0'),\n                id: z.union([z.string(), z.number().int()]),\n                result\n            })\n            .strict();\n\n    const JSONRPCResultResponseSchema = wireResultResponse(ResultSchema);\n    // The multi-round-trip methods may answer with either their final result or an\n    // InputRequiredResult (anchor: `result: CallToolResult | InputRequiredResult`).\n    const CallToolResultResponseSchema = wireResultResponse(z.union([CallToolResultSchema, InputRequiredResultSchema]));\n    const ListToolsResultResponseSchema = wireResultResponse(ListToolsResultSchema);\n    const ListPromptsResultResponseSchema = wireResultResponse(ListPromptsResultSchema);\n    const GetPromptResultResponseSchema = wireResultResponse(z.union([GetPromptResultSchema, InputRequiredResultSchema]));\n    const ListResourcesResultResponseSchema = wireResultResponse(ListResourcesResultSchema);\n    const ListResourceTemplatesResultResponseSchema = wireResultResponse(ListResourceTemplatesResultSchema);\n    const ReadResourceResultResponseSchema = wireResultResponse(z.union([ReadResourceResultSchema, InputRequiredResultSchema]));\n    const CompleteResultResponseSchema = wireResultResponse(CompleteResultSchema);\n    const DiscoverResultResponseSchema = wireResultResponse(DiscoverResultSchema);\n    const SubscriptionsListenResultResponseSchema = wireResultResponse(SubscriptionsListenResultSchema);\n\n    return {\n        JSONValueSchema,\n        JSONObjectSchema,\n        ProgressTokenSchema,\n        CursorSchema,\n        RequestIdSchema,\n        RoleSchema,\n        LoggingLevelSchema,\n        TaskMetadataSchema,\n        RelatedTaskMetadataSchema,\n        RequestMetaSchema,\n        BaseRequestParamsSchema,\n        TaskAugmentedRequestParamsSchema,\n        NotificationsParamsSchema,\n        NotificationSchema,\n        IconSchema,\n        IconsSchema,\n        BaseMetadataSchema,\n        ImplementationSchema,\n        ClientTasksCapabilitySchema,\n        ServerTasksCapabilitySchema,\n        ClientCapabilitiesSchema,\n        ServerCapabilitiesSchema,\n        ProgressSchema,\n        ProgressNotificationParamsSchema,\n        ProgressNotificationSchema,\n        LoggingMessageNotificationParamsSchema,\n        LoggingMessageNotificationSchema,\n        ResourceContentsSchema,\n        TextResourceContentsSchema,\n        BlobResourceContentsSchema,\n        AnnotationsSchema,\n        ResourceSchema,\n        ResourceTemplateSchema,\n        ResourceListChangedNotificationSchema,\n        ResourceUpdatedNotificationParamsSchema,\n        ResourceUpdatedNotificationSchema,\n        PromptArgumentSchema,\n        PromptSchema,\n        PromptListChangedNotificationSchema,\n        TextContentSchema,\n        ImageContentSchema,\n        AudioContentSchema,\n        ToolUseContentSchema,\n        EmbeddedResourceSchema,\n        ResourceLinkSchema,\n        ContentBlockSchema,\n        PromptMessageSchema,\n        ToolAnnotationsSchema,\n        ToolListChangedNotificationSchema,\n        ModelHintSchema,\n        ModelPreferencesSchema,\n        ToolChoiceSchema,\n        BooleanSchemaSchema,\n        StringSchemaSchema,\n        NumberSchemaSchema,\n        UntitledSingleSelectEnumSchemaSchema,\n        TitledSingleSelectEnumSchemaSchema,\n        LegacyTitledEnumSchemaSchema,\n        SingleSelectEnumSchemaSchema,\n        UntitledMultiSelectEnumSchemaSchema,\n        TitledMultiSelectEnumSchemaSchema,\n        MultiSelectEnumSchemaSchema,\n        EnumSchemaSchema,\n        PrimitiveSchemaDefinitionSchema,\n        ElicitRequestFormParamsSchema,\n        ResourceTemplateReferenceSchema,\n        PromptReferenceSchema,\n        RootSchema,\n        ClientCapabilities2026Schema,\n        ServerCapabilities2026Schema,\n        RequestMetaEnvelopeSchema,\n        ToolSchema,\n        ToolResultContentSchema,\n        SamplingMessageContentBlockSchema,\n        SamplingMessageSchema,\n        ResultTypeSchema,\n        ResultMetaSchema,\n        ResultSchema,\n        PaginatedResultSchema,\n        CallToolResultSchema,\n        ListToolsResultSchema,\n        ListPromptsResultSchema,\n        GetPromptResultSchema,\n        ListResourcesResultSchema,\n        ListResourceTemplatesResultSchema,\n        ReadResourceResultSchema,\n        CompleteResultSchema,\n        CacheableResultSchema,\n        DiscoverResultSchema,\n        CreateMessageRequestParamsSchema,\n        CreateMessageRequestSchema,\n        ListRootsRequestSchema,\n        CreateMessageResultSchema,\n        ListRootsResultSchema,\n        ElicitResultSchema,\n        ElicitRequestURLParamsSchema,\n        ElicitRequestParamsSchema,\n        ElicitRequestSchema,\n        InputRequestSchema,\n        InputResponseSchema,\n        InputRequestsSchema,\n        InputResponsesSchema,\n        InputRequiredResultSchema,\n        InputResponseRequestParamsSchema,\n        CallToolRequestSchema,\n        ListToolsRequestSchema,\n        ListPromptsRequestSchema,\n        GetPromptRequestSchema,\n        ListResourcesRequestSchema,\n        ListResourceTemplatesRequestSchema,\n        ReadResourceRequestSchema,\n        CompleteRequestSchema,\n        DiscoverRequestSchema,\n        SubscriptionFilterSchema,\n        SubscriptionsListenRequestSchema,\n        SubscriptionsListenResultMetaSchema,\n        SubscriptionsListenResultSchema,\n        dispatchRequestSchemas,\n        dispatchResultSchemas,\n        NotificationMetaSchema,\n        SubscriptionsAcknowledgedNotificationSchema,\n        CancelledNotificationParamsSchema,\n        CancelledNotificationSchema,\n        notificationSchemas2026,\n        JSONRPCResultResponseSchema,\n        CallToolResultResponseSchema,\n        ListToolsResultResponseSchema,\n        ListPromptsResultResponseSchema,\n        GetPromptResultResponseSchema,\n        ListResourcesResultResponseSchema,\n        ListResourceTemplatesResultResponseSchema,\n        ReadResourceResultResponseSchema,\n        CompleteResultResponseSchema,\n        DiscoverResultResponseSchema,\n        SubscriptionsListenResultResponseSchema\n    };\n}\n\n/** The full set of frozen 2026-07-28 wire schemas, as one built object (the memo target). */\nexport type Rev2026WireSchemas = ReturnType<typeof build>;\n\nlet memo: Rev2026WireSchemas | undefined;\n\n/**\n * Builds the era wire-schema set on first call and returns the same object\n * thereafter. Module evaluation stays construction-free so importing the\n * era codec/registry costs nothing until the first validation actually\n * needs a schema; the registry, the codec, and the eager `schemas.ts`\n * shim all pull through this memo, so reference identity holds across\n * every consumer.\n */\nexport function buildSchemas2026(): Rev2026WireSchemas {\n    return (memo ??= build());\n}\n","/**\n * Cache-hint plumbing for cacheable results (protocol revision 2026-07-28).\n *\n * The 2026-07-28 revision requires `ttlMs`/`cacheScope` on the cacheable\n * result types (SEP-2549 `CacheableResult`). The values are resolved at the\n * era-aware encode seam (the 2026 wire codec's `encodeResult`), most specific\n * author first:\n *\n *   1. fields the handler returned on the result itself (when valid),\n *   2. a configured cache hint attached by the server layer\n *      (per-registration hint, then the server-level per-operation hint,\n *      combined per field — see {@linkcode attachCacheHintFallback}),\n *   3. the conservative defaults `{ ttlMs: 0, cacheScope: 'private' }`.\n *\n * The configured hint travels from the (era-blind) server configuration to the\n * (era-aware) encode seam on a symbol-keyed property of the result object —\n * {@linkcode RESULT_CACHE_HINT_FALLBACK}. Symbol-keyed properties are never\n * serialized to JSON, so attaching a hint can never change what a 2025-era\n * response looks like on the wire: only the 2026-era codec reads (and removes)\n * it while filling the required fields. The 2025-era codec has no cache code\n * path at all.\n */\n\n/** The cache scopes defined for cacheable results (SEP-2549). */\nexport type CacheScope = 'public' | 'private';\n\n/**\n * A cache hint for a cacheable result (protocol revision 2026-07-28): the\n * values to emit for `ttlMs` / `cacheScope` when the handler does not provide\n * them itself. Absent fields fall back to the conservative defaults\n * (`ttlMs: 0`, `cacheScope: 'private'`).\n */\nexport interface CacheHint {\n    /** Cache lifetime in milliseconds. Must be a non-negative safe integer. */\n    ttlMs?: number;\n    /** Whether the result may be cached by shared caches (`public`) or only by the requesting client (`private`). */\n    cacheScope?: CacheScope;\n}\n\n/**\n * The operations whose results are cacheable on the 2026-07-28 revision (the\n * `CacheableResult` extenders). This list is closed: no other operation's\n * result ever receives cache fields from the SDK.\n */\nexport const CACHEABLE_RESULT_METHODS = [\n    'tools/list',\n    'prompts/list',\n    'resources/list',\n    'resources/templates/list',\n    'resources/read',\n    'server/discover'\n] as const;\n\n/** A method whose result is cacheable on the 2026-07-28 revision. */\nexport type CacheableResultMethod = (typeof CACHEABLE_RESULT_METHODS)[number];\n\n/** Whether the given method's result is cacheable on the 2026-07-28 revision. */\nexport function isCacheableResultMethod(method: string): method is CacheableResultMethod {\n    return (CACHEABLE_RESULT_METHODS as readonly string[]).includes(method);\n}\n\n/**\n * The symbol-keyed carrier for a configured cache hint on a result object.\n * Symbol properties are invisible to JSON serialization, so the carrier can be\n * attached era-blind: only the 2026-era encode seam consumes it.\n */\nexport const RESULT_CACHE_HINT_FALLBACK: unique symbol = Symbol('modelcontextprotocol.resultCacheHintFallback');\n\n/** A result object that may carry a configured cache-hint fallback. */\ninterface CacheHintCarrier {\n    [RESULT_CACHE_HINT_FALLBACK]?: CacheHint;\n}\n\n/**\n * Attaches a configured cache hint to a result as the encode-time fallback.\n * Returns the result unchanged when there is nothing to attach. When a more\n * specific hint is already attached, the two hints are combined per field\n * (most-specific-author-wins for each of `ttlMs` and `cacheScope`): the\n * per-registration hint attached by the feature layer keeps every field it\n * sets, and the server-level per-operation hint only fills the fields the\n * more specific hint leaves unset.\n */\nexport function attachCacheHintFallback<T extends object>(result: T, hint: CacheHint | undefined): T {\n    if (hint === undefined) {\n        return result;\n    }\n    const attached = (result as CacheHintCarrier)[RESULT_CACHE_HINT_FALLBACK];\n    if (attached === undefined) {\n        return { ...result, [RESULT_CACHE_HINT_FALLBACK]: hint };\n    }\n    const merged: CacheHint = {};\n    const ttlMs = attached.ttlMs ?? hint.ttlMs;\n    if (ttlMs !== undefined) {\n        merged.ttlMs = ttlMs;\n    }\n    const cacheScope = attached.cacheScope ?? hint.cacheScope;\n    if (cacheScope !== undefined) {\n        merged.cacheScope = cacheScope;\n    }\n    return { ...result, [RESULT_CACHE_HINT_FALLBACK]: merged };\n}\n\n/** Reads the configured cache-hint fallback attached to a result, if any. */\nexport function cacheHintFallbackOf(result: object): CacheHint | undefined {\n    return (result as CacheHintCarrier)[RESULT_CACHE_HINT_FALLBACK];\n}\n\n/**\n * Whether a value is a valid `ttlMs`: a non-negative safe integer. Safe\n * integers are required because the wire schemas validate `ttlMs` as an\n * integer within `Number.MIN_SAFE_INTEGER`/`Number.MAX_SAFE_INTEGER`; a value\n * outside that range is treated as invalid here so it falls through to the\n * next author instead of being emitted and rejected downstream.\n */\nexport function isValidCacheTtlMs(value: unknown): value is number {\n    return typeof value === 'number' && Number.isSafeInteger(value) && value >= 0;\n}\n\n/** Whether a value is a valid `cacheScope`. */\nexport function isValidCacheScope(value: unknown): value is CacheScope {\n    return value === 'public' || value === 'private';\n}\n\n/**\n * Validates a configured cache hint at configuration time. Throws a\n * `RangeError` naming the offending field, so misconfiguration fails at\n * startup/registration rather than silently degrading at encode time.\n */\nexport function assertValidCacheHint(hint: CacheHint, context: string): void {\n    if (hint.ttlMs !== undefined && !isValidCacheTtlMs(hint.ttlMs)) {\n        throw new RangeError(`Invalid cache hint for ${context}: ttlMs must be a non-negative safe integer (got ${String(hint.ttlMs)})`);\n    }\n    if (hint.cacheScope !== undefined && !isValidCacheScope(hint.cacheScope)) {\n        throw new RangeError(\n            `Invalid cache hint for ${context}: cacheScope must be 'public' or 'private' (got ${String(hint.cacheScope)})`\n        );\n    }\n}\n","/**\n * Error codes for protocol errors that cross the wire as JSON-RPC error responses.\n * These follow the JSON-RPC specification and MCP-specific extensions.\n */\nexport enum ProtocolErrorCode {\n    // Standard JSON-RPC error codes\n    ParseError = -32_700,\n    InvalidRequest = -32_600,\n    MethodNotFound = -32_601,\n    InvalidParams = -32_602,\n    InternalError = -32_603,\n\n    // MCP-specific error codes\n    /**\n     * Resource not found.\n     *\n     * Receive-tolerated only: the SDK never EMITS `-32002` — `resources/read`\n     * misses answer `-32602` (Invalid Params) on every protocol revision per\n     * the 2026-07-28 spec MUST, and a handler-thrown `-32002` is mapped to\n     * `-32602` at the era encode seam. The member stays importable so clients\n     * can recognise `-32002` from peers built on earlier SDK releases (the\n     * spec's \"clients SHOULD also accept `-32002`\" backwards-compatibility\n     * clause). Throw `ResourceNotFoundError` instead.\n     */\n    ResourceNotFound = -32_002,\n    /**\n     * Processing the request requires a capability the client did not declare\n     * in the request's `clientCapabilities` (protocol revision 2026-07-28).\n     */\n    MissingRequiredClientCapability = -32_021,\n    /**\n     * The request's protocol version is unknown to the server or unsupported\n     * by it (protocol revision 2026-07-28).\n     */\n    UnsupportedProtocolVersion = -32_022,\n    UrlElicitationRequired = -32_042\n}\n","import { brandedHasInstance, stampErrorBrands } from '../errors/crossBundleBrand';\nimport { ProtocolErrorCode } from './enums';\nimport type {\n    ClientCapabilities,\n    ElicitRequestURLParams,\n    MissingRequiredClientCapabilityErrorData,\n    UnsupportedProtocolVersionErrorData\n} from './types';\n\n/**\n * Protocol errors are JSON-RPC errors that cross the wire as error responses.\n * They use numeric error codes from the {@linkcode ProtocolErrorCode} enum.\n *\n * `instanceof` on this class (and its subclasses) is brand-matched, so it works\n * across separately bundled copies of the SDK — e.g. an error constructed by\n * `@modelcontextprotocol/client` matches the class re-exported by\n * `@modelcontextprotocol/server` in the same process.\n */\nexport class ProtocolError extends Error {\n    static {\n        Object.defineProperty(this, 'mcpBrand', { value: 'mcp.ProtocolError' });\n    }\n\n    static override [Symbol.hasInstance](value: unknown): boolean {\n        return brandedHasInstance(this, value);\n    }\n\n    /**\n     * Brand-based type guard: equivalent to `value instanceof this`, as an\n     * explicit static predicate (the axios/AWS-SDK `isInstance` style). Reads\n     * the caller's own brand via `this`, so every branded subclass gets a\n     * correctly-scoped guard by inheritance. Must be invoked on the class —\n     * in callback position write `v => SdkError.isInstance(v)`, not\n     * `.filter(SdkError.isInstance)` (detached calls throw rather than\n     * silently matching nothing).\n     */\n    static isInstance<T extends abstract new (...args: never[]) => unknown>(this: T, value: unknown): value is InstanceType<T> {\n        if (typeof this !== 'function') {\n            throw new TypeError(\n                'isInstance must be called on the class (e.g. `SdkError.isInstance(value)`); for callbacks use `v => SdkError.isInstance(v)`'\n            );\n        }\n        return brandedHasInstance(this, value);\n    }\n\n    constructor(\n        public readonly code: number,\n        message: string,\n        public readonly data?: unknown\n    ) {\n        super(message);\n        this.name = 'ProtocolError';\n        stampErrorBrands(this, new.target);\n    }\n\n    /**\n     * Factory method to create the appropriate error type based on the error code and data\n     */\n    static fromError(code: number, message: string, data?: unknown): ProtocolError {\n        // Check for specific error types\n        if (code === ProtocolErrorCode.UrlElicitationRequired && data) {\n            const errorData = data as { elicitations?: unknown[] };\n            if (errorData.elicitations) {\n                return new UrlElicitationRequiredError(errorData.elicitations as ElicitRequestURLParams[], message);\n            }\n        }\n\n        if (code === ProtocolErrorCode.UnsupportedProtocolVersion && data) {\n            const errorData = data as Partial<UnsupportedProtocolVersionErrorData>;\n            if (Array.isArray(errorData.supported) && typeof errorData.requested === 'string') {\n                return new UnsupportedProtocolVersionError({ supported: errorData.supported, requested: errorData.requested }, message);\n            }\n        }\n\n        // Resource not found is recognised on BOTH the spec-mandated −32602 and\n        // the legacy −32002 (the spec's \"clients SHOULD also accept −32002\"\n        // backwards-compatibility clause). On −32602 the data-shape parse is\n        // narrowed to \"exactly `{ uri: string }` and nothing else\": a server's\n        // own Invalid Params that happens to carry `data.uri` alongside other\n        // keys (e.g. `{ uri, reason: 'uri must be https' }`) stays a generic\n        // ProtocolError. On −32002 the code itself is the discriminator, so any\n        // `data.uri` string suffices.\n        if (code === ProtocolErrorCode.InvalidParams || code === ProtocolErrorCode.ResourceNotFound) {\n            const errorData = data as Record<string, unknown> | undefined;\n            if (\n                typeof errorData?.uri === 'string' &&\n                (code === ProtocolErrorCode.ResourceNotFound || Object.keys(errorData).length === 1)\n            ) {\n                return new ResourceNotFoundError(errorData.uri, message);\n            }\n        }\n\n        if (code === ProtocolErrorCode.MissingRequiredClientCapability && data) {\n            const errorData = data as Partial<MissingRequiredClientCapabilityErrorData>;\n            if (\n                errorData.requiredCapabilities !== null &&\n                typeof errorData.requiredCapabilities === 'object' &&\n                !Array.isArray(errorData.requiredCapabilities)\n            ) {\n                return new MissingRequiredClientCapabilityError({ requiredCapabilities: errorData.requiredCapabilities }, message);\n            }\n        }\n\n        // Default to generic ProtocolError\n        return new ProtocolError(code, message, data);\n    }\n}\n\n/**\n * Error type for a `resources/read` miss: the requested resource does not\n * exist. The wire code is `-32602` (Invalid Params) on every protocol\n * revision — the spec MUST for revision 2026-07-28, and the value the v1.x\n * SDK has always emitted on earlier revisions. The error data echoes the\n * requested URI.\n *\n * Recognise this error by checking `error.data` is exactly `{ uri: string }`\n * (a `-32602` whose data carries `uri` and nothing else is resource-not-found;\n * any other `-32602` is an ordinary Invalid Params). For backwards compatibility, clients should also\n * accept `-32002` as resource not found — earlier SDK builds emitted that\n * code, and {@linkcode ProtocolError.fromError} reconstructs this class for\n * either code **when `error.data` carries `uri`** (a bare `-32002` without\n * `data.uri` stays a generic {@linkcode ProtocolError}). `instanceof` checks\n * are brand-matched and work across separately bundled copies of the SDK.\n */\nexport class ResourceNotFoundError extends ProtocolError {\n    static {\n        Object.defineProperty(this, 'mcpBrand', { value: 'mcp.ResourceNotFoundError' });\n    }\n\n    constructor(uri: string, message: string = `Resource not found: ${uri}`) {\n        super(ProtocolErrorCode.InvalidParams, message, { uri });\n    }\n\n    /** The URI that was requested and not found. */\n    get uri(): string {\n        return (this.data as { uri: string }).uri;\n    }\n}\n\n/**\n * Specialized error type when a tool requires a URL mode elicitation.\n * 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.\n */\nexport class UrlElicitationRequiredError extends ProtocolError {\n    static {\n        Object.defineProperty(this, 'mcpBrand', { value: 'mcp.UrlElicitationRequiredError' });\n    }\n\n    constructor(elicitations: ElicitRequestURLParams[], message: string = `URL elicitation${elicitations.length > 1 ? 's' : ''} required`) {\n        super(ProtocolErrorCode.UrlElicitationRequired, message, {\n            elicitations: elicitations\n        });\n    }\n\n    get elicitations(): ElicitRequestURLParams[] {\n        return (this.data as { elicitations: ElicitRequestURLParams[] })?.elicitations ?? [];\n    }\n}\n\n/**\n * Error type for the `-32022` UnsupportedProtocolVersion protocol error (protocol\n * revision 2026-07-28): the request's protocol version is unknown to the server or\n * unsupported by it.\n *\n * The error data lists the protocol versions the receiver supports (`supported`),\n * so the sender can choose a mutually supported version and retry, and echoes the\n * version that was requested (`requested`).\n */\nexport class UnsupportedProtocolVersionError extends ProtocolError {\n    static {\n        Object.defineProperty(this, 'mcpBrand', { value: 'mcp.UnsupportedProtocolVersionError' });\n    }\n\n    constructor(data: UnsupportedProtocolVersionErrorData, message: string = `Unsupported protocol version: ${data.requested}`) {\n        super(ProtocolErrorCode.UnsupportedProtocolVersion, message, data);\n    }\n\n    /**\n     * Protocol versions the receiver supports.\n     */\n    get supported(): string[] {\n        return (this.data as UnsupportedProtocolVersionErrorData).supported;\n    }\n\n    /**\n     * The protocol version that was requested.\n     */\n    get requested(): string {\n        return (this.data as UnsupportedProtocolVersionErrorData).requested;\n    }\n}\n\n/**\n * Error type for the `-32021` MissingRequiredClientCapability protocol error\n * (protocol revision 2026-07-28): processing the request requires a capability\n * the client did not declare in the request's `clientCapabilities`.\n *\n * The error data lists the missing capabilities (`requiredCapabilities`) in\n * the `ClientCapabilities` shape, so the client can see exactly what it would\n * have to declare for the request to be served. On HTTP, the response status\n * is `400 Bad Request`.\n *\n * Recognize this error by its code and `data.requiredCapabilities`, or by\n * `instanceof` — checks are brand-matched and work across separately bundled\n * copies of the SDK.\n */\nexport class MissingRequiredClientCapabilityError extends ProtocolError {\n    static {\n        Object.defineProperty(this, 'mcpBrand', { value: 'mcp.MissingRequiredClientCapabilityError' });\n    }\n\n    constructor(\n        data: MissingRequiredClientCapabilityErrorData,\n        message: string = `Missing required client capabilities: ${Object.keys(data.requiredCapabilities).join(', ')}`\n    ) {\n        super(ProtocolErrorCode.MissingRequiredClientCapability, message, data);\n    }\n\n    /**\n     * The capabilities the server requires from the client to process the\n     * request (only the missing capabilities are listed).\n     */\n    get requiredCapabilities(): ClientCapabilities {\n        return (this.data as MissingRequiredClientCapabilityErrorData).requiredCapabilities;\n    }\n}\n","/**\n * The outbound result encode contract for the 2026-07-28 wire codec, as pure,\n * individually-testable steps. `encodeResult` applies them in order:\n *\n *  1. {@linkcode stampResultType} — the `resultType` discriminator. The SDK\n *     stamps `'complete'`; a handler-provided value passes through only for\n *     methods whose spec result vocabulary goes beyond `'complete'` (the\n *     multi round-trip request methods, whose results may be\n *     `input_required`). A non-`'complete'` value returned by a handler for\n *     any other method is a server bug and fails loudly (internal error)\n *     rather than being mis-typed on the wire.\n *  2. {@linkcode fillCacheFields} — the required `ttlMs`/`cacheScope` fields\n *     on cacheable results (SEP-2549), filled only when the post-stamp\n *     `resultType` is `'complete'` and the method is one of the cacheable\n *     operations. Resolution is most-specific-author-first: valid\n *     handler-returned values, then the configured cache hint attached by the\n *     server layer, then the conservative defaults\n *     `{ ttlMs: 0, cacheScope: 'private' }`. Invalid handler-returned values\n *     never reach the wire — they fall through to the next author.\n *  3. {@linkcode stampServerInfoMeta} — the `_meta` serverInfo key on every\n *     result (spec PR #3002: servers SHOULD identify themselves on every\n *     response). A handler-authored value wins; without a supplied identity\n *     the step is the identity function.\n *\n * Ordering matters and is pinned by tests: the stamp runs before the fill, so\n * an `input_required` result is never given cache fields.\n */\nimport type { CacheHint } from '../../shared/resultCacheHints';\nimport {\n    cacheHintFallbackOf,\n    isCacheableResultMethod,\n    isValidCacheScope,\n    isValidCacheTtlMs,\n    RESULT_CACHE_HINT_FALLBACK\n} from '../../shared/resultCacheHints';\nimport { SERVER_INFO_META_KEY } from '../../types/constants';\nimport { ProtocolErrorCode } from '../../types/enums';\nimport { ProtocolError } from '../../types/errors';\nimport type { Implementation, Result } from '../../types/types';\n\n/** The default cache policy when neither the handler nor configuration provides one. */\nexport const DEFAULT_CACHE_TTL_MS = 0;\nexport const DEFAULT_CACHE_SCOPE = 'private';\n\n/**\n * Request methods whose spec result vocabulary goes beyond `'complete'` on the\n * 2026-07-28 revision: their results may be `input_required` (multi\n * round-trip requests), so a handler-provided `resultType` passes through the\n * stamp untouched. `subscriptions/listen` is NOT in this set: it never emits\n * a JSON-RPC result — termination is stream close (HTTP) or\n * `notifications/cancelled` (stdio) per the spec.\n */\nexport const EXTENDED_RESULT_TYPE_METHODS: readonly string[] = ['tools/call', 'prompts/get', 'resources/read'];\n\n/**\n * Step 1 of the encode contract: ensure the outbound result carries the\n * required `resultType` discriminator.\n *\n * - No handler-provided value → stamp `'complete'`.\n * - Handler-provided `'complete'` → kept as-is.\n * - Handler-provided non-`'complete'` value on a method whose vocabulary\n *   allows it ({@linkcode EXTENDED_RESULT_TYPE_METHODS}) → passes through.\n *   The value is forwarded verbatim — the wire vocabulary is an open union and\n *   the SDK does not validate the string, so emitting a `resultType` the\n *   negotiated revision does not define is the handler author's\n *   responsibility.\n * - Handler-provided non-`'complete'` value on any other method → internal\n *   error (loud): the value would be mis-typed on the wire, and silently\n *   rewriting it would hide a server bug.\n */\nexport function stampResultType(method: string, result: Result): Result {\n    const provided = (result as Record<string, unknown>)['resultType'];\n    if (provided === undefined) {\n        return { ...result, resultType: 'complete' } as Result;\n    }\n    if (provided === 'complete') {\n        return result;\n    }\n    if (EXTENDED_RESULT_TYPE_METHODS.includes(method)) {\n        return result;\n    }\n    throw new ProtocolError(\n        ProtocolErrorCode.InternalError,\n        `Handler for ${method} returned resultType '${String(provided)}', but results of ${method} only support 'complete' on protocol revision 2026-07-28`\n    );\n}\n\n/**\n * Step 2 of the encode contract: fill the required `ttlMs`/`cacheScope` fields\n * on cacheable results.\n *\n * Applies only when the (post-stamp) `resultType` is `'complete'` and the\n * method is one of the cacheable operations; everything else is returned\n * untouched apart from removing the configured-hint carrier. Field resolution\n * is per field, most specific author first: a valid handler-returned value,\n * then the configured cache hint attached by the server layer, then the\n * defaults. Handler-returned values are validated at encode time (`ttlMs`\n * must be a non-negative integer, `cacheScope` must be `'public'` or\n * `'private'`); invalid values are ignored rather than emitted.\n */\nexport function fillCacheFields(method: string, result: Result): Result {\n    const fallback = cacheHintFallbackOf(result);\n    const resultType = (result as Record<string, unknown>)['resultType'];\n\n    if (resultType !== 'complete' || !isCacheableResultMethod(method)) {\n        // Not a cache-fill target. Drop the configured-hint carrier if one was\n        // attached so it never travels past the encode seam.\n        return fallback === undefined ? result : stripCacheHintFallback(result);\n    }\n\n    const provided = result as Record<string, unknown>;\n    const ttlMs = isValidCacheTtlMs(provided['ttlMs']) ? (provided['ttlMs'] as number) : resolveTtlMs(fallback);\n    const cacheScope = isValidCacheScope(provided['cacheScope']) ? (provided['cacheScope'] as string) : resolveCacheScope(fallback);\n\n    const filled = { ...provided, ttlMs, cacheScope } as Record<string | symbol, unknown>;\n    delete filled[RESULT_CACHE_HINT_FALLBACK];\n    return filled as Result;\n}\n\nfunction isPlainObject(value: unknown): value is Record<string, unknown> {\n    return value !== null && typeof value === 'object' && !Array.isArray(value);\n}\n\n/**\n * Step 3 of the encode contract: stamp the server's identity into the\n * result's `_meta` under `io.modelcontextprotocol/serverInfo` (spec PR #3002:\n * servers SHOULD include it on every response).\n *\n * - No `serverInfo` supplied (a client instance, or a hand-constructed\n *   protocol object) → identity function.\n * - The result's `_meta` already carries the key → kept as-is (the handler\n *   is the more specific author; mirrors the cache-fill resolution order).\n * - A present-but-non-object `_meta` (a dynamic-caller bug) → kept as-is:\n *   the stamp never rewrites handler material, and the malformed value fails\n *   loudly at the peer instead of being silently replaced here.\n * - Otherwise → the key is added, preserving any other `_meta` entries.\n *\n * Runs for every result regardless of `resultType`: the anchor types\n * `Result._meta` as `ResultMetaObject` on all results, `input_required`\n * included.\n */\nexport function stampServerInfoMeta(result: Result, serverInfo: Implementation | undefined): Result {\n    if (serverInfo === undefined) return result;\n    const meta = (result as Record<string, unknown>)['_meta'];\n    if (meta === undefined) {\n        return { ...result, _meta: { [SERVER_INFO_META_KEY]: serverInfo } } as Result;\n    }\n    if (!isPlainObject(meta)) return result;\n    // Value check, not `in`: a present-but-undefined key (an unset optional in\n    // handler code) must not suppress the stamp — JSON would drop the key and\n    // the response would ship with no identity at all.\n    if (meta[SERVER_INFO_META_KEY] !== undefined) return result;\n    return { ...result, _meta: { ...meta, [SERVER_INFO_META_KEY]: serverInfo } } as Result;\n}\n\nfunction resolveTtlMs(fallback: CacheHint | undefined): number {\n    return fallback !== undefined && isValidCacheTtlMs(fallback.ttlMs) ? fallback.ttlMs : DEFAULT_CACHE_TTL_MS;\n}\n\nfunction resolveCacheScope(fallback: CacheHint | undefined): string {\n    return fallback !== undefined && isValidCacheScope(fallback.cacheScope) ? fallback.cacheScope : DEFAULT_CACHE_SCOPE;\n}\n\nfunction stripCacheHintFallback(result: Result): Result {\n    const copy = { ...result } as Record<string | symbol, unknown>;\n    delete copy[RESULT_CACHE_HINT_FALLBACK];\n    return copy as Result;\n}\n","/**\n * In-band input-request vocabulary of the 2026-07-28 revision (SEP-2322\n * multi round-trip requests), dispatch view.\n *\n * The three former server→client wire requests (`elicitation/create`,\n * `sampling/createMessage`, `roots/list`) are NOT wire request methods on\n * this revision — they are demoted to de-JSON-RPC'd payloads embedded in an\n * `input_required` result. The multi-round-trip driver dispatches those\n * embedded payloads to the client's registered handlers through the normal\n * handler machinery, and these are the schemas that dispatch parses them\n * with: lenient where the anchor's wire-true artifacts are strict (an\n * embedded request never carries the per-request `_meta` envelope), exact\n * where the vocabulary forks (the sampling shapes compose the forked\n * SamplingMessage/Tool payloads).\n *\n * Registry membership is intentionally NOT granted here — these methods stay\n * absent from the 2026-era request registry (a peer sending one as a wire\n * request still gets −32601 by absence). Only the codec's\n * `inputRequestSchema`/`inputResponseSchema` accessors expose them.\n */\nimport * as z from 'zod/v4';\n\nimport type { RequestMethod, RequestTypeMap, ResultTypeMap } from '../../types/types';\nimport { buildSchemas2026 } from './buildSchemas';\n\n/** The embedded input-request methods of the 2026-07-28 revision. */\nexport const INPUT_REQUEST_METHODS_2026 = ['elicitation/create', 'sampling/createMessage', 'roots/list'] as const;\n\nexport type InputRequestMethod2026 = (typeof INPUT_REQUEST_METHODS_2026)[number];\n\n/* The embedded-request maps are built lazily through the era's memoized\n * schema factory (`buildSchemas2026`) so importing this module constructs no\n * zod schemas; the maps themselves are memoized alongside. */\ninterface InputSchemaMaps {\n    /** Dispatch-time (lenient) embedded request schemas, keyed by method. */\n    readonly request: Record<InputRequestMethod2026, z.ZodType>;\n    /** Embedded (bare) response schemas, keyed by the request method they answer. */\n    readonly response: Record<InputRequestMethod2026, z.ZodType>;\n}\n\nlet maps: InputSchemaMaps | undefined;\n\nfunction inputSchemaMaps(): InputSchemaMaps {\n    if (maps) return maps;\n    const s = buildSchemas2026();\n    maps = {\n        request: {\n            'elicitation/create': z.object({\n                method: z.literal('elicitation/create'),\n                params: s.ElicitRequestParamsSchema\n            }),\n            'sampling/createMessage': z.object({\n                method: z.literal('sampling/createMessage'),\n                params: s.CreateMessageRequestParamsSchema\n            }),\n            'roots/list': z.object({\n                method: z.literal('roots/list'),\n                params: z.looseObject({}).optional()\n            })\n        },\n        response: {\n            'elicitation/create': s.ElicitResultSchema,\n            'sampling/createMessage': s.CreateMessageResultSchema,\n            'roots/list': s.ListRootsResultSchema\n        }\n    };\n    return maps;\n}\n\n/**\n * Forces the lazy embedded-request maps (and, through them, the era's schema\n * memo). Warm-up hook for `preloadSchemas()` — no-op once the maps exist.\n */\nexport function warmInputSchemaMaps2026(): void {\n    inputSchemaMaps();\n}\n\nexport function isInputRequestMethod2026(method: string): method is InputRequestMethod2026 {\n    return (INPUT_REQUEST_METHODS_2026 as readonly string[]).includes(method);\n}\n\n/**\n * Gets the dispatch (lenient) schema for an embedded input request, or\n * `undefined` for methods that are not in-band vocabulary on this era.\n * The typed overload mirrors `WireCodec.inputRequestSchema`.\n */\nexport function getInputRequestSchema2026<M extends RequestMethod>(method: M): z.ZodType<RequestTypeMap[M]> | undefined;\nexport function getInputRequestSchema2026(method: string): z.ZodType | undefined;\nexport function getInputRequestSchema2026(method: string): z.ZodType | undefined {\n    return isInputRequestMethod2026(method) ? inputSchemaMaps().request[method] : undefined;\n}\n\n/**\n * Gets the bare embedded-response schema answering an embedded input request,\n * or `undefined` for methods that are not in-band vocabulary on this era.\n */\nexport function getInputResponseSchema2026<M extends RequestMethod>(method: M): z.ZodType<ResultTypeMap[M]> | undefined;\nexport function getInputResponseSchema2026(method: string): z.ZodType | undefined;\nexport function getInputResponseSchema2026(method: string): z.ZodType | undefined {\n    return isInputRequestMethod2026(method) ? inputSchemaMaps().response[method] : undefined;\n}\n","/**\n * The 2026-era method registries (protocol revision 2026-07-28).\n *\n * Registry membership IS the deletion story: there are NO entries for\n * `initialize`, `notifications/initialized`, `ping`, `logging/setLevel`,\n * `resources/subscribe`, `resources/unsubscribe`,\n * `notifications/roots/list_changed`, `notifications/elicitation/complete`\n * (removed from the draft schema; 2025-11-25-only vocabulary), the task\n * family, or the server→client wire-request channel — so an era-mismatched\n * method falls to −32601 by absence inbound and a typed local error outbound,\n * with no table to forget.\n *\n * HAND-REGISTRY SEED DECISIONS (pinned by the CI registry-diff oracle, which\n * fails LOUD if this list and the anchor diff ever disagree):\n * - `sampling/createMessage`, `elicitation/create`, `roots/list`: the anchor\n *   still carries their method literals on bare interfaces, but 2026 DEMOTES\n *   them from wire requests to in-band `InputRequest` payloads — the entire\n *   server→client JSON-RPC request channel is deleted (`ServerRequest` has\n *   no 2026 export). A generator walking method literals would re-admit them\n *   (the ATK-D flavor-b trap); this hand registry excludes them by\n *   construction. Their in-band role lands with the MRTR driver (#13).\n * - `subscriptions/listen` + `notifications/subscriptions/acknowledged`\n *   (SEP-1865): 2026-only vocabulary, present here as registry shells.\n *   Dispatch never reaches a registered handler — the serving entries\n *   (`createMcpHandler`, `serveStdio`) recognize listen at the entry layer\n *   and own ack/filter/stamp/teardown themselves; on the client side\n *   `Client.listen()` sends directly on the transport (string-typed\n *   request id, transport-level demux) rather than via `request()`.\n *\n * LAZY SCHEMA CONSTRUCTION: method membership and the exported method lists\n * are static (null-valued key objects below, mapped over the hand-registry\n * unions so drift is a compile error in both directions), while the dispatch\n * schema maps are pulled through the era's memoized `buildSchemas2026()`\n * factory on first lookup — importing this module constructs no zod schemas.\n */\nimport type * as z from 'zod/v4';\n\nimport type { NotificationMethod, NotificationTypeMap, RequestMethod, RequestTypeMap, ResultTypeMap } from '../../types/types';\nimport type { Rev2026NotificationMethod, Rev2026RequestMethod } from './buildSchemas';\nimport { buildSchemas2026 } from './buildSchemas';\n\n/* Static method membership — the schema-free half of the registry. Key order\n * matches the dispatch maps in `./buildSchemas.ts` so the exported method\n * lists are byte-identical to the pre-lazy `Object.keys(map)` derivation. */\nconst requestMethodKeys: { readonly [M in Rev2026RequestMethod]: null } = {\n    'tools/call': null,\n    'tools/list': null,\n    'prompts/get': null,\n    'prompts/list': null,\n    'resources/list': null,\n    'resources/templates/list': null,\n    'resources/read': null,\n    'completion/complete': null,\n    'server/discover': null,\n    'subscriptions/listen': null\n};\n\nconst notificationMethodKeys: { readonly [M in Rev2026NotificationMethod]: null } = {\n    'notifications/cancelled': null,\n    'notifications/progress': null,\n    'notifications/message': null,\n    'notifications/resources/updated': null,\n    'notifications/resources/list_changed': null,\n    'notifications/tools/list_changed': null,\n    'notifications/prompts/list_changed': null,\n    'notifications/subscriptions/acknowledged': null\n};\n\n/** The 2026-era request-method set (registry membership = the deletion story). */\nexport function hasRequestMethod2026(method: string): method is Rev2026RequestMethod {\n    return Object.prototype.hasOwnProperty.call(requestMethodKeys, method);\n}\n\n/** The 2026-era notification-method set. */\nexport function hasNotificationMethod2026(method: string): method is Rev2026NotificationMethod {\n    return Object.prototype.hasOwnProperty.call(notificationMethodKeys, method);\n}\n\n/** Result-map membership (same key set as the request map on this era). */\nfunction hasResultMethod2026(method: string): method is Rev2026RequestMethod {\n    return Object.prototype.hasOwnProperty.call(requestMethodKeys, method);\n}\n\n/**\n * Gets the dispatch (post-lift) Zod schema for a given request method.\n * Returns `undefined` for methods this era's registry does not define.\n * The typed overload mirrors `WireCodec.requestSchema` so call sites with a\n * statically known method need no type assertion.\n */\nexport function getRequestSchema2026<M extends RequestMethod>(method: M): z.ZodType<RequestTypeMap[M]> | undefined;\nexport function getRequestSchema2026(method: string): z.ZodType | undefined;\nexport function getRequestSchema2026(method: string): z.ZodType | undefined {\n    return hasRequestMethod2026(method) ? buildSchemas2026().dispatchRequestSchemas[method] : undefined;\n}\n\n/**\n * Gets the dispatch (post-lift) Zod schema for validating results of a given\n * request method. Returns `undefined` for methods this era's registry does\n * not define.\n * @see getRequestSchema2026 for the typed-overload contract.\n */\nexport function getResultSchema2026<M extends RequestMethod>(method: M): z.ZodType<ResultTypeMap[M]> | undefined;\nexport function getResultSchema2026(method: string): z.ZodType | undefined;\nexport function getResultSchema2026(method: string): z.ZodType | undefined {\n    return hasResultMethod2026(method) ? buildSchemas2026().dispatchResultSchemas[method] : undefined;\n}\n\n/**\n * Gets the Zod schema for a given notification method.\n * Returns `undefined` for methods this era's registry does not define.\n * @see getRequestSchema2026 for the typed-overload contract.\n */\nexport function getNotificationSchema2026<M extends NotificationMethod>(method: M): z.ZodType<NotificationTypeMap[M]> | undefined;\nexport function getNotificationSchema2026(method: string): z.ZodType | undefined;\nexport function getNotificationSchema2026(method: string): z.ZodType | undefined {\n    return hasNotificationMethod2026(method) ? buildSchemas2026().notificationSchemas2026[method] : undefined;\n}\n\n/** Registry method lists (for the spec-method universe and the CI registry-diff oracle). */\nexport const rev2026RequestMethods: readonly string[] = Object.keys(requestMethodKeys);\nexport const rev2026NotificationMethods: readonly string[] = Object.keys(notificationMethodKeys);\n","/**\n * The 2026-era wire codec (protocol revision 2026-07-28).\n *\n * Decode = raw-first `resultType` discrimination (the structural V-1 home:\n * the RAW value is inspected BEFORE any schema validation, so a non-complete\n * result can never be masked into a hollow success by a tolerant schema),\n * then wire-exact parse, then lift (drop the wire member). Encode = the\n * stamp seam: the known deleted-field set is strictly enforced (Q1-SD3 iii) —\n * the 2026 wire types have no slot for `execution.taskSupport` or\n * `capabilities.tasks`, so the encode mapping deletes them; era-blind\n * handlers stay era-invisible while deleted vocabulary cannot cross eras\n * through the parse-free outbound path — and then the encode contract steps\n * run (see `encodeContract.ts`): the `resultType` stamp (with handler\n * pass-through for the multi round-trip methods) followed by the required\n * `ttlMs`/`cacheScope` fill on cacheable results.\n *\n * Q1-SD3 postures implemented here:\n * (i)  absent `resultType` from a 2026-classified peer → typed error NAMING\n *      the violation. The spec's absent⇒complete bridge is scoped to\n *      EARLIER-revision servers (spec.types.2026-07-28.ts Result.resultType:\n *      \"Servers implementing this protocol version MUST include this field\")\n *      and is deliberately NOT extended to modern traffic.\n * (ii) `input_required` → the driver-seam payload (the multi-round-trip\n *      driver, M4.1/#13, consumes it; until then the protocol layer surfaces\n *      the discriminated kind as a typed local error, no retry).\n * (iii) unrecognized kinds → invalid, no retry (DQ5).\n */\nimport type * as z from 'zod/v4';\n\nimport { SdkError, SdkErrorCode } from '../../errors/sdkErrors';\nimport { CLIENT_CAPABILITIES_META_KEY, CLIENT_INFO_META_KEY, LOG_LEVEL_META_KEY, PROTOCOL_VERSION_META_KEY } from '../../types/constants';\nimport type { CallToolResult, Implementation, Result, ResultMetaObject } from '../../types/types';\nimport type { DecodedResult, EnvelopeIssue, LiftedWireMaterial, OutboundEnvelopeMaterial, ValidateOutcome, WireCodec } from '../codec';\nimport { appendTextFallbackForNonObject } from '../textFallback';\nimport { buildSchemas2026 } from './buildSchemas';\nimport { fillCacheFields, stampResultType, stampServerInfoMeta } from './encodeContract';\nimport { getInputRequestSchema2026, getInputResponseSchema2026 } from './inputRequired';\nimport {\n    getNotificationSchema2026,\n    getRequestSchema2026,\n    getResultSchema2026,\n    hasNotificationMethod2026,\n    hasRequestMethod2026\n} from './registry';\n\nfunction isPlainObject(value: unknown): value is Record<string, unknown> {\n    return value !== null && typeof value === 'object' && !Array.isArray(value);\n}\n\n/** Tri-state wrap of an optional Zod schema lookup (the function-only contract). */\nfunction triState<T>(schema: z.ZodType<T> | undefined, raw: unknown): ValidateOutcome<T> {\n    if (schema === undefined) return { ok: false, reason: 'not-in-era' };\n    const parsed = schema.safeParse(raw);\n    return parsed.success ? { ok: true, value: parsed.data } : { ok: false, reason: 'invalid', message: String(parsed.error) };\n}\n\nconst NOT_IN_ERA: ValidateOutcome<never> = { ok: false, reason: 'not-in-era' };\n\n/**\n * The reserved `_meta` keys an envelope must carry on this era (in reporting\n * order). `clientInfo` is NOT here: spec PR #3002 demoted it to SHOULD, so a\n * request without it is accepted (a present-but-malformed value still fails\n * the envelope schema parse below).\n */\nconst REQUIRED_ENVELOPE_KEYS: readonly string[] = [PROTOCOL_VERSION_META_KEY, CLIENT_CAPABILITIES_META_KEY];\n\n/** Strip the known deleted-field set from an outbound result (Q1-SD3 iii). */\nfunction enforceDeletedFields(method: string, result: Result): Result {\n    let next: Record<string, unknown> = result as Record<string, unknown>;\n    let copied = false;\n    const copy = () => {\n        if (!copied) {\n            next = { ...next };\n            copied = true;\n        }\n        return next;\n    };\n\n    // tools arrays: execution (the taskSupport carrier) is deleted vocabulary.\n    const tools = (result as { tools?: unknown }).tools;\n    if (method === 'tools/list' && Array.isArray(tools) && tools.some(tool => isPlainObject(tool) && 'execution' in tool)) {\n        copy().tools = tools.map(tool => {\n            if (!isPlainObject(tool) || !('execution' in tool)) return tool;\n            const rest = { ...tool };\n            delete rest['execution'];\n            return rest;\n        });\n    }\n\n    // capability objects: the `tasks` capability is deleted vocabulary.\n    const capabilities = (result as { capabilities?: unknown }).capabilities;\n    if (isPlainObject(capabilities) && 'tasks' in capabilities) {\n        const rest = { ...capabilities };\n        delete rest['tasks'];\n        copy().capabilities = rest;\n    }\n\n    return next as Result;\n}\n\nexport const rev2026Codec: WireCodec & {\n    /**\n     * @deprecated Off-interface in-band registry probe retained for the\n     * existing inputRequiredFunnel pin. Use {@link WireCodec.validateInputRequest}\n     * — its `not-in-era` outcome is the membership signal.\n     */\n    inputRequestSchema(method: string): unknown;\n} = {\n    era: '2026-07-28',\n\n    hasRequestMethod: hasRequestMethod2026,\n    hasNotificationMethod: hasNotificationMethod2026,\n    hasInputRequestMethod: (method: string): boolean => getInputRequestSchema2026(method) !== undefined,\n\n    // ── Function-only validation surface ──\n    validateRequest: (method: string, raw: unknown) => triState(getRequestSchema2026(method), raw),\n    validateResult: (method: string, raw: unknown) => triState(getResultSchema2026(method), raw),\n    validateNotification: (method: string, raw: unknown) => triState(getNotificationSchema2026(method), raw),\n    // In-band multi-round-trip vocabulary: the demoted elicitation/sampling/\n    // roots shapes carried inside `input_required` results (NOT wire request\n    // methods on this era — registry membership is deliberately not granted).\n    validateInputRequest: (method: string, raw: unknown) => triState(getInputRequestSchema2026(method), raw),\n    validateInputResponse: (method: string, raw: unknown) => triState(getInputResponseSchema2026(method), raw),\n\n    // Sampling is in-band on this era — callers fall through to\n    // `validateInputResponse('sampling/createMessage', …)`.\n    samplingResultVariant: (): ValidateOutcome<never> => NOT_IN_ERA,\n\n    outboundEnvelope(material: OutboundEnvelopeMaterial): Readonly<Record<string, unknown>> {\n        return {\n            [PROTOCOL_VERSION_META_KEY]: material.protocolVersion,\n            [CLIENT_INFO_META_KEY]: material.clientInfo,\n            [CLIENT_CAPABILITIES_META_KEY]: material.clientCapabilities,\n            ...(material.logLevel !== undefined && { [LOG_LEVEL_META_KEY]: material.logLevel })\n        };\n    },\n\n    validateEnvelopeMeta(meta: Readonly<Record<string, unknown>>): EnvelopeIssue[] {\n        const issues: EnvelopeIssue[] = [];\n        for (const key of REQUIRED_ENVELOPE_KEYS) {\n            if (!(key in meta)) issues.push({ key, problem: 'missing' });\n        }\n        const parsed = buildSchemas2026().RequestMetaEnvelopeSchema.safeParse(meta);\n        if (!parsed.success) {\n            for (const issue of parsed.error.issues) {\n                const path = issue.path.map(String);\n                const key = path.length > 0 ? path.join('.') : '_meta';\n                // Missing required keys were already reported above in canonical order.\n                if (path.length === 1 && issues.some(existing => existing.key === key && existing.problem === 'missing')) {\n                    continue;\n                }\n                issues.push({ key, problem: issue.message });\n            }\n        }\n        return issues;\n    },\n\n    // SEP-2106 result-side projection: no `{result:…}` wrap on the modern era\n    // (the wire shape carries the natural `structuredContent` directly), but\n    // the era-agnostic §4.3 TextContent auto-append still applies.\n    projectCallToolResult: (result: CallToolResult): CallToolResult => appendTextFallbackForNonObject(result),\n\n    // Retained off-interface for the inputRequiredFunnel registry-membership\n    // pin (asserts the in-band schema set without exercising parse): the\n    // function-only WireCodec contract carries no schema-returning members,\n    // so this lives only on the concrete object's widened type.\n    inputRequestSchema: getInputRequestSchema2026,\n\n    decodeResult(method: string, raw: unknown): DecodedResult {\n        if (!isPlainObject(raw)) {\n            return {\n                kind: 'invalid',\n                error: new SdkError(SdkErrorCode.InvalidResult, `Invalid result for ${method}: not an object`, { method })\n            };\n        }\n\n        // Step 1 — RAW discrimination, before any schema (V-1).\n        const rawResultType = raw['resultType'];\n        if (rawResultType === undefined) {\n            // Q1-SD3 (i): hard error naming the violation.\n            return {\n                kind: 'invalid',\n                error: new SdkError(\n                    SdkErrorCode.InvalidResult,\n                    `Invalid result for ${method}: missing required resultType — servers implementing protocol revision 2026-07-28 ` +\n                        `MUST include it (the absent-means-complete bridge applies only to earlier-revision servers)`,\n                    { method, violation: 'missing-resultType' }\n                )\n            };\n        }\n        if (typeof rawResultType !== 'string') {\n            return {\n                kind: 'invalid',\n                error: new SdkError(SdkErrorCode.InvalidResult, `Invalid result for ${method}: non-string resultType`, {\n                    method,\n                    resultType: rawResultType\n                })\n            };\n        }\n        if (rawResultType === 'input_required') {\n            // The driver seam (#13 consumes this payload).\n            const rawInputRequests = raw['inputRequests'];\n            const inputRequests = isPlainObject(rawInputRequests) ? rawInputRequests : {};\n            const requestState = raw['requestState'];\n            // Carry result-level `_meta` through, parsed as on complete results (malformed drops to absent).\n            const metaParse = raw['_meta'] === undefined ? undefined : buildSchemas2026().ResultMetaSchema.safeParse(raw['_meta']);\n            const meta = metaParse?.success ? (metaParse.data as ResultMetaObject) : undefined;\n            if (Object.keys(inputRequests).length === 0 && typeof requestState !== 'string') {\n                // At-least-one rule, client side: with neither inputRequests\n                // nor requestState there is nothing to fulfil and nothing to\n                // echo — retrying would only resend the original params until\n                // the round cap is exhausted, so fail fast instead.\n                return {\n                    kind: 'invalid',\n                    error: new SdkError(\n                        SdkErrorCode.InvalidResult,\n                        `Invalid result for ${method}: input_required carries neither inputRequests nor requestState ` +\n                            `(every input_required result must include at least one of the two)`,\n                        { method, violation: 'input-required-missing-both' }\n                    )\n                };\n            }\n            return {\n                kind: 'input_required',\n                inputRequests,\n                ...(typeof requestState === 'string' && { requestState }),\n                ...(meta !== undefined && { _meta: meta })\n            };\n        }\n        if (rawResultType !== 'complete') {\n            // Unrecognized kind ⇒ invalid, no retry (DQ5).\n            return {\n                kind: 'invalid',\n                error: new SdkError(SdkErrorCode.UnsupportedResultType, `Unsupported result type '${rawResultType}' for ${method}`, {\n                    resultType: rawResultType,\n                    method\n                })\n            };\n        }\n\n        // Step 2 — wire-exact parse (registry methods), with resultType present.\n        // Own-key lookup: `method` is peer-influenced on related-request\n        // paths, and a prototype-chain hit (e.g. 'constructor') must not\n        // masquerade as a schema and throw out of the decode hop.\n        const wireResultSchemas = getWireResultSchemas();\n        const wireSchema = Object.hasOwn(wireResultSchemas, method) ? wireResultSchemas[method] : undefined;\n        if (wireSchema !== undefined) {\n            const parsed = wireSchema.safeParse(raw);\n            if (!parsed.success) {\n                return {\n                    kind: 'invalid',\n                    error: new SdkError(SdkErrorCode.InvalidResult, `Invalid result for ${method}: ${parsed.error}`, { method })\n                };\n            }\n        }\n\n        // Step 3 — lift: the wire discriminator is consumed.\n        const lifted = { ...raw };\n        delete lifted['resultType'];\n        return { kind: 'complete', result: lifted as Result };\n    },\n\n    encodeResult(method: string, result: Result, serverInfo?: Implementation): Result {\n        // The stamp seam, in pinned order: deleted-field strictness, then the\n        // resultType stamp (handler pass-through only for methods whose\n        // vocabulary goes beyond 'complete'), then the cache fill for the\n        // cacheable operations (only on post-stamp 'complete' results), then\n        // the `_meta` serverInfo identity stamp (#3002 — every result,\n        // handler-authored value wins).\n        return stampServerInfoMeta(fillCacheFields(method, stampResultType(method, enforceDeletedFields(method, result))), serverInfo);\n    },\n\n    // The −32002 resource-not-found domain code maps to −32602 Invalid Params\n    // on the wire (the 2026-07-28 spec MUST for resources/read misses).\n    encodeErrorCode: (code: number): number => (code === -32_002 ? -32_602 : code),\n\n    checkInboundEnvelope(material: LiftedWireMaterial): string | undefined {\n        if (material.envelope === undefined) {\n            return (\n                'Request is missing the required _meta envelope for protocol revision 2026-07-28 ' +\n                '(io.modelcontextprotocol/protocolVersion, io.modelcontextprotocol/clientCapabilities)'\n            );\n        }\n        const parsed = buildSchemas2026().RequestMetaEnvelopeSchema.safeParse(material.envelope);\n        if (!parsed.success) {\n            return `Invalid _meta envelope for protocol revision 2026-07-28: ${parsed.error.issues.map(issue => issue.message).join('; ')}`;\n        }\n        return undefined;\n    }\n};\n\n/** Wire-true result wrappers consulted by decode step 2, keyed by method —\n * built once through the era's schema memo on the first decode. */\nlet wireResultSchemasMemo: Record<string, z.ZodType> | undefined;\n\nfunction getWireResultSchemas(): Record<string, z.ZodType> {\n    if (wireResultSchemasMemo) return wireResultSchemasMemo;\n    const s = buildSchemas2026();\n    wireResultSchemasMemo = {\n        'tools/call': s.CallToolResultSchema,\n        'tools/list': s.ListToolsResultSchema,\n        'prompts/get': s.GetPromptResultSchema,\n        'prompts/list': s.ListPromptsResultSchema,\n        'resources/list': s.ListResourcesResultSchema,\n        'resources/templates/list': s.ListResourceTemplatesResultSchema,\n        'resources/read': s.ReadResourceResultSchema,\n        'completion/complete': s.CompleteResultSchema,\n        'server/discover': s.DiscoverResultSchema\n    };\n    return wireResultSchemasMemo;\n}\n\n/**\n * Forces the lazy wire-result wrapper map (and, through it, the era's schema\n * memo). Warm-up hook for `preloadSchemas()` — no-op once the map exists.\n */\nexport function warmWireResultSchemas2026(): void {\n    getWireResultSchemas();\n}\n","/**\n * The era-granular wire-codec layer (Q1 increment 2).\n *\n * The SDK separates a revision-neutral model layer (the public types — no\n * `resultType`, no `_meta` envelope keys, no retry fields) from per-revision\n * WIRE CODECS that own revision-exact schemas, method registries, and the\n * decode (wire → neutral lift) / encode (neutral → wire stamp) transforms.\n * The codec is a pure function of the negotiated protocol version, which is\n * ordinary connection state on the `Protocol` instance: the client stores it\n * when its handshake completes, the server stores it at `_oninitialize` (and\n * modern-era server instances get it set at instance binding by the entry).\n * There is no side table — era resolution is `codecForVersion(<instance\n * state>)`, with the pre-negotiation window covered by the outbound method\n * pins in `bootstrap.ts`.\n *\n * REQUIRED DISCLOSURE (Q1-SD1, era granularity): \"the negotiated version\n * determines which types are serialized/deserialized over the wire\" cashes\n * out as \"the negotiated wire ERA determines them\". All five legacy protocol\n * versions (2024-10-07 … 2025-11-25) share one wire vocabulary and map to the\n * single 2025-era codec — exactly how the single schema set already served\n * all five — and '2026-07-28' maps to the 2026-era codec. A new codec exists\n * only when wire vocabulary actually diverges; intra-era vocabulary is NOT\n * keyed by exact version.\n *\n * Deletions are physical: registry membership is the deletion story. The\n * 2026-era registry has no `tasks/*`, `initialize`, `ping`, `logging/setLevel`,\n * `resources/(un)subscribe` or server→client wire-request entries, so an\n * inbound era-mismatched method falls to −32601 by absence — even when a\n * handler is registered — and an outbound one dies locally with a typed\n * `SdkError` before anything reaches the transport. The 2025-era registry has\n * no `server/discover`/`subscriptions/listen`/MRTR entries, symmetrically.\n *\n * Custom-handler shadowing policy (both directions): a method that belongs to\n * the SPEC-METHOD UNIVERSE — the union of every codec's registry, derived,\n * not hand-curated — is ALWAYS era-gated, so a custom handler registered for\n * a deleted spec method (e.g. `tasks/result`) serves it only on the era that\n * defines it. Methods outside the universe are consumer-owned extension\n * methods: they are era-blind and require explicit schemas, exactly as today.\n * Exception: `isExtensionReusedRequestMethod`, the Tasks extension names sent or served with an explicit schema.\n *\n * Everything in `wire/` is internal to the bundled, `private: true` core —\n * nothing per-revision is public surface, and nothing here may ever be\n * exported from `core/public`.\n */\nimport type { SdkError } from '../errors/sdkErrors';\nimport { isModernProtocolVersion } from '../shared/protocolEras';\nimport type {\n    CallToolResult,\n    ClientCapabilities,\n    CreateMessageResult,\n    CreateMessageResultWithTools,\n    Implementation,\n    LoggingLevel,\n    MessageClassification,\n    NotificationMethod,\n    NotificationTypeMap,\n    RequestMetaEnvelope,\n    RequestMethod,\n    RequestTypeMap,\n    Result,\n    ResultMetaObject,\n    ResultTypeMap\n} from '../types/types';\nimport { rev2025Codec } from './rev2025-11-25/codec';\nimport { rev2026Codec } from './rev2026-07-28/codec';\n\n/** Wire eras with distinct vocabulary. */\nexport type WireEra = '2025-11-25' | '2026-07-28';\n\n/**\n * The modern wire revision literal. Internal only — deliberately NOT a public\n * constant (G-D2-4: no public modern-version constant ships before era-aware\n * list semantics exist).\n */\nexport const MODERN_WIRE_REVISION = '2026-07-28';\n\n/**\n * Wire-only material lifted off an inbound message by the protocol layer\n * before dispatch (the V-3 seam): the reserved `_meta` envelope keys and the\n * multi-round-trip driver fields. This is the typed driver-material channel\n * of the codec contract — handlers never see it; the protocol layer surfaces\n * it via `ctx.mcpReq.envelope` / `.inputResponses` / `.requestState`, and the\n * MRTR driver (M4.1) consumes the retry fields from here.\n */\nexport interface LiftedWireMaterial {\n    // Partial: the lift surfaces whichever reserved keys the message actually\n    // carried — a peer on an adjacent revision may legally send a subset, and\n    // envelope requiredness is enforced per request at dispatch time\n    // (`checkInboundEnvelope`), not by the lift.\n    envelope?: Partial<RequestMetaEnvelope>;\n    inputResponses?: Record<string, unknown>;\n    requestState?: string;\n}\n\n/**\n * Tri-state validation outcome — the function-only contract for what the\n * schema-getter pair (`hasRequestMethod` ⇒ −32601-by-absence; `…Schema(m)\n * .parse` throw ⇒ −32602) used to encode in two pieces. Preserving the split\n * is the point: collapsing 'absent from this era's registry' into 'invalid'\n * would make the in-band fallback chain (validate → on `not-in-era` fall to\n * validateInputRequest) treat absence as failure and never fall through.\n */\nexport type ValidateOutcome<T> =\n    | { readonly ok: true; readonly value: T }\n    /**\n     * Method is spec vocabulary but absent from THIS era's registry. Callers\n     * map to −32601 (inbound) or a typed local SdkError (outbound), or fall\n     * through to the in-band validator.\n     */\n    | { readonly ok: false; readonly reason: 'not-in-era' }\n    /**\n     * Method is in this era's registry; payload failed the era-exact schema.\n     * Callers map to −32602.\n     */\n    | { readonly ok: false; readonly reason: 'invalid'; readonly message: string };\n\n/** A single self-identifying problem found while validating a per-request `_meta` envelope. */\nexport interface EnvelopeIssue {\n    /**\n     * The envelope key the problem is about: one of the reserved `_meta`\n     * keys, or a dotted path inside one.\n     */\n    readonly key: string;\n    /** A short description of what is wrong with that key (`missing`, or a validation message). */\n    readonly problem: string;\n}\n\n/** Material a Client supplies for an era to build its per-request `_meta` envelope from. */\nexport interface OutboundEnvelopeMaterial {\n    readonly protocolVersion: string;\n    readonly clientInfo: Implementation;\n    readonly clientCapabilities: ClientCapabilities;\n    readonly logLevel?: LoggingLevel;\n}\n\n/** Result decode outcomes — the raw-first discrimination (V-1) lives in `decodeResult`. */\nexport type DecodedResult =\n    | {\n          kind: 'complete';\n          /** The neutral result value: wire-only material consumed/stripped. */\n          result: Result;\n      }\n    | {\n          kind: 'input_required';\n          /**\n           * Driver-only material (never consumer-visible). The full\n           * multi-round-trip driver is M4.1 scope; this seam carries the\n           * discriminated payload to it.\n           */\n          inputRequests: Record<string, unknown>;\n          requestState?: string;\n          /** Result-level `_meta`, carried through so a manual caller sees it. */\n          _meta?: ResultMetaObject;\n      }\n    | { kind: 'invalid'; error: SdkError };\n\n/**\n * The per-era wire codec contract (design C §3, adapted to the live funnel\n * layout: the universal wire-only LIFT runs once in the protocol layer for\n * every message — spec, custom, and fallback paths alike — and codecs consume\n * the lifted material rather than re-implementing the strip per era).\n */\nexport interface WireCodec {\n    readonly era: WireEra;\n\n    /** Registry membership — the deletion story (inbound −32601 by absence; outbound typed local error). */\n    hasRequestMethod(method: string): boolean;\n    hasNotificationMethod(method: string): boolean;\n    hasInputRequestMethod(method: string): boolean;\n\n    // ── Function-only validation surface ──────────────────────────────────\n    // The validator-agnostic contract: callers never see a Zod schema, only a\n    // tri-state outcome. The method-literal overloads carry the typed parse\n    // result exactly as the (now-deprecated) *Schema getters did.\n\n    /** Era-exact request validation. `not-in-era` ≡ −32601-by-absence; `invalid` ≡ −32602. */\n    validateRequest<M extends RequestMethod>(method: M, raw: unknown): ValidateOutcome<RequestTypeMap[M]>;\n    validateRequest(method: string, raw: unknown): ValidateOutcome<unknown>;\n\n    /** Era-exact result validation (same registry as `validateRequest`). */\n    validateResult<M extends RequestMethod>(method: M, raw: unknown): ValidateOutcome<ResultTypeMap[M]>;\n    validateResult(method: string, raw: unknown): ValidateOutcome<unknown>;\n\n    /** Era-exact notification validation. */\n    validateNotification<M extends NotificationMethod>(method: M, raw: unknown): ValidateOutcome<NotificationTypeMap[M]>;\n    validateNotification(method: string, raw: unknown): ValidateOutcome<unknown>;\n\n    /**\n     * In-band (de-JSON-RPC'd) input-request validation — the embedded\n     * requests a multi-round-trip `input_required` result may carry. Always\n     * `not-in-era` on the 2025 era (elicitation/sampling/roots are wire\n     * request methods there). Does NOT grant registry membership.\n     */\n    validateInputRequest<M extends RequestMethod>(method: M, raw: unknown): ValidateOutcome<RequestTypeMap[M]>;\n    validateInputRequest(method: string, raw: unknown): ValidateOutcome<unknown>;\n\n    /** In-band bare-response validation answering an embedded input request. */\n    validateInputResponse<M extends RequestMethod>(method: M, raw: unknown): ValidateOutcome<ResultTypeMap[M]>;\n    validateInputResponse(method: string, raw: unknown): ValidateOutcome<unknown>;\n\n    /**\n     * Param-conditional `sampling/createMessage` result validation — the one\n     * spec result whose schema depends on REQUEST params (tools vs no tools).\n     * The 2025 era owns the with-tools/plain frozen schemas; the 2026 era\n     * returns `not-in-era` (sampling is in-band there — callers fall through\n     * to `validateInputResponse`).\n     */\n    samplingResultVariant(hasTools: true, raw: unknown): ValidateOutcome<CreateMessageResultWithTools>;\n    samplingResultVariant(hasTools: false, raw: unknown): ValidateOutcome<CreateMessageResult>;\n    samplingResultVariant(hasTools: boolean, raw: unknown): ValidateOutcome<CreateMessageResult | CreateMessageResultWithTools>;\n\n    /**\n     * Outbound per-request `_meta` envelope encode. Returns the keyed object\n     * to merge into `params._meta` on this era, or `undefined` when this era\n     * carries no per-request envelope (the 2025 era — legacy wire stays\n     * byte-identical).\n     */\n    outboundEnvelope(material: OutboundEnvelopeMaterial): Readonly<Record<string, unknown>> | undefined;\n\n    /**\n     * Structured envelope validation: maps a `_meta` object to\n     * self-identifying issues. The 2025 era never requires an envelope and\n     * always returns `[]`; the 2026 era owns the required-key pre-pass plus\n     * the wire-exact `RequestMetaEnvelopeSchema` parse.\n     */\n    validateEnvelopeMeta(meta: Readonly<Record<string, unknown>>): EnvelopeIssue[];\n\n    /**\n     * Per-registration `tools/call` result projection. Two independent\n     * decisions, both owned here so server-side code never re-derives them:\n     *\n     * - SEP-2106 §4.3 TextContent auto-append (EVERY era, value-shape-based):\n     *   when `structuredContent` is a non-object value (array/primitive/\n     *   `null`) and the handler authored no `type:'text'` block, append\n     *   `{type:'text', text: JSON.stringify(value)}` so consumers that read\n     *   only `content` still receive a rendering. The author opts out by\n     *   returning any `text` block themselves.\n     *\n     * - `{result:…}` wrap (2025 era only): wrap as `{result:<value>}` when the\n     *   value is non-object (the 2025 wire shape requires `structuredContent`\n     *   to be an object — a schema-less tool returning `[1,2,3]` would\n     *   otherwise ship wire-illegal bytes) OR when the tool's ADVERTISED\n     *   `outputSchema` has a non-object root (so the result matches the\n     *   `encodeResult('tools/list')` projection of the same tool). Identity on\n     *   the 2026 era — the wire shape carries the natural value directly.\n     */\n    projectCallToolResult(result: CallToolResult, advertisedOutputSchema: Readonly<Record<string, unknown>> | undefined): CallToolResult;\n\n    /**\n     * Step 1 of result decoding: RAW `resultType` handling BEFORE any schema\n     * validation (V-1's structural home). Era postures (Q1-SD3):\n     * - 2026 era: required discriminator — absent ⇒ typed error naming the\n     *   spec violation; `input_required` ⇒ driver payload; unknown ⇒ invalid,\n     *   no retry; `complete` ⇒ consume + lift.\n     * - 2025 era: `resultType` is foreign vocabulary ⇒ strip-on-lift.\n     */\n    decodeResult(method: string, raw: unknown): DecodedResult;\n\n    /**\n     * Outbound result mapping (the stamp seam). The 2025-era codec is the\n     * identity — it has NO stamp code path (the never-stamp guarantee; it\n     * never reads `serverInfo`). The 2026-era codec strictly enforces the\n     * 2026 wire shape for the known deleted-field set\n     * (`execution.taskSupport`, `capabilities.tasks` — Q1-SD3 iii), stamps\n     * `resultType`, fills the required `ttlMs`/`cacheScope` fields on\n     * cacheable results, and — when the caller supplies its identity —\n     * stamps `_meta['io.modelcontextprotocol/serverInfo']` on every result\n     * (spec PR #3002 SHOULD; a handler-authored value wins). `Server`\n     * instances pass their identity; clients and hand-constructed protocol\n     * objects pass nothing and no identity is ever invented.\n     */\n    encodeResult(method: string, result: Result, serverInfo?: Implementation): Result;\n\n    /**\n     * Outbound error-code mapping (the error half of the stamp seam). A\n     * handler-thrown `ProtocolError`'s numeric code passes through here on\n     * its way to the JSON-RPC error response, so per-era wire-code selection\n     * lives in the codec rather than in handler/funnel code. The current\n     * mapping is identical on both eras (the `-32002` resource-not-found\n     * domain code maps to `-32602` Invalid Params on the wire — the\n     * 2026-07-28 spec MUST, and what the deployed v1.x SDK already emits on\n     * earlier revisions); the seam is the structural home for any future\n     * per-era divergence. Unknown codes pass through unchanged.\n     */\n    encodeErrorCode(code: number): number;\n\n    /**\n     * @deprecated Use {@link validateEnvelopeMeta}. Inbound envelope\n     * enforcement for era-classified traffic: validates the lifted envelope\n     * material of a request. Returns an error message when the era requires\n     * an envelope and it is missing/invalid (→ −32602 at the dispatch\n     * layer); `undefined` when acceptable. The 2025 era never requires an\n     * envelope.\n     */\n    checkInboundEnvelope(material: LiftedWireMaterial): string | undefined;\n}\n\n/**\n * Era resolution, many-to-one (Q1-SD1): every modern-era revision\n * (`>= 2026-07-28`) → the 2026-era codec; every legacy revision (the five\n * `SUPPORTED_PROTOCOL_VERSIONS`) and `undefined`/unknown → the 2025-era\n * codec (the DV-13 default posture — hand-constructed instances and\n * unclassified traffic are legacy-era). This is the same era predicate the\n * rest of the SDK uses ({@link isModernProtocolVersion}); a pinned modern\n * revision other than the literal '2026-07-28' must still resolve modern.\n */\nexport function codecForVersion(version: string | undefined): WireCodec {\n    return version !== undefined && isModernProtocolVersion(version) ? rev2026Codec : rev2025Codec;\n}\n\n/**\n * The wire era an edge classification names (Q2 — produced at the\n * transport/entry edge; this layer only CONSUMES it). The dispatch funnel no\n * longer resolves a codec FROM the classification: era is instance state, and\n * a classified inbound message is VALIDATED against the instance era — a\n * mismatch is an entry/routing error, never a per-message era switch. The\n * exact `revision` wins over the coarse era flag when both are present.\n */\nexport function classifiedWireEra(classification: MessageClassification): WireEra {\n    if (classification.revision !== undefined) return codecForVersion(classification.revision).era;\n    return classification.era === 'modern' ? rev2026Codec.era : rev2025Codec.era;\n}\n\n/**\n * The derived spec-method universe: the union of every codec registry. A\n * method in this set is era-gated at dispatch and send time; a method outside\n * it is a consumer-owned extension method (era-blind, schema-explicit).\n * Derived from the registries — never hand-curated (the LEGACY_ONLY_METHODS\n * table class is exactly what registry membership replaces).\n */\nexport function isSpecRequestMethod(method: string): boolean {\n    return ALL_CODECS.some(codec => codec.hasRequestMethod(method));\n}\n\nexport function isSpecNotificationMethod(method: string): boolean {\n    return ALL_CODECS.some(codec => codec.hasNotificationMethod(method));\n}\n\n/** The names SEP-2663 re-defines for the Tasks extension on the era that removed them from core. */\nexport function isExtensionReusedRequestMethod(method: string): boolean {\n    return method === 'tasks/get' || method === 'tasks/cancel';\n}\n\nconst ALL_CODECS: readonly WireCodec[] = [rev2025Codec, rev2026Codec];\n","// Moved: the spec Zod schemas now live in @modelcontextprotocol/core (packages/core/src/schemas.ts).\n// This module re-exports them one-to-one so every existing import path keeps working; a name\n// added to core/src/schemas.ts must be added here too (specTypeSchema.ts imports through this\n// module, so a missing name fails typecheck loudly).\n//\n// Add new schemas in packages/core/src/schemas.ts, never here — this file only forwards, and\n// core-internal's schemaShims test enforces that it stays free of zod imports and definitions.\nexport {\n    AnnotationsSchema,\n    AudioContentSchema,\n    BaseMetadataSchema,\n    BaseRequestParamsSchema,\n    BlobResourceContentsSchema,\n    BooleanSchemaSchema,\n    CallToolRequestParamsSchema,\n    CallToolRequestSchema,\n    CallToolResultSchema,\n    CancelledNotificationParamsSchema,\n    CancelledNotificationSchema,\n    CancelTaskRequestSchema,\n    CancelTaskResultSchema,\n    ClientCapabilitiesSchema,\n    ClientNotificationSchema,\n    ClientRequestSchema,\n    ClientResultSchema,\n    ClientTasksCapabilitySchema,\n    CompatibilityCallToolResultSchema,\n    CompleteRequestParamsSchema,\n    CompleteRequestSchema,\n    CompleteResultSchema,\n    ContentBlockSchema,\n    CreateMessageRequestParamsSchema,\n    CreateMessageRequestSchema,\n    CreateMessageResultSchema,\n    CreateMessageResultWithToolsSchema,\n    CreateTaskResultSchema,\n    CursorSchema,\n    DiscoverRequestSchema,\n    DiscoverResultSchema,\n    ElicitationCompleteNotificationParamsSchema,\n    ElicitationCompleteNotificationSchema,\n    ElicitRequestFormParamsSchema,\n    ElicitRequestParamsSchema,\n    ElicitRequestSchema,\n    ElicitRequestURLParamsSchema,\n    ElicitResultSchema,\n    EmbeddedResourceSchema,\n    EmptyResultSchema,\n    EnumSchemaSchema,\n    GetPromptRequestParamsSchema,\n    GetPromptRequestSchema,\n    GetPromptResultSchema,\n    GetTaskPayloadRequestSchema,\n    GetTaskPayloadResultSchema,\n    GetTaskRequestSchema,\n    GetTaskResultSchema,\n    IconSchema,\n    IconsSchema,\n    ImageContentSchema,\n    ImplementationSchema,\n    InitializedNotificationSchema,\n    InitializeRequestParamsSchema,\n    InitializeRequestSchema,\n    InitializeResultSchema,\n    JSONArraySchema,\n    JSONObjectSchema,\n    JSONRPCErrorResponseSchema,\n    JSONRPCMessageSchema,\n    JSONRPCNotificationSchema,\n    JSONRPCRequestSchema,\n    JSONRPCResponseSchema,\n    JSONRPCResultResponseSchema,\n    JSONValueSchema,\n    LegacyTitledEnumSchemaSchema,\n    ListChangedOptionsBaseSchema,\n    ListPromptsRequestSchema,\n    ListPromptsResultSchema,\n    ListResourcesRequestSchema,\n    ListResourcesResultSchema,\n    ListResourceTemplatesRequestSchema,\n    ListResourceTemplatesResultSchema,\n    ListRootsRequestSchema,\n    ListRootsResultSchema,\n    ListTasksRequestSchema,\n    ListTasksResultSchema,\n    ListToolsRequestSchema,\n    ListToolsResultSchema,\n    LoggingLevelSchema,\n    LoggingMessageNotificationParamsSchema,\n    LoggingMessageNotificationSchema,\n    ModelHintSchema,\n    ModelPreferencesSchema,\n    MultiSelectEnumSchemaSchema,\n    NotificationSchema,\n    NotificationsParamsSchema,\n    NumberSchemaSchema,\n    PaginatedRequestParamsSchema,\n    PaginatedRequestSchema,\n    PaginatedResultSchema,\n    PingRequestSchema,\n    PrimitiveSchemaDefinitionSchema,\n    ProgressNotificationParamsSchema,\n    ProgressNotificationSchema,\n    ProgressSchema,\n    ProgressTokenSchema,\n    PromptArgumentSchema,\n    PromptListChangedNotificationSchema,\n    PromptMessageSchema,\n    PromptReferenceSchema,\n    PromptSchema,\n    ReadResourceRequestParamsSchema,\n    ReadResourceRequestSchema,\n    ReadResourceResultSchema,\n    RelatedTaskMetadataSchema,\n    RequestIdSchema,\n    RequestMetaSchema,\n    RequestSchema,\n    ResourceContentsSchema,\n    ResourceLinkSchema,\n    ResourceListChangedNotificationSchema,\n    ResourceRequestParamsSchema,\n    ResourceSchema,\n    ResourceTemplateReferenceSchema,\n    ResourceTemplateSchema,\n    ResourceUpdatedNotificationParamsSchema,\n    ResourceUpdatedNotificationSchema,\n    ResultMetaObjectSchema,\n    ResultSchema,\n    RoleSchema,\n    RootSchema,\n    RootsListChangedNotificationSchema,\n    SamplingContentSchema,\n    SamplingMessageContentBlockSchema,\n    SamplingMessageSchema,\n    ServerCapabilitiesSchema,\n    ServerNotificationSchema,\n    ServerRequestSchema,\n    ServerResultSchema,\n    ServerTasksCapabilitySchema,\n    SetLevelRequestParamsSchema,\n    SetLevelRequestSchema,\n    SingleSelectEnumSchemaSchema,\n    StringSchemaSchema,\n    SubscribeRequestParamsSchema,\n    SubscribeRequestSchema,\n    SubscriptionFilterSchema,\n    SubscriptionsAcknowledgedNotificationParamsSchema,\n    SubscriptionsAcknowledgedNotificationSchema,\n    SubscriptionsListenRequestParamsSchema,\n    SubscriptionsListenRequestSchema,\n    SubscriptionsListenResultMetaSchema,\n    SubscriptionsListenResultSchema,\n    TaskAugmentedRequestParamsSchema,\n    TaskCreationParamsSchema,\n    TaskMetadataSchema,\n    TaskSchema,\n    TaskStatusNotificationParamsSchema,\n    TaskStatusNotificationSchema,\n    TaskStatusSchema,\n    TextContentSchema,\n    TextResourceContentsSchema,\n    TitledMultiSelectEnumSchemaSchema,\n    TitledSingleSelectEnumSchemaSchema,\n    ToolAnnotationsSchema,\n    ToolChoiceSchema,\n    ToolExecutionSchema,\n    ToolListChangedNotificationSchema,\n    ToolResultContentSchema,\n    ToolSchema,\n    ToolUseContentSchema,\n    UnsubscribeRequestParamsSchema,\n    UnsubscribeRequestSchema,\n    UntitledMultiSelectEnumSchemaSchema,\n    UntitledSingleSelectEnumSchemaSchema\n} from '@modelcontextprotocol/core/internal';\n","import {\n    CallToolResultSchema,\n    InitializedNotificationSchema,\n    InitializeRequestSchema,\n    JSONRPCErrorResponseSchema,\n    JSONRPCMessageSchema,\n    JSONRPCNotificationSchema,\n    JSONRPCRequestSchema,\n    JSONRPCResponseSchema,\n    JSONRPCResultResponseSchema,\n    TaskAugmentedRequestParamsSchema\n} from './schemas';\nimport type {\n    CallToolResult,\n    CompleteRequest,\n    CompleteRequestPrompt,\n    CompleteRequestResourceTemplate,\n    InitializedNotification,\n    InitializeRequest,\n    InputRequiredResult,\n    JSONRPCErrorResponse,\n    JSONRPCMessage,\n    JSONRPCNotification,\n    JSONRPCRequest,\n    JSONRPCResponse,\n    JSONRPCResultResponse,\n    TaskAugmentedRequestParams\n} from './types';\n\n/**\n * Validates and parses an unknown value as a JSON-RPC message.\n *\n * Use this to validate incoming messages in custom transport implementations.\n * Throws if the value does not conform to the JSON-RPC message schema.\n *\n * @param value - The value to validate (typically a parsed JSON object).\n * @returns The validated {@linkcode JSONRPCMessage}.\n * @throws If validation fails.\n */\nexport function parseJSONRPCMessage(value: unknown): JSONRPCMessage {\n    return JSONRPCMessageSchema.parse(value);\n}\n\nexport const isJSONRPCRequest = (value: unknown): value is JSONRPCRequest => JSONRPCRequestSchema.safeParse(value).success;\n\nexport const isJSONRPCNotification = (value: unknown): value is JSONRPCNotification => JSONRPCNotificationSchema.safeParse(value).success;\n\n/**\n * Checks if a value is a valid {@linkcode JSONRPCResultResponse}.\n * @param value - The value to check.\n *\n * @returns True if the value is a valid {@linkcode JSONRPCResultResponse}, false otherwise.\n */\nexport const isJSONRPCResultResponse = (value: unknown): value is JSONRPCResultResponse =>\n    JSONRPCResultResponseSchema.safeParse(value).success;\n\n/**\n * Checks if a value is a valid {@linkcode JSONRPCErrorResponse}.\n * @param value - The value to check.\n *\n * @returns True if the value is a valid {@linkcode JSONRPCErrorResponse}, false otherwise.\n */\nexport const isJSONRPCErrorResponse = (value: unknown): value is JSONRPCErrorResponse =>\n    JSONRPCErrorResponseSchema.safeParse(value).success;\n\n/**\n * Checks if a value is a valid {@linkcode JSONRPCResponse} (either a result or error response).\n * @param value - The value to check.\n *\n * @returns True if the value is a valid {@linkcode JSONRPCResponse}, false otherwise.\n */\nexport const isJSONRPCResponse = (value: unknown): value is JSONRPCResponse => JSONRPCResponseSchema.safeParse(value).success;\n\n/**\n * Checks if a value is a valid {@linkcode CallToolResult}.\n *\n * This is a consumer-side VALUE check against the neutral model, not a wire\n * validator: a raw wire object that additionally carries wire-only members\n * (e.g. `resultType`) still passes through the loose index signature. Use a\n * transport-level parse to validate raw wire traffic.\n *\n * @param value - The value to check.\n *\n * @returns True if the value is a valid {@linkcode CallToolResult}, false otherwise.\n */\nexport const isCallToolResult = (value: unknown): value is CallToolResult => {\n    // content === undefined covers an explicit undefined key too: the schema's\n    // .default([]) would parse it, but the narrowed type requires the array.\n    if (typeof value !== 'object' || value === null || (value as { content?: unknown }).content === undefined) return false;\n    return CallToolResultSchema.safeParse(value).success;\n};\n\n/**\n * Checks whether a value is an input-required result (protocol revision\n * 2026-07-28): the multi-round-trip return shape discriminated by\n * `resultType: 'input_required'`.\n *\n * This is a discriminator check, not a full validator — the at-least-one rule\n * (`inputRequests` or `requestState`) is enforced by the `inputRequired()`\n * builder and re-checked by the server seam for hand-built values.\n *\n * @param value - The value to check.\n * @returns True if the value carries the `input_required` discriminator.\n */\nexport const isInputRequiredResult = (value: unknown): value is InputRequiredResult =>\n    typeof value === 'object' &&\n    value !== null &&\n    !Array.isArray(value) &&\n    (value as { resultType?: unknown }).resultType === 'input_required';\n\n/**\n * Checks if a value is a valid {@linkcode TaskAugmentedRequestParams}.\n * @param value - The value to check.\n *\n * @returns True if the value is a valid {@linkcode TaskAugmentedRequestParams}, false otherwise.\n *\n * @deprecated Recognizes 2025-11-25 task wire vocabulary, which has no SDK\n * runtime; kept importable for interoperability only.\n */\nexport const isTaskAugmentedRequestParams = (value: unknown): value is TaskAugmentedRequestParams =>\n    TaskAugmentedRequestParamsSchema.safeParse(value).success;\n\nexport const isInitializeRequest = (value: unknown): value is InitializeRequest => InitializeRequestSchema.safeParse(value).success;\n\nexport const isInitializedNotification = (value: unknown): value is InitializedNotification =>\n    InitializedNotificationSchema.safeParse(value).success;\n\nexport function assertCompleteRequestPrompt(request: CompleteRequest): asserts request is CompleteRequestPrompt {\n    if (request.params.ref.type !== 'ref/prompt') {\n        throw new TypeError(`Expected CompleteRequestPrompt, but got ${request.params.ref.type}`);\n    }\n    void (request as CompleteRequestPrompt);\n}\n\nexport function assertCompleteRequestResourceTemplate(request: CompleteRequest): asserts request is CompleteRequestResourceTemplate {\n    if (request.params.ref.type !== 'ref/resource') {\n        throw new TypeError(`Expected CompleteRequestResourceTemplate, but got ${request.params.ref.type}`);\n    }\n    void (request as CompleteRequestResourceTemplate);\n}\n","/**\n * SEP-2243 `Mcp-Param-*` header codec (protocol revision 2026-07-28).\n *\n * Pure functions for the custom-header half of SEP-2243: scanning a tool's\n * `inputSchema` for `x-mcp-header` declarations, encoding argument values into\n * `Mcp-Param-{Name}` HTTP headers (with the `=?base64?…?=` sentinel for values\n * that cannot be safely represented as plain ASCII field values), decoding\n * those headers, and validating that the headers a request carries match the\n * argument values in its body.\n *\n * The standard-header half (`MCP-Protocol-Version`, `Mcp-Method`, `Mcp-Name`)\n * lives with the inbound classifier — this module is the custom-header half\n * only, and it consumes the same `-32020` (`HeaderMismatch`) emission shape the\n * classifier established for header/body cross-check failures.\n *\n * Spec text at the implementation's spec pin:\n * - draft/basic/transports/streamable-http.mdx § \"Custom Headers from Tool Parameters\"\n *   (constraints, value encoding, the 5-step client algorithm, the\n *   server-behavior table, the `400` + `-32020` rejection)\n * - draft/server/tools.mdx § \"x-mcp-header\" (the schema-extension property and\n *   its constraints)\n */\nimport type { InboundLadderRejection } from './inboundClassification';\nimport { HEADER_MISMATCH_ERROR_CODE } from './inboundClassification';\n\n/* ------------------------------------------------------------------------ *\n * Declaration scan\n * ------------------------------------------------------------------------ */\n\n/** The fixed prefix every custom-parameter header carries. */\nexport const MCP_PARAM_HEADER_PREFIX = 'Mcp-Param-';\n\n/** The schema-extension property name a tool's `inputSchema` carries. */\nexport const X_MCP_HEADER_KEY = 'x-mcp-header';\n\n/**\n * One `x-mcp-header` declaration found inside a tool's `inputSchema`.\n *\n * `path` is the property path from the arguments root (the spec permits\n * declarations at any nesting depth under `properties`); `headerName` is the\n * `{Name}` portion as declared (case preserved for emission; comparison is\n * case-insensitive); `type` is the JSON Schema `type` of the declaring\n * property.\n */\nexport interface XMcpHeaderDeclaration {\n    path: readonly string[];\n    headerName: string;\n    type: string;\n}\n\n/** The result of scanning a tool's `inputSchema`; an invalid one carries `declarations` when `number` types are its only fault. */\nexport type XMcpHeaderScanResult =\n    | { valid: true; declarations: readonly XMcpHeaderDeclaration[] }\n    | { valid: false; reason: string; declarations?: readonly XMcpHeaderDeclaration[] };\n\n/**\n * RFC 9110 §5.1 `token` syntax (`1*tchar`). Rejects empty, space, control\n * characters (including CR/LF), and the listed delimiters.\n */\nconst RFC9110_TOKEN = /^[!#$%&'*+\\-.^_`|~0-9A-Za-z]+$/;\n\n/**\n * JSON Schema `type` values the spec admits on an `x-mcp-header` property:\n * `integer`, `string` and `boolean`. `number` is explicitly not permitted\n * (2026-07-28 Streamable HTTP, \"Schema Extension\"), so a tool that annotates a\n * `number`-typed property is invalid (the server still checks its headers).\n * Everything else (`object`, `array`, `null`, absent) is rejected too.\n */\nconst PERMITTED_X_MCP_HEADER_TYPES: ReadonlySet<string> = new Set(['string', 'integer', 'boolean']);\n\n/**\n * Scan a tool's JSON-serialized `inputSchema` for `x-mcp-header` declarations\n * and validate every constraint the spec places on them. Returns either the\n * collected declarations (possibly empty) or the first violated constraint\n * (with the declarations too, when `number`-typed declarations are the only fault).\n *\n * The walk descends through `properties` at any depth (the spec's \"any nesting\n * depth\" clause). The static-reachability MUST is enforced as a structural\n * sweep: every position the chain MUST NOT pass through (`items`/\n * `additionalProperties`, `oneOf`/`anyOf`/`allOf`/`not`, `if`/`then`/`else`,\n * `$defs`, `$ref` targets within `$defs`) is visited too, and an\n * `x-mcp-header` found anywhere on that path invalidates the schema — \"an\n * annotation anywhere else makes the tool definition invalid\".\n */\nexport function scanXMcpHeaderDeclarations(inputSchema: unknown): XMcpHeaderScanResult {\n    const declarations: XMcpHeaderDeclaration[] = [];\n    const seenLower = new Map<string, string>();\n    let numberFault: string | undefined;\n\n    const visit = (node: unknown, path: readonly string[], reachable: boolean): string | undefined => {\n        if (node === null || typeof node !== 'object') return undefined;\n        const schema = node as Record<string, unknown>;\n\n        if (X_MCP_HEADER_KEY in schema) {\n            if (!reachable || path.length === 0) {\n                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)`;\n            }\n            const raw = schema[X_MCP_HEADER_KEY];\n            if (typeof raw !== 'string' || raw.length === 0) {\n                return `${pathName(path)}: x-mcp-header MUST be a non-empty string`;\n            }\n            if (!RFC9110_TOKEN.test(raw)) {\n                return `${pathName(path)}: x-mcp-header '${raw}' is not a valid RFC 9110 token (no spaces, control characters or HTTP delimiters)`;\n            }\n            const type = typeof schema.type === 'string' ? schema.type : undefined;\n            if (type === undefined || !PERMITTED_X_MCP_HEADER_TYPES.has(type)) {\n                const fault = `${pathName(path)}: x-mcp-header is only permitted on primitive-typed properties (string, integer, boolean); got ${type ?? '<none>'}`;\n                // A `number` type is a fault, but the walk goes on so the server can still check the tool's headers.\n                if (type !== 'number') return fault;\n                numberFault ??= fault;\n            }\n            const lower = raw.toLowerCase();\n            const prior = seenLower.get(lower);\n            if (prior !== undefined) {\n                return `x-mcp-header '${raw}' is not case-insensitively unique (also declared as '${prior}')`;\n            }\n            seenLower.set(lower, raw);\n            declarations.push({ path, headerName: raw, type });\n        }\n\n        const properties = schema.properties;\n        if (properties !== null && typeof properties === 'object') {\n            for (const [key, child] of Object.entries(properties as Record<string, unknown>)) {\n                const fault = visit(child, [...path, key], reachable);\n                if (fault !== undefined) return fault;\n            }\n        }\n        // Static-reachability sweep: descend the keywords the chain MUST NOT\n        // pass through with `reachable: false` so an annotation under any of\n        // them is reported (rather than silently ignored). `$defs` covers\n        // `$ref`-within-`$defs` — chasing arbitrary `$ref` URIs is out of scope.\n        for (const k of NON_REACHABLE_SUBSCHEMA_KEYWORDS) {\n            const sub = schema[k];\n            if (sub === undefined) continue;\n            const branches: unknown[] = Array.isArray(sub)\n                ? sub\n                : sub !== null && typeof sub === 'object' && OBJECT_VALUED_SUBSCHEMA_KEYWORDS.has(k)\n                  ? Object.values(sub as Record<string, unknown>)\n                  : [sub];\n            for (const branch of branches) {\n                const fault = visit(branch, [...path, `<${k}>`], false);\n                if (fault !== undefined) return fault;\n            }\n        }\n        return undefined;\n    };\n\n    const fault = visit(inputSchema, [], true);\n    if (fault !== undefined) return { valid: false, reason: numberFault ?? fault };\n    return numberFault === undefined ? { valid: true, declarations } : { valid: false, reason: numberFault, declarations };\n}\n\n/**\n * JSON Schema keywords whose subschemas the SEP-2243 static-reachability\n * constraint excludes from the `properties`-only chain. An `x-mcp-header`\n * found under any of these invalidates the tool definition.\n */\nconst NON_REACHABLE_SUBSCHEMA_KEYWORDS = [\n    'items',\n    'prefixItems',\n    'contains',\n    'additionalProperties',\n    'unevaluatedProperties',\n    'unevaluatedItems',\n    'propertyNames',\n    'patternProperties',\n    'dependentSchemas',\n    'oneOf',\n    'anyOf',\n    'allOf',\n    'not',\n    'if',\n    'then',\n    'else',\n    '$defs',\n    'definitions'\n] as const;\n\n/**\n * Subschema-carrying keywords whose value is a `name → subschema` object\n * (not a single subschema or array of subschemas). The visit branches over\n * `Object.values()` for these.\n */\nconst OBJECT_VALUED_SUBSCHEMA_KEYWORDS: ReadonlySet<string> = new Set(['patternProperties', 'dependentSchemas', '$defs', 'definitions']);\n\nfunction pathName(path: readonly string[]): string {\n    return path.length === 0 ? '<root>' : path.join('.');\n}\n\n/* ------------------------------------------------------------------------ *\n * Value encoding\n * ------------------------------------------------------------------------ */\n\nconst BASE64_SENTINEL_PREFIX = '=?base64?';\nconst BASE64_SENTINEL_SUFFIX = '?=';\n// RFC 4648 §4, padding required (the spec's encoding-examples table and the\n// conformance referee's invalid-padding cell both require canonical padding).\nconst BASE64_CANONICAL = /^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/;\n// Strict decimal — gates the numeric comparison in `validateMcpParamHeaders`\n// so `Number()` never sees the looser forms it would otherwise accept\n// (`'0x1a'`, `' 42 '`, `'1e3'`).\nconst CANONICAL_DECIMAL = /^-?\\d+(\\.\\d+)?$/;\n\n/**\n * Convert a primitive argument value to its string representation per the\n * spec's type-conversion rules: strings pass through, integers and numbers\n * become their decimal string, booleans become lowercase `'true'` / `'false'`.\n * Non-finite numbers and integers outside the safe range are refused (the\n * caller treats `undefined` as \"do not emit a header for this value\").\n */\nexport function mcpParamPrimitiveToString(value: unknown): string | undefined {\n    if (typeof value === 'string') return value;\n    if (typeof value === 'boolean') return value ? 'true' : 'false';\n    if (typeof value === 'number') {\n        if (!Number.isFinite(value)) return undefined;\n        if (Number.isInteger(value) && !Number.isSafeInteger(value)) return undefined;\n        return String(value);\n    }\n    return undefined;\n}\n\n/**\n * `true` when `s` cannot be safely represented as a plain ASCII HTTP field\n * value per RFC 9110 §5.5: it contains a byte outside `0x20–0x7E` / `0x09`, it\n * has leading or trailing whitespace (which field parsing strips), or it\n * already matches the Base64 sentinel pattern (the spec's \"to avoid ambiguity\"\n * rule).\n */\nfunction needsBase64(s: string): boolean {\n    if (s.length === 0) return true;\n    if (s.startsWith(BASE64_SENTINEL_PREFIX) && s.endsWith(BASE64_SENTINEL_SUFFIX)) return true;\n    if (s !== s.trim()) return true;\n    for (let i = 0; i < s.length; i++) {\n        const c = s.codePointAt(i)!;\n        // Visible ASCII 0x21–0x7E, plus space 0x20 and horizontal tab 0x09; a\n        // tab is only safe when it is interior whitespace (the trim() check\n        // above already covered leading/trailing).\n        if (c === 0x09 || (c >= 0x20 && c <= 0x7e)) continue;\n        return true;\n    }\n    return false;\n}\n\nfunction utf8ToBase64(s: string): string {\n    const bytes = new TextEncoder().encode(s);\n    let bin = '';\n    for (const b of bytes) bin += String.fromCodePoint(b);\n    return btoa(bin);\n}\n\nfunction base64ToUtf8(b64: string): string {\n    const bin = atob(b64);\n    const bytes = new Uint8Array(bin.length);\n    for (let i = 0; i < bin.length; i++) bytes[i] = bin.codePointAt(i)!;\n    return new TextDecoder('utf-8', { fatal: true }).decode(bytes);\n}\n\n/**\n * Encode a string value as an HTTP field value per the spec's value-encoding\n * rules: a value that is already a safe plain-ASCII field value is passed\n * through unchanged; anything else is wrapped as `=?base64?{b64-of-utf8}?=`.\n */\nexport function encodeMcpParamValue(value: string): string {\n    return needsBase64(value) ? `${BASE64_SENTINEL_PREFIX}${utf8ToBase64(value)}${BASE64_SENTINEL_SUFFIX}` : value;\n}\n\n/**\n * Decode an `Mcp-Param-*` header value: when it carries the Base64 sentinel,\n * the payload is decoded as UTF-8; otherwise the value is returned as-is.\n * Returns `undefined` when the sentinel is present but the payload is not\n * canonical Base64 (or not valid UTF-8) — the spec requires servers to reject\n * such values.\n */\nexport function decodeMcpParamValue(value: string): string | undefined {\n    if (!(value.startsWith(BASE64_SENTINEL_PREFIX) && value.endsWith(BASE64_SENTINEL_SUFFIX))) {\n        return value;\n    }\n    const b64 = value.slice(BASE64_SENTINEL_PREFIX.length, value.length - BASE64_SENTINEL_SUFFIX.length);\n    if (!BASE64_CANONICAL.test(b64)) return undefined;\n    try {\n        return base64ToUtf8(b64);\n    } catch {\n        return undefined;\n    }\n}\n\n/* ------------------------------------------------------------------------ *\n * Client-side header construction (the 5-step MUST algorithm, steps 3–5)\n * ------------------------------------------------------------------------ */\n\nfunction valueAtPath(root: unknown, path: readonly string[]): unknown {\n    let node: unknown = root;\n    for (const key of path) {\n        if (node === null || typeof node !== 'object') return undefined;\n        node = (node as Record<string, unknown>)[key];\n    }\n    return node;\n}\n\n/**\n * Build the `Mcp-Param-{Name}` headers for one `tools/call` from a scan of the\n * tool's `inputSchema` and the call's `arguments`. A declaration whose value is\n * `null` or absent in `arguments` is omitted (the spec's \"client MUST omit the\n * header\" rows); a value that is not a primitive of the declared kind is\n * omitted rather than emitted malformed.\n */\nexport function buildMcpParamHeaders(\n    declarations: readonly XMcpHeaderDeclaration[],\n    args: Record<string, unknown> | undefined\n): Record<string, string> {\n    const out: Record<string, string> = {};\n    for (const decl of declarations) {\n        const raw = valueAtPath(args, decl.path);\n        if (raw === undefined || raw === null) continue;\n        const stringValue = mcpParamPrimitiveToString(raw);\n        if (stringValue === undefined) continue;\n        out[`${MCP_PARAM_HEADER_PREFIX}${decl.headerName}`] = encodeMcpParamValue(stringValue);\n    }\n    return out;\n}\n\n/* ------------------------------------------------------------------------ *\n * Server-side validation\n * ------------------------------------------------------------------------ */\n\n/**\n * The header/body comparison the server performs at tool-resolution time.\n *\n * For each `x-mcp-header` declaration on the named tool: when the body\n * `arguments` carries a value, the matching `Mcp-Param-{Name}` header MUST be\n * present and decode to an equal value; when the body value is `null` or\n * absent the server MUST NOT expect the header (a present header is ignored).\n * A sentinel-carrying header whose payload is not canonical Base64 / valid\n * UTF-8 is rejected as invalid characters.\n *\n * Integer- and number-typed declarations are compared numerically (the spec's SHOULD —\n * `42.0` and `42` are equal); everything else is compared as decoded strings.\n *\n * Returns `undefined` when every check passes, or an\n * {@linkcode InboundLadderRejection} carrying the same `-32020`\n * (`HeaderMismatch`) shape the inbound classifier emits for the\n * standard-header cross-checks — `400 Bad Request` with the disagreeing pair\n * in `data.mismatch`.\n */\nexport function validateMcpParamHeaders(\n    declarations: readonly XMcpHeaderDeclaration[],\n    args: Record<string, unknown> | undefined,\n    headers: Headers\n): InboundLadderRejection | undefined {\n    for (const decl of declarations) {\n        const headerKey = `${MCP_PARAM_HEADER_PREFIX}${decl.headerName}`;\n        const headerValue = headers.get(headerKey);\n        const bodyRaw = valueAtPath(args, decl.path);\n\n        if (bodyRaw === undefined || bodyRaw === null) {\n            // Server MUST NOT expect the header for a null/absent value.\n            continue;\n        }\n        const bodyString = mcpParamPrimitiveToString(bodyRaw);\n        if (bodyString === undefined) {\n            // Body carries a non-primitive where the schema declares one;\n            // params validation owns that fault. Skip the header check.\n            continue;\n        }\n        if (headerValue === null) {\n            return paramHeaderMismatchRejection(\n                'param-header-missing',\n                headerKey,\n                `the body carries ${pathName(decl.path)}=${JSON.stringify(bodyRaw)} but the ${headerKey} header is absent`\n            );\n        }\n        const decoded = decodeMcpParamValue(headerValue);\n        if (decoded === undefined) {\n            return paramHeaderMismatchRejection(\n                'param-header-invalid-encoding',\n                headerKey,\n                `the ${headerKey} header carries an invalid Base64 sentinel value`\n            );\n        }\n        // Integer/number-typed declarations compare numerically (the spec's\n        // SHOULD — `42.0` and `42` are equal). The strict-decimal gate is\n        // applied to the *header* side only (so `'0x1a'`, `' 42 '`, `'1e3'`\n        // etc. never coerce); the body side is gated on being an actual JS\n        // number — `String(0.0000001) === '1e-7'` would fail the regex even\n        // though the value is perfectly canonical. A non-numeric body\n        // primitive (e.g. `'abc'` where the schema declares `integer`) is a\n        // body-vs-schema fault that params validation owns; fall back to\n        // string comparison and let dispatch emit `-32602` instead so an\n        // identical non-numeric pair never reports a mismatch.\n        const numericComparable =\n            (decl.type === 'integer' || decl.type === 'number') && CANONICAL_DECIMAL.test(decoded) && typeof bodyRaw === 'number';\n        const equal = numericComparable ? Number(decoded) === bodyRaw : decoded === bodyString;\n        if (!equal) {\n            return paramHeaderMismatchRejection(\n                'param-header-mismatch',\n                headerKey,\n                `the ${headerKey} header decodes to ${JSON.stringify(decoded)} but the body carries ${pathName(decl.path)}=${JSON.stringify(bodyRaw)}`\n            );\n        }\n    }\n    return undefined;\n}\n\n/**\n * Build the `-32020` (`HeaderMismatch`) rejection for an `Mcp-Param-*`\n * disagreement. Same shape as the inbound classifier's standard-header\n * cross-check mismatch (HTTP `400`, `data.mismatch` naming the disagreeing\n * pair, `settled: true`); only the rung differs because this check runs at the\n * pre-dispatch step against a known tool's schema rather than at the edge.\n */\nexport function paramHeaderMismatchRejection(cell: string, header: string, body: string): InboundLadderRejection {\n    return {\n        kind: 'reject',\n        rung: 'param-header-validation',\n        cell,\n        httpStatus: 400,\n        code: HEADER_MISMATCH_ERROR_CODE,\n        message: `Bad Request: the request headers and body disagree: ${body}`,\n        data: { mismatch: { header, body } },\n        settled: true\n    };\n}\n","/**\n * Inbound HTTP request classification and the inbound validation ladder\n * (protocol revision 2026-07-28).\n *\n * `classifyInboundRequest` is the body-primary era predicate for an HTTP\n * entry that serves both protocol eras on one endpoint. It is evaluated\n * exactly once, at the entry boundary, on the already-parsed request body:\n *\n * - `initialize` is a legacy-era request by definition (the modern era has no\n *   `initialize` handshake) — unless it carries a valid envelope claim naming\n *   a modern revision, in which case the claim wins and the request is\n *   classified like any other enveloped request (the modern era then answers\n *   it with method-not-found, exactly like every other method it does not\n *   define).\n * - A request whose `params._meta` carries the reserved protocol-version key\n *   claims the per-request envelope mechanism and classifies into the era the\n *   named revision belongs to (a malformed envelope behind a present claim is\n *   a validation error, never a silent fall back to legacy handling).\n * - A request without a claim is legacy-era traffic.\n * - The `MCP-Protocol-Version` header is a cross-check only *for\n *   classification*: it never upgrades or downgrades a body-derived\n *   classification, and a disagreement between header and body is an explicit\n *   ladder outcome. Its absence likewise never changes the era — but the spec\n *   requires the header on every modern *request* POST, so a\n *   modern-classified request that omits it is refused one rung later, by\n *   {@linkcode validateStandardRequestHeaders}, not here. Notification POSTs\n *   are exempt (see the next bullet), and that rung enforces presence on\n *   requests only.\n * - Notifications carry no envelope claim of their own under the current\n *   spec, so for notification POSTs without a body claim the modern header is\n *   determinative; the `Mcp-Method` header is validated against the body when\n *   the message classifies modern and is never enforced on legacy traffic.\n *   A notification that does carry a claim is treated body-primary like a\n *   request, and a malformed claim is rejected the same way a request's\n *   malformed claim is — never silently resolved against the header.\n *   The notification-POST header cross-checks here are an SDK-defensive\n *   posture, not a spec requirement: the spec leaves header rules for posted\n *   notifications undefined (core client notifications do not occur over\n *   Streamable HTTP); applying the request rules symmetrically is what an\n *   ecosystem custom-notification POST expects, and the −32020 cells stay\n *   passing for them.\n * - `GET`/`DELETE` (and any other non-`POST` method) are body-less 2025-era\n *   session operations: the modern era is `POST`-only, so they are routed to\n *   legacy serving when it is configured and rejected otherwise.\n * - Array (batch) bodies are classified element-wise: an array containing a\n *   modern-claiming or invalid element is rejected, an all-legacy array is\n *   legacy traffic unchanged, and a single-element array is still an array.\n *\n * The classifier returns plain values (it never throws and never touches a\n * transport): a routing outcome (`legacy`/`modern`) or a ladder rejection\n * carrying the JSON-RPC error to emit and the HTTP status to emit it with.\n * Legacy routing outcomes deliberately carry NO `MessageClassification` —\n * legacy and hand-wired traffic is never classified, which keeps its\n * dispatch behavior byte-identical to today's.\n *\n * Error codes for the modern-path rejection cells follow the published\n * conformance suite (and the spec text it asserts):\n *\n * - A header/body cross-check mismatch (the `MCP-Protocol-Version` header\n *   disagreeing with the body, or the `Mcp-Method` header disagreeing with the\n *   body method) is rejected with `-32020` (`HeaderMismatch`) on HTTP 400.\n * - A request whose protocol-version header names a modern revision but whose\n *   body carries no `_meta` envelope claim — including an envelope present but\n *   missing the required protocol-version key — is rejected with `-32602`\n *   (invalid params) naming the missing key(s), on HTTP 400.\n *\n * Should a future spec revision or conformance release change these\n * assignments, the affected cells are re-derived against that release; the\n * `settled` flag on {@linkcode InboundLadderRejection} stays available to mark\n * a cell provisional again while such a change is in flight.\n */\nimport { PROTOCOL_VERSION_META_KEY } from '../types/constants';\nimport { ProtocolErrorCode } from '../types/enums';\nimport { ProtocolError, UnsupportedProtocolVersionError } from '../types/errors';\nimport { isJSONRPCErrorResponse, isJSONRPCNotification, isJSONRPCRequest, isJSONRPCResultResponse } from '../types/guards';\nimport type { JSONRPCNotification, JSONRPCRequest, MessageClassification } from '../types/types';\nimport { envelopeClaimVersion, hasEnvelopeClaim, requestMetaOf, validateEnvelopeMeta } from './envelope';\n// Value encoding is shared between the standard `Mcp-Name` header and the\n// custom `Mcp-Param-*` headers; the codec module already imports the\n// `HeaderMismatch` constant and rejection type from here, so this is a benign\n// two-module cycle (both sides only consume the other's exports inside\n// function bodies, never at module-evaluation time).\nimport { decodeMcpParamValue } from './mcpParamHeaders';\nimport { isModernProtocolVersion } from './protocolEras';\n\n/* ------------------------------------------------------------------------ *\n * Classifier input\n * ------------------------------------------------------------------------ */\n\n/**\n * The transport-neutral description of an inbound HTTP request the classifier\n * evaluates. The caller (the HTTP entry) reads the body exactly once and\n * extracts the two protocol headers; the classifier never touches a request\n * object itself.\n */\nexport interface InboundHttpRequest {\n    /** The HTTP request method, e.g. `POST`, `GET`, `DELETE`. */\n    httpMethod: string;\n    /** The value of the `MCP-Protocol-Version` header, when present. */\n    protocolVersionHeader?: string;\n    /** The value of the `Mcp-Method` header, when present. */\n    mcpMethodHeader?: string;\n    /** The value of the `Mcp-Name` header, when present. */\n    mcpNameHeader?: string;\n    /** The parsed JSON request body (`undefined` for body-less methods). */\n    body?: unknown;\n}\n\n/* ------------------------------------------------------------------------ *\n * Classifier outcomes\n * ------------------------------------------------------------------------ */\n\n/** Why an inbound request was routed to legacy-era serving. */\nexport type InboundLegacyRouteReason =\n    /** Non-`POST` HTTP method: a body-less 2025-era session operation. */\n    | 'http-method'\n    /** An `initialize` request without a valid modern envelope claim — the legacy handshake by definition. */\n    | 'initialize'\n    /** A request without a per-request envelope claim. */\n    | 'no-claim'\n    /** A notification without a body claim or a modern protocol-version header. */\n    | 'notification'\n    /** An all-legacy JSON-RPC batch array. */\n    | 'batch'\n    /** A JSON-RPC response posted to the endpoint (2025-era session traffic). */\n    | 'response';\n\n/**\n * The request is legacy-era traffic. It carries no classification on purpose:\n * legacy serving receives it exactly as a hand-wired 2025 transport would.\n */\nexport interface InboundLegacyRoute {\n    kind: 'legacy';\n    reason: InboundLegacyRouteReason;\n    /**\n     * The protocol version the request named, when it named one (an\n     * `initialize` body's `protocolVersion`, or the `MCP-Protocol-Version`\n     * header). Used to echo `requested` when legacy serving is not configured.\n     */\n    requestedVersion?: string;\n}\n\n/**\n * The request claims the per-request envelope mechanism and is served on the\n * modern path. Discriminated by `messageKind` so the typed `message` narrows\n * with it — the classifier has already proved the JSON-RPC shape via the\n * `isJSONRPCRequest` / `isJSONRPCNotification` guards, so consumers never\n * cast the body again.\n */\nexport type InboundModernRoute =\n    | {\n          kind: 'modern';\n          messageKind: 'request';\n          /** The classified body — guard-proved {@linkcode JSONRPCRequest} shape. */\n          message: JSONRPCRequest;\n          /**\n           * The classification handed to the per-request transport and validated by\n           * the protocol layer against the serving instance's negotiated era.\n           */\n          classification: MessageClassification;\n      }\n    | {\n          kind: 'modern';\n          messageKind: 'notification';\n          /** The classified body — guard-proved {@linkcode JSONRPCNotification} shape. */\n          message: JSONRPCNotification;\n          classification: MessageClassification;\n      };\n\n/** The named steps of the inbound validation ladder, in evaluation order. */\nexport type InboundValidationRung =\n    | 'http-method'\n    | 'jsonrpc-shape'\n    | 'era-classification'\n    | 'envelope'\n    | 'method-registry'\n    | 'request-params'\n    | 'standard-header-validation'\n    | 'client-capabilities'\n    | 'param-header-validation';\n\n/** A ladder rejection: the JSON-RPC error to emit and the HTTP status to emit it with. */\nexport interface InboundLadderRejection {\n    kind: 'reject';\n    /** The ladder rung that produced the rejection. */\n    rung: InboundValidationRung;\n    /** The cell this rejection corresponds to on the ladder cell sheet (stable identifier for tests). */\n    cell: string;\n    /** The HTTP status the rejection is emitted with. */\n    httpStatus: number;\n    /** The JSON-RPC error code. */\n    code: number;\n    /** The JSON-RPC error message. */\n    message: string;\n    /** Structured error data (recognizers parse this; they never rely on class identity). */\n    data?: unknown;\n    /**\n     * `false` when the exact error code for this cell is not settled upstream\n     * yet and the emitted code is provisional.\n     */\n    settled: boolean;\n}\n\n/** The outcome of classifying one inbound HTTP request. */\nexport type InboundClassificationOutcome = InboundLegacyRoute | InboundModernRoute | InboundLadderRejection;\n\n/* ------------------------------------------------------------------------ *\n * Header cross-check mismatches\n * ------------------------------------------------------------------------ */\n\n/**\n * The error code emitted for header/body cross-check mismatches: the\n * `MCP-Protocol-Version` header disagreeing with the body's envelope claim (or\n * with the body's classification), and the `Mcp-Method` header disagreeing\n * with the body method.\n *\n * `-32020` is the draft schema's `HEADER_MISMATCH` constant (the SEP-2243\n * `HeaderMismatch` code; the spec requires HTTP 400 for it), as also asserted\n * by the published conformance suite for header-validation failures. It has no\n * {@linkcode ProtocolErrorCode} member because it is not part of the 2025-era\n * wire vocabulary; the validation ladder is its only emitter.\n */\nexport const HEADER_MISMATCH_ERROR_CODE = -32_020;\n\n/* ------------------------------------------------------------------------ *\n * The validation ladder as data\n * ------------------------------------------------------------------------ */\n\n/** One rung of the inbound validation ladder. */\nexport interface InboundValidationRungDescriptor {\n    rung: InboundValidationRung;\n    /** Evaluation order: lower runs first; an earlier rung's outcome wins over a later rung's. */\n    order: number;\n    /**\n     * Where the rung is evaluated: at the HTTP entry edge by\n     * {@linkcode classifyInboundRequest} (`edge`), by the HTTP entry after\n     * classification but before dispatch (`pre-dispatch`), or by the protocol\n     * layer at dispatch (`dispatch`).\n     */\n    evaluatedAt: 'edge' | 'pre-dispatch' | 'dispatch';\n    /** The JSON-RPC error codes this rung can produce (empty when the rung only routes). */\n    codes: readonly number[];\n    /** Conformance scenarios that exercise this rung (where one exists). */\n    conformance: readonly string[];\n    /** Why the rung sits where it does. */\n    rationale: string;\n}\n\n/**\n * The inbound validation ladder, expressed as data rather than control flow.\n *\n * The edge rungs are evaluated by {@linkcode classifyInboundRequest}; the\n * dispatch rungs are evaluated by the protocol layer once the classified\n * message is injected into a per-request server instance (the era registry\n * gate, the envelope requiredness check, and per-method params validation).\n * The client-capability rung is evaluated by the HTTP entry itself,\n * pre-dispatch, on the validated envelope the classifier produced — see that\n * rung's rationale for the ordering caveat. The order is the precedence: a\n * request that fails several rungs is answered by the earliest one.\n */\nexport const INBOUND_VALIDATION_LADDER: readonly InboundValidationRungDescriptor[] = [\n    {\n        rung: 'http-method',\n        order: 1,\n        evaluatedAt: 'edge',\n        codes: [-32_000],\n        conformance: [],\n        rationale:\n            'The modern era is POST-only; GET/DELETE are body-less 2025-era session operations and are method-routed to legacy ' +\n            'serving (405 when legacy serving is not configured), before any body is read.'\n    },\n    {\n        rung: 'jsonrpc-shape',\n        order: 2,\n        evaluatedAt: 'edge',\n        codes: [ProtocolErrorCode.InvalidRequest],\n        conformance: ['server-stateless'],\n        rationale:\n            'The body must be a JSON-RPC request or notification: posted responses and batch arrays containing a modern or ' +\n            'invalid element are rejected before classification (element-wise batch rule); all-legacy arrays stay legacy traffic.'\n    },\n    {\n        rung: 'era-classification',\n        order: 3,\n        evaluatedAt: 'edge',\n        codes: [HEADER_MISMATCH_ERROR_CODE, ProtocolErrorCode.UnsupportedProtocolVersion],\n        conformance: ['server-stateless', 'http-header-validation', 'http-custom-header-server-validation'],\n        rationale:\n            'Body-primary era classification with the protocol-version header as a cross-check; a header/body disagreement is rejected ' +\n            'with -32020 (HeaderMismatch), and an envelope-less request on a modern-only endpoint is answered with the ' +\n            'unsupported-protocol-version error naming the supported revisions.'\n    },\n    {\n        rung: 'envelope',\n        order: 4,\n        evaluatedAt: 'edge',\n        codes: [ProtocolErrorCode.InvalidParams],\n        conformance: ['server-stateless'],\n        rationale:\n            'A present envelope claim with a malformed envelope — and a missing envelope on a request whose protocol-version header ' +\n            'names a modern revision — is an invalid-params rejection naming the offending or missing key(s); never a silent fall ' +\n            'back to legacy handling. This is the only place an invalid-params rejection maps to HTTP 400.'\n    },\n    {\n        rung: 'method-registry',\n        order: 5,\n        evaluatedAt: 'dispatch',\n        codes: [ProtocolErrorCode.MethodNotFound],\n        conformance: ['server-stateless'],\n        rationale:\n            'Method existence outranks parameter validity: a method absent from the negotiated revision’s registry (or with no ' +\n            'handler installed) answers method-not-found before params or capabilities are looked at.'\n    },\n    {\n        rung: 'request-params',\n        order: 6,\n        evaluatedAt: 'dispatch',\n        codes: [ProtocolErrorCode.InvalidParams],\n        conformance: [],\n        rationale: 'Per-method params validation; emitted in-band by the dispatch layer (HTTP 200), never via the ladder status table.'\n    },\n    {\n        rung: 'standard-header-validation',\n        order: 7,\n        evaluatedAt: 'pre-dispatch',\n        codes: [HEADER_MISMATCH_ERROR_CODE],\n        conformance: ['http-header-validation'],\n        rationale:\n            'SEP-2243 standard `MCP-Protocol-Version` / `Mcp-Method` / `Mcp-Name` headers — presence, sentinel decoding, and ' +\n            '`Mcp-Name` ↔ body cross-check — are validated by the HTTP entry on a modern-classified request after the ' +\n            'supported-revision gate and before dispatch. The spec requires `MCP-Protocol-Version` and `Mcp-Method` on every ' +\n            'modern *request* POST (`Mcp-Name` only for the methods that mirror `params.name` / `params.uri` / `params.taskId`, ' +\n            'see `MCP_NAME_HEADER_SOURCE`) and names them ' +\n            'in that order, so a request missing several is answered by the earliest. Notification POSTs are exempt: the ' +\n            'presence half runs on requests only, so a modern-enveloped notification is dispatched even with no standard ' +\n            'headers at all. The classifier’s own header-mismatch cells ' +\n            '(protocol-version, `Mcp-Method` mismatch) stay on the edge ' +\n            '`era-classification` rung; this rung carries the entry-layer presence/`Mcp-Name` half — including the missing ' +\n            '`MCP-Protocol-Version` cell, which cannot live on the edge rung without breaking body-primary classification. ' +\n            'Evaluated before the ' +\n            'capability gate, the factory call, and the `Mcp-Param-*` rung so a request that fails several rungs is answered by ' +\n            'the standard-header rung first. The documented order (after method-registry 5 and request-params 6) is NOT the ' +\n            'observed precedence: serveModern evaluates this rung immediately after the supported-revision gate, so a request ' +\n            'that also fails a dispatch rung is answered here before the dispatch rungs (5–6) are consulted.'\n    },\n    {\n        rung: 'client-capabilities',\n        order: 8,\n        evaluatedAt: 'pre-dispatch',\n        codes: [ProtocolErrorCode.MissingRequiredClientCapability],\n        conformance: ['server-stateless'],\n        rationale:\n            'The capability requirement is checked by the HTTP entry, pre-dispatch, against the validated envelope the ' +\n            'classifier produced — pinning the spec-mandated HTTP 400 independently of how dispatch- and handler-produced ' +\n            'errors are mapped. The documented order (after method resolution and params validation) is preserved observably ' +\n            'only while the requirement table is empty: once a served method gains a requirement entry, a request that is ' +\n            'missing the capability and would also fail a dispatch rung is answered by this gate first, so the entry must ' +\n            'consult the method registry before the gate if the documented precedence is to stay observable.'\n    },\n    {\n        rung: 'param-header-validation',\n        order: 9,\n        evaluatedAt: 'pre-dispatch',\n        codes: [HEADER_MISMATCH_ERROR_CODE],\n        conformance: ['http-custom-header-server-validation'],\n        rationale:\n            'SEP-2243 `Mcp-Param-*` headers are validated against the named tool’s `x-mcp-header` declarations and the body ' +\n            '`arguments` after the tool registry is known and before dispatch reaches the handler; a missing/disagreeing/malformed ' +\n            'header is rejected 400 / -32020 with the same shape as the standard-header cross-checks. The documented order ' +\n            '(after method resolution and params validation) is preserved observably only when the body `arguments` would ' +\n            'otherwise validate: the check runs pre-dispatch, so a `tools/call` that fails BOTH this rung and a dispatch-time ' +\n            'rung (e.g. order-6 `request-params`, -32602) is answered by this gate first with 400 / -32020, not by the ' +\n            'earlier-ordered rung.'\n    }\n];\n\n/* ------------------------------------------------------------------------ *\n * HTTP status mapping for ladder-originated errors\n * ------------------------------------------------------------------------ */\n\n/**\n * HTTP status for ladder-originated JSON-RPC error codes.\n *\n * Keyed on origin, not on the bare code: this table only applies to errors\n * the ladder (or a pre-handler protocol gate) produced. Errors produced by\n * request handlers — whatever their code — stay in-band on HTTP 200, and are\n * never mapped to an HTTP status by this table; in particular `-32603` and\n * domain-specific codes never become a blanket 500. The single exception is\n * `MissingRequiredClientCapability` (-32021) — see\n * {@linkcode httpStatusForErrorCode}.\n *\n * `-32602` (invalid params) deliberately has NO entry: the only invalid-params\n * rejection that maps to HTTP 400 is the classifier's own envelope rung\n * short-circuit, which carries its HTTP status directly. A dispatch- or\n * handler-produced invalid-params error is always in-band.\n */\nexport const LADDER_ERROR_HTTP_STATUS: Readonly<Record<number, number>> = {\n    [ProtocolErrorCode.ParseError]: 400,\n    [ProtocolErrorCode.InvalidRequest]: 400,\n    [ProtocolErrorCode.MethodNotFound]: 404,\n    [ProtocolErrorCode.UnsupportedProtocolVersion]: 400,\n    [ProtocolErrorCode.MissingRequiredClientCapability]: 400,\n    [HEADER_MISMATCH_ERROR_CODE]: 400\n};\n\n/**\n * The HTTP status to answer a JSON-RPC error with, keyed on the error's\n * origin. `in-band` errors (anything produced by a request handler) are\n * HTTP 200 — the JSON-RPC error response is the payload, not an HTTP\n * failure — with ONE exception: `MissingRequiredClientCapability` (-32021),\n * whose 400 the spec mandates on the error itself with no origin condition,\n * and which the SDK genuinely produces after dispatch (the `input_required`\n * capability gate). A handler relaying some downstream peer's `-32020`/`-32022`\n * is NOT that peer's spec error and stays in-band like every other handler\n * code. `ladder` errors map through {@linkcode LADDER_ERROR_HTTP_STATUS}.\n *\n * The per-request transport intentionally does NOT delegate to this function:\n * its `?? 400` ladder fallback is only correct for entry-gate codes known to\n * the table, and would wrongly map dispatch-window errors outside it (a\n * window `-32602` must stay in-band on 200). The transport indexes the table\n * directly; keep the two in agreement when editing either.\n */\nexport function httpStatusForErrorCode(code: number, origin: 'ladder' | 'in-band'): number {\n    if (origin === 'in-band') {\n        return code === ProtocolErrorCode.MissingRequiredClientCapability ? 400 : 200;\n    }\n    return LADDER_ERROR_HTTP_STATUS[code] ?? 400;\n}\n\n/* ------------------------------------------------------------------------ *\n * The classifier\n * ------------------------------------------------------------------------ */\n\nfunction rejection(\n    rung: InboundValidationRung,\n    cell: string,\n    httpStatus: number,\n    error: ProtocolError,\n    settled: boolean\n): InboundLadderRejection {\n    return {\n        kind: 'reject',\n        rung,\n        cell,\n        httpStatus,\n        code: error.code,\n        message: error.message,\n        ...(error.data !== undefined && { data: error.data }),\n        settled\n    };\n}\n\nfunction crossCheckMismatch(\n    cell: string,\n    header: string,\n    body: string,\n    rung: InboundValidationRung = 'era-classification'\n): InboundLadderRejection {\n    return rejection(\n        rung,\n        cell,\n        400,\n        new ProtocolError(HEADER_MISMATCH_ERROR_CODE, `Bad Request: the request headers and body disagree: ${body}`, {\n            mismatch: { header, body }\n        }),\n        true\n    );\n}\n\n/** The body field the `Mcp-Name` header mirrors for a method on {@linkcode MCP_NAME_HEADER_SOURCE}. */\nexport type McpNameSourceField = 'name' | 'uri' | 'taskId';\n\n/**\n * The methods whose body carries a `params.name` / `params.uri` /\n * `params.taskId` value the `Mcp-Name` header must mirror, and which body\n * field supplies it. The core rows come from SEP-2243 § Standard Request\n * Headers (`Required For` column); the `tasks/*` rows come from SEP-2663's\n * Streamable HTTP binding (\"the client MUST set the `Mcp-Name` header to the\n * value of `params.taskId`\" for `tasks/get` / `tasks/update` /\n * `tasks/cancel`, so intermediaries can route every request for a task to the\n * instance holding its state). Shared by the client transport (header\n * emission) and the server ladder (validation) so both sides derive from one\n * table.\n */\nexport const MCP_NAME_HEADER_SOURCE: Readonly<Record<string, McpNameSourceField>> = {\n    'tools/call': 'name',\n    'prompts/get': 'name',\n    'resources/read': 'uri',\n    'tasks/get': 'taskId',\n    'tasks/update': 'taskId',\n    'tasks/cancel': 'taskId'\n};\n\n/**\n * Resolve the `Mcp-Name` source for one request against\n * {@linkcode MCP_NAME_HEADER_SOURCE}: which body field the header mirrors for\n * `method`, and the string value that field carries in `params`.\n *\n * Returns `undefined` when `method` is off-table (no `Mcp-Name` is emitted or\n * required). Otherwise `value` is the field's string value, or `undefined`\n * when `params` is not a plain object or the field is absent / not a string —\n * the client emits no header then, and the server leaves that body to the\n * rungs further down the ladder.\n *\n * `method` is peer-supplied on the server and caller-supplied on the client,\n * so the table lookup is `Object.hasOwn`-guarded against `Object.prototype`\n * collisions (`constructor`, `toString`, …). Shared by the client transport\n * (emission) and {@linkcode validateStandardRequestHeaders} (validation) so\n * the extraction — not just the table — cannot drift between the two sides.\n */\nexport function mcpNameSource(method: string, params: unknown): { field: McpNameSourceField; value: string | undefined } | undefined {\n    const field = Object.hasOwn(MCP_NAME_HEADER_SOURCE, method) ? MCP_NAME_HEADER_SOURCE[method] : undefined;\n    if (field === undefined) {\n        return undefined;\n    }\n    const raw = isPlainObject(params) ? params[field] : undefined;\n    return { field, value: typeof raw === 'string' ? raw : undefined };\n}\n\n/** Strip RFC 9110 optional whitespace (SP / HTAB) around a field value in linear time. */\nfunction stripHttpOws(value: string): string {\n    let start = 0;\n    while (start < value.length) {\n        const code = value.codePointAt(start);\n        if (code !== 0x09 && code !== 0x20) break;\n        start += 1;\n    }\n\n    let end = value.length;\n    while (end > start) {\n        const code = value.codePointAt(end - 1);\n        if (code !== 0x09 && code !== 0x20) break;\n        end -= 1;\n    }\n\n    return start === 0 && end === value.length ? value : value.slice(start, end);\n}\n\n/**\n * SEP-2243 standard-header server-side validation, evaluated by the HTTP\n * entry on a modern-classified request immediately after\n * {@linkcode classifyInboundRequest} returns a modern route.\n *\n * Returns the `-32020` (`HeaderMismatch`) ladder rejection (HTTP `400`,\n * `standard-header-validation` rung — the same shape\n * {@linkcode classifyInboundRequest} already emits on the edge\n * `era-classification` rung for the `MCP-Protocol-Version` and\n * `Mcp-Method` *mismatch* cells) when:\n *\n * - the required `MCP-Protocol-Version` header is absent (SEP-2243 requires it\n *   on every modern *request* POST, and lists it first among the required\n *   standard headers — so a request missing it *and* `Mcp-Method` is answered\n *   by this cell);\n * - the required `Mcp-Method` header is absent;\n * - the required `Mcp-Name` header is absent on a `tools/call`,\n *   `prompts/get`, `resources/read`, or (per SEP-2663's Streamable HTTP\n *   binding) `tasks/get` / `tasks/update` / `tasks/cancel` request whose\n *   body carries the `params.name` / `params.uri` / `params.taskId` value\n *   the header mirrors;\n * - the `Mcp-Name` header carries an invalid `=?base64?…?=` sentinel; or\n * - the (decoded) `Mcp-Name` value disagrees with the body's\n *   `params.name` / `params.uri` / `params.taskId`.\n *\n * Returns `undefined` (pass) for notifications (the spec table reads\n * \"All requests\"), for methods that have no `Mcp-Name` source, and when the\n * headers agree with the body. Never enforced on legacy traffic — the entry\n * only calls this on a modern route.\n *\n * Kept separate from {@linkcode classifyInboundRequest} so that a body-only\n * call to the classifier (no headers passed) keeps routing a modern request\n * unchanged: the classifier remains a pure body-primary router, and this\n * function is the presence/`Mcp-Name` half of the standard-header rung the\n * entry layers on top. That separation is what lets the missing\n * `MCP-Protocol-Version` cell live here without disturbing the body-primary\n * rule — classification still resolves from the body (a proxy stripping the\n * header must not change the era), and only this rung refuses to serve it.\n */\nexport function validateStandardRequestHeaders(request: InboundHttpRequest, route: InboundModernRoute): InboundLadderRejection | undefined {\n    if (route.messageKind !== 'request') {\n        return undefined;\n    }\n    const method = route.message.method;\n\n    // SEP-2243 names `MCP-Protocol-Version` first among the required standard\n    // headers, so a request missing both it and `Mcp-Method` is answered by\n    // the header the spec names first. The presence check lives here rather\n    // than in `classifyInboundRequest` on purpose: classification stays\n    // body-primary (a proxy stripping the header must not change the era), and\n    // only this rung refuses to serve the request.\n    if (request.protocolVersionHeader === undefined) {\n        const claimed = route.classification.revision;\n        return crossCheckMismatch(\n            'version-header-missing',\n            '(missing)',\n            claimed === undefined\n                ? 'the body carries a modern per-request envelope but the required MCP-Protocol-Version header is absent'\n                : `the body envelope names protocol version ${claimed} but the required MCP-Protocol-Version header is absent`,\n            'standard-header-validation'\n        );\n    }\n\n    if (request.mcpMethodHeader === undefined) {\n        return crossCheckMismatch(\n            'method-header-missing',\n            '(missing)',\n            `the body names method ${method} but the required Mcp-Method header is absent`,\n            'standard-header-validation'\n        );\n    }\n\n    const source = mcpNameSource(method, route.message.params);\n    if (source === undefined) {\n        return undefined;\n    }\n    const { field: sourceField, value: bodyValue } = source;\n\n    if (request.mcpNameHeader === undefined) {\n        // The header is required for these methods whenever the body carries\n        // the source value. A body without the source field (`params.name` /\n        // `params.uri` / `params.taskId`) is answered by the rungs further\n        // down the ladder; this rung only answers the missing-header case it\n        // can observe.\n        if (bodyValue === undefined) {\n            return undefined;\n        }\n        return crossCheckMismatch(\n            'name-header-missing',\n            '(missing)',\n            `the body carries params.${sourceField}=\"${bodyValue}\" but the required Mcp-Name header is absent`,\n            'standard-header-validation'\n        );\n    }\n\n    const normalizedNameHeader = stripHttpOws(request.mcpNameHeader);\n    const decoded = decodeMcpParamValue(normalizedNameHeader);\n    if (decoded === undefined) {\n        return crossCheckMismatch(\n            'name-header-invalid-encoding',\n            normalizedNameHeader,\n            'the Mcp-Name header carries an invalid Base64 sentinel value',\n            'standard-header-validation'\n        );\n    }\n    if (bodyValue !== undefined && decoded !== bodyValue) {\n        return crossCheckMismatch(\n            'name-header-mismatch',\n            normalizedNameHeader,\n            `the body carries params.${sourceField}=\"${bodyValue}\" but the Mcp-Name header names \"${decoded}\"`,\n            'standard-header-validation'\n        );\n    }\n    return undefined;\n}\n\nfunction isPlainObject(value: unknown): value is Record<string, unknown> {\n    return value !== null && typeof value === 'object' && !Array.isArray(value);\n}\n\nfunction classificationForClaim(claimedVersion: string | undefined): MessageClassification {\n    if (claimedVersion === undefined) {\n        return { era: 'modern' };\n    }\n    return { era: isModernProtocolVersion(claimedVersion) ? 'modern' : 'legacy', revision: claimedVersion };\n}\n\n/**\n * Whether a request's params carry a per-request envelope claim that is both\n * well-formed and names a modern protocol revision.\n *\n * Used by the `initialize` precedence rule: only such a claim overrides the\n * `initialize` ⇒ legacy-handshake classification — a request carrying a valid\n * modern envelope is a modern request regardless of its method name, and the\n * modern era then answers `initialize` exactly like any other method it does\n * not define (method-not-found). A malformed claim, or one naming a pre-2026\n * revision, keeps the legacy-handshake routing unchanged.\n *\n * Exported on the core internal barrel for the stdio serving entry, which\n * applies the same precedence rule to a connection's opening message; not\n * public API.\n */\nexport function carriesValidModernEnvelopeClaim(params: unknown): boolean {\n    if (!hasEnvelopeClaim(params)) {\n        return false;\n    }\n    const claimedVersion = envelopeClaimVersion(params);\n    if (claimedVersion === undefined || !isModernProtocolVersion(claimedVersion)) {\n        return false;\n    }\n    const meta = requestMetaOf(params);\n    return meta !== undefined && validateEnvelopeMeta(meta).length === 0;\n}\n\nfunction classifyBatch(body: readonly unknown[]): InboundClassificationOutcome {\n    if (body.length === 0) {\n        return rejection(\n            'jsonrpc-shape',\n            'empty-batch',\n            400,\n            new ProtocolError(ProtocolErrorCode.InvalidRequest, 'Bad Request: empty JSON-RPC batch'),\n            true\n        );\n    }\n    for (const element of body) {\n        const params = isPlainObject(element) ? element['params'] : undefined;\n        if (hasEnvelopeClaim(params)) {\n            // Element-wise rule: a single modern element makes the whole array\n            // unservable — modern requests are single-message POSTs, and the\n            // legacy path must never serve an envelope-claiming element.\n            return rejection(\n                'jsonrpc-shape',\n                'batch-with-modern-element',\n                400,\n                new ProtocolError(\n                    ProtocolErrorCode.InvalidRequest,\n                    'Bad Request: JSON-RPC batches may not contain requests for protocol revision 2026-07-28 or later'\n                ),\n                true\n            );\n        }\n        const valid =\n            isJSONRPCRequest(element) ||\n            isJSONRPCNotification(element) ||\n            isJSONRPCResultResponse(element) ||\n            isJSONRPCErrorResponse(element);\n        if (!valid) {\n            return rejection(\n                'jsonrpc-shape',\n                'batch-with-invalid-element',\n                400,\n                new ProtocolError(ProtocolErrorCode.InvalidRequest, 'Bad Request: JSON-RPC batch contains an invalid message'),\n                true\n            );\n        }\n    }\n    // All elements are legacy-era messages: legacy serving takes the array unchanged.\n    return { kind: 'legacy', reason: 'batch' };\n}\n\nfunction classifyRequestBody(request: InboundHttpRequest, body: JSONRPCRequest): InboundClassificationOutcome {\n    const params = body.params;\n    const method = body.method;\n    const headerVersion = request.protocolVersionHeader;\n    const headerNamesModern = headerVersion !== undefined && isModernProtocolVersion(headerVersion);\n\n    // `initialize` is the legacy handshake by definition — unless the request\n    // carries a valid envelope claim naming a modern revision, in which case\n    // the claim wins: the request is classified like any other enveloped\n    // request and served on the modern path, where the modern registry answers\n    // `initialize` as method-not-found like every other method it does not\n    // define. A malformed or absent claim, or a claim naming a pre-2026\n    // revision, keeps the legacy-handshake classification below.\n    if (method === 'initialize' && !carriesValidModernEnvelopeClaim(params)) {\n        if (headerNamesModern) {\n            return crossCheckMismatch(\n                'initialize-with-modern-header',\n                headerVersion,\n                'an initialize request (legacy handshake) was sent with a modern MCP-Protocol-Version header'\n            );\n        }\n        const requestedVersion =\n            isPlainObject(params) && typeof params['protocolVersion'] === 'string' ? params['protocolVersion'] : undefined;\n        return { kind: 'legacy', reason: 'initialize', ...(requestedVersion !== undefined && { requestedVersion }) };\n    }\n\n    if (hasEnvelopeClaim(params)) {\n        // A present claim is validated, never silently ignored: a malformed\n        // envelope behind the claim is an invalid-params rejection naming the\n        // offending key, not a fall back to legacy handling.\n        const meta = requestMetaOf(params);\n        const issues = meta === undefined ? [] : validateEnvelopeMeta(meta);\n        const firstIssue = issues[0];\n        if (firstIssue !== undefined) {\n            return rejection(\n                'envelope',\n                'envelope-invalid',\n                400,\n                new ProtocolError(\n                    ProtocolErrorCode.InvalidParams,\n                    `Invalid _meta envelope for protocol revision 2026-07-28: ${firstIssue.key}: ${firstIssue.problem}`,\n                    { envelope: firstIssue }\n                ),\n                true\n            );\n        }\n\n        const claimedVersion = envelopeClaimVersion(params);\n        if (headerVersion !== undefined && claimedVersion !== undefined && headerVersion !== claimedVersion) {\n            return crossCheckMismatch(\n                'header-body-version-mismatch',\n                headerVersion,\n                `the body envelope names protocol version ${claimedVersion} but the MCP-Protocol-Version header names ${headerVersion}`\n            );\n        }\n        if (request.mcpMethodHeader !== undefined && request.mcpMethodHeader !== method) {\n            return crossCheckMismatch(\n                'method-header-mismatch',\n                request.mcpMethodHeader,\n                `the body names method ${method} but the Mcp-Method header names ${request.mcpMethodHeader}`\n            );\n        }\n        return { kind: 'modern', messageKind: 'request', message: body, classification: classificationForClaim(claimedVersion) };\n    }\n\n    // No claim: legacy-era traffic — unless the protocol-version header names a\n    // modern revision. The modern revisions carry their request metadata in the\n    // per-request `_meta` envelope, so a modern-classified request without one\n    // is missing required params: it is rejected with invalid params naming the\n    // missing key(s), never silently served as legacy traffic and never\n    // upgraded from the header alone.\n    if (headerNamesModern) {\n        const meta = requestMetaOf(params);\n        const missingFromEnvelope = validateEnvelopeMeta(meta ?? {})\n            .filter(issue => issue.problem === 'missing')\n            .map(issue => issue.key);\n        const missing = meta === undefined ? ['_meta'] : missingFromEnvelope.length > 0 ? missingFromEnvelope : [PROTOCOL_VERSION_META_KEY];\n        return rejection(\n            'envelope',\n            'modern-header-without-claim',\n            400,\n            new ProtocolError(\n                ProtocolErrorCode.InvalidParams,\n                `Invalid params: the MCP-Protocol-Version header names protocol revision ${headerVersion}, but the request is missing ` +\n                    `the required per-request envelope key(s): ${missing.join(', ')}`,\n                { envelope: { missing } }\n            ),\n            true\n        );\n    }\n    return { kind: 'legacy', reason: 'no-claim', ...(headerVersion !== undefined && { requestedVersion: headerVersion }) };\n}\n\nfunction classifyNotificationBody(request: InboundHttpRequest, body: JSONRPCNotification): InboundClassificationOutcome {\n    const params = body.params;\n    const method = body.method;\n    const headerVersion = request.protocolVersionHeader;\n    const headerNamesModern = headerVersion !== undefined && isModernProtocolVersion(headerVersion);\n\n    if (hasEnvelopeClaim(params)) {\n        // Body-primary even for notifications: a body claim wins over the\n        // header, and a disagreement between them is rejected rather than\n        // letting either signal silently pick the serving path.\n        const claimedVersion = envelopeClaimVersion(params);\n        if (claimedVersion === undefined) {\n            // The claim key is present but its value is malformed (not a\n            // string). Validated exactly like a request claim: an\n            // invalid-params rejection naming the offending key — never a\n            // silent win against (or loss to) a disagreeing header.\n            const meta = requestMetaOf(params);\n            const issues = meta === undefined ? [] : validateEnvelopeMeta(meta);\n            const claimIssue = issues.find(issue => issue.key === PROTOCOL_VERSION_META_KEY) ?? {\n                key: PROTOCOL_VERSION_META_KEY,\n                problem: 'expected a protocol version string'\n            };\n            return rejection(\n                'envelope',\n                'notification-envelope-invalid',\n                400,\n                new ProtocolError(\n                    ProtocolErrorCode.InvalidParams,\n                    `Invalid _meta envelope for protocol revision 2026-07-28: ${claimIssue.key}: ${claimIssue.problem}`,\n                    { envelope: claimIssue }\n                ),\n                true\n            );\n        }\n        if (headerVersion !== undefined && headerVersion !== claimedVersion) {\n            return crossCheckMismatch(\n                'notification-header-body-version-mismatch',\n                headerVersion,\n                `the notification envelope names protocol version ${claimedVersion} but the MCP-Protocol-Version header names ${headerVersion}`\n            );\n        }\n        const classification = classificationForClaim(claimedVersion);\n        if (classification.era === 'modern' && request.mcpMethodHeader !== undefined && request.mcpMethodHeader !== method) {\n            return crossCheckMismatch(\n                'notification-method-header-mismatch',\n                request.mcpMethodHeader,\n                `the notification body names method ${method} but the Mcp-Method header names ${request.mcpMethodHeader}`\n            );\n        }\n        return { kind: 'modern', messageKind: 'notification', message: body, classification };\n    }\n\n    // Notifications carry no body claim under the current spec, so the\n    // protocol-version header is determinative for them: a modern header\n    // routes the notification to modern serving; a missing or legacy header\n    // keeps it legacy traffic. The Mcp-Method header is validated only when\n    // the notification classifies modern — it is never enforced on legacy\n    // notifications.\n    if (headerNamesModern) {\n        if (request.mcpMethodHeader !== undefined && request.mcpMethodHeader !== method) {\n            return crossCheckMismatch(\n                'notification-method-header-mismatch',\n                request.mcpMethodHeader,\n                `the notification body names method ${method} but the Mcp-Method header names ${request.mcpMethodHeader}`\n            );\n        }\n        return {\n            kind: 'modern',\n            messageKind: 'notification',\n            message: body,\n            classification: { era: 'modern', revision: headerVersion }\n        };\n    }\n    return { kind: 'legacy', reason: 'notification', ...(headerVersion !== undefined && { requestedVersion: headerVersion }) };\n}\n\n/**\n * Classifies one inbound HTTP request for dual-era serving.\n *\n * The body-primary predicate, evaluated once at the entry boundary: see the\n * module documentation for the rules. Returns a routing outcome (`legacy` or\n * `modern`) or a ladder rejection; it never throws.\n */\nexport function classifyInboundRequest(request: InboundHttpRequest): InboundClassificationOutcome {\n    // RFC 9110 §5.5: field parsing excludes optional whitespace around a\n    // field value. Fetch implementations normally perform this normalization,\n    // but transport-neutral callers and some runtimes can expose raw OWS.\n    request = {\n        ...request,\n        ...(request.protocolVersionHeader !== undefined && {\n            protocolVersionHeader: stripHttpOws(request.protocolVersionHeader)\n        }),\n        ...(request.mcpMethodHeader !== undefined && { mcpMethodHeader: stripHttpOws(request.mcpMethodHeader) }),\n        ...(request.mcpNameHeader !== undefined && { mcpNameHeader: stripHttpOws(request.mcpNameHeader) })\n    };\n\n    if (request.httpMethod.toUpperCase() !== 'POST') {\n        // Body-less 2025-era session operations (and any other non-POST\n        // method): the modern era is POST-only.\n        return { kind: 'legacy', reason: 'http-method' };\n    }\n\n    const body = request.body;\n    if (Array.isArray(body)) {\n        return classifyBatch(body);\n    }\n    if (isJSONRPCResultResponse(body) || isJSONRPCErrorResponse(body)) {\n        // Posted responses are 2025-era session traffic (replies to\n        // server-initiated requests over a session); the modern era has no\n        // such channel.\n        return { kind: 'legacy', reason: 'response' };\n    }\n    if (isPlainObject(body) && isJSONRPCRequest(body)) {\n        return classifyRequestBody(request, body);\n    }\n    if (isPlainObject(body) && isJSONRPCNotification(body)) {\n        return classifyNotificationBody(request, body);\n    }\n    return rejection(\n        'jsonrpc-shape',\n        'invalid-json-rpc-body',\n        400,\n        new ProtocolError(ProtocolErrorCode.InvalidRequest, 'Bad Request: the request body is not a valid JSON-RPC message'),\n        true\n    );\n}\n\n/* ------------------------------------------------------------------------ *\n * Modern-only (strict) mapping of legacy routes\n * ------------------------------------------------------------------------ */\n\n/**\n * The rejection a modern-only endpoint (no legacy serving configured)\n * answers a legacy-classified request with.\n *\n * - Envelope-less requests (including `initialize`) are answered with the\n *   unsupported-protocol-version error carrying the endpoint's supported\n *   versions and echoing the version the request named (when it named one —\n *   `requested` is omitted rather than fabricated when the request named no\n *   version at all), so a legacy client can discover what the endpoint serves\n *   from the error alone.\n * - Posted responses and batch arrays are invalid requests on the modern era.\n * - Non-`POST` methods are not allowed.\n * - Legacy-classified notifications return `undefined`: the caller answers\n *   202 with no body and does not dispatch the notification (accept-and-drop).\n */\nexport function modernOnlyStrictRejection(\n    route: InboundLegacyRoute,\n    supportedVersions: readonly string[]\n): InboundLadderRejection | undefined {\n    switch (route.reason) {\n        case 'http-method': {\n            return rejection('http-method', 'modern-only-method-not-allowed', 405, new ProtocolError(-32_000, 'Method not allowed.'), true);\n        }\n        case 'batch': {\n            return rejection(\n                'jsonrpc-shape',\n                'modern-only-batch-not-supported',\n                400,\n                new ProtocolError(ProtocolErrorCode.InvalidRequest, 'Bad Request: JSON-RPC batches are not supported by this endpoint'),\n                true\n            );\n        }\n        case 'response': {\n            return rejection(\n                'jsonrpc-shape',\n                'modern-only-response-post',\n                400,\n                new ProtocolError(ProtocolErrorCode.InvalidRequest, 'Bad Request: JSON-RPC responses cannot be posted to this endpoint'),\n                true\n            );\n        }\n        case 'notification': {\n            return undefined;\n        }\n        case 'initialize':\n        case 'no-claim': {\n            // `requested` reflects what the request actually named (an\n            // initialize body's `protocolVersion` or the protocol-version\n            // header); when the request named no version at all the field is\n            // omitted rather than fabricated.\n            const requested = route.requestedVersion;\n            const error =\n                requested === undefined\n                    ? new ProtocolError(\n                          ProtocolErrorCode.UnsupportedProtocolVersion,\n                          'Unsupported protocol version: the request did not name a protocol version',\n                          { supported: [...supportedVersions] }\n                      )\n                    : new UnsupportedProtocolVersionError({ supported: [...supportedVersions], requested });\n            return rejection('era-classification', 'modern-only-missing-envelope', 400, error, true);\n        }\n    }\n}\n","/**\n * Internal Zod schema utilities for protocol handling.\n * These are used internally by the SDK for protocol message validation.\n */\n\nimport * as z from 'zod/v4';\n\n/**\n * Base type for any Zod schema.\n */\nexport type AnySchema = z.core.$ZodType;\n\n/**\n * A Zod schema for objects specifically.\n */\nexport type AnyObjectSchema = z.core.$ZodObject;\n\n/**\n * Extracts the output type from a Zod schema.\n */\nexport type SchemaOutput<T extends AnySchema> = z.output<T>;\n\n/**\n * Parses data against a Zod schema (synchronous).\n * Returns a discriminated union with success/error.\n */\nexport function parseSchema<T extends AnySchema>(\n    schema: T,\n    data: unknown\n): { success: true; data: z.output<T> } | { success: false; error: z.core.$ZodError } {\n    return z.safeParse(schema, data);\n}\n\n/**\n * Union of the declared shape keys across several Zod object schemas.\n */\nexport function shapeKeys(schemas: Array<{ shape: Record<string, unknown> }>): ReadonlySet<string> {\n    return new Set(schemas.flatMap(schema => Object.keys(schema.shape)));\n}\n","/**\n * Standard Schema utilities for user-provided schemas.\n * Supports Zod v4, Valibot, ArkType, and other Standard Schema implementations.\n * @see https://standardschema.dev\n */\n\n/* eslint-disable @typescript-eslint/no-namespace */\n\nimport * as z from 'zod/v4';\n\nimport type { StringSchema } from '../types/types';\n\n// Standard Schema interfaces — vendored from https://standardschema.dev (spec v1, Jan 2025)\n\nexport interface StandardTypedV1<Input = unknown, Output = Input> {\n    readonly '~standard': StandardTypedV1.Props<Input, Output>;\n}\n\nexport namespace StandardTypedV1 {\n    export interface Props<Input = unknown, Output = Input> {\n        readonly version: 1;\n        readonly vendor: string;\n        readonly types?: Types<Input, Output> | undefined;\n    }\n\n    export interface Types<Input = unknown, Output = Input> {\n        readonly input: Input;\n        readonly output: Output;\n    }\n\n    export type InferInput<Schema extends StandardTypedV1> = NonNullable<Schema['~standard']['types']>['input'];\n    export type InferOutput<Schema extends StandardTypedV1> = NonNullable<Schema['~standard']['types']>['output'];\n}\n\nexport interface StandardSchemaV1<Input = unknown, Output = Input> {\n    readonly '~standard': StandardSchemaV1.Props<Input, Output>;\n}\n\nexport namespace StandardSchemaV1 {\n    export interface Props<Input = unknown, Output = Input> extends StandardTypedV1.Props<Input, Output> {\n        readonly validate: (value: unknown, options?: Options | undefined) => Result<Output> | Promise<Result<Output>>;\n    }\n\n    export interface Options {\n        readonly libraryOptions?: Record<string, unknown> | undefined;\n    }\n\n    export type Result<Output> = SuccessResult<Output> | FailureResult;\n\n    export interface SuccessResult<Output> {\n        readonly value: Output;\n        readonly issues?: undefined;\n    }\n\n    export interface FailureResult {\n        readonly issues: ReadonlyArray<Issue>;\n    }\n\n    export interface Issue {\n        readonly message: string;\n        readonly path?: ReadonlyArray<PropertyKey | PathSegment> | undefined;\n    }\n\n    export interface PathSegment {\n        readonly key: PropertyKey;\n    }\n\n    export type InferInput<Schema extends StandardTypedV1> = StandardTypedV1.InferInput<Schema>;\n    export type InferOutput<Schema extends StandardTypedV1> = StandardTypedV1.InferOutput<Schema>;\n}\n\nexport interface StandardJSONSchemaV1<Input = unknown, Output = Input> {\n    readonly '~standard': StandardJSONSchemaV1.Props<Input, Output>;\n}\n\nexport namespace StandardJSONSchemaV1 {\n    export interface Props<Input = unknown, Output = Input> extends StandardTypedV1.Props<Input, Output> {\n        readonly jsonSchema: Converter;\n    }\n\n    export interface Converter {\n        readonly input: (options: Options) => Record<string, unknown>;\n        readonly output: (options: Options) => Record<string, unknown>;\n    }\n\n    export type Target = 'draft-2020-12' | 'draft-07' | 'openapi-3.0' | (object & string);\n\n    export interface Options {\n        readonly target: Target;\n        readonly libraryOptions?: Record<string, unknown> | undefined;\n    }\n\n    export type InferInput<Schema extends StandardTypedV1> = StandardTypedV1.InferInput<Schema>;\n    export type InferOutput<Schema extends StandardTypedV1> = StandardTypedV1.InferOutput<Schema>;\n}\n\n/**\n * Combined interface for schemas with both validation and JSON Schema conversion —\n * the intersection of {@linkcode StandardSchemaV1} and {@linkcode StandardJSONSchemaV1}.\n *\n * This is the type accepted by `registerTool` / `registerPrompt`. The SDK needs\n * `~standard.jsonSchema` to advertise the tool's argument shape in `tools/list`, and\n * `~standard.validate` to check incoming arguments when a `tools/call` arrives.\n *\n * Zod v4, ArkType, and Valibot (via `@valibot/to-json-schema`'s `toStandardJsonSchema`)\n * all implement both interfaces.\n *\n * @see https://standardschema.dev/ for the Standard Schema specification\n */\nexport interface StandardSchemaWithJSON<Input = unknown, Output = Input> {\n    readonly '~standard': StandardSchemaV1.Props<Input, Output> & StandardJSONSchemaV1.Props<Input, Output>;\n}\n\nexport namespace StandardSchemaWithJSON {\n    export type InferInput<Schema extends StandardTypedV1> = StandardTypedV1.InferInput<Schema>;\n    export type InferOutput<Schema extends StandardTypedV1> = StandardTypedV1.InferOutput<Schema>;\n}\n\n/**\n * Narrowing of {@linkcode StandardSchemaV1} whose `validate` is guaranteed synchronous.\n *\n * The Zod schemas backing `specTypeSchemas` contain no async refinements or transforms,\n * so every entry satisfies this interface. Consumers can call `validate()` and access\n * `.issues` / `.value` on the result without `await`.\n *\n * `StandardSchemaV1Sync` is assignable to `StandardSchemaV1` — it is a strict subtype.\n */\nexport interface StandardSchemaV1Sync<Input = unknown, Output = Input> extends StandardSchemaV1<Input, Output> {\n    readonly '~standard': StandardSchemaV1Sync.Props<Input, Output>;\n}\n\nexport namespace StandardSchemaV1Sync {\n    export interface Props<Input = unknown, Output = Input> extends StandardSchemaV1.Props<Input, Output> {\n        readonly validate: (value: unknown, options?: StandardSchemaV1.Options | undefined) => StandardSchemaV1.Result<Output>;\n    }\n\n    export type InferInput<Schema extends StandardTypedV1> = StandardTypedV1.InferInput<Schema>;\n    export type InferOutput<Schema extends StandardTypedV1> = StandardTypedV1.InferOutput<Schema>;\n}\n\n// Type guards\n\nexport function isStandardJSONSchema(schema: unknown): schema is StandardJSONSchemaV1 {\n    if (schema == null) return false;\n    const schemaType = typeof schema;\n    if (schemaType !== 'object' && schemaType !== 'function') return false;\n    if (!('~standard' in (schema as object))) return false;\n    const std = (schema as StandardJSONSchemaV1)['~standard'];\n    return typeof std?.jsonSchema?.input === 'function' && typeof std?.jsonSchema?.output === 'function';\n}\n\nexport function isStandardSchema(schema: unknown): schema is StandardSchemaV1 {\n    if (schema == null) return false;\n    const schemaType = typeof schema;\n    if (schemaType !== 'object' && schemaType !== 'function') return false;\n    if (!('~standard' in (schema as object))) return false;\n    const std = (schema as StandardSchemaV1)['~standard'];\n    return typeof std?.validate === 'function';\n}\n\nexport function isStandardSchemaWithJSON(schema: unknown): schema is StandardSchemaWithJSON {\n    return isStandardJSONSchema(schema) && isStandardSchema(schema);\n}\n\n// JSON Schema conversion\n\nlet warnedZodFallback = false;\n\n/** JSON Schema draft targeted by every conversion; shared so pattern references above stay in lockstep. */\nexport const JSON_SCHEMA_CONVERSION_TARGET = 'draft-2020-12';\n\n/**\n * Converts a StandardSchema to JSON Schema for use as an MCP tool/prompt schema.\n *\n * MCP requires `type: \"object\"` at the root of tool `inputSchema` and prompt\n * argument schemas; `outputSchema` may have any JSON Schema root (SEP-2106).\n * Zod's discriminated unions emit `{oneOf: [...]}` without a top-level `type`,\n * so for `io: 'input'` this function defaults `type` to `\"object\"` when absent\n * and throws on an explicit non-object `type` (e.g. `z.string()`). For\n * `io: 'output'` a non-object root is returned as-is; the `\"object\"` default is\n * applied only when the root is provably object-shaped.\n */\nexport function standardSchemaToJsonSchema(schema: StandardJSONSchemaV1, io: 'input' | 'output' = 'input'): Record<string, unknown> {\n    const std = schema['~standard'];\n    let result: Record<string, unknown>;\n    if (std.jsonSchema) {\n        result = std.jsonSchema[io]({ target: JSON_SCHEMA_CONVERSION_TARGET });\n    } else if (std.vendor === 'zod') {\n        // zod 4.0–4.1 implements StandardSchemaV1 but not StandardJSONSchemaV1 (`~standard.jsonSchema`).\n        // The SDK already bundles zod 4, so fall back to its converter rather than crashing on tools/list.\n        // zod 3 schemas (which also report vendor 'zod') have `_def` but not `_zod`; the SDK-bundled\n        // zod 4 `z.toJSONSchema()` cannot introspect them, so throw a clear error instead of crashing.\n        if (!('_zod' in (schema as object))) {\n            throw new Error(\n                'Schema appears to be from zod 3, which the SDK cannot convert to JSON Schema. ' +\n                    'Upgrade to zod >=4.2.0, or wrap your JSON Schema with fromJsonSchema().'\n            );\n        }\n        if (!warnedZodFallback) {\n            warnedZodFallback = true;\n            console.warn(\n                '[mcp-sdk] Your zod version does not implement `~standard.jsonSchema` (added in zod 4.2.0). ' +\n                    'Falling back to z.toJSONSchema(). Upgrade to zod >=4.2.0 to silence this warning.'\n            );\n        }\n        result = z.toJSONSchema(schema as unknown as z.ZodType, { target: JSON_SCHEMA_CONVERSION_TARGET, io }) as Record<string, unknown>;\n    } else {\n        throw new Error(\n            `Schema library \"${std.vendor}\" does not implement StandardJSONSchemaV1 (\\`~standard.jsonSchema\\`). ` +\n                `Upgrade to a version that does, or wrap your JSON Schema with fromJsonSchema().`\n        );\n    }\n    if (io === 'output') {\n        // SEP-2106: outputSchema may have any JSON Schema root. An explicit `type` (object or\n        // not) is returned as-is. A typeless root only gets `type:'object'` defaulted when it is\n        // PROVABLY object-shaped — it carries object keywords at the root, it is a `$ref` to a\n        // `type:'object'` definition, or every\n        // member of a root `oneOf`/`anyOf`/`allOf` is itself `type:'object'` (the\n        // `z.discriminatedUnion(...)`, `z.union([z.object(...), ...])`, `z.intersection(...)`\n        // cases). Those pre-SEP schemas were valid 2025 wire data via the unconditional stamp,\n        // so the stamp is kept where it is provably safe. A typeless root that is NOT provably\n        // object-shaped (e.g. `z.union([z.string(), z.number()])` → `{anyOf:[…]}`) is returned\n        // as-is — stamping there would be self-contradictory. Anything that does not end up\n        // `type:'object'` is wrapped as `{type:'object', properties:{result:…}}` by the 2025\n        // codec's legacy projection (see `wire/rev2025-11-25/legacyWrap.ts`).\n        if (result.type !== undefined) return result;\n        return isProvablyObjectShapedRoot(result) ? { type: 'object', ...result } : result;\n    }\n    if (result.type !== undefined && result.type !== 'object') {\n        throw new Error(\n            `MCP tool and prompt schemas must describe objects (got type: ${JSON.stringify(result.type)}). ` +\n                `Wrap your schema in z.object({...}) or equivalent.`\n        );\n    }\n    return { type: 'object', ...result };\n}\n\nconst LOCAL_DEFINITION_REF = /^#\\/(\\$defs|definitions)\\/([^/~%]+)$/;\n\n/**\n * A typeless JSON Schema root is \"provably object-shaped\" when either it carries object keywords\n * directly (`properties`/`patternProperties`/`additionalProperties`/`required`), or it is a\n * composition (`oneOf`/`anyOf`/`allOf`) whose every member is itself `type:'object'` or recursively\n * provably object-shaped (e.g. a nested `discriminatedUnion`). A `$ref` is followed one hop, to an\n * entry of the root's `$defs`/`definitions` that is itself `type:'object'`. Used to\n * decide whether stamping `type:'object'` is safe (redundant-but-valid) versus self-contradictory.\n */\nfunction isProvablyObjectShapedRoot(schema: Record<string, unknown>, root = schema): boolean {\n    if ('properties' in schema || 'patternProperties' in schema || 'additionalProperties' in schema || 'required' in schema) {\n        return true;\n    }\n    const ref = typeof schema.$ref === 'string' && LOCAL_DEFINITION_REF.exec(schema.$ref);\n    if (ref && (root[ref[1]!] as Record<string, { type?: unknown } | undefined> | undefined)?.[ref[2]!]?.type === 'object') {\n        return true;\n    }\n    for (const key of ['oneOf', 'anyOf', 'allOf'] as const) {\n        const members = schema[key];\n        if (Array.isArray(members) && members.length > 0) {\n            // A member with its own `$id` may rebase `#/…`, so its refs are not followed.\n            return members.every(\n                m =>\n                    m !== null &&\n                    typeof m === 'object' &&\n                    ((m as Record<string, unknown>).type === 'object' ||\n                        isProvablyObjectShapedRoot(m as Record<string, unknown>, '$id' in m ? {} : root))\n            );\n        }\n    }\n    return false;\n}\n\n// Validation\n\nexport type StandardSchemaValidationResult<T> = { success: true; data: T } | { success: false; error: string };\n\nfunction formatIssue(issue: StandardSchemaV1.Issue): string {\n    if (!issue.path?.length) return issue.message;\n    const path = issue.path.map(p => String(typeof p === 'object' ? p.key : p)).join('.');\n    return `${path}: ${issue.message}`;\n}\n\nexport async function validateStandardSchema<T extends StandardSchemaV1>(\n    schema: T,\n    data: unknown\n): Promise<StandardSchemaValidationResult<StandardSchemaV1.InferOutput<T>>> {\n    const result = await schema['~standard'].validate(data);\n    if (result.issues && result.issues.length > 0) {\n        return { success: false, error: result.issues.map(i => formatIssue(i)).join(', ') };\n    }\n    return { success: true, data: (result as StandardSchemaV1.SuccessResult<unknown>).value as StandardSchemaV1.InferOutput<T> };\n}\n\n/*\n * Format-companion patterns: libraries realize a string `format` check as a companion\n * `pattern` regex, which the elicitation wire schema cannot carry. zod's are derived\n * from the resolved zod at runtime (never vendored — in-range releases change them), so\n * customized zod patterns are distinguishable and reject; other vendors' realizations\n * are unknowable (e.g. ArkType's `string.email`), so their patterns are trusted-and-dropped.\n */\n\nfunction zodEmittedPattern(schema: z.ZodType): string | undefined {\n    const jsonSchema = z.toJSONSchema(schema, { target: JSON_SCHEMA_CONVERSION_TARGET, io: 'input' }) as Record<string, unknown>;\n    return typeof jsonSchema.pattern === 'string' ? jsonSchema.pattern : undefined;\n}\n\nconst DATETIME_FRACTION_DIGITS = /\\\\\\.\\\\d\\{(\\d+)\\}/;\n\nfunction datetimeReferenceSchemas(pattern: string): z.ZodType[] {\n    // Options (offset/local/precision) vary the emission; recovering the fraction-digit\n    // count keeps the candidate set finite.\n    const fractionDigits = DATETIME_FRACTION_DIGITS.exec(pattern);\n    const precisions: Array<number | undefined> = [undefined, -1, 0];\n    if (fractionDigits) {\n        precisions.push(Number(fractionDigits[1]));\n    }\n    return [false, true].flatMap(local =>\n        [false, true].flatMap(offset => precisions.map(precision => z.iso.datetime({ local, offset, precision })))\n    );\n}\n\n// Exhaustive over the wire's format enum: a new spec format is a compile error here.\nfunction referencePatternsForFormat(format: NonNullable<StringSchema['format']>, pattern: string): ReadonlySet<string> {\n    let referenceSchemas: z.ZodType[];\n    switch (format) {\n        case 'email': {\n            referenceSchemas = [z.email()];\n            break;\n        }\n        case 'uri': {\n            referenceSchemas = [z.url()];\n            break;\n        }\n        case 'date': {\n            referenceSchemas = [z.iso.date()];\n            break;\n        }\n        case 'date-time': {\n            referenceSchemas = datetimeReferenceSchemas(pattern);\n            break;\n        }\n    }\n    return new Set(referenceSchemas.map(schema => zodEmittedPattern(schema)).filter((emitted): emitted is string => emitted !== undefined));\n}\n\n/** Whether `pattern` is the library's own realization of `format` (droppable) rather than a user customization. */\nexport function isLibraryFormatPattern(format: NonNullable<StringSchema['format']>, pattern: string, vendor: string): boolean {\n    if (vendor !== 'zod') {\n        return true;\n    }\n    return referencePatternsForFormat(format, pattern).has(pattern);\n}\n\n// Prompt argument extraction\n\nexport function promptArgumentsFromStandardSchema(\n    schema: StandardJSONSchemaV1\n): Array<{ name: string; description?: string; required: boolean }> {\n    const jsonSchema = standardSchemaToJsonSchema(schema, 'input');\n    const properties = (jsonSchema.properties as Record<string, { description?: string }>) || {};\n    const required = (jsonSchema.required as string[]) || [];\n\n    return Object.entries(properties).map(([name, prop]) => ({\n        name,\n        description: prop?.description,\n        required: required.includes(name)\n    }));\n}\n","import { ProtocolErrorCode } from '../types/enums';\nimport { ProtocolError } from '../types/errors';\nimport {\n    BooleanSchemaSchema,\n    ElicitRequestFormParamsSchema,\n    LegacyTitledEnumSchemaSchema,\n    NumberSchemaSchema,\n    PrimitiveSchemaDefinitionSchema,\n    StringSchemaSchema,\n    TitledMultiSelectEnumSchemaSchema,\n    TitledSingleSelectEnumSchemaSchema,\n    UntitledMultiSelectEnumSchemaSchema,\n    UntitledSingleSelectEnumSchemaSchema\n} from '../types/schemas';\nimport type { ElicitRequestFormParams, StringSchema } from '../types/types';\nimport { parseSchema, shapeKeys } from '../util/schema';\nimport type { StandardSchemaWithJSON } from '../util/standardSchema';\nimport { isLibraryFormatPattern, isStandardSchema, standardSchemaToJsonSchema } from '../util/standardSchema';\n\n/** Input accepted by `inputRequired.elicit()`: a wire-ready elicitation JSON Schema or a Standard Schema. */\nexport type ElicitInputParams = Omit<ElicitRequestFormParams, 'requestedSchema'> & {\n    requestedSchema: ElicitRequestFormParams['requestedSchema'] | StandardSchemaWithJSON;\n};\n\nfunction isJsonObject(value: unknown): value is Record<string, unknown> {\n    return typeof value === 'object' && value !== null && !Array.isArray(value);\n}\n\nfunction convertStandardElicitationSchema(schema: StandardSchemaWithJSON): Record<string, unknown> {\n    try {\n        return standardSchemaToJsonSchema(schema, 'input');\n    } catch (error) {\n        const detail = error instanceof Error ? error.message : String(error);\n        throw new ProtocolError(\n            ProtocolErrorCode.InvalidParams,\n            `Elicitation requestedSchema must describe an object with flat primitive properties: ${detail}`\n        );\n    }\n}\n\n// JSON Schema metadata-vocabulary keys: positions that cannot carry them drop them silently.\nconst ANNOTATION_ONLY_JSON_SCHEMA_KEYWORDS = new Set([\n    '$comment',\n    'deprecated',\n    'description',\n    'examples',\n    'readOnly',\n    'title',\n    'writeOnly'\n]);\n\nfunction isAnnotationOnlyJsonSchemaKeyword(key: string): boolean {\n    return ANNOTATION_ONLY_JSON_SCHEMA_KEYWORDS.has(key) || key.startsWith('x-');\n}\n\n// The wire grammar, derived from the wire schemas so it tracks spec revisions. `$schema`\n// is spec-declared on the root but reaches the wire type via its catchall.\nconst ROOT_KEYS = new Set(['$schema', ...Object.keys(ElicitRequestFormParamsSchema.shape.requestedSchema.shape)]);\n\nconst PROPERTY_KEYS_BY_TYPE: Record<string, ReadonlySet<string>> = {\n    string: shapeKeys([\n        StringSchemaSchema,\n        UntitledSingleSelectEnumSchemaSchema,\n        TitledSingleSelectEnumSchemaSchema,\n        LegacyTitledEnumSchemaSchema\n    ]),\n    number: shapeKeys([NumberSchemaSchema]),\n    integer: shapeKeys([NumberSchemaSchema]),\n    boolean: shapeKeys([BooleanSchemaSchema]),\n    array: shapeKeys([UntitledMultiSelectEnumSchemaSchema, TitledMultiSelectEnumSchemaSchema])\n};\n\nconst SUPPORTED_STRING_FORMATS: ReadonlySet<string> = new Set(StringSchemaSchema.shape.format.unwrap().options);\n\n/** Walks one property node: keeps grammar keys, drops the library format pattern, rejects unknown constraints. */\nfunction walkProperty(node: unknown, path: string, vendor: string, unsupported: string[]): unknown {\n    if (!isJsonObject(node)) {\n        return node;\n    }\n    // Object.hasOwn: a `type` like 'constructor' must not resolve through the prototype chain.\n    const allowedKeys =\n        typeof node.type === 'string' && Object.hasOwn(PROPERTY_KEYS_BY_TYPE, node.type) ? PROPERTY_KEYS_BY_TYPE[node.type] : undefined;\n    if (allowedKeys === undefined) {\n        // Unknown `type` — value validation rejects the node and names it.\n        return node;\n    }\n\n    const pruned: Record<string, unknown> = {};\n    for (const [key, value] of Object.entries(node)) {\n        if (allowedKeys.has(key) || isAnnotationOnlyJsonSchemaKeyword(key)) {\n            pruned[key] = value;\n        } else if (key === 'pattern' && node.type === 'string' && typeof node.format === 'string') {\n            if (!SUPPORTED_STRING_FORMATS.has(node.format)) {\n                pruned[key] = value; // the unsupported format itself fails value validation\n            } else if (\n                typeof value !== 'string' ||\n                !isLibraryFormatPattern(node.format as NonNullable<StringSchema['format']>, value, vendor)\n            ) {\n                // A customized pattern must not be silently weakened.\n                unsupported.push(`${path}.${key}`);\n            }\n        } else {\n            unsupported.push(`${path}.${key}`);\n        }\n    }\n    return pruned;\n}\n\n/** Walks the schema root: keeps the spec root keys, drops annotations, rejects the rest. */\nfunction walkRequestedSchema(converted: Record<string, unknown>, vendor: string): Record<string, unknown> {\n    const pruned: Record<string, unknown> = {};\n    const unsupported: string[] = [];\n    for (const [key, value] of Object.entries(converted)) {\n        if (key === 'properties' && isJsonObject(value)) {\n            pruned[key] = Object.fromEntries(\n                Object.entries(value).map(([name, node]) => [name, walkProperty(node, `properties.${name}`, vendor, unsupported)])\n            );\n        } else if (ROOT_KEYS.has(key)) {\n            pruned[key] = value;\n        } else if (!isAnnotationOnlyJsonSchemaKeyword(key)) {\n            unsupported.push(key);\n        }\n    }\n    if (unsupported.length > 0) {\n        throw new ProtocolError(\n            ProtocolErrorCode.InvalidParams,\n            `Elicitation requestedSchema contains unsupported JSON Schema constraint(s) after Standard Schema conversion: ${unsupported.join(', ')}`\n        );\n    }\n    return pruned;\n}\n\n/** Names the properties that fail value validation, instead of surfacing a raw union dump. */\nfunction describeUnsupportedProperties(pruned: Record<string, unknown>, fallback: string): string {\n    if (!isJsonObject(pruned.properties)) {\n        return fallback;\n    }\n    const offenders = Object.entries(pruned.properties)\n        .filter(([, node]) => !parseSchema(PrimitiveSchemaDefinitionSchema, node).success)\n        .map(([name]) => `properties.${name}`);\n    return offenders.length > 0 ? offenders.join(', ') : fallback;\n}\n\n// Safety net: value validation strips key combinations no single wire shape carries\n// (e.g. `format` beside `enum`); a dropped non-annotation key must reject.\nfunction findDroppedConstraintPaths(original: unknown, parsed: unknown, path = ''): string[] {\n    if (Array.isArray(original) && Array.isArray(parsed)) {\n        return original.flatMap((item, index) => findDroppedConstraintPaths(item, parsed[index], `${path}[${index}]`));\n    }\n    if (!isJsonObject(original) || !isJsonObject(parsed)) {\n        return [];\n    }\n    return Object.entries(original).flatMap(([key, value]) => {\n        const childPath = path ? `${path}.${key}` : key;\n        if (!Object.prototype.hasOwnProperty.call(parsed, key)) {\n            return isAnnotationOnlyJsonSchemaKeyword(key) ? [] : [childPath];\n        }\n        return findDroppedConstraintPaths(value, parsed[key], childPath);\n    });\n}\n\n/** Converts an authoring-friendly elicitation input into its wire-ready form. */\nexport function normalizeElicitInputParams(input: ElicitInputParams): ElicitRequestFormParams {\n    // Route on `~standard.validate`: the converter owns the per-vendor fallback (zod\n    // 4.0/4.1 has no `~standard.jsonSchema`) — same decision as normalizeRawShapeSchema.\n    if (!isStandardSchema(input.requestedSchema)) {\n        return { ...input, mode: 'form', requestedSchema: input.requestedSchema };\n    }\n\n    const vendor = input.requestedSchema['~standard'].vendor;\n    const pruned = walkRequestedSchema(convertStandardElicitationSchema(input.requestedSchema), vendor);\n\n    // Scoped to the converted schema so params-level fields behave as on the raw branch.\n    const parsed = parseSchema(ElicitRequestFormParamsSchema.shape.requestedSchema, pruned);\n    if (!parsed.success) {\n        throw new ProtocolError(\n            ProtocolErrorCode.InvalidParams,\n            `Elicitation requestedSchema only supports flat primitive properties (string, number, integer, boolean, and string enums): ${describeUnsupportedProperties(pruned, parsed.error.message)}`\n        );\n    }\n\n    const droppedConstraints = findDroppedConstraintPaths(pruned, parsed.data);\n    if (droppedConstraints.length > 0) {\n        throw new ProtocolError(\n            ProtocolErrorCode.InvalidParams,\n            `Elicitation requestedSchema contains unsupported JSON Schema constraint(s) after Standard Schema conversion: ${droppedConstraints.join(', ')}`\n        );\n    }\n\n    // Converters can lose exotic property names from `properties` while keeping them in\n    // `required` (zod's toJSONSchema does for `__proto__`).\n    const danglingRequired = (parsed.data.required ?? []).filter(key => !Object.prototype.hasOwnProperty.call(parsed.data.properties, key));\n    if (danglingRequired.length > 0) {\n        throw new ProtocolError(\n            ProtocolErrorCode.InvalidParams,\n            `Elicitation requestedSchema lists required properties that are not defined in properties: ${danglingRequired.join(', ')}`\n        );\n    }\n\n    return { ...input, mode: 'form', requestedSchema: parsed.data };\n}\n","/**\n * Authoring helpers for multi-round-trip requests (protocol revision\n * 2026-07-28).\n *\n * A handler for one of the multi-round-trip methods (`tools/call`,\n * `prompts/get`, `resources/read`) requests additional client input by\n * returning an {@linkcode InputRequiredResult} instead of a final result. The\n * helpers here build that return value and its embedded requests as NEUTRAL\n * values; only the 2026-07-28 wire codec maps them to/from the wire. The\n * 2025-era codec has no input-required vocabulary — on a 2025-era request the\n * server's legacy shim (on by default) fulfils the embedded requests as real\n * server→client requests and re-enters the handler, so the same return shape\n * serves both eras; `ServerOptions.inputRequired.legacyShim: false` restores\n * the pre-shim loud failure.\n *\n * There is no nominal brand: `resultType: 'input_required'` is the\n * discriminator, and hand-built result literals are equally legal — the\n * server seam re-checks the at-least-one rule for them.\n */\nimport { ProtocolError } from '../types/errors';\nimport { isInputRequiredResult } from '../types/guards';\nimport type {\n    CreateMessageRequestParams,\n    CreateMessageResult,\n    CreateMessageResultWithTools,\n    ElicitRequestURLParams,\n    InputRequest,\n    InputRequests,\n    InputRequiredResult,\n    InputResponses,\n    Root\n} from '../types/types';\nimport type { StandardSchemaV1 } from '../util/standardSchema';\nimport type { ElicitInputParams } from './elicitation';\nimport { normalizeElicitInputParams } from './elicitation';\n\nexport type { ElicitInputParams } from './elicitation';\n\n/** The shape accepted by {@linkcode inputRequired}. */\nexport interface InputRequiredSpec {\n    /** Embedded requests the client must fulfil before retrying. */\n    inputRequests?: InputRequests;\n    /** Opaque server state echoed back verbatim by the client on retry. */\n    requestState?: string;\n}\n\ninterface InputRequiredBuilder {\n    /**\n     * Builds the input-required return value for a multi-round-trip handler.\n     *\n     * At least one of `inputRequests` or `requestState` must be provided\n     * (spec: basic/patterns/mrtr, server requirements) — the builder throws a\n     * `TypeError` otherwise, and the server seam re-checks the same rule for\n     * hand-built results.\n     *\n     * `requestState` is opaque, server-minted state. It round-trips through\n     * the client and comes back as attacker-controlled input: a server that\n     * lets it influence authorization, resource access, or business logic\n     * MUST integrity-protect it (e.g. HMAC or AEAD) and MUST reject state\n     * that fails verification. The SDK does not do this for you.\n     */\n    (spec: InputRequiredSpec): InputRequiredResult;\n\n    /**\n     * Builds an embedded form-mode elicitation request (`elicitation/create`).\n     *\n     * A Standard Schema `requestedSchema` is converted to the restricted wire shape;\n     * shapes it cannot express throw a `TypeError` before anything is sent. Responses\n     * are not validated against it — pass the same schema to `acceptedContent()` on\n     * re-entry for validated, typed content.\n     */\n    elicit(params: ElicitInputParams): InputRequest;\n\n    /**\n     * Builds an embedded URL-mode elicitation request (`elicitation/create`).\n     * On the 2026-07-28 revision URL elicitation rides the multi-round-trip\n     * flow — the `-32042` error of earlier revisions never appears on this\n     * era's wire. The 2025-era `elicitationId` is not part of the 2026-07-28\n     * URL-mode shape; correlation across retries is the server's own\n     * identifier inside `requestState`.\n     */\n    elicitUrl(params: Omit<ElicitRequestURLParams, 'mode' | 'elicitationId'>): InputRequest;\n\n    /** Builds an embedded sampling request (`sampling/createMessage`). */\n    createMessage(params: CreateMessageRequestParams): InputRequest;\n\n    /** Builds an embedded roots listing request (`roots/list`). */\n    listRoots(): InputRequest;\n}\n\nfunction buildInputRequired(spec: InputRequiredSpec): InputRequiredResult {\n    const hasInputRequests = spec.inputRequests !== undefined && Object.keys(spec.inputRequests).length > 0;\n    const hasRequestState = typeof spec.requestState === 'string';\n    if (!hasInputRequests && !hasRequestState) {\n        throw new TypeError(\n            'inputRequired() requires at least one of inputRequests (with at least one entry) or requestState ' +\n                '(spec: every InputRequiredResult MUST include at least one of the two)'\n        );\n    }\n    return {\n        resultType: 'input_required',\n        ...(spec.inputRequests !== undefined && { inputRequests: spec.inputRequests }),\n        ...(spec.requestState !== undefined && { requestState: spec.requestState })\n    };\n}\n\n/**\n * Builder for the input-required return value of multi-round-trip handlers,\n * with per-kind constructors for the embedded requests\n * (`inputRequired.elicit`, `inputRequired.elicitUrl`,\n * `inputRequired.createMessage`, `inputRequired.listRoots`).\n *\n * @example Write-once tool requesting confirmation\n * ```ts\n * server.registerTool('deploy', { inputSchema: z.object({ env: z.string() }) }, async ({ env }, ctx) => {\n *     const confirmationSchema = z.object({ confirm: z.boolean() });\n *     const confirmed = acceptedContent(ctx.mcpReq.inputResponses, 'confirm', confirmationSchema);\n *     if (confirmed?.confirm !== true) {\n *         return inputRequired({\n *             inputRequests: {\n *                 confirm: inputRequired.elicit({\n *                     message: `Deploy to ${env}?`,\n *                     requestedSchema: confirmationSchema\n *                 })\n *             }\n *         });\n *     }\n *     return { content: [{ type: 'text', text: `deployed to ${env}` }] };\n * });\n * ```\n */\nexport const inputRequired: InputRequiredBuilder = Object.assign(buildInputRequired, {\n    elicit(params: ElicitInputParams): InputRequest {\n        try {\n            return { method: 'elicitation/create', params: normalizeElicitInputParams(params) };\n        } catch (error) {\n            throw error instanceof ProtocolError ? new TypeError(error.message, { cause: error }) : error;\n        }\n    },\n    elicitUrl(params: Omit<ElicitRequestURLParams, 'mode' | 'elicitationId'>): InputRequest {\n        // The neutral ElicitRequestURLParams keeps `elicitationId` (it is required on the\n        // frozen 2025-11-25 revision); the 2026-07-28 in-band shape does not carry it.\n        return { method: 'elicitation/create', params: { ...params, mode: 'url' } as ElicitRequestURLParams };\n    },\n    createMessage(params: CreateMessageRequestParams): InputRequest {\n        return { method: 'sampling/createMessage', params };\n    },\n    listRoots(): InputRequest {\n        return { method: 'roots/list' };\n    }\n});\n\n/**\n * Reads the accepted content of a form-mode elicitation response from a\n * retried request's `inputResponses` (`ctx.mcpReq.inputResponses`).\n *\n * Returns the response's `content` for `key` when the entry is an accepted\n * elicitation result, and `undefined` otherwise (missing key, declined or\n * cancelled elicitation, or a response of another kind). The values arrive\n * from the client and are not re-validated here — treat them as untrusted\n * input.\n */\nexport function acceptedContent<T extends Record<string, unknown> = Record<string, unknown>>(\n    responses: InputResponses | Record<string, unknown> | undefined,\n    key: string\n): T | undefined;\n\n/**\n * Schema-aware overload: validates the accepted content against the given\n * schema (any Standard Schema, e.g. a zod object) before returning it, so the\n * untrusted client value arrives in the handler already validated and typed.\n *\n * Returns `undefined` when the response is missing/declined/of another kind\n * (as the two-argument form does) AND when the accepted content fails schema\n * validation — handlers treat both the same way (re-issue the request or\n * give up). Only synchronous schemas are supported (zod schemas without async\n * refinements are synchronous); an asynchronously-validating schema throws a\n * `TypeError`.\n */\nexport function acceptedContent<S extends StandardSchemaV1>(\n    responses: InputResponses | Record<string, unknown> | undefined,\n    key: string,\n    schema: S\n): StandardSchemaV1.InferOutput<S> | undefined;\n\nexport function acceptedContent(\n    responses: InputResponses | Record<string, unknown> | undefined,\n    key: string,\n    schema?: StandardSchemaV1\n): unknown {\n    const view = inputResponse(responses, key);\n    if (view.kind !== 'elicit' || view.action !== 'accept' || view.content === undefined) return undefined;\n    if (schema === undefined) return view.content;\n    const outcome = schema['~standard'].validate(view.content);\n    if (outcome instanceof Promise) {\n        throw new TypeError('acceptedContent(responses, key, schema) requires a synchronously-validating schema');\n    }\n    return outcome.issues === undefined ? outcome.value : undefined;\n}\n\n/**\n * The discriminated view {@linkcode inputResponse} returns: which kind of\n * embedded response (if any) a retried request carried for a key. Bare\n * response objects are discriminated structurally — an `action` member means\n * an elicitation result, a `roots` array a roots listing, a `role` + `content`\n * pair a sampling result. A missing key or an entry that matches none of the\n * three shapes reads as `{ kind: 'missing' }`.\n */\nexport type InputResponseView =\n    | { kind: 'missing' }\n    | { kind: 'elicit'; action: 'accept' | 'decline' | 'cancel'; content?: Record<string, unknown> }\n    | { kind: 'sampling'; result: CreateMessageResult | CreateMessageResultWithTools }\n    | { kind: 'roots'; roots: Root[] };\n\n/**\n * Reads one entry of a retried request's `inputResponses`\n * (`ctx.mcpReq.inputResponses`) as a discriminated view, covering\n * decline/cancel detection and the non-elicitation response kinds that\n * {@linkcode acceptedContent} does not surface.\n *\n * The values arrive from the client and are not re-validated here — treat\n * them as untrusted input (validate elicitation content with the\n * schema-aware {@linkcode acceptedContent} overload where it matters).\n */\nexport function inputResponse(responses: InputResponses | Record<string, unknown> | undefined, key: string): InputResponseView {\n    if (responses === undefined || typeof responses !== 'object' || responses === null) return { kind: 'missing' };\n    const entry = (responses as Record<string, unknown>)[key];\n    if (entry === null || typeof entry !== 'object' || Array.isArray(entry)) return { kind: 'missing' };\n    const candidate = entry as Record<string, unknown>;\n    if (candidate['action'] === 'accept' || candidate['action'] === 'decline' || candidate['action'] === 'cancel') {\n        const content = candidate['content'];\n        return {\n            kind: 'elicit',\n            action: candidate['action'],\n            ...(content !== null &&\n                typeof content === 'object' &&\n                !Array.isArray(content) && { content: content as Record<string, unknown> })\n        };\n    }\n    if (Array.isArray(candidate['roots'])) {\n        return { kind: 'roots', roots: candidate['roots'] as Root[] };\n    }\n    if (typeof candidate['role'] === 'string' && candidate['content'] !== undefined) {\n        return { kind: 'sampling', result: candidate as unknown as CreateMessageResult | CreateMessageResultWithTools };\n    }\n    return { kind: 'missing' };\n}\n\n/**\n * Wraps a result schema so a request issued through `client.request()` /\n * `ctx.mcpReq.send()` with `allowInputRequired: true` is typed as either the\n * schema's result or an {@linkcode InputRequiredResult}.\n *\n * The manual multi-round-trip path: pass `{ allowInputRequired: true }` in the\n * request options so an `input_required` response is handed back to the\n * caller instead of being auto-fulfilled (or rejected), and wrap the result\n * schema with `withInputRequired()` so the returned value is typed and\n * validated correctly for both outcomes — `input_required` values pass\n * through as-is, complete results validate against the wrapped schema.\n */\nexport function withInputRequired<S extends StandardSchemaV1>(\n    schema: S\n): StandardSchemaV1<unknown, StandardSchemaV1.InferOutput<S> | InputRequiredResult> {\n    return {\n        '~standard': {\n            version: 1,\n            vendor: 'modelcontextprotocol',\n            validate: (value: unknown, options?: StandardSchemaV1.Options) => {\n                if (isInputRequiredResult(value)) {\n                    return { value };\n                }\n                return schema['~standard'].validate(value, options) as\n                    | StandardSchemaV1.Result<StandardSchemaV1.InferOutput<S> | InputRequiredResult>\n                    | Promise<StandardSchemaV1.Result<StandardSchemaV1.InferOutput<S> | InputRequiredResult>>;\n            }\n        }\n    };\n}\n","/**\n * The multi-round-trip auto-fulfilment driver (protocol revision 2026-07-28).\n *\n * When a request to one of the multi-round-trip methods comes back as\n * `input_required`, the driver fulfils the embedded input requests by\n * dispatching them to the client's already-registered handlers (elicitation,\n * sampling, roots — one generic engine, no per-feature API), then retries the\n * original request with the collected `inputResponses` and a byte-exact echo\n * of `requestState`, on a fresh request id, until the server returns a\n * complete result or the round cap is exhausted.\n *\n * The driver is a LAYER OVER THE MANUAL PATH: each retry is issued with the\n * same primitive a manual caller uses (`allowInputRequired` semantics — the\n * retry hands back the next `input_required` payload instead of recursing),\n * so the loop, the cap, and the pacing live in one place and disabling\n * auto-fulfilment (`inputRequired.autoFulfill: false`) simply skips this\n * module. Timeouts ride the EXISTING knobs: the per-leg `timeout` applies to\n * every wire leg unchanged, and `maxTotalTimeout` bounds the whole flow by\n * shrinking the budget passed to each leg — no new timer system.\n */\nimport { SdkError, SdkErrorCode } from '../errors/sdkErrors';\nimport { isInputRequiredResult } from '../types/guards';\nimport type { Progress } from '../types/types';\n\n/**\n * Whether the multi-round-trip driver fulfils `input_required` results\n * automatically when the consumer has not configured\n * `inputRequired.autoFulfill`. The single switch for the default posture.\n */\nexport const DEFAULT_INPUT_REQUIRED_AUTO_FULFILL = true;\n\n/**\n * Default round cap for the auto-fulfilment driver (both request legs and\n * requestState-only legs count). Aligned with the other SDK client engines.\n */\nexport const DEFAULT_INPUT_REQUIRED_MAX_ROUNDS = 10;\n\n/**\n * Fixed pacing applied before retrying a requestState-only (load-shedding)\n * leg — a leg that carries no embedded input requests, so nothing slows the\n * loop down naturally. Counted in the same round cap.\n */\nexport const REQUEST_STATE_ONLY_LEG_PACING_MS = 250;\n\n/**\n * Multi-round-trip driver options (`inputRequired` on the client options bag).\n */\nexport interface InputRequiredOptions {\n    /**\n     * Fulfil `input_required` results automatically by dispatching the\n     * embedded requests to the registered handlers and retrying.\n     *\n     * Set to `false` for manual mode: an `input_required` response then\n     * surfaces as a typed error unless the individual call opts in with\n     * `allowInputRequired: true` (and, for typed results on the explicit\n     * schema path, `withInputRequired()`).\n     *\n     * @default true\n     */\n    autoFulfill?: boolean;\n\n    /**\n     * Maximum number of rounds (retries) the driver performs for a single\n     * call before failing with a typed\n     * {@linkcode SdkErrorCode.InputRequiredRoundsExceeded} error.\n     *\n     * @default 10\n     */\n    maxRounds?: number;\n}\n\n/** The driver configuration with defaults applied. */\nexport interface ResolvedInputRequiredDriverConfig {\n    autoFulfill: boolean;\n    maxRounds: number;\n}\n\nexport function resolveInputRequiredDriverConfig(options: InputRequiredOptions | undefined): ResolvedInputRequiredDriverConfig {\n    return {\n        autoFulfill: options?.autoFulfill ?? DEFAULT_INPUT_REQUIRED_AUTO_FULFILL,\n        maxRounds: options?.maxRounds ?? DEFAULT_INPUT_REQUIRED_MAX_ROUNDS\n    };\n}\n\n/** The discriminated `input_required` payload the wire codec hands to the driver. */\nexport interface InputRequiredPayload {\n    inputRequests: Record<string, unknown>;\n    requestState?: string;\n}\n\n/** The slice of per-request options the driver consumes. */\nexport interface InputRequiredDriverRequestOptions {\n    timeout?: number;\n    maxTotalTimeout?: number;\n    onprogress?: (progress: Progress) => void;\n}\n\n/** Per-leg options the driver passes back to the funnel for each retry. */\nexport interface InputRequiredRetryLegOptions {\n    timeout?: number;\n    maxTotalTimeout?: number;\n}\n\n/** The hooks the engine provides to the driver. */\nexport interface InputRequiredDriverHooks {\n    /**\n     * Dispatches one embedded input request to the locally registered handler\n     * and resolves with the bare response value. Rejections fail the whole\n     * call (typed errors: unknown kind, missing handler, handler failure).\n     * The signal is the per-round abort: when one sibling fails (or the\n     * caller aborts the originating call) the remaining dispatches are\n     * cancelled.\n     */\n    dispatchInputRequest(key: string, entry: unknown, signal: AbortSignal): Promise<unknown>;\n\n    /**\n     * Re-issues the original request with the given params on a fresh request\n     * id, using the manual primitive: a complete result resolves validated,\n     * and a further `input_required` response resolves as the raw\n     * input-required value (never recursing into another driver run).\n     */\n    retry(params: Record<string, unknown> | undefined, legOptions: InputRequiredRetryLegOptions): Promise<unknown>;\n}\n\n/** Builds the retry params: original params + this round's responses + byte-exact requestState echo. */\nexport function buildInputRequiredRetryParams(\n    originalParams: Record<string, unknown> | undefined,\n    responses: Record<string, unknown> | undefined,\n    requestState: string | undefined\n): Record<string, unknown> | undefined {\n    const hasResponses = responses !== undefined && Object.keys(responses).length > 0;\n    if (!hasResponses && requestState === undefined) {\n        return originalParams;\n    }\n    return {\n        ...originalParams,\n        ...(hasResponses && { inputResponses: responses }),\n        // Byte-exact echo: the opaque string is copied verbatim, never parsed.\n        // When the result carried no requestState, the retry carries none.\n        ...(requestState !== undefined && { requestState })\n    };\n}\n\n/**\n * The message both multi-round-trip loops emit when the round cap is\n * exhausted — the client driver as a typed error, the server-side legacy\n * shim as its per-family failure. One formatter so the texts cannot drift\n * (hosts and models read the tool-result copy verbatim).\n */\nexport function inputRequiredRoundsExceededMessage(method: string, maxRounds: number): string {\n    return `Multi-round-trip request '${method}' still required input after ${maxRounds} rounds (inputRequired.maxRounds)`;\n}\n\n/**\n * Abortable delay: resolves after `ms`, or rejects with the signal's reason\n * (wrapped in an `SdkError` when it isn't already one) if the signal aborts\n * first. Aborting after resolution is a no-op. Shared with the server-side\n * legacy shim (the pacing semantics must match per era).\n */\nexport function sleep(ms: number, signal: AbortSignal | undefined): Promise<void> {\n    return new Promise((resolve, reject) => {\n        if (signal?.aborted) {\n            reject(signal.reason instanceof SdkError ? signal.reason : new SdkError(SdkErrorCode.RequestTimeout, String(signal.reason)));\n            return;\n        }\n        const timer = setTimeout(() => {\n            signal?.removeEventListener('abort', onAbort);\n            resolve();\n        }, ms);\n        const onAbort = (): void => {\n            clearTimeout(timer);\n            reject(signal?.reason instanceof SdkError ? signal.reason : new SdkError(SdkErrorCode.RequestTimeout, String(signal?.reason)));\n        };\n        signal?.addEventListener('abort', onAbort, { once: true });\n    });\n}\n\n/**\n * A per-round abort linked to the caller's signal: the embedded sibling\n * dispatches share it, so the first failure (or a caller abort) cancels the\n * others instead of leaving them running. Shared with the server-side legacy\n * shim (the abort-linkage semantics must match per era).\n */\nexport function linkedRoundAbort(outer: AbortSignal | undefined): {\n    signal: AbortSignal;\n    abort: (reason: unknown) => void;\n    dispose: () => void;\n} {\n    const controller = new AbortController();\n    const onOuterAbort = (): void => controller.abort(outer?.reason);\n    outer?.addEventListener('abort', onOuterAbort, { once: true });\n    if (outer?.aborted) controller.abort(outer.reason);\n    return {\n        signal: controller.signal,\n        abort: reason => controller.abort(reason),\n        dispose: () => outer?.removeEventListener('abort', onOuterAbort)\n    };\n}\n\n/**\n * Runs the auto-fulfilment loop for one originating request. Resolves with\n * the final complete result (already validated by the retry leg) or rejects\n * with a typed error.\n *\n * `flowStartedAt` is the timestamp the ORIGINAL request was issued at (not\n * when the driver started): `maxTotalTimeout` bounds the whole flow, so the\n * first wire leg counts against the budget too. When omitted, accounting\n * starts when the driver starts.\n */\nexport async function runInputRequiredDriver(args: {\n    config: ResolvedInputRequiredDriverConfig;\n    method: string;\n    originalParams: Record<string, unknown> | undefined;\n    firstPayload: InputRequiredPayload;\n    requestOptions: InputRequiredDriverRequestOptions;\n    hooks: InputRequiredDriverHooks;\n    /** The originating call's abort signal — chains through every round and the pacing sleep. */\n    signal?: AbortSignal;\n    flowStartedAt?: number;\n}): Promise<unknown> {\n    const { config, method, originalParams, requestOptions, hooks, signal } = args;\n    const startedAt = args.flowStartedAt ?? Date.now();\n    let payload = args.firstPayload;\n    let round = 0;\n\n    // eslint-disable-next-line no-constant-condition\n    while (true) {\n        round += 1;\n        if (round > config.maxRounds) {\n            throw new SdkError(SdkErrorCode.InputRequiredRoundsExceeded, inputRequiredRoundsExceededMessage(method, config.maxRounds), {\n                rounds: config.maxRounds,\n                lastResult: {\n                    inputRequests: payload.inputRequests,\n                    ...(payload.requestState !== undefined && { requestState: payload.requestState })\n                }\n            });\n        }\n\n        // Surface the round as synthetic progress: long interactive flows stay\n        // observable, and consumers composing `resetTimeoutOnProgress`-style\n        // watchdogs around the call see liveness instead of silence.\n        requestOptions.onprogress?.({ progress: round, message: `Fulfilling input required by '${method}' (round ${round})` });\n\n        const entries = Object.entries(payload.inputRequests ?? {});\n        let responses: Record<string, unknown> | undefined;\n        if (entries.length > 0) {\n            // Fulfil concurrently (the embedded requests are independent); a\n            // single failure fails the call AND aborts the siblings via the\n            // linked per-round signal so they do not keep running.\n            const round = linkedRoundAbort(signal);\n            try {\n                const fulfilled = await Promise.all(\n                    entries.map(async ([key, entry]) => {\n                        try {\n                            return [key, await hooks.dispatchInputRequest(key, entry, round.signal)] as const;\n                        } catch (error) {\n                            round.abort(error);\n                            throw error;\n                        }\n                    })\n                );\n                responses = Object.fromEntries(fulfilled);\n            } finally {\n                round.dispose();\n            }\n        } else {\n            // requestState-only (load-shedding) leg: fixed pacing so the loop\n            // never hot-spins; counted in the same round cap. The sleep\n            // honors the caller's abort signal.\n            await sleep(REQUEST_STATE_ONLY_LEG_PACING_MS, signal);\n        }\n\n        const legOptions: InputRequiredRetryLegOptions = {\n            ...(requestOptions.timeout !== undefined && { timeout: requestOptions.timeout })\n        };\n        if (requestOptions.maxTotalTimeout !== undefined) {\n            const totalElapsed = Date.now() - startedAt;\n            const remaining = requestOptions.maxTotalTimeout - totalElapsed;\n            if (remaining <= 0) {\n                throw new SdkError(SdkErrorCode.RequestTimeout, 'Maximum total timeout exceeded', {\n                    maxTotalTimeout: requestOptions.maxTotalTimeout,\n                    totalElapsed\n                });\n            }\n            legOptions.maxTotalTimeout = remaining;\n        }\n\n        const result = await hooks.retry(buildInputRequiredRetryParams(originalParams, responses, payload.requestState), legOptions);\n        if (isInputRequiredResult(result)) {\n            payload = {\n                inputRequests: result.inputRequests ?? {},\n                ...(result.requestState !== undefined && { requestState: result.requestState })\n            };\n            continue;\n        }\n        return result;\n    }\n}\n","import type * as z from 'zod/v4';\n\nimport {\n    IdJagTokenExchangeResponseSchema,\n    OAuthClientInformationFullSchema,\n    OAuthClientInformationSchema,\n    OAuthClientMetadataSchema,\n    OAuthClientRegistrationErrorSchema,\n    OAuthErrorResponseSchema,\n    OAuthMetadataSchema,\n    OAuthProtectedResourceMetadataSchema,\n    OAuthTokenRevocationRequestSchema,\n    OAuthTokensSchema,\n    OpenIdProviderDiscoveryMetadataSchema,\n    OpenIdProviderMetadataSchema\n} from '../shared/auth';\nimport type { StandardSchemaV1, StandardSchemaV1Sync } from '../util/standardSchema';\nimport * as schemas from './schemas';\n\n/**\n * Explicit allowlist of protocol Zod schemas that correspond to a public spec type in `types.ts`.\n *\n * This intentionally excludes internal helper schemas exported from `schemas.ts` that have no\n * matching public type (e.g. `ListChangedOptionsBaseSchema`, `BaseRequestParamsSchema`,\n * `NotificationsParamsSchema`, `ClientTasksCapabilitySchema`, `ServerTasksCapabilitySchema`).\n * Keeping the list explicit means new public spec types must be added here deliberately, and\n * internals never leak into `SpecTypeName`.\n *\n * `ResourceTemplateSchema` is included; its public type is exported as `ResourceTemplateType`\n * (the bare name collides with the server package's `ResourceTemplate` class), so\n * `SpecTypes['ResourceTemplate']` is structurally equal to `ResourceTemplateType` rather than to\n * a type literally named `ResourceTemplate`.\n */\nconst SPEC_SCHEMA_KEYS = [\n    'AnnotationsSchema',\n    'AudioContentSchema',\n    'BaseMetadataSchema',\n    'BlobResourceContentsSchema',\n    'BooleanSchemaSchema',\n    'CallToolRequestSchema',\n    'CallToolRequestParamsSchema',\n    'CallToolResultSchema',\n    'CancelledNotificationSchema',\n    'CancelledNotificationParamsSchema',\n    'CancelTaskRequestSchema',\n    'CancelTaskResultSchema',\n    'ClientCapabilitiesSchema',\n    'ClientNotificationSchema',\n    'ClientRequestSchema',\n    'ClientResultSchema',\n    'CompatibilityCallToolResultSchema',\n    'CompleteRequestSchema',\n    'CompleteRequestParamsSchema',\n    'CompleteResultSchema',\n    'ContentBlockSchema',\n    'CreateMessageRequestSchema',\n    'CreateMessageRequestParamsSchema',\n    'CreateMessageResultSchema',\n    'CreateMessageResultWithToolsSchema',\n    'CreateTaskResultSchema',\n    'CursorSchema',\n    'DiscoverRequestSchema',\n    'DiscoverResultSchema',\n    'ElicitationCompleteNotificationSchema',\n    'ElicitationCompleteNotificationParamsSchema',\n    'ElicitRequestSchema',\n    'ElicitRequestFormParamsSchema',\n    'ElicitRequestParamsSchema',\n    'ElicitRequestURLParamsSchema',\n    'ElicitResultSchema',\n    'EmbeddedResourceSchema',\n    'EmptyResultSchema',\n    'EnumSchemaSchema',\n    'GetPromptRequestSchema',\n    'GetPromptRequestParamsSchema',\n    'GetPromptResultSchema',\n    'GetTaskPayloadRequestSchema',\n    'GetTaskPayloadResultSchema',\n    'GetTaskRequestSchema',\n    'GetTaskResultSchema',\n    'IconSchema',\n    'IconsSchema',\n    'ImageContentSchema',\n    'ImplementationSchema',\n    'InitializedNotificationSchema',\n    'InitializeRequestSchema',\n    'InitializeRequestParamsSchema',\n    'InitializeResultSchema',\n    'JSONArraySchema',\n    'JSONObjectSchema',\n    'JSONRPCErrorResponseSchema',\n    'JSONRPCMessageSchema',\n    'JSONRPCNotificationSchema',\n    'JSONRPCRequestSchema',\n    'JSONRPCResponseSchema',\n    'JSONRPCResultResponseSchema',\n    'JSONValueSchema',\n    'LegacyTitledEnumSchemaSchema',\n    'ListPromptsRequestSchema',\n    'ListPromptsResultSchema',\n    'ListResourcesRequestSchema',\n    'ListResourcesResultSchema',\n    'ListResourceTemplatesRequestSchema',\n    'ListResourceTemplatesResultSchema',\n    'ListRootsRequestSchema',\n    'ListRootsResultSchema',\n    'ListTasksRequestSchema',\n    'ListTasksResultSchema',\n    'ListToolsRequestSchema',\n    'ListToolsResultSchema',\n    'LoggingLevelSchema',\n    'LoggingMessageNotificationSchema',\n    'LoggingMessageNotificationParamsSchema',\n    'ModelHintSchema',\n    'ModelPreferencesSchema',\n    'MultiSelectEnumSchemaSchema',\n    'NotificationSchema',\n    'NumberSchemaSchema',\n    'PaginatedRequestSchema',\n    'PaginatedRequestParamsSchema',\n    'PaginatedResultSchema',\n    'PingRequestSchema',\n    'PrimitiveSchemaDefinitionSchema',\n    'ProgressSchema',\n    'ProgressNotificationSchema',\n    'ProgressNotificationParamsSchema',\n    'ProgressTokenSchema',\n    'PromptSchema',\n    'PromptArgumentSchema',\n    'PromptListChangedNotificationSchema',\n    'PromptMessageSchema',\n    'PromptReferenceSchema',\n    'ReadResourceRequestSchema',\n    'ReadResourceRequestParamsSchema',\n    'ReadResourceResultSchema',\n    'RelatedTaskMetadataSchema',\n    'RequestSchema',\n    'RequestIdSchema',\n    'RequestMetaSchema',\n    'ResourceSchema',\n    'ResourceContentsSchema',\n    'ResourceLinkSchema',\n    'ResourceListChangedNotificationSchema',\n    'ResourceRequestParamsSchema',\n    'ResourceTemplateSchema',\n    'ResourceTemplateReferenceSchema',\n    'ResourceUpdatedNotificationSchema',\n    'ResourceUpdatedNotificationParamsSchema',\n    'ResultMetaObjectSchema',\n    'ResultSchema',\n    'RoleSchema',\n    'RootSchema',\n    'RootsListChangedNotificationSchema',\n    'SamplingContentSchema',\n    'SamplingMessageSchema',\n    'SamplingMessageContentBlockSchema',\n    'ServerCapabilitiesSchema',\n    'ServerNotificationSchema',\n    'ServerRequestSchema',\n    'ServerResultSchema',\n    'SetLevelRequestSchema',\n    'SetLevelRequestParamsSchema',\n    'SingleSelectEnumSchemaSchema',\n    'StringSchemaSchema',\n    'SubscribeRequestSchema',\n    'SubscribeRequestParamsSchema',\n    'SubscriptionFilterSchema',\n    'SubscriptionsAcknowledgedNotificationSchema',\n    'SubscriptionsAcknowledgedNotificationParamsSchema',\n    'SubscriptionsListenRequestSchema',\n    'SubscriptionsListenRequestParamsSchema',\n    'SubscriptionsListenResultSchema',\n    'SubscriptionsListenResultMetaSchema',\n    'TaskAugmentedRequestParamsSchema',\n    'TaskCreationParamsSchema',\n    'TaskMetadataSchema',\n    'TaskSchema',\n    'TaskStatusSchema',\n    'TaskStatusNotificationSchema',\n    'TaskStatusNotificationParamsSchema',\n    'TextContentSchema',\n    'TextResourceContentsSchema',\n    'TitledMultiSelectEnumSchemaSchema',\n    'TitledSingleSelectEnumSchemaSchema',\n    'ToolSchema',\n    'ToolAnnotationsSchema',\n    'ToolChoiceSchema',\n    'ToolExecutionSchema',\n    'ToolListChangedNotificationSchema',\n    'ToolResultContentSchema',\n    'ToolUseContentSchema',\n    'UnsubscribeRequestSchema',\n    'UnsubscribeRequestParamsSchema',\n    'UntitledMultiSelectEnumSchemaSchema',\n    'UntitledSingleSelectEnumSchemaSchema'\n] as const satisfies readonly (keyof typeof schemas)[];\n\nconst authSchemas = {\n    IdJagTokenExchangeResponseSchema,\n    OAuthClientInformationFullSchema,\n    OAuthClientInformationSchema,\n    OAuthClientMetadataSchema,\n    OAuthClientRegistrationErrorSchema,\n    OAuthErrorResponseSchema,\n    OAuthMetadataSchema,\n    OAuthProtectedResourceMetadataSchema,\n    OAuthTokenRevocationRequestSchema,\n    OAuthTokensSchema,\n    OpenIdProviderDiscoveryMetadataSchema,\n    OpenIdProviderMetadataSchema\n} as const;\n\ntype ProtocolSchemaKey = (typeof SPEC_SCHEMA_KEYS)[number];\ntype AuthSchemaKey = keyof typeof authSchemas;\ntype SchemaKey = ProtocolSchemaKey | AuthSchemaKey;\n\ntype SchemaFor<K extends SchemaKey> = K extends ProtocolSchemaKey\n    ? (typeof schemas)[K]\n    : K extends AuthSchemaKey\n      ? (typeof authSchemas)[K]\n      : never;\n\ntype StripSchemaSuffix<K> = K extends `${infer N}Schema` ? N : never;\n\n/**\n * Union of every named type in the SDK's protocol and OAuth schemas (e.g. `'CallToolResult'`,\n * `'ContentBlock'`, `'Tool'`, `'OAuthTokens'`). Derived from the internal Zod schemas, so it stays\n * in sync with the spec.\n */\nexport type SpecTypeName = StripSchemaSuffix<SchemaKey>;\n\n/**\n * Maps each {@linkcode SpecTypeName} to its TypeScript type.\n *\n * `SpecTypes['Tool']` is equivalent to importing the `Tool` type directly.\n * These validators cover the NEUTRAL model — the consumer-facing shapes with\n * no wire-only members (`resultType`, the reserved `_meta` envelope keys).\n * Per-revision WIRE validators are deliberately not public surface; they are\n * planned to return as versioned `zod-schemas/<revision>` exports for\n * consumers who validate raw wire traffic themselves.\n */\nexport type SpecTypes = {\n    [K in SchemaKey as StripSchemaSuffix<K>]: SchemaFor<K> extends z.ZodType ? z.output<SchemaFor<K>> : never;\n};\n\n/**\n * Input shape for each {@linkcode SpecTypeName}. For most types this equals {@linkcode SpecTypes},\n * but a few schemas apply defaults/preprocessing, so the accepted input may be looser than the\n * resulting output type.\n */\ntype SpecTypeInputs = {\n    [K in SchemaKey as StripSchemaSuffix<K>]: SchemaFor<K> extends z.ZodType ? z.input<SchemaFor<K>> : never;\n};\n\ntype SchemaRecord = { readonly [K in SpecTypeName]: StandardSchemaV1Sync<SpecTypeInputs[K], SpecTypes[K]> };\ntype GuardRecord = { readonly [K in SpecTypeName]: (value: unknown) => value is SpecTypeInputs[K] };\n\nconst _specTypeSchemas: Record<string, StandardSchemaV1> = {};\nconst _isSpecType: Record<string, (value: unknown) => boolean> = {};\nfunction register(key: string, schema: z.ZodType): void {\n    const name = key.slice(0, -'Schema'.length);\n    _specTypeSchemas[name] = schema;\n    _isSpecType[name] = (v: unknown) => schema.safeParse(v).success;\n}\nfor (const key of SPEC_SCHEMA_KEYS) {\n    // eslint-disable-next-line import/namespace -- key is constrained to keyof typeof schemas via the satisfies clause above\n    register(key, schemas[key]);\n}\nfor (const [key, schema] of Object.entries(authSchemas)) {\n    register(key, schema);\n}\n\n/**\n * Runtime validators for every MCP spec type, keyed by type name.\n *\n * Use this when you need to validate a spec-defined shape at a boundary the SDK does not own, for\n * example an extension's custom-method payload that embeds a `CallToolResult`, or a value read from\n * storage that should be a `Tool`.\n *\n * Each entry implements the Standard Schema interface, so it composes with any\n * Standard-Schema-aware library. For a simple boolean check, use {@linkcode isSpecType} instead.\n *\n * @example\n * ```ts source=\"./specTypeSchema.examples.ts#specTypeSchemas_basicUsage\"\n * const result = specTypeSchemas.CallToolResult['~standard'].validate(untrusted);\n * if (result.issues === undefined) {\n *     // result.value is CallToolResult\n * }\n * ```\n */\nexport const specTypeSchemas: SchemaRecord = Object.freeze(_specTypeSchemas as SchemaRecord);\n\n/**\n * Type predicates for every MCP spec type, keyed by type name.\n *\n * Returns `true` if the value satisfies the schema's input type (`z.input<>`, before defaults and\n * transforms are applied), and narrows to that input type. For schemas with `.default()` or\n * `.preprocess()`, this may accept values that do not structurally match the named output type;\n * for example `isSpecType.CallToolResult({})` is `true` because `content` has a default. Use\n * `specTypeSchemas.X['~standard'].validate(value)` when you need the validated output value.\n *\n * Each guard is a standalone function, so it can be passed directly as a callback.\n *\n * @example\n * ```ts source=\"./specTypeSchema.examples.ts#isSpecType_basicUsage\"\n * if (isSpecType.ContentBlock(value)) {\n *     // value is ContentBlock\n * }\n *\n * const blocks = mixed.filter(isSpecType.ContentBlock);\n * ```\n */\nexport const isSpecType: GuardRecord = Object.freeze(_isSpecType as GuardRecord);\n","/**\n * Static era pins for lifecycle messages on the OUTBOUND path (the\n * chicken-and-egg bootstrap): these messages are sent while the instance's\n * negotiated protocol version is still unset, and they self-identify their\n * era by construction — `initialize`/`notifications/initialized` ARE the\n * legacy handshake (`initialize` ⇒ legacy), and `server/discover` exists only\n * on the 2026 era. The pins apply only during that pre-negotiation window\n * (`Protocol._resolveOutboundCodec` consults them when the negotiated version\n * is `undefined`); once a version is negotiated, every send resolves through\n * the instance's era.\n *\n * Scope notes:\n * - OUTBOUND ONLY. Inbound era truth is the instance's negotiated protocol\n *   version (connection state); an edge classification, when present, is\n *   VALIDATED against that instance era — never used to pick a codec per\n *   message — so pinning inbound would have nothing to attach to. An\n *   inbound `server/discover` on a legacy-era instance correctly falls to\n *   −32601 by registry absence; serving it requires an instance bound to\n *   the modern era.\n * - `ping` is deliberately NOT pinned. A bare `{method: 'ping'}` carries no\n *   era marker, and pinning it would let a negotiated-modern session emit a\n *   2025-only method onto the modern leg (the exact inverse leak registry\n *   membership exists to prevent). `ping` era-gates like any other method:\n *   present on the 2025 era, absent from the 2026 era (the modern keepalive\n *   story is owned by the negotiation milestones).\n */\nimport type { WireCodec } from './codec';\nimport { codecForVersion, MODERN_WIRE_REVISION } from './codec';\n\nexport function bootstrapOutboundCodec(method: string): WireCodec | undefined {\n    switch (method) {\n        case 'initialize':\n        case 'notifications/initialized': {\n            // The legacy handshake, by definition (Q2).\n            return codecForVersion(undefined);\n        }\n        case 'server/discover': {\n            // The modern discovery exchange, 2026-era only.\n            return codecForVersion(MODERN_WIRE_REVISION);\n        }\n        default: {\n            return undefined;\n        }\n    }\n}\n","import { SdkError, SdkErrorCode } from '../errors/sdkErrors';\nimport type {\n    AuthInfo,\n    CancelledNotification,\n    ClientCapabilities,\n    CreateMessageRequest,\n    CreateMessageResult,\n    CreateMessageResultWithTools,\n    ElicitRequestFormParams,\n    ElicitRequestURLParams,\n    ElicitResult,\n    HandlerResultTypeMap,\n    Implementation,\n    JSONRPCErrorResponse,\n    JSONRPCNotification,\n    JSONRPCRequest,\n    JSONRPCResponse,\n    JSONRPCResultResponse,\n    LoggingLevel,\n    MessageExtraInfo,\n    Notification,\n    NotificationMethod,\n    NotificationTypeMap,\n    Progress,\n    ProgressNotification,\n    Request,\n    RequestId,\n    RequestMeta,\n    RequestMetaEnvelope,\n    RequestMethod,\n    RequestTypeMap,\n    Result,\n    ResultTypeMap,\n    ServerCapabilities\n} from '../types/index';\nimport {\n    CLIENT_CAPABILITIES_META_KEY,\n    CLIENT_INFO_META_KEY,\n    isJSONRPCErrorResponse,\n    isJSONRPCNotification,\n    isJSONRPCRequest,\n    isJSONRPCResultResponse,\n    LOG_LEVEL_META_KEY,\n    PROTOCOL_VERSION_META_KEY,\n    ProtocolError,\n    ProtocolErrorCode,\n    SUPPORTED_PROTOCOL_VERSIONS\n} from '../types/index';\nimport type { StandardSchemaV1 } from '../util/standardSchema';\nimport { isStandardSchema, validateStandardSchema } from '../util/standardSchema';\nimport { bootstrapOutboundCodec } from '../wire/bootstrap';\nimport type { LiftedWireMaterial, WireCodec } from '../wire/codec';\nimport {\n    classifiedWireEra,\n    codecForVersion,\n    isExtensionReusedRequestMethod,\n    isSpecNotificationMethod,\n    isSpecRequestMethod,\n    MODERN_WIRE_REVISION\n} from '../wire/codec';\nimport { manualInputRequiredValue, partitionInputResponses } from './inputRequiredEngine';\nimport type { Transport, TransportSendOptions } from './transport';\n\n/**\n * Callback for progress notifications.\n */\nexport type ProgressCallback = (progress: Progress) => void;\n\n/**\n * Additional initialization options.\n */\nexport type ProtocolOptions = {\n    /**\n     * Protocol versions supported. The legacy `initialize` handshake offers and\n     * falls back to the first 2025-era entry in the list (the client sends it,\n     * the server counter-offers it); 2026-era entries are only ever selected via\n     * `server/discover`. Passed to transport during {@linkcode Protocol.connect | connect()}.\n     *\n     * @default {@linkcode SUPPORTED_PROTOCOL_VERSIONS}\n     */\n    supportedProtocolVersions?: string[];\n\n    /**\n     * Whether to restrict emitted requests to only those that the remote side has indicated that they can handle, through their advertised capabilities.\n     *\n     * Note that this DOES NOT affect checking of _local_ side capabilities, as it is considered a logic error to mis-specify those.\n     *\n     * Currently this defaults to `false`, for backwards compatibility with SDK versions that did not advertise capabilities correctly. In future, this will default to `true`.\n     */\n    enforceStrictCapabilities?: boolean;\n    /**\n     * An array of notification method names that should be automatically debounced.\n     * Any notifications with a method in this list will be coalesced if they\n     * occur in the same tick of the event loop.\n     * e.g., `['notifications/tools/list_changed']`\n     */\n    debouncedNotificationMethods?: string[];\n};\n\n/**\n * The default request timeout, in milliseconds.\n */\nexport const DEFAULT_REQUEST_TIMEOUT_MSEC = 60_000;\n\n/**\n * Options that can be given per request.\n */\nexport type RequestOptions = {\n    /**\n     * If set, requests progress notifications from the remote end (if supported). When progress notifications are received, this callback will be invoked.\n     */\n    onprogress?: ProgressCallback;\n\n    /**\n     * Can be used to cancel an in-flight request. This will cause an `AbortError` to be raised from {@linkcode Protocol.request | request()}.\n     */\n    signal?: AbortSignal;\n\n    /**\n     * A timeout (in milliseconds) for this request. If exceeded, an {@linkcode SdkError} with code {@linkcode SdkErrorCode.RequestTimeout} will be raised from {@linkcode Protocol.request | request()}.\n     *\n     * If not specified, {@linkcode DEFAULT_REQUEST_TIMEOUT_MSEC} will be used as the timeout.\n     */\n    timeout?: number;\n\n    /**\n     * If `true`, receiving a progress notification will reset the request timeout.\n     * This is useful for long-running operations that send periodic progress updates.\n     * Default: `false`\n     */\n    resetTimeoutOnProgress?: boolean;\n\n    /**\n     * Maximum total time (in milliseconds) to wait for a response.\n     * If exceeded, an {@linkcode SdkError} with code {@linkcode SdkErrorCode.RequestTimeout} will be raised, regardless of progress notifications.\n     * If not specified, there is no maximum total timeout.\n     *\n     * For multi-round-trip requests fulfilled by the auto-fulfilment driver\n     * (protocol revision 2026-07-28), the budget bounds the WHOLE flow: every\n     * retry leg is given only the time remaining.\n     */\n    maxTotalTimeout?: number;\n\n    /**\n     * Manual multi-round-trip mode for this call (protocol revision\n     * 2026-07-28): when the response is an `input_required` result, hand it\n     * back to the caller instead of auto-fulfilling it (or raising a typed\n     * error). The resolved value is the neutral input-required shape\n     * (`resultType: 'input_required'`, `inputRequests?`, `requestState?`);\n     * wrap the result schema with `withInputRequired()` on the explicit\n     * schema path to type both outcomes. The caller is then responsible for\n     * gathering the requested input and retrying the original request with\n     * `inputResponses` / `requestState` params and a fresh request.\n     *\n     * Default: `false`.\n     */\n    allowInputRequired?: boolean;\n} & TransportSendOptions;\n\n/**\n * Flow context handed to {@linkcode Protocol._resolveNonCompleteResult}: the\n * originating request, its options, the wire codec that decoded the response,\n * the timestamp the originating leg was issued at (for whole-flow timeout\n * accounting), and a `retry` closure that re-enters the request funnel with\n * fresh params on a fresh request id.\n */\nexport interface NonCompleteResultFlow<T extends StandardSchemaV1 = StandardSchemaV1> {\n    codec: WireCodec;\n    request: Request;\n    resultSchema: T;\n    options: RequestOptions | undefined;\n    flowStartedAt: number;\n    /** Re-issue the originating request with the given params and per-leg options. */\n    retry(params: Record<string, unknown> | undefined, legOptions: RequestOptions): Promise<unknown>;\n}\n\n/**\n * Options that can be given per notification.\n */\nexport type NotificationOptions = {\n    /**\n     * May be used to indicate to the transport which incoming request to associate this outgoing notification with.\n     */\n    relatedRequestId?: RequestId;\n};\n\n/**\n * The reserved per-request `_meta` envelope keys (protocol revision\n * 2026-07-28). The protocol layer lifts these out of inbound `_meta` before\n * handlers run and surfaces them at `ctx.mcpReq.envelope` — they are\n * wire-level bookkeeping, not handler material.\n */\nconst RESERVED_ENVELOPE_META_KEYS: readonly string[] = [\n    PROTOCOL_VERSION_META_KEY,\n    CLIENT_INFO_META_KEY,\n    CLIENT_CAPABILITIES_META_KEY,\n    LOG_LEVEL_META_KEY\n];\n\n/**\n * Top-level params members carrying multi-round-trip driver material\n * (protocol revision 2026-07-28). The spec reserves these names on\n * client-initiated REQUESTS only — notification params keep them untouched\n * (a vendor notification may legitimately use the same names).\n */\nconst RETRY_PARAMS_KEYS = ['inputResponses', 'requestState'] as const;\n\n/**\n * Lift wire-only material out of an inbound message so handlers see exactly\n * the 2025-era shape, and surface it for the protocol layer (requests: via\n * `ctx.mcpReq`). What counts as wire-only depends on the message kind: the\n * reserved envelope `_meta` keys are reserved on every message, while the\n * multi-round-trip retry fields (`inputResponses`/`requestState`) are\n * reserved on client-initiated requests only — so notifications get only the\n * envelope lift, and their top-level params stay untouched. Messages without\n * wire-only material are returned unchanged (same reference).\n */\nfunction liftWireOnlyMaterial<T extends JSONRPCRequest | JSONRPCNotification>(\n    message: T,\n    kind: 'request' | 'notification'\n): { message: T; lifted: LiftedWireMaterial } {\n    const params = (message as { params?: unknown }).params;\n    if (!isPlainObject(params)) return { message, lifted: {} };\n\n    const meta = params._meta;\n    const envelopeKeys = isPlainObject(meta) ? RESERVED_ENVELOPE_META_KEYS.filter(key => key in meta) : [];\n    const retryKeys = kind === 'request' ? RETRY_PARAMS_KEYS.filter(key => key in params) : [];\n    if (envelopeKeys.length === 0 && retryKeys.length === 0) return { message, lifted: {} };\n\n    const lifted: LiftedWireMaterial = {};\n    const nextParams: Record<string, unknown> = { ...params };\n\n    if (envelopeKeys.length > 0 && isPlainObject(meta)) {\n        const envelope: Record<string, unknown> = {};\n        const nextMeta: Record<string, unknown> = { ...meta };\n        for (const key of envelopeKeys) {\n            envelope[key] = meta[key];\n            delete nextMeta[key];\n        }\n        // Surfaced as received; validation/enforcement is the dispatch-time\n        // classifier's job, not the lift's.\n        lifted.envelope = envelope as Partial<RequestMetaEnvelope>;\n        if (Object.keys(nextMeta).length > 0) {\n            nextParams._meta = nextMeta;\n        } else {\n            delete nextParams._meta;\n        }\n    }\n\n    for (const key of retryKeys) {\n        // Driver material reaches the protocol layer un-deleted, verbatim.\n        if (key === 'inputResponses') lifted.inputResponses = nextParams[key] as Record<string, unknown>;\n        if (key === 'requestState') lifted.requestState = nextParams[key] as string;\n        delete nextParams[key];\n    }\n\n    return { message: { ...message, params: nextParams } as T, lifted };\n}\n\n/**\n * Standard Schema adapter over the era codec's `validateResult` function (the\n * function-only WireCodec contract exposes no schema objects). Used by the\n * spec-method `request()` overload so the request funnel keeps a single\n * `StandardSchemaV1`-shaped validation seam for both spec and explicit-schema\n * paths.\n *\n * Returns `undefined` when the method has no result entry on this era's\n * registry — the caller maps that to the synchronous \"pass a result schema\"\n * TypeError, exactly matching the pre-function-only behavior the\n * typedMapAlignment suite pins (the result map deliberately excludes the\n * `tasks/*` methods, so the spec-method overload refuses them up front).\n */\nfunction codecResultValidator(codec: WireCodec, method: string): StandardSchemaV1 | undefined {\n    // Probe for result-registry membership through the function-only\n    // contract: a `not-in-era` outcome means no result entry for this method\n    // (the probe value is irrelevant — every spec result schema rejects\n    // `undefined`, so a method with an entry returns `invalid`, never\n    // `not-in-era`).\n    const probe = codec.validateResult(method, undefined);\n    if (!probe.ok && probe.reason === 'not-in-era') return undefined;\n    return {\n        '~standard': {\n            version: 1,\n            vendor: 'mcp-wire-codec',\n            validate(value: unknown): StandardSchemaV1.Result<unknown> {\n                const outcome = codec.validateResult(method, value);\n                if (outcome.ok) return { value: outcome.value };\n                return { issues: [{ message: outcome.reason === 'invalid' ? outcome.message : `not-in-era: ${method}` }] };\n            }\n        }\n    };\n}\n\n/**\n * The type of `ctx.mcpReq.requestState`. The type parameter is\n * caller-asserted (no validation, like the two-argument `acceptedContent<T>`)\n * — pair with `createRequestStateCodec<T>` so the claim is backed by the\n * codec's verification.\n */\nexport type RequestStateAccessor = <T = unknown>() => T | undefined;\n\n/**\n * Builds the `ctx.mcpReq.requestState` accessor for a resolved value. The\n * `as T` below is the one place {@linkcode RequestStateAccessor}'s\n * caller-asserted typing is implemented — no implementation can produce an\n * arbitrary `T` from a runtime value honestly.\n */\nexport function requestStateAccessor(value: unknown): RequestStateAccessor {\n    return <T>(): T | undefined => value as T | undefined;\n}\n\n/** Shared no-state accessor: the common case allocates nothing per request. */\nconst NO_REQUEST_STATE = requestStateAccessor(undefined);\n\n/**\n * Returns a context whose `requestState` accessor reads the given value —\n * how the server seam hands a verify hook's decoded payload (or the legacy\n * shim's per-round echo) to the handler without mutating the original\n * context.\n */\nexport function withRequestStateValue<ContextT extends BaseContext>(ctx: ContextT, value: unknown): ContextT {\n    return {\n        ...ctx,\n        mcpReq: {\n            ...ctx.mcpReq,\n            requestState: requestStateAccessor(value)\n        }\n    };\n}\n\n/**\n * Base context provided to all request handlers.\n */\nexport type BaseContext = {\n    /**\n     * The session ID from the transport, if available.\n     */\n    sessionId?: string;\n\n    /**\n     * Information about the MCP request being handled.\n     */\n    mcpReq: {\n        /**\n         * The JSON-RPC ID of the request being handled.\n         */\n        id: RequestId;\n\n        /**\n         * The method name of the request (e.g., 'tools/call', 'ping').\n         */\n        method: string;\n\n        /**\n         * Metadata from the original request, with the reserved\n         * `io.modelcontextprotocol/*` envelope keys already lifted out\n         * (readable via `ctx.mcpReq.envelope`).\n         */\n        _meta?: RequestMeta;\n\n        /**\n         * The per-request `_meta` envelope (protocol revision 2026-07-28):\n         * the reserved `io.modelcontextprotocol/*` keys carried by the\n         * request, lifted out of the `_meta` the handler sees. Surfaced as\n         * received — `Partial` because only the keys the request actually\n         * carried are present (envelope requiredness is enforced per request\n         * at dispatch time, not by the lift); only present at all when the\n         * request carried envelope keys.\n         */\n        envelope?: Partial<RequestMetaEnvelope>;\n\n        /**\n         * Multi-round-trip input responses carried by a retried request\n         * (protocol revision 2026-07-28), lifted out of the params the\n         * handler sees. Entries are the BARE response objects keyed by the\n         * identifiers the server assigned in `inputRequests`; entries that do\n         * not look like bare responses (e.g. a `{method, result}` wrapper)\n         * are dropped and their keys recorded in `droppedInputResponseKeys`.\n         *\n         * The values arrive from the client and are NOT validated by the SDK\n         * — treat them as untrusted input.\n         */\n        inputResponses?: Record<string, unknown>;\n\n        /**\n         * Keys of `inputResponses` entries the SDK dropped because they were\n         * not bare response objects (for example the wrapped `{method,\n         * result}` shape some peers emit). Surfaced so a handler can re-issue\n         * the corresponding input request rather than hard-fail.\n         */\n        droppedInputResponseKeys?: string[];\n\n        /**\n         * Reads the multi-round-trip request state for the current round:\n         * the value the configured `ServerOptions.requestState.verify` hook\n         * resolved with (e.g. `createRequestStateCodec.verify`'s decoded\n         * payload — `mint<T>`/`requestState<T>()` are the typed pair), the\n         * raw wire string when no hook is configured, or `undefined` when\n         * the round carried no state. The type parameter is a compile-time\n         * cast only.\n         *\n         * SECURITY: `requestState` round-trips through the client and MUST\n         * be treated as attacker-controlled input. The SDK applies no\n         * integrity protection by default — servers whose state influences\n         * authorization or business logic MUST integrity-protect it and\n         * verify via the `requestState.verify` hook (spec:\n         * basic/patterns/mrtr, server requirements 4–5).\n         */\n        requestState: RequestStateAccessor;\n\n        /**\n         * An abort signal used to communicate if the request was cancelled from the sender's side.\n         */\n        signal: AbortSignal;\n\n        /**\n         * Sends a request that relates to the current request being handled.\n         *\n         * This is used by certain transports to correctly associate related messages.\n         *\n         * For spec methods the result type is inferred from the method name.\n         * For custom (non-spec) methods, pass a result schema as the second argument.\n         */\n        send: {\n            <M extends RequestMethod>(\n                request: { method: M; params?: Record<string, unknown> },\n                options?: RequestOptions\n            ): Promise<ResultTypeMap[M]>;\n            <T extends StandardSchemaV1>(\n                request: Request,\n                resultSchema: T,\n                options?: RequestOptions\n            ): Promise<StandardSchemaV1.InferOutput<T>>;\n        };\n\n        /**\n         * Sends a notification that relates to the current request being handled.\n         *\n         * This is used by certain transports to correctly associate related messages.\n         */\n        notify: (notification: Notification) => Promise<void>;\n    };\n\n    /**\n     * HTTP transport information, only available when using an HTTP-based transport.\n     */\n    http?: {\n        /**\n         * Information about a validated access token, provided to request handlers.\n         */\n        authInfo?: AuthInfo;\n    };\n};\n\n/**\n * Context provided to server-side request handlers, extending {@linkcode BaseContext} with server-specific fields.\n */\nexport type ServerContext = BaseContext & {\n    mcpReq: {\n        /**\n         * Send a log message notification to the client.\n         * Respects the client's log level filter set via logging/setLevel.\n         *\n         * @deprecated Deprecated as of protocol version 2026-07-28 (SEP-2577).\n         * Remains functional during the deprecation window (at least twelve months).\n         * Migrate to stderr logging (STDIO servers) or OpenTelemetry.\n         */\n        log: (level: LoggingLevel, data: unknown, logger?: string) => Promise<void>;\n\n        /**\n         * Send an elicitation request to the client, requesting user input.\n         *\n         * @deprecated Throws on a 2026-07-28-era request — return `inputRequired(...)`\n         * (multi-round-trip) from the handler instead. The 2025 push-style server-to-client request model is\n         * replaced by input_required results in the 2026-07-28 protocol. If your factory serves\n         * both eras, this only works on the legacy path.\n         */\n        elicitInput: (params: ElicitRequestFormParams | ElicitRequestURLParams, options?: RequestOptions) => Promise<ElicitResult>;\n\n        /**\n         * Request LLM sampling from the client.\n         *\n         * @deprecated Deprecated as of protocol version 2026-07-28 (SEP-2577).\n         * Throws on a 2026-07-28-era request — return `inputRequired(...)` (multi-round-trip)\n         * from the handler instead, or migrate to calling LLM provider APIs directly. The 2025 push-style\n         * server-to-client request model is replaced by input_required results in the 2026-07-28\n         * protocol. If your factory serves both eras, this only works on the legacy path.\n         */\n        requestSampling: (\n            params: CreateMessageRequest['params'],\n            options?: RequestOptions\n        ) => Promise<CreateMessageResult | CreateMessageResultWithTools>;\n    };\n\n    http?: {\n        /**\n         * The original HTTP request.\n         */\n        req?: globalThis.Request;\n\n        /**\n         * Closes the SSE stream for this request, triggering client reconnection.\n         * Only available when using a StreamableHTTPServerTransport with eventStore configured.\n         */\n        closeSSE?: () => void;\n\n        /**\n         * Closes the standalone GET SSE stream, triggering client reconnection.\n         * Only available when using a StreamableHTTPServerTransport with eventStore configured.\n         */\n        closeStandaloneSSE?: () => void;\n    };\n};\n\n/**\n * Context provided to client-side request handlers.\n */\nexport type ClientContext = BaseContext;\n\n/**\n * Information about a request's timeout state\n */\ntype TimeoutInfo = {\n    timeoutId: ReturnType<typeof setTimeout>;\n    startTime: number;\n    timeout: number;\n    maxTotalTimeout?: number;\n    resetTimeoutOnProgress: boolean;\n    onTimeout: () => void;\n};\n\n/*\n * Package-internal write access to Protocol's negotiated-protocol-version state.\n *\n * The negotiated version is a protected field on Protocol that the role classes\n * (Client/Server) assign directly. Tests and the modern-era server entry still\n * need to set it from outside the class hierarchy, so Protocol's static\n * initializer hands this module-scoped closure privileged access and\n * `setNegotiatedProtocolVersion` re-exports it on the core INTERNAL barrel\n * only — deliberately not public API.\n */\nlet writeNegotiatedProtocolVersion: <ContextT extends BaseContext>(instance: Protocol<ContextT>, version: string | undefined) => void;\n\n/**\n * Package-internal write channel for a {@linkcode Protocol} instance's\n * negotiated protocol version, for callers outside the class hierarchy:\n * tests and the (future) modern-era server entry that marks a factory\n * instance modern at binding time. Exported on the core internal barrel\n * only — never public API.\n */\nexport function setNegotiatedProtocolVersion<ContextT extends BaseContext>(\n    instance: Protocol<ContextT>,\n    version: string | undefined\n): void {\n    writeNegotiatedProtocolVersion(instance, version);\n}\n\n/**\n * Implements MCP protocol framing on top of a pluggable transport, including\n * features like request/response linking, notifications, and progress.\n *\n * `Protocol` is abstract; `Client` and `Server` are the concrete role-specific\n * implementations most code should use.\n */\nexport abstract class Protocol<ContextT extends BaseContext> {\n    private _transport?: Transport;\n    private _requestMessageId = 0;\n    private _requestHandlers: Map<string, (request: JSONRPCRequest, ctx: ContextT) => Promise<Result>> = new Map();\n    /** Methods registered with an explicit schema; the era gate in `_onrequest` reads it for the Tasks extension names. */\n    private _customSchemaRequestMethods = new Set<string>();\n    private _requestHandlerAbortControllers: Map<RequestId, AbortController> = new Map();\n    private _notificationHandlers: Map<string, (notification: JSONRPCNotification, codec: WireCodec) => Promise<void>> = new Map();\n    private _responseHandlers: Map<number, (response: JSONRPCResultResponse | Error) => void> = new Map();\n    private _progressHandlers: Map<number, ProgressCallback> = new Map();\n    private _timeoutInfo: Map<number, TimeoutInfo> = new Map();\n    private _pendingDebouncedNotifications = new Set<string>();\n\n    /**\n     * The protocol version negotiated for the current connection (`undefined`\n     * before negotiation completes), which determines the wire era this\n     * instance speaks. Set by the SDK's negotiation and initialize paths\n     * (`Client.connect`, `Server._oninitialize`).\n     */\n    protected _negotiatedProtocolVersion?: string;\n\n    static {\n        writeNegotiatedProtocolVersion = (instance, version) => {\n            instance._negotiatedProtocolVersion = version;\n        };\n    }\n\n    protected _supportedProtocolVersions: string[];\n\n    /**\n     * Callback for when the connection is closed for any reason.\n     *\n     * This is invoked when {@linkcode Protocol.close | close()} is called as well.\n     */\n    onclose?: () => void;\n\n    /**\n     * Callback for when an error occurs.\n     *\n     * Note that errors are not necessarily fatal; they are used for reporting any kind of exceptional condition out of band.\n     */\n    onerror?: (error: Error) => void;\n\n    /**\n     * A handler to invoke for any request types that do not have their own handler installed.\n     */\n    fallbackRequestHandler?: (request: JSONRPCRequest, ctx: ContextT) => Promise<Result>;\n\n    /**\n     * A handler to invoke for any notification types that do not have their own handler installed.\n     */\n    fallbackNotificationHandler?: (notification: Notification) => Promise<void>;\n\n    constructor(private _options?: ProtocolOptions) {\n        this._supportedProtocolVersions = _options?.supportedProtocolVersions ?? SUPPORTED_PROTOCOL_VERSIONS;\n\n        this.setNotificationHandler('notifications/cancelled', notification => {\n            this._oncancel(notification);\n        });\n\n        this.setNotificationHandler('notifications/progress', notification => {\n            this._onprogress(notification);\n        });\n\n        this.setRequestHandler(\n            'ping',\n            // Automatic pong by default.\n            _request => ({}) as Result\n        );\n    }\n\n    /**\n     * Builds the context object for request handlers. Subclasses must override\n     * to return the appropriate context type (e.g., ServerContext adds HTTP request info).\n     */\n    protected abstract buildContext(ctx: BaseContext, transportInfo?: MessageExtraInfo): ContextT;\n\n    /**\n     * Drop consult for inbound messages whose transport did not classify them\n     * at the edge — long-lived channels such as stdio, where a role class may\n     * need to decline traffic the negotiated era has no answer for (the\n     * client-side inbound-request drop on modern-era connections: the\n     * 2026-07-28 era has no server→client request channel, and on stdio the\n     * client must never write JSON-RPC responses).\n     *\n     * Consulted ONLY when the transport supplied no\n     * {@linkcode MessageExtraInfo.classification}: edge-classified traffic\n     * never reaches the hook. Returning `'drop'` discards the message without\n     * writing any response (requests are surfaced via `onerror`). The base\n     * implementation returns `undefined`: unclassified traffic keeps today's\n     * dispatch path unchanged. Era selection never happens here — era is\n     * instance state, owned by the serving entry that constructed and\n     * connected the instance.\n     */\n    protected _shouldDropInbound(_message: JSONRPCRequest | JSONRPCNotification): 'drop' | undefined {\n        return undefined;\n    }\n\n    /**\n     * The per-request `_meta` envelope this instance attaches to every outgoing\n     * request and notification, when one applies. The base implementation\n     * returns `undefined` (no envelope — the 2025-era posture, so legacy-era\n     * outbound traffic is byte-identical to a build without this seam).\n     * `Client` overrides it on a connection that negotiated a modern (2026-07-28+)\n     * era to return the reserved protocol-version / client-info /\n     * client-capabilities keys. User-supplied `_meta` keys take precedence over\n     * the auto-attached ones.\n     */\n    protected _outboundMetaEnvelope(): Readonly<Record<string, unknown>> | undefined {\n        return undefined;\n    }\n\n    /**\n     * Attach this instance's outbound `_meta` envelope (when one is configured)\n     * to a request or notification. A no-op when the seam returns `undefined`\n     * — the message returns by reference, so the legacy-era wire stays\n     * byte-identical. User-supplied `_meta` keys are spread last so they win\n     * over the auto-attached envelope keys.\n     */\n    private _envelopeOutbound<T extends JSONRPCRequest | JSONRPCNotification>(message: T): T {\n        const envelope = this._outboundMetaEnvelope();\n        if (envelope === undefined) {\n            return message;\n        }\n        const params = (message.params ?? {}) as { _meta?: Record<string, unknown> };\n        return {\n            ...message,\n            params: { ...params, _meta: { ...envelope, ...params._meta } }\n        };\n    }\n\n    /**\n     * Extension point for non-`complete` decoded results in the response\n     * funnel: a result the wire codec discriminated into a kind other than\n     * `'complete'` or `'invalid'` is handed here for the role class to\n     * resolve. The base default surfaces it as a typed\n     * {@linkcode SdkErrorCode.UnsupportedResultType} error (no retry).\n     *\n     * Intended consumers (named so the seam stays accountable):\n     * - the `Client`'s multi-round-trip auto-fulfilment engine, which fulfils\n     *   `'input_required'` results through the registered\n     *   elicitation/sampling/roots handlers and retries via `flow.retry`;\n     * - a future client-side terminal-result handler for\n     *   `subscriptions/listen`, when the spec defines one.\n     *\n     * `Server` instances never receive `input_required` responses on their\n     * outbound legs and leave the base behavior in place.\n     */\n    protected _resolveNonCompleteResult<T extends StandardSchemaV1>(\n        decoded: ReturnType<WireCodec['decodeResult']> & { kind: 'input_required' },\n        flow: NonCompleteResultFlow<T>\n    ): Promise<unknown> {\n        return Promise.reject(\n            new SdkError(SdkErrorCode.UnsupportedResultType, `Unsupported result type '${decoded.kind}' for ${flow.request.method}`, {\n                resultType: decoded.kind,\n                method: flow.request.method\n            })\n        );\n    }\n\n    /**\n     * Protected accessor for a registered request handler. Used by role\n     * classes that dispatch synthesized requests through the same stored\n     * handler chain (e.g. the `Client` fulfilling an embedded multi-round-trip\n     * input request).\n     */\n    protected _getRequestHandler(method: string): ((request: JSONRPCRequest, ctx: ContextT) => Promise<Result>) | undefined {\n        return this._requestHandlers.get(method);\n    }\n\n    private async _oncancel(notification: CancelledNotification): Promise<void> {\n        // `requestId` is optional on the 2025-era wire schema. Absent is the\n        // only thing that means \"no id\": `0` and `''` are legal request ids.\n        if (notification.params.requestId === undefined) {\n            return;\n        }\n        // Handle request cancellation\n        const controller = this._requestHandlerAbortControllers.get(notification.params.requestId);\n        controller?.abort(notification.params.reason);\n    }\n\n    private _setupTimeout(\n        messageId: number,\n        timeout: number,\n        maxTotalTimeout: number | undefined,\n        onTimeout: () => void,\n        resetTimeoutOnProgress: boolean = false\n    ) {\n        this._timeoutInfo.set(messageId, {\n            timeoutId: setTimeout(onTimeout, timeout),\n            startTime: Date.now(),\n            timeout,\n            maxTotalTimeout,\n            resetTimeoutOnProgress,\n            onTimeout\n        });\n    }\n\n    private _resetTimeout(messageId: number): boolean {\n        const info = this._timeoutInfo.get(messageId);\n        if (!info) return false;\n\n        const totalElapsed = Date.now() - info.startTime;\n        if (info.maxTotalTimeout && totalElapsed >= info.maxTotalTimeout) {\n            this._timeoutInfo.delete(messageId);\n            throw new SdkError(SdkErrorCode.RequestTimeout, 'Maximum total timeout exceeded', {\n                maxTotalTimeout: info.maxTotalTimeout,\n                totalElapsed\n            });\n        }\n\n        clearTimeout(info.timeoutId);\n        info.timeoutId = setTimeout(info.onTimeout, info.timeout);\n        return true;\n    }\n\n    private _cleanupTimeout(messageId: number) {\n        const info = this._timeoutInfo.get(messageId);\n        if (info) {\n            clearTimeout(info.timeoutId);\n            this._timeoutInfo.delete(messageId);\n        }\n    }\n\n    /**\n     * Attaches to the given transport, starts it, and starts listening for messages.\n     *\n     * 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.\n     */\n    async connect(transport: Transport): Promise<void> {\n        this._transport = transport;\n        const _onclose = this.transport?.onclose;\n        this._transport.onclose = () => {\n            try {\n                _onclose?.();\n            } finally {\n                this._onclose();\n            }\n        };\n\n        const _onerror = this.transport?.onerror;\n        this._transport.onerror = (error: Error) => {\n            _onerror?.(error);\n            this._onerror(error);\n        };\n\n        const _onmessage = this._transport?.onmessage;\n        this._transport.onmessage = (message, extra) => {\n            _onmessage?.(message, extra);\n            if (isJSONRPCResultResponse(message) || isJSONRPCErrorResponse(message)) {\n                this._onresponse(message);\n            } else if (isJSONRPCRequest(message)) {\n                this._onrequest(message, extra);\n            } else if (isJSONRPCNotification(message)) {\n                this._onnotification(message, extra);\n            } else {\n                this._onerror(new Error(`Unknown message type: ${JSON.stringify(message)}`));\n            }\n        };\n\n        // Pass supported protocol versions to transport for header validation\n        transport.setSupportedProtocolVersions?.(this._supportedProtocolVersions);\n\n        await this._transport.start();\n    }\n\n    /**\n     * Transport-close hook. Subclass overrides MUST call `super._onclose()`\n     * after their own cleanup — base teardown (response-handler settlement,\n     * timeout clearing, in-flight request abort) does not run otherwise.\n     */\n    protected _onclose(): void {\n        const responseHandlers = this._responseHandlers;\n        this._responseHandlers = new Map();\n        this._progressHandlers.clear();\n        this._pendingDebouncedNotifications.clear();\n\n        for (const info of this._timeoutInfo.values()) {\n            clearTimeout(info.timeoutId);\n        }\n        this._timeoutInfo.clear();\n\n        const requestHandlerAbortControllers = this._requestHandlerAbortControllers;\n        this._requestHandlerAbortControllers = new Map();\n\n        const error = new SdkError(SdkErrorCode.ConnectionClosed, 'Connection closed');\n\n        this._transport = undefined;\n\n        try {\n            this.onclose?.();\n        } finally {\n            for (const handler of responseHandlers.values()) {\n                handler(error);\n            }\n\n            for (const controller of requestHandlerAbortControllers.values()) {\n                controller.abort(error);\n            }\n        }\n    }\n\n    private _onerror(error: Error): void {\n        this.onerror?.(error);\n    }\n\n    /**\n     * Inbound-notification dispatch. Subclass overrides MUST delegate\n     * unmatched traffic to `super._onnotification(rawNotification, extra)` —\n     * an override that consumes only what it owns and falls through to base\n     * dispatch for everything else.\n     */\n    protected _onnotification(rawNotification: JSONRPCNotification, extra?: MessageExtraInfo): void {\n        // Hide wire-only material from notification handlers too — but ONLY\n        // the reserved envelope `_meta` keys (the retry params names are\n        // reserved on requests, not notifications). There is no\n        // per-notification context, so the lifted envelope keys are dropped,\n        // not surfaced; the protocol layer owns them.\n        const { message: notification } = liftWireOnlyMaterial(rawNotification, 'notification');\n\n        // Era is instance state: the negotiated protocol version selects the\n        // codec for everything this connection receives (legacy until\n        // negotiated). Classification is never a per-message era switch — an\n        // edge classification is validated against the instance era below.\n        const codec = this._negotiatedWireCodec();\n\n        // Drop consult (only when the transport did not classify; edge-\n        // classified traffic never reaches the hook): a role class may decline\n        // unclassified inbound traffic the negotiated era has no answer for.\n        if (extra?.classification === undefined && this._shouldDropInbound(rawNotification) === 'drop') {\n            return;\n        }\n\n        // Edge→instance handoff check: a classification that disagrees with\n        // the instance era means the entry routed another era's traffic onto\n        // this instance. That is a routing error — drop the notification and\n        // surface it out of band; never serve it on a guessed era.\n        if (extra?.classification !== undefined) {\n            const classified = classifiedWireEra(extra.classification);\n            if (classified !== codec.era) {\n                this._onerror(\n                    new Error(\n                        `Era mismatch on inbound notification '${notification.method}': classified as ${classified} but this instance serves ${codec.era}`\n                    )\n                );\n                return;\n            }\n        }\n\n        // Era gate — deletions are physical: a spec notification that is not\n        // in this era's registry is dropped even when a handler is\n        // registered (notifications get no error response; silent drop is\n        // the protocol-correct outcome, matching today's unknown-method\n        // posture). Methods outside the spec universe are consumer-owned\n        // extension notifications and stay era-blind.\n        if (isSpecNotificationMethod(notification.method) && !codec.hasNotificationMethod(notification.method)) {\n            return;\n        }\n\n        const handler = this._notificationHandlers.get(notification.method);\n        const fallback = this.fallbackNotificationHandler;\n\n        // Ignore notifications not being subscribed to.\n        if (handler === undefined && fallback === undefined) {\n            return;\n        }\n\n        // Starting with Promise.resolve() puts any synchronous errors into the monad as well.\n        Promise.resolve()\n            .then(() => (handler === undefined ? fallback!(notification) : handler(notification, codec)))\n            .catch(error => this._onerror(new Error(`Uncaught error in notification handler: ${error}`)));\n    }\n\n    private _onrequest(rawRequest: JSONRPCRequest, extra?: MessageExtraInfo): void {\n        // Lift wire-only material before dispatch: handlers (including the\n        // fallback handler and the per-method schema parse) see exactly the\n        // 2025-era shape; the envelope and retry fields surface via ctx.\n        const { message: request, lifted } = liftWireOnlyMaterial(rawRequest, 'request');\n\n        // Era is instance state: the negotiated protocol version selects the\n        // codec for everything this connection receives (legacy until\n        // negotiated). Classification (Q2; produced at the transport/entry\n        // edge — this layer only CONSUMES MessageExtraInfo.classification) is\n        // never a per-message era switch — it is validated against the\n        // instance era below. Hand-wired legacy transports never classify, so\n        // their behavior is untouched.\n        const codec = this._negotiatedWireCodec();\n\n        // Drop consult (only when the transport did not classify; edge-\n        // classified traffic never reaches the hook): a role class may decline\n        // unclassified inbound traffic the negotiated era has no answer for.\n        if (extra?.classification === undefined && this._shouldDropInbound(rawRequest) === 'drop') {\n            this._onerror(new Error(`Dropped inbound request '${rawRequest.method}': not servable on this connection's protocol era`));\n            return;\n        }\n\n        // Capture the current transport at request time to ensure responses go to the correct client\n        const capturedTransport = this._transport;\n\n        const sendErrorResponse = (code: number, message: string, data?: unknown) => {\n            const errorResponse: JSONRPCErrorResponse = {\n                jsonrpc: '2.0',\n                id: request.id,\n                error: { code, message, ...(data !== undefined && { data }) }\n            };\n            capturedTransport?.send(errorResponse).catch(error => this._onerror(new Error(`Failed to send an error response: ${error}`)));\n        };\n\n        // Edge→instance handoff check: a classification that disagrees with\n        // the instance era means the entry routed another era's traffic onto\n        // this instance. That is a routing error: answer with the typed era\n        // error (−32022 Unsupported protocol version) and surface it out of\n        // band — never serve the request on a guessed era.\n        if (extra?.classification !== undefined) {\n            const classified = classifiedWireEra(extra.classification);\n            if (classified !== codec.era) {\n                this._onerror(\n                    new Error(\n                        `Era mismatch on inbound request '${request.method}': classified as ${classified} but this instance serves ${codec.era}`\n                    )\n                );\n                // `requested` echoes the protocol version the classification\n                // actually named when it carried one; the wire-era label is\n                // only the fallback for classifications without an exact\n                // revision.\n                const requested = extra.classification.revision ?? classified;\n                sendErrorResponse(ProtocolErrorCode.UnsupportedProtocolVersion, `Unsupported protocol version: ${requested}`, {\n                    // Per spec, `supported` is the full list of protocol\n                    // versions the receiver supports — not just the version\n                    // this connection is on — so the peer can pick a mutually\n                    // supported version from the error alone. (Revisit when\n                    // instances are bound to the modern era at the entry: a\n                    // bound instance's configured list may not name the\n                    // revision it was bound to.)\n                    supported: this._supportedProtocolVersions,\n                    requested\n                });\n                return;\n            }\n        }\n\n        // Era gate — deletions are physical: a spec method that is not in\n        // this era's registry is −32601 BY ABSENCE, before any handler\n        // lookup, even when a handler is registered (a custom handler cannot\n        // shadow a deleted spec method across eras). Methods outside the\n        // spec universe are consumer-owned extension methods and stay\n        // era-blind.\n        // Exception: the Tasks extension names (SEP-2663), when registered with an explicit schema.\n        if (\n            isSpecRequestMethod(request.method) &&\n            !codec.hasRequestMethod(request.method) &&\n            !(isExtensionReusedRequestMethod(request.method) && this._customSchemaRequestMethods.has(request.method))\n        ) {\n            sendErrorResponse(ProtocolErrorCode.MethodNotFound, 'Method not found');\n            return;\n        }\n\n        const handler = this._requestHandlers.get(request.method) ?? this.fallbackRequestHandler;\n\n        if (handler === undefined) {\n            sendErrorResponse(ProtocolErrorCode.MethodNotFound, 'Method not found');\n            return;\n        }\n\n        // Envelope enforcement: the 2026 era requires the per-request `_meta`\n        // envelope on every request (spec.types.2026-07-28 RequestParams).\n        // The lift extracted it above; the era codec validates requiredness.\n        // Deliberately AFTER the era gate and the handler-existence check:\n        // an unknown method answers −32601 even when the envelope is also\n        // missing — method existence outranks parameter validity. (The\n        // canonical precedence table for the full inbound validation ladder\n        // arrives with the validation-ladder milestone; this site encodes\n        // only the −32601-over-−32602 rule.)\n        const envelopeError = codec.checkInboundEnvelope(lifted);\n        if (envelopeError !== undefined) {\n            sendErrorResponse(ProtocolErrorCode.InvalidParams, envelopeError);\n            return;\n        }\n\n        // Related sends resolve through the SAME instance era as every other\n        // sender (the per-request/instance asymmetry is deliberately gone):\n        // the codec is resolved at send time from the connection state.\n        const sendNotification = (notification: Notification, options?: NotificationOptions) =>\n            this._notificationViaCodec(this._resolveOutboundCodec(notification.method), notification, {\n                ...options,\n                relatedRequestId: request.id\n            });\n        const sendRequest = <U extends StandardSchemaV1>(r: Request, resultSchema: U, options?: RequestOptions) =>\n            this._requestWithSchemaViaCodec(this._resolveOutboundCodec(r.method), r, resultSchema, {\n                ...options,\n                relatedRequestId: request.id\n            });\n\n        const abortController = new AbortController();\n        this._requestHandlerAbortControllers.set(request.id, abortController);\n\n        // Multi-round-trip retry material: only BARE response objects are\n        // surfaced to the handler; entries that look like a wrapped\n        // `{method, result}` shape (or are not objects at all) are dropped\n        // and their keys recorded so the handler can re-issue the input\n        // request instead of hard-failing (D-059 posture).\n        const partitionedInputResponses = lifted.inputResponses === undefined ? undefined : partitionInputResponses(lifted.inputResponses);\n\n        const baseCtx: BaseContext = {\n            sessionId: capturedTransport?.sessionId,\n            mcpReq: {\n                id: request.id,\n                method: request.method,\n                _meta: request.params?._meta,\n                ...(lifted.envelope !== undefined && { envelope: lifted.envelope }),\n                ...(partitionedInputResponses !== undefined && { inputResponses: partitionedInputResponses.accepted }),\n                ...(partitionedInputResponses !== undefined &&\n                    partitionedInputResponses.droppedKeys.length > 0 && {\n                        droppedInputResponseKeys: partitionedInputResponses.droppedKeys\n                    }),\n                // The accessor surfaces the raw lifted value (captured as the\n                // string primitive so the lift record stays collectable); the\n                // server seam swaps in the verify hook's decoded payload\n                // before the handler runs.\n                requestState: lifted.requestState === undefined ? NO_REQUEST_STATE : requestStateAccessor(lifted.requestState),\n                signal: abortController.signal,\n                // BaseContext.mcpReq.send is declared with two overloads (spec-method-keyed and explicit-schema). Arrow\n                // literals can't carry overload signatures, so the inferred single-signature type isn't assignable to\n                // that overloaded property type. The cast is sound: this impl dispatches both overload paths via the\n                // isStandardSchema guard, and sendRequest validates the result against the resolved schema either way.\n                send: ((r: Request, schemaOrOptions?: StandardSchemaV1 | RequestOptions, maybeOptions?: RequestOptions) => {\n                    // Related requests resolve through the instance era at\n                    // send time, exactly like direct sends: era-gate first,\n                    // then method-keyed schema resolution.\n                    const sendCodec = this._resolveOutboundCodec(r.method);\n                    this._assertOutboundRequestInEra(sendCodec, r.method);\n                    if (isStandardSchema(schemaOrOptions)) {\n                        return sendRequest(r, schemaOrOptions, maybeOptions);\n                    }\n                    const validate = codecResultValidator(sendCodec, r.method);\n                    if (validate === undefined) {\n                        throw new TypeError(\n                            `'${r.method}' is not a spec method; pass a result schema as the second argument to ctx.mcpReq.send().`\n                        );\n                    }\n                    return sendRequest(r, validate, schemaOrOptions);\n                }) as BaseContext['mcpReq']['send'],\n                notify: sendNotification\n            },\n            http: extra?.authInfo ? { authInfo: extra.authInfo } : undefined\n        };\n        const ctx = this.buildContext(baseCtx, extra);\n\n        // Starting with Promise.resolve() puts any synchronous errors into the monad as well.\n        Promise.resolve()\n            .then(() => handler(request, ctx))\n            .then(\n                async result => {\n                    if (abortController.signal.aborted) {\n                        // Request was cancelled\n                        return;\n                    }\n\n                    // The outbound stamp seam: the era codec maps the neutral\n                    // handler result to its wire shape. The 2025-era codec is\n                    // the identity (never-stamp); the 2026-era codec stamps\n                    // `resultType` and enforces the deleted-field set. A throw\n                    // here is a NEW failure mode between handler success and\n                    // the transport send (and the seam grows ttlMs/cacheScope\n                    // stamping content in M3.2) — it must answer the peer with\n                    // −32603 rather than stranding the request until timeout.\n                    let encoded: Result;\n                    try {\n                        encoded = codec.encodeResult(request.method, result, this._outboundServerInfo());\n                    } catch (error) {\n                        this._onerror(new Error(`Failed to encode result for ${request.method}: ${error}`));\n                        sendErrorResponse(ProtocolErrorCode.InternalError, 'Internal error');\n                        return;\n                    }\n\n                    const response: JSONRPCResponse = {\n                        result: encoded,\n                        jsonrpc: '2.0',\n                        id: request.id\n                    };\n                    await capturedTransport?.send(response);\n                },\n                async error => {\n                    if (abortController.signal.aborted) {\n                        // Request was cancelled\n                        return;\n                    }\n\n                    // The error half of the encode seam: the era codec selects\n                    // the wire code for a handler-thrown error, so per-era\n                    // wire-code policy lives in the codec rather than in any\n                    // handler. Non-integer codes still fall through to −32603.\n                    const thrownCode = Number.isSafeInteger(error['code']) ? (error['code'] as number) : ProtocolErrorCode.InternalError;\n                    const errorResponse: JSONRPCErrorResponse = {\n                        jsonrpc: '2.0',\n                        id: request.id,\n                        error: {\n                            code: codec.encodeErrorCode(thrownCode),\n                            message: error.message ?? 'Internal error',\n                            ...(error['data'] !== undefined && { data: error['data'] })\n                        }\n                    };\n                    await capturedTransport?.send(errorResponse);\n                }\n            )\n            .catch(error => this._onerror(new Error(`Failed to send response: ${error}`)))\n            .finally(() => {\n                if (this._requestHandlerAbortControllers.get(request.id) === abortController) {\n                    this._requestHandlerAbortControllers.delete(request.id);\n                }\n            });\n    }\n\n    private _onprogress(notification: ProgressNotification): void {\n        const { progressToken, ...params } = notification.params;\n        const messageId = Number(progressToken);\n\n        const handler = this._progressHandlers.get(messageId);\n        if (!handler) {\n            this._onerror(new Error(`Received a progress notification for an unknown token: ${JSON.stringify(notification)}`));\n            return;\n        }\n\n        const responseHandler = this._responseHandlers.get(messageId);\n        const timeoutInfo = this._timeoutInfo.get(messageId);\n\n        if (timeoutInfo && responseHandler && timeoutInfo.resetTimeoutOnProgress) {\n            try {\n                this._resetTimeout(messageId);\n            } catch (error) {\n                // Clean up if maxTotalTimeout was exceeded\n                this._responseHandlers.delete(messageId);\n                this._progressHandlers.delete(messageId);\n                this._cleanupTimeout(messageId);\n                responseHandler(error as Error);\n                return;\n            }\n        }\n\n        handler(params);\n    }\n\n    /**\n     * Inbound-response dispatch. Subclass overrides MUST delegate unmatched\n     * traffic to `super._onresponse(response)` — an override that consumes\n     * only what it owns and falls through to base dispatch for everything\n     * else.\n     */\n    protected _onresponse(response: JSONRPCResponse | JSONRPCErrorResponse): void {\n        const messageId = Number(response.id);\n\n        const handler = this._responseHandlers.get(messageId);\n        if (handler === undefined) {\n            this._onerror(new Error(`Received a response for an unknown message ID: ${JSON.stringify(response)}`));\n            return;\n        }\n\n        this._responseHandlers.delete(messageId);\n        this._cleanupTimeout(messageId);\n        this._progressHandlers.delete(messageId);\n\n        if (isJSONRPCResultResponse(response)) {\n            handler(response);\n        } else {\n            const error = ProtocolError.fromError(response.error.code, response.error.message, response.error.data);\n            handler(error);\n        }\n    }\n\n    get transport(): Transport | undefined {\n        return this._transport;\n    }\n\n    /**\n     * Closes the connection.\n     */\n    async close(): Promise<void> {\n        await this._transport?.close();\n    }\n\n    /**\n     * A method to check if a capability is supported by the remote side, for the given method to be called.\n     *\n     * This should be implemented by subclasses.\n     */\n    protected abstract assertCapabilityForMethod(method: RequestMethod | string): void;\n\n    /**\n     * A method to check if a notification is supported by the local side, for the given method to be sent.\n     *\n     * This should be implemented by subclasses.\n     */\n    protected abstract assertNotificationCapability(method: NotificationMethod | string): void;\n\n    /**\n     * A method to check if a request handler is supported by the local side, for the given method to be handled.\n     *\n     * This should be implemented by subclasses.\n     */\n    protected abstract assertRequestHandlerCapability(method: string): void;\n\n    /**\n     * Sends a request and waits for a response.\n     *\n     * For spec methods the result schema is resolved automatically from the method name\n     * and the return type is method-keyed. For custom (non-spec) methods, pass a\n     * `resultSchema` as the second argument; the response is validated against it and\n     * the return type is inferred from the schema.\n     *\n     * Do not use this method to emit notifications! Use {@linkcode Protocol.notification | notification()} instead.\n     */\n    request<M extends RequestMethod>(\n        request: { method: M; params?: Record<string, unknown> },\n        options?: RequestOptions\n    ): Promise<ResultTypeMap[M]>;\n    request<T extends StandardSchemaV1>(\n        request: Request,\n        resultSchema: T,\n        options?: RequestOptions\n    ): Promise<StandardSchemaV1.InferOutput<T>>;\n    request(request: Request, schemaOrOptions?: StandardSchemaV1 | RequestOptions, maybeOptions?: RequestOptions): Promise<unknown> {\n        const codec = this._resolveOutboundCodec(request.method);\n        if (isStandardSchema(schemaOrOptions)) {\n            // Only the Tasks extension names skip the era gate here; every other spec method stays gated.\n            if (!isExtensionReusedRequestMethod(request.method)) this._assertOutboundRequestInEra(codec, request.method);\n            return this._requestWithSchemaViaCodec(codec, request, schemaOrOptions, maybeOptions);\n        }\n        this._assertOutboundRequestInEra(codec, request.method);\n        const validate = codecResultValidator(codec, request.method);\n        if (validate === undefined) {\n            throw new TypeError(`'${request.method}' is not a spec method; pass a result schema as the second argument to request().`);\n        }\n        return this._requestWithSchemaViaCodec(codec, request, validate, schemaOrOptions);\n    }\n\n    /**\n     * The wire codec for this instance's negotiated era — the phase-2 truth:\n     * everything an established connection sends and receives resolves\n     * through it. Legacy until a version has been negotiated.\n     */\n    private _negotiatedWireCodec(): WireCodec {\n        return codecForVersion(this._negotiatedProtocolVersion);\n    }\n\n    /**\n     * Protected accessor for the instance's negotiated wire codec, for role\n     * classes (Client/Server/McpServer) routing era-dependent behavior\n     * through the codec's function-only surface — `samplingResultVariant`,\n     * `outboundEnvelope`, `projectCallToolResult` — instead of branching on\n     * the protocol version themselves.\n     */\n    protected _wireCodec(): WireCodec {\n        return this._negotiatedWireCodec();\n    }\n\n    /**\n     * Outbound codec resolution: while the negotiated version is still unset\n     * (the negotiation window), lifecycle messages are bootstrap-pinned BY\n     * METHOD — they self-identify their era (`initialize` IS the legacy\n     * handshake, `server/discover` IS the modern probe). Once a version has\n     * been negotiated, the instance era is authoritative for everything — a\n     * negotiated session never re-routes a method onto the other era.\n     */\n    private _resolveOutboundCodec(method: string): WireCodec {\n        if (this._negotiatedProtocolVersion === undefined) {\n            const pinned = bootstrapOutboundCodec(method);\n            if (pinned) return pinned;\n        }\n        return this._negotiatedWireCodec();\n    }\n\n    /**\n     * Era gate for outbound requests — deletions are physical in BOTH\n     * directions: sending a spec method that the resolved era does not define\n     * dies locally with a typed error before anything reaches the transport.\n     * Methods outside the spec universe are consumer-owned extension methods\n     * and stay era-blind.\n     */\n    private _assertOutboundRequestInEra(codec: WireCodec, method: string): void {\n        if (isSpecRequestMethod(method) && !codec.hasRequestMethod(method)) {\n            throw new SdkError(\n                SdkErrorCode.MethodNotSupportedByProtocolVersion,\n                `Method '${method}' is not supported by the negotiated protocol version (wire era ${codec.era})`,\n                { method, era: codec.era }\n            );\n        }\n    }\n\n    /**\n     * Sends a request and waits for a response, using the provided schema for\n     * validation instead of the era registry's method-keyed entry.\n     *\n     * This is the internal implementation used by SDK methods whose result\n     * schema cannot be expressed as a method-keyed registry entry — the one\n     * surviving case is `server.createMessage`, whose result schema depends\n     * on the REQUEST params (tools vs no tools) — and by callers passing\n     * explicit compatibility schemas. Spec methods are still era-gated here:\n     * an explicit schema never smuggles a deleted method onto the wire.\n     */\n    protected _requestWithSchema<T extends StandardSchemaV1>(\n        request: Request,\n        resultSchema: T,\n        options?: RequestOptions\n    ): Promise<StandardSchemaV1.InferOutput<T>> {\n        const codec = this._resolveOutboundCodec(request.method);\n        this._assertOutboundRequestInEra(codec, request.method);\n        return this._requestWithSchemaViaCodec(codec, request, resultSchema, options);\n    }\n\n    /**\n     * The request funnel proper, keyed by the resolved era codec: the codec\n     * owns result decoding (raw-first `resultType` discrimination — V-1 —\n     * and the era's lift posture) before the schema validation step.\n     */\n    private _requestWithSchemaViaCodec<T extends StandardSchemaV1>(\n        codec: WireCodec,\n        request: Request,\n        resultSchema: T,\n        options?: RequestOptions\n    ): Promise<StandardSchemaV1.InferOutput<T>> {\n        const { relatedRequestId, resumptionToken, onresumptiontoken, headers } = options ?? {};\n        // Flow start for non-complete result resolution: `maxTotalTimeout`\n        // bounds the WHOLE flow, so the budget is measured from the original\n        // request, not from when an extension takes over after the first leg.\n        const flowStartedAt = Date.now();\n\n        let onAbort: (() => void) | undefined;\n        let cleanupMessageId: number | undefined;\n\n        // Send the request\n        return new Promise<StandardSchemaV1.InferOutput<T>>((resolve, reject) => {\n            const earlyReject = (error: unknown) => {\n                reject(error);\n            };\n\n            if (!this._transport) {\n                earlyReject(new Error('Not connected'));\n                return;\n            }\n\n            if (this._options?.enforceStrictCapabilities === true) {\n                try {\n                    this.assertCapabilityForMethod(request.method);\n                } catch (error) {\n                    earlyReject(error);\n                    return;\n                }\n            }\n\n            // An already-aborted caller signal must surface the same way an\n            // in-flight abort does (`SdkError(RequestTimeout, reason)` via\n            // `cancel()` below). Bare `throwIfAborted()` would propagate the\n            // raw `signal.reason` instead, so callers that introduce an async\n            // hop before `request()` (e.g. a cache freshness check) would see\n            // a different rejection type depending on where the abort lands.\n            if (options?.signal?.aborted) {\n                const reason = options.signal.reason;\n                throw reason instanceof SdkError ? reason : new SdkError(SdkErrorCode.RequestTimeout, String(reason));\n            }\n\n            // Spec basic/patterns/cancellation §Transport-Specific (2026-07-28):\n            // on Streamable HTTP, closing the per-request SSE stream IS the\n            // cancellation signal — \"no notifications/cancelled message is\n            // required or expected\". When the negotiated era is modern AND the\n            // transport opens a per-request stream (`hasPerRequestStream`),\n            // cancel() aborts that stream via `requestSignal` INSTEAD OF\n            // POSTing `notifications/cancelled`. Every other (era × transport)\n            // combination — legacy era on any transport, modern era on stdio /\n            // in-memory — keeps today's `notifications/cancelled` POST path\n            // unchanged.\n            const streamCloseCancels = codec.era === MODERN_WIRE_REVISION && this._transport.hasPerRequestStream === true;\n            const requestAbort = streamCloseCancels ? new AbortController() : undefined;\n\n            const messageId = this._requestMessageId++;\n            cleanupMessageId = messageId;\n            const jsonrpcRequest: JSONRPCRequest = {\n                ...request,\n                jsonrpc: '2.0',\n                id: messageId\n            };\n\n            if (options?.onprogress) {\n                this._progressHandlers.set(messageId, options.onprogress);\n                jsonrpcRequest.params = {\n                    ...request.params,\n                    _meta: {\n                        ...request.params?._meta,\n                        progressToken: messageId\n                    }\n                };\n            }\n\n            // Per-request envelope auto-attach (after the progressToken merge so\n            // both share the same `_meta`): a no-op on the legacy era — the\n            // envelope seam returns undefined and the request goes out exactly as\n            // built above.\n            const outbound = this._envelopeOutbound(jsonrpcRequest);\n\n            let responseReceived = false;\n\n            const cancel = (reason: unknown) => {\n                if (responseReceived) {\n                    return;\n                }\n                this._progressHandlers.delete(messageId);\n\n                if (requestAbort === undefined) {\n                    // \"A client MUST NOT attempt to cancel its `initialize`\n                    // request\" (spec basic/lifecycle, mirrored on\n                    // `CancelledNotification`). The handshake is the one request\n                    // whose cancellation is forbidden outright, so an abort or\n                    // timeout on it settles purely locally: the promise still\n                    // rejects below, but nothing goes on the wire. Only the\n                    // legacy era can reach this — `initialize` is absent from the\n                    // modern registry, which negotiates via `server/discover`.\n                    if (request.method !== 'initialize') {\n                        this._transport\n                            ?.send(\n                                this._envelopeOutbound({\n                                    jsonrpc: '2.0',\n                                    method: 'notifications/cancelled',\n                                    params: {\n                                        requestId: messageId,\n                                        reason: String(reason)\n                                    }\n                                }),\n                                { relatedRequestId, resumptionToken, onresumptiontoken }\n                            )\n                            .catch(error => this._onerror(new Error(`Failed to send cancellation: ${error}`)));\n                    }\n                } else {\n                    // Modern-era per-request-stream transport: aborting the\n                    // request's underlying stream IS the spec cancel signal.\n                    // The transport already swallows the resulting AbortError\n                    // (no spurious `onerror`); a post-abort send() rejection\n                    // re-hits an already-settled promise below and is a no-op.\n                    requestAbort.abort();\n                }\n\n                // Wrap the reason in an SdkError if it isn't already\n                const error = reason instanceof SdkError ? reason : new SdkError(SdkErrorCode.RequestTimeout, String(reason));\n                reject(error);\n            };\n\n            this._responseHandlers.set(messageId, response => {\n                if (options?.signal?.aborted) {\n                    return;\n                }\n                responseReceived = true;\n\n                if (response instanceof Error) {\n                    return reject(response);\n                }\n\n                // Codec decode hop — the structural V-1 home. The era codec\n                // owns the raw-first resultType postures (Q1-SD3):\n                // - 2026 era: REQUIRED discriminator; absent → typed error\n                //   naming the spec violation; input_required → driver seam;\n                //   unknown kind → invalid, no retry; complete → wire-exact\n                //   parse then lift.\n                // - 2025 era: resultType is foreign vocabulary → strip-on-\n                //   lift, then today's schema validation decides.\n                // Either way a non-complete body can never be masked into a\n                // hollow success by a tolerant result schema.\n                // Guarded: this callback runs synchronously inside\n                // `_onresponse`, so a throw out of the decode hop would\n                // otherwise propagate into the transport's onmessage instead\n                // of failing this request.\n                let decoded: ReturnType<WireCodec['decodeResult']>;\n                try {\n                    decoded = codec.decodeResult(request.method, response.result);\n                } catch (error) {\n                    return reject(error instanceof Error ? error : new Error(String(error)));\n                }\n                if (decoded.kind === 'invalid') {\n                    return reject(decoded.error);\n                }\n                if (decoded.kind === 'input_required') {\n                    // Manual mode (the primitive any driver layers over):\n                    // hand the input-required value back to the caller.\n                    if (options?.allowInputRequired === true) {\n                        return resolve(manualInputRequiredValue(decoded) as StandardSchemaV1.InferOutput<T>);\n                    }\n                    // Non-complete result extension point: the role class may\n                    // resolve the flow itself (the Client wires the\n                    // multi-round-trip auto-fulfilment engine here). The base\n                    // default is the typed UnsupportedResultType error.\n                    const flow: NonCompleteResultFlow<T> = {\n                        codec,\n                        request,\n                        resultSchema,\n                        options,\n                        flowStartedAt,\n                        retry: (params, legOptions) =>\n                            this._requestWithSchemaViaCodec(\n                                codec,\n                                params === undefined ? { method: request.method } : { method: request.method, params },\n                                resultSchema,\n                                legOptions\n                            )\n                    };\n                    return resolve(this._resolveNonCompleteResult(decoded, flow) as Promise<StandardSchemaV1.InferOutput<T>>);\n                }\n                const result = decoded.result;\n\n                validateStandardSchema(resultSchema, result).then(parseResult => {\n                    if (parseResult.success) {\n                        resolve(parseResult.data);\n                    } else {\n                        reject(new SdkError(SdkErrorCode.InvalidResult, `Invalid result for ${request.method}: ${parseResult.error}`));\n                    }\n                }, reject);\n            });\n\n            onAbort = () => cancel(options?.signal?.reason);\n            options?.signal?.addEventListener('abort', onAbort, { once: true });\n\n            const timeout = options?.timeout ?? DEFAULT_REQUEST_TIMEOUT_MSEC;\n            const timeoutHandler = () => cancel(new SdkError(SdkErrorCode.RequestTimeout, 'Request timed out', { timeout }));\n\n            this._setupTimeout(messageId, timeout, options?.maxTotalTimeout, timeoutHandler, options?.resetTimeoutOnProgress ?? false);\n\n            this._transport\n                .send(outbound, { relatedRequestId, resumptionToken, onresumptiontoken, headers, requestSignal: requestAbort?.signal })\n                .catch(error => {\n                    this._progressHandlers.delete(messageId);\n                    reject(error);\n                });\n        }).finally(() => {\n            // Per-request cleanup that must run on every exit path. Consolidated\n            // here so new exit paths added to the promise body can't forget it.\n            // _progressHandlers is NOT cleaned up here: _onresponse deletes it\n            // on resolution, and error paths above delete it inline.\n            if (onAbort) {\n                options?.signal?.removeEventListener('abort', onAbort);\n            }\n            if (cleanupMessageId !== undefined) {\n                this._responseHandlers.delete(cleanupMessageId);\n                this._cleanupTimeout(cleanupMessageId);\n            }\n        });\n    }\n\n    /**\n     * Emits a notification, which is a one-way message that does not expect a response.\n     */\n    async notification(notification: Notification, options?: NotificationOptions): Promise<void> {\n        return await this._notificationViaCodec(this._resolveOutboundCodec(notification.method), notification, options);\n    }\n\n    /**\n     * The notification funnel proper, keyed by the resolved era codec —\n     * direct sends and related notifications (`ctx.mcpReq.notify`) alike\n     * resolve through the instance's negotiated era at send time.\n     */\n    private async _notificationViaCodec(codec: WireCodec, notification: Notification, options?: NotificationOptions): Promise<void> {\n        if (!this._transport) {\n            throw new SdkError(SdkErrorCode.NotConnected, 'Not connected');\n        }\n\n        // Era gate — outbound deletions are physical for notifications too: a\n        // spec notification the resolved era does not define dies locally.\n        if (isSpecNotificationMethod(notification.method) && !codec.hasNotificationMethod(notification.method)) {\n            throw new SdkError(\n                SdkErrorCode.MethodNotSupportedByProtocolVersion,\n                `Notification '${notification.method}' is not supported by the negotiated protocol version (wire era ${codec.era})`,\n                { method: notification.method, era: codec.era }\n            );\n        }\n\n        this.assertNotificationCapability(notification.method);\n\n        const jsonrpcNotification = this._envelopeOutbound({ jsonrpc: '2.0' as const, ...notification });\n\n        const debouncedMethods = this._options?.debouncedNotificationMethods ?? [];\n        // A notification can only be debounced if it's in the list AND it's \"simple\"\n        // (i.e., has no parameters and no related request ID that could be lost).\n        // Absent is the only thing that means \"no id\" here too: `0` and `''` are\n        // legal request ids, and the pending set is keyed by method alone, so\n        // treating them as absent lets a related notification be coalesced away.\n        const canDebounce =\n            debouncedMethods.includes(notification.method) && !notification.params && options?.relatedRequestId === undefined;\n\n        if (canDebounce) {\n            // If a notification of this type is already scheduled, do nothing.\n            if (this._pendingDebouncedNotifications.has(notification.method)) {\n                return;\n            }\n\n            // Mark this notification type as pending.\n            this._pendingDebouncedNotifications.add(notification.method);\n\n            // Schedule the actual send to happen in the next microtask.\n            // This allows all synchronous calls in the current event loop tick to be coalesced.\n            Promise.resolve().then(() => {\n                // Un-mark the notification so the next one can be scheduled.\n                this._pendingDebouncedNotifications.delete(notification.method);\n\n                // SAFETY CHECK: If the connection was closed while this was pending, abort.\n                if (!this._transport) {\n                    return;\n                }\n\n                // Send the notification, but don't await it here to avoid blocking.\n                // Handle potential errors with a .catch().\n                this._transport?.send(jsonrpcNotification, options).catch(error => this._onerror(error));\n            });\n\n            // Return immediately.\n            return;\n        }\n\n        await this._transport.send(jsonrpcNotification, options);\n    }\n\n    /**\n     * Registers a handler to invoke when this protocol object receives a request with the given method.\n     *\n     * Note that this will replace any previous request handler for the same method.\n     *\n     * For spec methods, pass `(method, handler)`; the request is parsed with the spec\n     * schema and the handler receives the typed `Request`. For custom (non-spec)\n     * methods, pass `(method, schemas, handler)`; `params` are validated against\n     * `schemas.params` and the handler receives the parsed params object directly.\n     * Supplying `schemas.result` types the handler's return value.\n     *\n     * @example Custom request method\n     * ```ts source=\"./protocol.examples.ts#Protocol_setRequestHandler_customMethod\"\n     * const SearchParams = z.object({ query: z.string(), limit: z.number().optional() });\n     * const SearchResult = z.object({ hits: z.array(z.string()) });\n     *\n     * protocol.setRequestHandler('acme/search', { params: SearchParams, result: SearchResult }, async (params, _ctx) => {\n     *     return { hits: [`result for ${params.query}`] };\n     * });\n     * ```\n     */\n    setRequestHandler<M extends RequestMethod>(\n        method: M,\n        handler: (request: RequestTypeMap[M], ctx: ContextT) => HandlerResultTypeMap[M] | Promise<HandlerResultTypeMap[M]>\n    ): void;\n    setRequestHandler<P extends StandardSchemaV1, R extends StandardSchemaV1 | undefined = undefined>(\n        method: string,\n        schemas: { params: P; result?: R },\n        handler: (params: StandardSchemaV1.InferOutput<P>, ctx: ContextT) => InferHandlerResult<R> | Promise<InferHandlerResult<R>>\n    ): void;\n    setRequestHandler(\n        method: string,\n        schemasOrHandler: RequestHandlerSchemas | ((request: unknown, ctx: ContextT) => Result | Promise<Result>),\n        maybeHandler?: (params: unknown, ctx: ContextT) => Result | Promise<Result>\n    ): void {\n        this.assertRequestHandlerCapability(method);\n\n        let stored: (request: JSONRPCRequest, ctx: ContextT) => Promise<Result>;\n\n        if (typeof schemasOrHandler === 'function') {\n            if (!isSpecRequestMethod(method)) {\n                throw new TypeError(\n                    `'${method}' is not a spec request method; pass schemas as the second argument to setRequestHandler().`\n                );\n            }\n            // Dispatch-time schema resolution: the request is parsed with the\n            // schema of the era serving this connection (the instance era at\n            // dispatch time), never with a schema captured at registration\n            // time. On the 2026-07-28 era the demoted server→client methods\n            // (elicitation/sampling/roots) are not wire request methods —\n            // they reach a handler only as embedded input requests dispatched\n            // by the multi-round-trip driver, and parse with the era's\n            // in-band schema instead.\n            stored = (request, ctx) => {\n                const dispatchCodec = this._negotiatedWireCodec();\n                let outcome = dispatchCodec.validateRequest(method, request);\n                if (!outcome.ok && outcome.reason === 'not-in-era') {\n                    outcome = dispatchCodec.validateInputRequest(method, request);\n                }\n                if (!outcome.ok) {\n                    if (outcome.reason === 'not-in-era') {\n                        // Unreachable: the dispatch era gate rejects\n                        // era-mismatched spec methods with −32601 before any\n                        // handler runs.\n                        throw new ProtocolError(ProtocolErrorCode.InternalError, `No wire schema for ${method} in the resolved era`);\n                    }\n                    // Preserves the pre-function-only error surface: the Zod\n                    // parse threw out of the handler and the funnel mapped it\n                    // to −32603 Internal error (specCorpusDispatch pins this).\n                    throw new Error(outcome.message);\n                }\n                return Promise.resolve(schemasOrHandler(outcome.value, ctx));\n            };\n        } else if (maybeHandler) {\n            stored = async (request, ctx) => {\n                // Custom handlers receive `_meta` present-minus-reserved: the\n                // wire-only lift already removed the reserved envelope keys,\n                // and the remaining metadata (progressToken, extension keys)\n                // is handler material — consistent with the spec-method path.\n                // (Behavior migration: `_meta` used to be deleted here.)\n                const parsed = await validateStandardSchema(schemasOrHandler.params, { ...request.params });\n                if (!parsed.success) {\n                    throw new ProtocolError(ProtocolErrorCode.InvalidParams, `Invalid params for ${method}: ${parsed.error}`);\n                }\n                return maybeHandler(parsed.data, ctx);\n            };\n        } else {\n            throw new TypeError('setRequestHandler: handler is required');\n        }\n\n        // The era gate reads how the handler was registered; a method-keyed re-registration ends the exemption.\n        if (typeof schemasOrHandler === 'function') {\n            this._customSchemaRequestMethods.delete(method);\n        } else {\n            this._customSchemaRequestMethods.add(method);\n        }\n\n        this._requestHandlers.set(method, this._wrapHandler(method, stored));\n    }\n\n    /**\n     * Hook for subclasses to wrap a registered request handler with role-specific\n     * validation or behavior (e.g. `Server` validates `tools/call` results, `Client`\n     * validates `elicitation/create` mode and result). Runs for both the 2-arg and\n     * 3-arg registration paths. The default implementation is identity.\n     *\n     * Subclasses overriding this hook avoid redeclaring `setRequestHandler`'s overload set.\n     */\n    protected _wrapHandler(\n        _method: string,\n        handler: (request: JSONRPCRequest, ctx: ContextT) => Promise<Result>\n    ): (request: JSONRPCRequest, ctx: ContextT) => Promise<Result> {\n        return handler;\n    }\n\n    /**\n     * Hook for subclasses to supply the implementation identity the 2026-era\n     * encode seam stamps into outbound result `_meta` under\n     * `io.modelcontextprotocol/serverInfo` (spec PR #3002: servers SHOULD\n     * identify themselves on every response). The default is `undefined` — no\n     * stamp. Only `Server` overrides this: the key identifies the software\n     * producing a response, and the 2025-era codec never stamps anything\n     * regardless (the never-stamp guarantee).\n     */\n    protected _outboundServerInfo(): Implementation | undefined {\n        return undefined;\n    }\n\n    /**\n     * Removes the request handler for the given method.\n     */\n    removeRequestHandler(method: RequestMethod | string): void {\n        this._requestHandlers.delete(method);\n        this._customSchemaRequestMethods.delete(method);\n    }\n\n    /**\n     * Asserts that a request handler has not already been set for the given method, in preparation for a new one being automatically installed.\n     */\n    assertCanSetRequestHandler(method: RequestMethod | string): void {\n        if (this._requestHandlers.has(method)) {\n            throw new Error(`A request handler for ${method} already exists, which would be overridden`);\n        }\n    }\n\n    /**\n     * Registers a handler to invoke when this protocol object receives a notification with the given method.\n     *\n     * Note that this will replace any previous notification handler for the same method.\n     *\n     * For spec methods, pass `(method, handler)`; the notification is parsed with the\n     * spec schema. For custom (non-spec) methods, pass `(method, schemas, handler)`;\n     * `params` are validated against `schemas.params` and the handler receives the\n     * parsed params object directly. The raw notification is passed as the second\n     * argument; `_meta` is recoverable via `notification.params?._meta` (minus the\n     * reserved `io.modelcontextprotocol/*` envelope keys, which the protocol layer\n     * lifts out before dispatch).\n     */\n    setNotificationHandler<M extends NotificationMethod>(\n        method: M,\n        handler: (notification: NotificationTypeMap[M]) => void | Promise<void>\n    ): void;\n    setNotificationHandler<P extends StandardSchemaV1>(\n        method: string,\n        schemas: { params: P },\n        handler: (params: StandardSchemaV1.InferOutput<P>, notification: Notification) => void | Promise<void>\n    ): void;\n    setNotificationHandler(\n        method: string,\n        schemasOrHandler: { params: StandardSchemaV1 } | ((notification: unknown) => void | Promise<void>),\n        maybeHandler?: (params: unknown, notification: Notification) => void | Promise<void>\n    ): void {\n        if (typeof schemasOrHandler === 'function') {\n            if (!isSpecNotificationMethod(method)) {\n                throw new TypeError(\n                    `'${method}' is not a spec notification method; pass schemas as the second argument to setNotificationHandler().`\n                );\n            }\n            // Dispatch-time schema resolution, same as setRequestHandler: the\n            // era serving the message picks the schema.\n            this._notificationHandlers.set(method, (notification, codec) => {\n                const outcome = codec.validateNotification(method, notification);\n                if (!outcome.ok) {\n                    if (outcome.reason === 'not-in-era') {\n                        // Unreachable: the dispatch era gate drops\n                        // era-mismatched spec notifications before any\n                        // handler runs.\n                        throw new ProtocolError(ProtocolErrorCode.InternalError, `No wire schema for ${method} in the resolved era`);\n                    }\n                    // Preserves the pre-function-only error surface (parse\n                    // threw out of the handler).\n                    throw new Error(outcome.message);\n                }\n                return Promise.resolve(schemasOrHandler(outcome.value));\n            });\n            return;\n        }\n\n        if (!maybeHandler) {\n            throw new TypeError('setNotificationHandler: handler is required');\n        }\n        this._notificationHandlers.set(method, async notification => {\n            // `_meta` present-minus-reserved, matching the custom request\n            // path (the lift already removed the reserved envelope keys).\n            const parsed = await validateStandardSchema(schemasOrHandler.params, { ...notification.params });\n            if (!parsed.success) {\n                throw new ProtocolError(ProtocolErrorCode.InvalidParams, `Invalid params for notification ${method}: ${parsed.error}`);\n            }\n            await maybeHandler(parsed.data, notification);\n        });\n    }\n\n    /**\n     * Removes the notification handler for the given method.\n     */\n    removeNotificationHandler(method: NotificationMethod | string): void {\n        this._notificationHandlers.delete(method);\n    }\n}\n\n/**\n * Schema bundle accepted by {@linkcode Protocol.setRequestHandler | setRequestHandler}'s 3-arg form.\n *\n * `params` is required and validates the inbound `request.params`. `result` is optional;\n * when supplied it types the handler's return value (no runtime validation is performed\n * on the result).\n */\nexport interface RequestHandlerSchemas<\n    P extends StandardSchemaV1 = StandardSchemaV1,\n    R extends StandardSchemaV1 | undefined = StandardSchemaV1 | undefined\n> {\n    params: P;\n    result?: R;\n}\n\ntype InferHandlerResult<R extends StandardSchemaV1 | undefined> = R extends StandardSchemaV1 ? StandardSchemaV1.InferOutput<R> : Result;\n\nfunction isPlainObject(value: unknown): value is Record<string, unknown> {\n    return value !== null && typeof value === 'object' && !Array.isArray(value);\n}\n\nexport function mergeCapabilities(base: ServerCapabilities, additional: Partial<ServerCapabilities>): ServerCapabilities;\nexport function mergeCapabilities(base: ClientCapabilities, additional: Partial<ClientCapabilities>): ClientCapabilities;\nexport function mergeCapabilities<T extends ServerCapabilities | ClientCapabilities>(base: T, additional: Partial<T>): T {\n    const result: T = { ...base };\n    for (const key in additional) {\n        const k = key as keyof T;\n        const addValue = additional[k];\n        if (addValue === undefined) continue;\n        const baseValue = result[k];\n        result[k] =\n            isPlainObject(baseValue) && isPlainObject(addValue)\n                ? ({ ...(baseValue as Record<string, unknown>), ...(addValue as Record<string, unknown>) } as T[typeof k])\n                : (addValue as T[typeof k]);\n    }\n    return result;\n}\n","/**\n * The multi-round-trip auto-fulfilment ENGINE (protocol revision 2026-07-28):\n * the wiring between the protocol layer's response funnel, the\n * already-registered input handlers, and the pure {@link runInputRequiredDriver}\n * loop. The engine is what the `Client` plugs into the funnel's\n * `_resolveNonCompleteResult` extension point — `Protocol` itself only knows\n * the input-required branch exists.\n *\n * Relocated here so the shared `Protocol` base stays generic: the only\n * MRTR-specific code that remains in `protocol.ts` is the irreducible\n * input-required branch in the response path, the type surface (the\n * `allowInputRequired` request option and the `inputResponses`/`requestState`/\n * `droppedInputResponseKeys` context fields), and the named extension point.\n */\nimport { SdkError, SdkErrorCode } from '../errors/sdkErrors';\nimport type { InputRequiredResult, JSONRPCRequest, RequestMeta, Result, ResultMetaObject } from '../types/types';\nimport type { StandardSchemaV1 } from '../util/standardSchema';\nimport type { WireCodec } from '../wire/codec';\nimport type {\n    InputRequiredDriverHooks,\n    InputRequiredPayload,\n    InputRequiredRetryLegOptions,\n    ResolvedInputRequiredDriverConfig\n} from './inputRequiredDriver';\nimport { runInputRequiredDriver } from './inputRequiredDriver';\nimport type { BaseContext, NonCompleteResultFlow, RequestOptions } from './protocol';\nimport { requestStateAccessor } from './protocol';\n\nfunction isPlainObject(value: unknown): value is Record<string, unknown> {\n    return typeof value === 'object' && value !== null && !Array.isArray(value);\n}\n\n/**\n * Splits a retried request's `inputResponses` map into the BARE response\n * entries the spec defines and everything else. The spec's embedded responses\n * are the bare result objects (an `ElicitResult`, `CreateMessageResult`, or\n * `ListRootsResult`); a wrapped `{method, result}` envelope (a shape some\n * peers emit) is never accepted as a response — its key is recorded so the\n * handler can re-issue the corresponding input request.\n */\nexport function partitionInputResponses(inputResponses: unknown): { accepted: Record<string, unknown>; droppedKeys: string[] } {\n    const accepted: Record<string, unknown> = {};\n    const droppedKeys: string[] = [];\n    if (!isPlainObject(inputResponses)) {\n        return { accepted, droppedKeys };\n    }\n    for (const [key, entry] of Object.entries(inputResponses)) {\n        // Bare responses never carry `method` or `result` members — both are\n        // the signature of the wrapped (JSON-RPC-shaped) form.\n        if (!isPlainObject(entry) || 'method' in entry || 'result' in entry) {\n            droppedKeys.push(key);\n            continue;\n        }\n        accepted[key] = entry;\n    }\n    return { accepted, droppedKeys };\n}\n\n/**\n * Related send/notify are unavailable inside an embedded input-request\n * handler: the request is fulfilled locally by the multi-round-trip driver,\n * so there is no live peer request to relate messages to.\n */\nfunction relatedMessagingUnavailable(member: string): never {\n    throw new SdkError(\n        SdkErrorCode.SendFailed,\n        `ctx.mcpReq.${member} is not available while fulfilling an embedded input request: ` +\n            `the request is fulfilled locally and has no related peer request`\n    );\n}\n\n/**\n * The synthesized {@linkcode BaseContext} for an embedded input request: the\n * id is the `inputRequests` key (correlation only — it is not a JSON-RPC\n * message id), the supplied abort signal chains the originating call's signal\n * through, and related `send`/`notify` are unavailable because there is no\n * live peer request to relate them to.\n */\nexport function synthesizeInputRequestContext(\n    key: string,\n    method: string,\n    params: Record<string, unknown> | undefined,\n    signal: AbortSignal,\n    sessionId: string | undefined\n): BaseContext {\n    return {\n        sessionId,\n        mcpReq: {\n            id: key,\n            method,\n            _meta: params?.['_meta'] as RequestMeta | undefined,\n            // Embedded input requests never carry multi-round-trip state.\n            requestState: requestStateAccessor(undefined),\n            signal,\n            send: (() => relatedMessagingUnavailable('send')) as BaseContext['mcpReq']['send'],\n            notify: () => relatedMessagingUnavailable('notify')\n        }\n    };\n}\n\n/**\n * Hooks the engine needs from the consuming role class (the `Client`): how to\n * look up a registered handler and how to enrich a base context.\n */\nexport interface InputRequiredEngineHost {\n    /** The handler registered for the given method, or `undefined`. */\n    getRequestHandler(method: string): ((request: JSONRPCRequest, ctx: unknown) => Promise<Result>) | undefined;\n    /** Builds the role-specific context from a {@linkcode BaseContext}. */\n    buildContext(baseCtx: BaseContext): unknown;\n    /** The transport's session identifier, when there is one. */\n    sessionId: string | undefined;\n}\n\n/**\n * Dispatches one embedded (de-JSON-RPC'd) input request to the locally\n * registered handler for its method and resolves with the bare response.\n *\n * The handler runs through the same stored handler chain as a wire request\n * (including role-specific validation installed by `_wrapHandler`), with a\n * synthesized context (see {@link synthesizeInputRequestContext}).\n */\nexport async function dispatchInputRequest(\n    host: InputRequiredEngineHost,\n    codec: WireCodec,\n    key: string,\n    entry: unknown,\n    signal: AbortSignal\n): Promise<unknown> {\n    if (!isPlainObject(entry) || typeof entry['method'] !== 'string') {\n        throw new SdkError(\n            SdkErrorCode.InvalidResult,\n            `Invalid input request '${key}': each inputRequests entry must be an embedded request object with a method`,\n            { key }\n        );\n    }\n    const method = entry['method'];\n    if (!codec.hasInputRequestMethod(method)) {\n        throw new SdkError(\n            SdkErrorCode.InvalidResult,\n            `Invalid input request '${key}': '${method}' is not an embedded request the ${codec.era} revision defines ` +\n                `(expected elicitation/create, sampling/createMessage, or roots/list)`,\n            { key, method }\n        );\n    }\n    const handler = host.getRequestHandler(method);\n    if (handler === undefined) {\n        throw new SdkError(\n            SdkErrorCode.CapabilityNotSupported,\n            `Cannot fulfil input request '${key}': no handler is registered for '${method}' on this client. ` +\n                `Declare the corresponding capability and register a handler, or handle input_required results manually.`,\n            { key, method }\n        );\n    }\n\n    const params = isPlainObject(entry['params']) ? (entry['params'] as Record<string, unknown>) : undefined;\n    const synthesizedRequest: JSONRPCRequest = {\n        jsonrpc: '2.0',\n        id: key,\n        method,\n        ...(params !== undefined && { params })\n    };\n    const ctx = host.buildContext(synthesizeInputRequestContext(key, method, params, signal, host.sessionId));\n    return await handler(synthesizedRequest, ctx);\n}\n\n/**\n * Builds the per-retry-leg {@linkcode RequestOptions} from the originating\n * call's options.\n *\n * Only the fields that are correct to apply to every leg carry over (a\n * deliberate whitelist): the per-leg `timeout`, the (shrinking) total budget\n * `maxTotalTimeout`, the caller's `onprogress`/`resetTimeoutOnProgress`, and\n * the caller's abort `signal`. Everything else — in particular\n * `relatedRequestId`, `resumptionToken`, and `onresumptiontoken` — is scoped\n * to the originating wire leg and is NOT inherited by retries.\n */\nexport function buildRetryLegRequestOptions(options: RequestOptions | undefined, legOptions: InputRequiredRetryLegOptions): RequestOptions {\n    return {\n        ...(options?.signal !== undefined && { signal: options.signal }),\n        ...(options?.onprogress !== undefined && { onprogress: options.onprogress }),\n        ...(options?.resetTimeoutOnProgress !== undefined && { resetTimeoutOnProgress: options.resetTimeoutOnProgress }),\n        // Per-request HTTP headers (SEP-2243 `Mcp-Param-*`) carry over: the\n        // retry's `arguments` are byte-identical to the originating leg (the\n        // driver only adds `inputResponses`/`requestState`), so the param\n        // headers built for the first leg remain correct for every retry leg.\n        ...(options?.headers !== undefined && { headers: options.headers }),\n        ...(legOptions.timeout !== undefined && { timeout: legOptions.timeout }),\n        ...(legOptions.maxTotalTimeout !== undefined && { maxTotalTimeout: legOptions.maxTotalTimeout }),\n        // The driver re-enters the funnel with the manual primitive: a further\n        // input_required answer is handed back to the loop instead of\n        // recursing into another driver run (the round cap is global to the\n        // flow).\n        allowInputRequired: true\n    };\n}\n\n/**\n * Runs the auto-fulfilment flow for one originating request whose response\n * came back as `input_required`: builds the driver hooks (embedded-request\n * dispatch + retry through the funnel) and hands them to\n * {@link runInputRequiredDriver}. Resolves with the final complete result\n * (already validated by the retry leg) or rejects with a typed error.\n */\nexport function runInputRequiredFlow<T extends StandardSchemaV1>(\n    host: InputRequiredEngineHost,\n    config: ResolvedInputRequiredDriverConfig,\n    decoded: { inputRequests: Record<string, unknown>; requestState?: string },\n    flow: NonCompleteResultFlow<T>\n): Promise<unknown> {\n    const { codec, request, options, flowStartedAt } = flow;\n    const firstPayload: InputRequiredPayload = {\n        inputRequests: decoded.inputRequests,\n        ...(decoded.requestState !== undefined && { requestState: decoded.requestState })\n    };\n    const hooks: InputRequiredDriverHooks = {\n        dispatchInputRequest: (key, entry, signal) => dispatchInputRequest(host, codec, key, entry, signal),\n        retry: (params, legOptions) => flow.retry(params, buildRetryLegRequestOptions(options, legOptions))\n    };\n    return runInputRequiredDriver({\n        config,\n        method: request.method,\n        originalParams: request.params,\n        firstPayload,\n        flowStartedAt,\n        signal: options?.signal,\n        requestOptions: {\n            ...(options?.timeout !== undefined && { timeout: options.timeout }),\n            ...(options?.maxTotalTimeout !== undefined && { maxTotalTimeout: options.maxTotalTimeout }),\n            ...(options?.onprogress !== undefined && { onprogress: options.onprogress })\n        },\n        hooks\n    });\n}\n\n/**\n * Builds the manual-mode {@linkcode InputRequiredResult} value from the\n * codec's decoded payload — what an `allowInputRequired: true` caller\n * receives instead of the auto-fulfilled complete result.\n */\nexport function manualInputRequiredValue(decoded: {\n    inputRequests: Record<string, unknown>;\n    requestState?: string;\n    _meta?: ResultMetaObject;\n}): InputRequiredResult {\n    return {\n        resultType: 'input_required',\n        inputRequests: decoded.inputRequests as InputRequiredResult['inputRequests'],\n        ...(decoded.requestState !== undefined && { requestState: decoded.requestState }),\n        ...(decoded._meta !== undefined && { _meta: decoded._meta })\n    };\n}\n","/*!\n * content-type\n * Copyright(c) 2015 Douglas Christopher Wilson\n * MIT Licensed\n */\n\n'use strict'\n\n/**\n * RegExp to match *( \";\" parameter ) in RFC 7231 sec 3.1.1.1\n *\n * parameter     = token \"=\" ( token / quoted-string )\n * token         = 1*tchar\n * tchar         = \"!\" / \"#\" / \"$\" / \"%\" / \"&\" / \"'\" / \"*\"\n *               / \"+\" / \"-\" / \".\" / \"^\" / \"_\" / \"`\" / \"|\" / \"~\"\n *               / DIGIT / ALPHA\n *               ; any VCHAR, except delimiters\n * quoted-string = DQUOTE *( qdtext / quoted-pair ) DQUOTE\n * qdtext        = HTAB / SP / %x21 / %x23-5B / %x5D-7E / obs-text\n * obs-text      = %x80-FF\n * quoted-pair   = \"\\\" ( HTAB / SP / VCHAR / obs-text )\n */\nvar PARAM_REGEXP = /; *([!#$%&'*+.^_`|~0-9A-Za-z-]+) *= *(\"(?:[\\u000b\\u0020\\u0021\\u0023-\\u005b\\u005d-\\u007e\\u0080-\\u00ff]|\\\\[\\u000b\\u0020-\\u00ff])*\"|[!#$%&'*+.^_`|~0-9A-Za-z-]+) */g // eslint-disable-line no-control-regex\nvar TEXT_REGEXP = /^[\\u000b\\u0020-\\u007e\\u0080-\\u00ff]+$/ // eslint-disable-line no-control-regex\nvar TOKEN_REGEXP = /^[!#$%&'*+.^_`|~0-9A-Za-z-]+$/\n\n/**\n * RegExp to match quoted-pair in RFC 7230 sec 3.2.6\n *\n * quoted-pair = \"\\\" ( HTAB / SP / VCHAR / obs-text )\n * obs-text    = %x80-FF\n */\nvar QESC_REGEXP = /\\\\([\\u000b\\u0020-\\u00ff])/g // eslint-disable-line no-control-regex\n\n/**\n * RegExp to match chars that must be quoted-pair in RFC 7230 sec 3.2.6\n */\nvar QUOTE_REGEXP = /([\\\\\"])/g\n\n/**\n * RegExp to match type in RFC 7231 sec 3.1.1.1\n *\n * media-type = type \"/\" subtype\n * type       = token\n * subtype    = token\n */\nvar TYPE_REGEXP = /^[!#$%&'*+.^_`|~0-9A-Za-z-]+\\/[!#$%&'*+.^_`|~0-9A-Za-z-]+$/\n\n/**\n * Module exports.\n * @public\n */\n\nexports.format = format\nexports.parse = parse\n\n/**\n * Format object to media type.\n *\n * @param {object} obj\n * @return {string}\n * @public\n */\n\nfunction format (obj) {\n  if (!obj || typeof obj !== 'object') {\n    throw new TypeError('argument obj is required')\n  }\n\n  var parameters = obj.parameters\n  var type = obj.type\n\n  if (!type || !TYPE_REGEXP.test(type)) {\n    throw new TypeError('invalid type')\n  }\n\n  var string = type\n\n  // append parameters\n  if (parameters && typeof parameters === 'object') {\n    var param\n    var params = Object.keys(parameters).sort()\n\n    for (var i = 0; i < params.length; i++) {\n      param = params[i]\n\n      if (!TOKEN_REGEXP.test(param)) {\n        throw new TypeError('invalid parameter name')\n      }\n\n      string += '; ' + param + '=' + qstring(parameters[param])\n    }\n  }\n\n  return string\n}\n\n/**\n * Parse media type to object.\n *\n * @param {string|object} string\n * @return {Object}\n * @public\n */\n\nfunction parse (string) {\n  if (!string) {\n    throw new TypeError('argument string is required')\n  }\n\n  // support req/res-like objects as argument\n  var header = typeof string === 'object'\n    ? getcontenttype(string)\n    : string\n\n  if (typeof header !== 'string') {\n    throw new TypeError('argument string is required to be a string')\n  }\n\n  var index = header.indexOf(';')\n  var type = index !== -1\n    ? header.slice(0, index).trim()\n    : header.trim()\n\n  if (!TYPE_REGEXP.test(type)) {\n    throw new TypeError('invalid media type')\n  }\n\n  var obj = new ContentType(type.toLowerCase())\n\n  // parse parameters\n  if (index !== -1) {\n    var key\n    var match\n    var value\n\n    PARAM_REGEXP.lastIndex = index\n\n    while ((match = PARAM_REGEXP.exec(header))) {\n      if (match.index !== index) {\n        throw new TypeError('invalid parameter format')\n      }\n\n      index += match[0].length\n      key = match[1].toLowerCase()\n      value = match[2]\n\n      if (value.charCodeAt(0) === 0x22 /* \" */) {\n        // remove quotes\n        value = value.slice(1, -1)\n\n        // remove escapes\n        if (value.indexOf('\\\\') !== -1) {\n          value = value.replace(QESC_REGEXP, '$1')\n        }\n      }\n\n      obj.parameters[key] = value\n    }\n\n    if (index !== header.length) {\n      throw new TypeError('invalid parameter format')\n    }\n  }\n\n  return obj\n}\n\n/**\n * Get content-type from req/res objects.\n *\n * @param {object}\n * @return {Object}\n * @private\n */\n\nfunction getcontenttype (obj) {\n  var header\n\n  if (typeof obj.getHeader === 'function') {\n    // res-like\n    header = obj.getHeader('content-type')\n  } else if (typeof obj.headers === 'object') {\n    // req-like\n    header = obj.headers && obj.headers['content-type']\n  }\n\n  if (typeof header !== 'string') {\n    throw new TypeError('content-type header is missing from object')\n  }\n\n  return header\n}\n\n/**\n * Quote a string if necessary.\n *\n * @param {string} val\n * @return {string}\n * @private\n */\n\nfunction qstring (val) {\n  var str = String(val)\n\n  // no need to quote tokens\n  if (TOKEN_REGEXP.test(str)) {\n    return str\n  }\n\n  if (str.length > 0 && !TEXT_REGEXP.test(str)) {\n    throw new TypeError('invalid parameter value')\n  }\n\n  return '\"' + str.replace(QUOTE_REGEXP, '\\\\$1') + '\"'\n}\n\n/**\n * Class to represent a content type.\n * @private\n */\nfunction ContentType (type) {\n  this.parameters = Object.create(null)\n  this.type = type\n}\n","import contentType from 'content-type';\n\n/**\n * Extracts the media type (the lowercased `type/subtype` pair, without\n * parameters) from a raw `Content-Type` header value, or `undefined` when the\n * header is missing or empty.\n *\n * Content-Type comparisons must use the parsed media type, never a substring\n * search of the raw header: a value like `text/plain; a=application/json`\n * contains the substring `application/json` but its media type is\n * `text/plain`, and case variants or parameters make naive string comparison\n * wrong in both directions.\n *\n * \"Essence\" is the WHATWG MIME Sniffing standard's term for the bare\n * `type/subtype` pair (https://mimesniff.spec.whatwg.org/#mime-type-essence);\n * the Fetch standard's request classification is defined against it\n * (https://fetch.spec.whatwg.org/#cors-safelisted-request-header).\n *\n * Parsing is RFC 9110 (`content-type` package) first. When the parameter\n * section is malformed (`application/json;`, `application/json; charset=`),\n * browsers and most HTTP stacks still derive the media type from the segment\n * before the first `;` — the fallback matches that widely-implemented\n * behavior, so a header whose media type is unambiguous is not rejected for\n * a sloppy parameter section.\n */\nexport function mediaTypeEssence(header: string | null | undefined): string | undefined {\n    if (!header) {\n        return undefined;\n    }\n    try {\n        return contentType.parse(header).type;\n    } catch {\n        const essence = (header.split(';', 1)[0] ?? '').trim().toLowerCase();\n        // A comma in the parameter tail of an unparseable value indicates\n        // joined duplicate headers — ambiguous, so no essence at all (keeps\n        // duplicate-header handling uniform whether or not the first copy\n        // carries parameters).\n        if (essence === '' || header.slice(essence.length).includes(',')) {\n            return undefined;\n        }\n        return essence;\n    }\n}\n\n/**\n * Whether a raw `Content-Type` header value denotes `application/json`.\n * Parameters (for example `charset=utf-8`) are allowed and ignored; malformed\n * parameter sections do not reject a header whose media type is unambiguously\n * `application/json` (see `mediaTypeEssence` for the exact grammar).\n */\nexport function isJsonContentType(header: string | null | undefined): boolean {\n    // Fast path: the exact literal is what SDK clients send on every POST.\n    if (header === 'application/json') {\n        return true;\n    }\n    return mediaTypeEssence(header) === 'application/json';\n}\n","import type { BaseMetadata } from '../types/index';\n\n/**\n * Utilities for working with {@linkcode BaseMetadata} objects.\n */\n\n/**\n * Gets the display name for an object with {@linkcode BaseMetadata}.\n * For tools, the precedence is: `title` → {@linkcode index.ToolAnnotations | annotations}.`title` → `name`\n * For other objects: `title` → `name`\n * This implements the spec requirement: \"if no title is provided, name should be used for display purposes\"\n */\nexport function getDisplayName(metadata: BaseMetadata | (BaseMetadata & { annotations?: { title?: string } })): string {\n    // First check for title (not undefined and not empty string)\n    if (metadata.title !== undefined && metadata.title !== '') {\n        return metadata.title;\n    }\n\n    // Then check for annotations.title (only present in Tool objects)\n    if ('annotations' in metadata && metadata.annotations?.title) {\n        return metadata.annotations.title;\n    }\n\n    // Finally fall back to name\n    return metadata.name;\n}\n","import type { JSONRPCMessage } from '../types/index';\nimport { JSONRPCMessageSchema } from '../types/index';\n\nexport const STDIO_DEFAULT_MAX_BUFFER_SIZE = 10 * 1024 * 1024;\n\n/**\n * Buffers a continuous stdio stream into discrete JSON-RPC messages.\n */\nexport class ReadBuffer {\n    private _buffer?: Buffer;\n    private _maxBufferSize: number;\n\n    constructor(options?: { maxBufferSize?: number }) {\n        this._maxBufferSize = options?.maxBufferSize ?? STDIO_DEFAULT_MAX_BUFFER_SIZE;\n    }\n\n    append(chunk: Buffer): void {\n        const newSize = (this._buffer?.length ?? 0) + chunk.length;\n        if (newSize > this._maxBufferSize) {\n            this.clear();\n            throw new Error(`ReadBuffer exceeded maximum size of ${this._maxBufferSize} bytes`);\n        }\n        this._buffer = this._buffer ? Buffer.concat([this._buffer, chunk]) : chunk;\n    }\n\n    readMessage(): JSONRPCMessage | null {\n        while (this._buffer) {\n            const index = this._buffer.indexOf('\\n');\n            if (index === -1) {\n                return null;\n            }\n\n            const line = this._buffer.toString('utf8', 0, index).replace(/\\r$/, '');\n            this._buffer = this._buffer.subarray(index + 1);\n\n            try {\n                return deserializeMessage(line);\n            } catch (error) {\n                // Skip non-JSON lines (e.g., debug output from hot-reload tools like\n                // tsx or nodemon that write to stdout). Schema validation errors still\n                // throw so malformed-but-valid-JSON messages surface via onerror.\n                if (error instanceof SyntaxError) {\n                    continue;\n                }\n                throw error;\n            }\n        }\n        return null;\n    }\n\n    clear(): void {\n        this._buffer = undefined;\n    }\n}\n\nexport function deserializeMessage(line: string): JSONRPCMessage {\n    return JSONRPCMessageSchema.parse(JSON.parse(line));\n}\n\nexport function serializeMessage(message: JSONRPCMessage): string {\n    return JSON.stringify(message) + '\\n';\n}\n","import type { JSONRPCMessage, MessageExtraInfo, RequestId } from '../types/index';\n\nexport type FetchLike = (url: string | URL, init?: RequestInit) => Promise<Response>;\n\n/**\n * Normalizes `HeadersInit` to a plain `Record<string, string>` for manipulation.\n * Handles `Headers` objects, arrays of tuples, and plain objects.\n */\nexport function normalizeHeaders(headers: RequestInit['headers'] | undefined): Record<string, string> {\n    if (!headers) return {};\n\n    if (headers instanceof Headers) {\n        return Object.fromEntries(headers.entries());\n    }\n\n    if (Array.isArray(headers)) {\n        return Object.fromEntries(headers);\n    }\n\n    return { ...(headers as Record<string, string>) };\n}\n\n/**\n * Creates a fetch function that includes base `RequestInit` options.\n * This ensures requests inherit settings like credentials, mode, headers, etc. from the base init.\n *\n * @param baseFetch - The base fetch function to wrap (defaults to global `fetch`)\n * @param baseInit - The base `RequestInit` to merge with each request\n * @returns A wrapped fetch function that merges base options with call-specific options\n */\nexport function createFetchWithInit(baseFetch: FetchLike = fetch, baseInit?: RequestInit): FetchLike {\n    if (!baseInit) {\n        return baseFetch;\n    }\n\n    // Return a wrapped fetch that merges base RequestInit with call-specific init\n    return async (url: string | URL, init?: RequestInit): Promise<Response> => {\n        const mergedInit: RequestInit = {\n            ...baseInit,\n            ...init,\n            // Headers need special handling - merge instead of replace\n            headers: init?.headers ? { ...normalizeHeaders(baseInit.headers), ...normalizeHeaders(init.headers) } : baseInit.headers\n        };\n        return baseFetch(url, mergedInit);\n    };\n}\n\nconst REDIRECT_STATUSES = new Set([301, 302, 303, 307, 308]);\nconst MAX_REDIRECTS = 5;\n\n/** Whether `to` has the scheme, host and port of `from`, or is its https form with both on the default port. */\nexport function isWithinOrigin(from: URL, to: URL): boolean {\n    if (from.protocol === to.protocol && from.host === to.host) return true;\n    return from.protocol === 'http:' && to.protocol === 'https:' && from.hostname === to.hostname && !from.port && !to.port;\n}\n\n/** The URL that a redirect `response` to a request for `url` points at, if it names one. */\nfunction redirectTarget(url: string | URL, response: Response): URL | undefined {\n    const location = REDIRECT_STATUSES.has(response.status) ? response.headers?.get('location') : undefined;\n    if (!location) return undefined;\n    try {\n        return new URL(location, url);\n    } catch {\n        return undefined;\n    }\n}\n\nconst leftToFetch = new WeakSet<FetchLike>();\n\n/** A copy of `baseFetch` that `fetchWithinOrigin` returns as it is, which leaves redirects to `baseFetch`. */\nexport function fetchLeavingRedirects(baseFetch: FetchLike): FetchLike {\n    const copy: FetchLike = (url, init) => baseFetch(url, init);\n    leftToFetch.add(copy);\n    return copy;\n}\n\n/** Wraps `baseFetch` to follow a redirect only when it keeps the method and stays within the origin of the request. */\nexport function fetchWithinOrigin(baseFetch: FetchLike): FetchLike {\n    if (leftToFetch.has(baseFetch)) return baseFetch;\n    return async (url, init) => {\n        // A request that sets `redirect` to 'error' or 'manual' is handed to the base fetch as it is.\n        if (init?.redirect === 'error' || init?.redirect === 'manual') return baseFetch(url, init);\n        const method = (init?.method ?? 'GET').toUpperCase();\n        let current = url;\n        for (let followed = 0; ; followed++) {\n            // Browsers answer a manual redirect with an opaque response (status 0, no Location); it is returned as it is.\n            const response = await baseFetch(current, { ...init, redirect: 'manual' });\n            const target = redirectTarget(current, response);\n            if (!target || followed === MAX_REDIRECTS) return response;\n            const from = new URL(current);\n            const keepsMethod = method === 'GET' || response.status === 307 || response.status === 308;\n            const keepsUserinfo =\n                !(target.username || target.password) || (target.username === from.username && target.password === from.password);\n            if (!keepsMethod || !keepsUserinfo || !isWithinOrigin(from, target)) return response;\n            await response.text?.().catch(() => {});\n            current = target;\n        }\n    };\n}\n\n/** Error text for a redirect `response` to a request for `url` that was not followed, or `undefined` for any other response. */\nexport function unfollowedRedirect(url: string | URL, response: Response): string | undefined {\n    if (response.type === 'opaqueredirect') return 'Redirect not followed: this runtime does not expose where it points';\n    const target = redirectTarget(response.url || url, response);\n    if (!target) return undefined;\n    target.username = target.password = target.search = target.hash = '';\n    if (target.protocol === 'http:' && new URL(response.url || url).protocol === 'https:') {\n        target.protocol = 'https:';\n        return `Redirect from https to plain http not followed; try ${target.href} as the endpoint`;\n    }\n    return `Redirect to ${target.href} not followed; use that URL as the endpoint if it is the intended server`;\n}\n\n/**\n * Options for sending a JSON-RPC message.\n */\nexport type TransportSendOptions = {\n    /**\n     * If present, `relatedRequestId` is used to indicate to the transport which incoming request to associate this outgoing message with.\n     */\n    relatedRequestId?: RequestId | undefined;\n\n    /**\n     * The resumption token used to continue long-running requests that were interrupted.\n     *\n     * This allows clients to reconnect and continue from where they left off, if supported by the transport.\n     */\n    resumptionToken?: string | undefined;\n\n    /**\n     * A callback that is invoked when the resumption token changes, if supported by the transport.\n     *\n     * This allows clients to persist the latest token for potential reconnection.\n     */\n    onresumptiontoken?: ((token: string) => void) | undefined;\n\n    /**\n     * An abort signal for THIS outbound message's underlying request, when the\n     * transport sends one outbound message per underlying request (the\n     * Streamable HTTP transport's POST-per-request model). Aborting it cancels\n     * the underlying request (and its SSE response stream) without closing the\n     * transport. Transports that share a single channel (stdio, in-memory)\n     * ignore it.\n     */\n    requestSignal?: AbortSignal | undefined;\n\n    /**\n     * Fired by transports that open a per-request stream (the Streamable HTTP\n     * transport's POST-per-request SSE response) when that stream ends or\n     * errors for any reason OTHER than a deliberate `requestSignal` abort —\n     * i.e. the server closed the stream, the network dropped it, or\n     * reconnection was exhausted. Transports that share a single channel\n     * (stdio, in-memory) ignore it.\n     */\n    onRequestStreamEnd?: (() => void) | undefined;\n\n    /**\n     * Additional HTTP headers to send with THIS outbound message, when the\n     * transport sends one outbound message per underlying HTTP request (the\n     * Streamable HTTP transport's POST-per-request model). Transports that\n     * share a single channel (stdio, in-memory) ignore it.\n     *\n     * The Client uses this to attach SEP-2243 `Mcp-Param-{Name}` headers to a\n     * `tools/call` request on a 2026-07-28 connection. Values are sent\n     * verbatim — encode anything that is not a safe RFC 9110 field value\n     * before passing it here.\n     */\n    headers?: Readonly<Record<string, string>> | undefined;\n};\n/**\n * Describes the minimal contract for an MCP transport that a client or server can communicate over.\n */\nexport interface Transport {\n    /**\n     * Starts processing messages on the transport, including any connection steps that might need to be taken.\n     *\n     * This method should only be called after callbacks are installed, or else messages may be lost.\n     *\n     * NOTE: This method should not be called explicitly when using {@linkcode @modelcontextprotocol/client!client/client.Client | Client} or {@linkcode @modelcontextprotocol/server!server/server.Server | Server} classes, as they will implicitly call {@linkcode Transport.start | start()}.\n     */\n    start(): Promise<void>;\n\n    /**\n     * Sends a JSON-RPC message (request or response).\n     *\n     * If present, `relatedRequestId` is used to indicate to the transport which incoming request to associate this outgoing message with.\n     */\n    send(message: JSONRPCMessage, options?: TransportSendOptions): Promise<void>;\n\n    /**\n     * Closes the connection.\n     */\n    close(): Promise<void>;\n\n    /**\n     * `true` when this transport opens one underlying request per outbound\n     * JSON-RPC request (the Streamable HTTP POST-per-request model) and\n     * therefore honors {@linkcode TransportSendOptions.requestSignal}. The\n     * 2026-07-28 spec makes closing that per-request stream the cancellation\n     * signal — the protocol layer aborts `requestSignal` instead of POSTing\n     * `notifications/cancelled` when this flag is set on a 2026-era\n     * connection. Transports that share a single channel (stdio, in-memory)\n     * leave it `undefined`.\n     */\n    readonly hasPerRequestStream?: boolean;\n\n    /**\n     * Callback for when the connection is closed for any reason.\n     *\n     * This should be invoked when {@linkcode Transport.close | close()} is called as well.\n     */\n    onclose?: (() => void) | undefined;\n\n    /**\n     * Callback for when an error occurs.\n     *\n     * Note that errors are not necessarily fatal; they are used for reporting any kind of exceptional condition out of band.\n     */\n    onerror?: ((error: Error) => void) | undefined;\n\n    /**\n     * Callback for when a message (request or response) is received over the connection.\n     *\n     * Includes the {@linkcode MessageExtraInfo.request | request} and {@linkcode MessageExtraInfo.authInfo | authInfo} if the transport is authenticated.\n     *\n     * The {@linkcode MessageExtraInfo.request | request} can be used to get the original request information (headers, etc.)\n     */\n    onmessage?: (<T extends JSONRPCMessage>(message: T, extra?: MessageExtraInfo) => void) | undefined;\n\n    /**\n     * The session ID generated for this connection.\n     */\n    sessionId?: string | undefined;\n\n    /**\n     * Sets the protocol version used for the connection (called when the initialize response is received).\n     */\n    setProtocolVersion?: ((version: string) => void) | undefined;\n\n    /**\n     * Sets the supported protocol versions for header validation (called during connect).\n     * This allows the server to pass its supported versions to the transport.\n     */\n    setSupportedProtocolVersions?: ((versions: string[]) => void) | undefined;\n}\n","// Claude-authored implementation of RFC 6570 URI Templates\n\nexport type Variables = Record<string, string | string[]>;\n\nconst MAX_TEMPLATE_LENGTH = 1_000_000; // 1MB\nconst MAX_VARIABLE_LENGTH = 1_000_000; // 1MB\nconst MAX_TEMPLATE_EXPRESSIONS = 10_000;\nconst MAX_REGEX_LENGTH = 1_000_000; // 1MB\n\nexport class UriTemplate {\n    /**\n     * Returns true if the given string contains any URI template expressions.\n     * A template expression is a sequence of characters enclosed in curly braces,\n     * like `{foo}` or `{?bar}`.\n     */\n    static isTemplate(str: string): boolean {\n        // Look for any sequence of characters between curly braces\n        // that isn't just whitespace\n        return /\\{[^}\\s]+\\}/.test(str);\n    }\n\n    private static validateLength(str: string, max: number, context: string): void {\n        if (str.length > max) {\n            throw new Error(`${context} exceeds maximum length of ${max} characters (got ${str.length})`);\n        }\n    }\n    private readonly template: string;\n    private readonly parts: Array<string | { name: string; operator: string; names: string[]; exploded: boolean }>;\n\n    get variableNames(): string[] {\n        return this.parts.flatMap(part => (typeof part === 'string' ? [] : part.names));\n    }\n\n    constructor(template: string) {\n        UriTemplate.validateLength(template, MAX_TEMPLATE_LENGTH, 'Template');\n        this.template = template;\n        this.parts = this.parse(template);\n    }\n\n    toString(): string {\n        return this.template;\n    }\n\n    private parse(template: string): Array<string | { name: string; operator: string; names: string[]; exploded: boolean }> {\n        const parts: Array<string | { name: string; operator: string; names: string[]; exploded: boolean }> = [];\n        let currentText = '';\n        let i = 0;\n        let expressionCount = 0;\n\n        while (i < template.length) {\n            if (template[i] === '{') {\n                if (currentText) {\n                    parts.push(currentText);\n                    currentText = '';\n                }\n                const end = template.indexOf('}', i);\n                if (end === -1) throw new Error('Unclosed template expression');\n\n                expressionCount++;\n                if (expressionCount > MAX_TEMPLATE_EXPRESSIONS) {\n                    throw new Error(`Template contains too many expressions (max ${MAX_TEMPLATE_EXPRESSIONS})`);\n                }\n\n                const expr = template.slice(i + 1, end);\n                const operator = this.getOperator(expr);\n                const exploded = expr.includes('*');\n                const names = this.getNames(expr);\n                const name = names[0]!;\n\n                // Validate variable name length\n                for (const name of names) {\n                    UriTemplate.validateLength(name, MAX_VARIABLE_LENGTH, 'Variable name');\n                }\n\n                parts.push({ name, operator, names, exploded });\n                i = end + 1;\n            } else {\n                currentText += template[i];\n                i++;\n            }\n        }\n\n        if (currentText) {\n            parts.push(currentText);\n        }\n\n        return parts;\n    }\n\n    private getOperator(expr: string): string {\n        const operators = ['+', '#', '.', '/', '?', '&'];\n        return operators.find(op => expr.startsWith(op)) || '';\n    }\n\n    private getNames(expr: string): string[] {\n        const operator = this.getOperator(expr);\n        return expr\n            .slice(operator.length)\n            .split(',')\n            .map(name => name.replace('*', '').trim())\n            .filter(name => name.length > 0);\n    }\n\n    private encodeValue(value: string, operator: string): string {\n        UriTemplate.validateLength(value, MAX_VARIABLE_LENGTH, 'Variable value');\n        if (operator === '+' || operator === '#') {\n            return encodeURI(value);\n        }\n        return encodeURIComponent(value);\n    }\n\n    private expandPart(\n        part: {\n            name: string;\n            operator: string;\n            names: string[];\n            exploded: boolean;\n        },\n        variables: Variables\n    ): string {\n        if (part.operator === '?' || part.operator === '&') {\n            const pairs = part.names\n                .map(name => {\n                    const value = variables[name];\n                    if (value === undefined) return '';\n                    const encoded = Array.isArray(value)\n                        ? value.map(v => this.encodeValue(v, part.operator)).join(',')\n                        : this.encodeValue(value.toString(), part.operator);\n                    return `${name}=${encoded}`;\n                })\n                .filter(pair => pair.length > 0);\n\n            if (pairs.length === 0) return '';\n            const separator = part.operator === '?' ? '?' : '&';\n            return separator + pairs.join('&');\n        }\n\n        if (part.names.length > 1) {\n            const values = part.names.map(name => variables[name]).filter(v => v !== undefined);\n            if (values.length === 0) return '';\n            return values.map(v => (Array.isArray(v) ? v[0] : v)).join(',');\n        }\n\n        const value = variables[part.name];\n        if (value === undefined) return '';\n\n        const values = Array.isArray(value) ? value : [value];\n        const encoded = values.map(v => this.encodeValue(v, part.operator));\n\n        switch (part.operator) {\n            case '': {\n                return encoded.join(',');\n            }\n            case '+': {\n                return encoded.join(',');\n            }\n            case '#': {\n                return '#' + encoded.join(',');\n            }\n            case '.': {\n                return '.' + encoded.join('.');\n            }\n            case '/': {\n                return '/' + encoded.join('/');\n            }\n            default: {\n                return encoded.join(',');\n            }\n        }\n    }\n\n    expand(variables: Variables): string {\n        let result = '';\n        let hasQueryParam = false;\n\n        for (const part of this.parts) {\n            if (typeof part === 'string') {\n                result += part;\n                continue;\n            }\n\n            const expanded = this.expandPart(part, variables);\n            if (!expanded) continue;\n\n            // Convert ? to & if we already have a query parameter\n            result += (part.operator === '?' || part.operator === '&') && hasQueryParam ? expanded.replace('?', '&') : expanded;\n\n            if (part.operator === '?' || part.operator === '&') {\n                hasQueryParam = true;\n            }\n        }\n\n        return result;\n    }\n\n    private escapeRegExp(str: string): string {\n        return str.replaceAll(/[.*+?^${}()|[\\]\\\\]/g, String.raw`\\$&`);\n    }\n\n    private partToRegExp(part: {\n        name: string;\n        operator: string;\n        names: string[];\n        exploded: boolean;\n    }): Array<{ pattern: string; name: string }> {\n        const patterns: Array<{ pattern: string; name: string }> = [];\n\n        // Validate variable name length for matching\n        for (const name of part.names) {\n            UriTemplate.validateLength(name, MAX_VARIABLE_LENGTH, 'Variable name');\n        }\n\n        if (part.operator === '?' || part.operator === '&') {\n            for (let i = 0; i < part.names.length; i++) {\n                const name = part.names[i]!;\n                const prefix = i === 0 ? '\\\\' + part.operator : '&';\n                patterns.push({\n                    pattern: prefix + this.escapeRegExp(name) + '=([^&]+)',\n                    name\n                });\n            }\n            return patterns;\n        }\n\n        let pattern: string;\n        const name = part.name;\n\n        switch (part.operator) {\n            case '': {\n                pattern = part.exploded ? '([^/,]+(?:,[^/,]+)*)' : '([^/,]+)';\n                break;\n            }\n            case '+':\n            case '#': {\n                pattern = '(.+)';\n                break;\n            }\n            case '.': {\n                pattern = String.raw`\\.([^/,]+)`;\n                break;\n            }\n            case '/': {\n                pattern = '/' + (part.exploded ? '([^/,]+(?:,[^/,]+)*)' : '([^/,]+)');\n                break;\n            }\n            default: {\n                pattern = '([^/]+)';\n            }\n        }\n\n        patterns.push({ pattern, name });\n        return patterns;\n    }\n\n    match(uri: string): Variables | null {\n        UriTemplate.validateLength(uri, MAX_TEMPLATE_LENGTH, 'URI');\n        let pattern = '^';\n        const names: Array<{ name: string; exploded: boolean }> = [];\n\n        for (const part of this.parts) {\n            if (typeof part === 'string') {\n                pattern += this.escapeRegExp(part);\n            } else {\n                const patterns = this.partToRegExp(part);\n                for (const { pattern: partPattern, name } of patterns) {\n                    pattern += partPattern;\n                    names.push({ name, exploded: part.exploded });\n                }\n            }\n        }\n\n        pattern += '$';\n        UriTemplate.validateLength(pattern, MAX_REGEX_LENGTH, 'Generated regex pattern');\n        const regex = new RegExp(pattern);\n        const match = uri.match(regex);\n\n        if (!match) return null;\n\n        const result: Variables = {};\n        for (const [i, name_] of names.entries()) {\n            const { name, exploded } = name_!;\n            const value = match[i + 1]!;\n            const cleanName = name.replace('*', '');\n\n            result[cleanName] = exploded && value.includes(',') ? value.split(',') : value;\n        }\n\n        return result;\n    }\n}\n","import { SdkError, SdkErrorCode } from '../errors/sdkErrors';\nimport type { Transport } from '../shared/transport';\nimport type { AuthInfo, JSONRPCMessage, RequestId } from '../types/index';\n\ninterface QueuedMessage {\n    message: JSONRPCMessage;\n    extra?: { authInfo?: AuthInfo };\n}\n\n/**\n * In-memory transport for creating clients and servers that talk to each other within the same process.\n *\n * Intended for testing and development. For production in-process connections, use\n * `StreamableHTTPClientTransport` against a local server URL.\n */\nexport class InMemoryTransport implements Transport {\n    private _otherTransport?: InMemoryTransport;\n    private _messageQueue: QueuedMessage[] = [];\n    private _closed = false;\n\n    onclose?: () => void;\n    onerror?: (error: Error) => void;\n    onmessage?: (message: JSONRPCMessage, extra?: { authInfo?: AuthInfo }) => void;\n    sessionId?: string;\n\n    /**\n     * 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}.\n     */\n    static createLinkedPair(): [InMemoryTransport, InMemoryTransport] {\n        const clientTransport = new InMemoryTransport();\n        const serverTransport = new InMemoryTransport();\n        clientTransport._otherTransport = serverTransport;\n        serverTransport._otherTransport = clientTransport;\n        return [clientTransport, serverTransport];\n    }\n\n    async start(): Promise<void> {\n        // Process any messages that were queued before start was called\n        while (this._messageQueue.length > 0) {\n            const queuedMessage = this._messageQueue.shift()!;\n            this.onmessage?.(queuedMessage.message, queuedMessage.extra);\n        }\n    }\n\n    async close(): Promise<void> {\n        if (this._closed) return;\n        this._closed = true;\n\n        const other = this._otherTransport;\n        this._otherTransport = undefined;\n        try {\n            await other?.close();\n        } finally {\n            this.onclose?.();\n        }\n    }\n\n    /**\n     * Sends a message with optional auth info.\n     * This is useful for testing authentication scenarios.\n     */\n    async send(message: JSONRPCMessage, options?: { relatedRequestId?: RequestId; authInfo?: AuthInfo }): Promise<void> {\n        if (!this._otherTransport) {\n            throw new SdkError(SdkErrorCode.NotConnected, 'Not connected');\n        }\n\n        if (this._otherTransport.onmessage) {\n            this._otherTransport.onmessage(message, { authInfo: options?.authInfo });\n        } else {\n            this._otherTransport._messageQueue.push({ message, extra: { authInfo: options?.authInfo } });\n        }\n    }\n}\n","/**\n * Explicit warm-up entry for the lazy wire-schema layers.\n *\n * The per-revision wire schemas are built lazily: each era's schema set sits\n * behind a memoized factory (`buildSchemas2025`/`buildSchemas2026`), and the\n * registry/codec lookup maps above those factories are memoized the same way.\n * That laziness is the right default on process-per-invocation runtimes (CLI\n * tools, dev servers), where module evaluation IS startup latency and most\n * short-lived processes never validate a message on both eras.\n *\n * On platforms that bill request CPU but not module evaluation — isolate-based\n * edge/serverless runtimes such as Cloudflare Workers — the trade inverts:\n * module-scope work runs during isolate warm-up outside any request, while\n * lazy construction lands inside the first request's billed (and latency\n * budgeted) CPU. `preloadSchemas()` lets deployments on such platforms move\n * the one-time construction cost back to module scope by calling it at module\n * scope themselves. The packages' own workerd shims already do this, so\n * Workers deployments get eager construction automatically.\n */\nimport { buildSchemas2025 } from './rev2025-11-25/buildSchemas';\nimport { warmRegistryMaps2025 } from './rev2025-11-25/registry';\nimport { buildSchemas2026 } from './rev2026-07-28/buildSchemas';\nimport { warmWireResultSchemas2026 } from './rev2026-07-28/codec';\nimport { warmInputSchemaMaps2026 } from './rev2026-07-28/inputRequired';\n\n/**\n * Eagerly builds every lazily-constructed wire-schema layer, so that no later\n * validation pays schema-construction cost.\n *\n * Synchronous and idempotent: every layer is a memo, so the first call does\n * all the work and subsequent calls return immediately. Reference identity is\n * unaffected — this forces the same memos every lazy consumer pulls through.\n *\n * Call it at module scope on platforms that bill per-request CPU but not\n * module evaluation (isolate-based edge/serverless runtimes), where deferring\n * construction would move it into the first request of every fresh isolate:\n *\n * ```ts\n * // from '@modelcontextprotocol/server' or '@modelcontextprotocol/client' —\n * // each package bundles its own schema copy, so warm the one(s) you import.\n * preloadSchemas(); // module scope — runs during isolate warm-up\n * ```\n *\n * On Node CLIs and other process-per-invocation runtimes, prefer the lazy\n * default — there, module-scope construction is pure added boot latency.\n */\nexport function preloadSchemas(): void {\n    // The era schema factories — the bulk of the construction cost.\n    buildSchemas2025();\n    buildSchemas2026();\n    // The memoized lookup layers above the factories. (The 2026 registry has\n    // no map memo of its own — it reads the dispatch maps straight off the\n    // built schema set.)\n    warmRegistryMaps2025();\n    warmInputSchemaMaps2026();\n    warmWireResultSchemas2026();\n}\n","import type { StandardSchemaV1, StandardSchemaWithJSON } from '../util/standardSchema';\nimport type { JsonSchemaType, jsonSchemaValidator } from './types';\n\n/**\n * Wrap a raw JSON Schema object as a {@linkcode StandardSchemaWithJSON} so it can be\n * passed to `registerTool` / `registerPrompt`. Use this when you already have JSON\n * Schema (e.g. from TypeBox, or hand-written) and want to register it without going\n * through a Standard Schema library.\n *\n * The callback arguments will be typed `unknown` (raw JSON Schema has no TypeScript\n * types attached). Cast at the call site, or use the generic `fromJsonSchema<MyType>(...)`.\n *\n * @param schema - A JSON Schema object describing the expected shape\n * @param validator - A validator provider. When importing `fromJsonSchema` from\n *   `@modelcontextprotocol/server` or `@modelcontextprotocol/client`, a runtime-appropriate\n *   default is provided automatically (AJV on Node.js, CfWorker on edge runtimes).\n *\n * @example\n * ```ts source=\"./fromJsonSchema.examples.ts#fromJsonSchema_basicUsage\"\n * const inputSchema = fromJsonSchema<{ name: string }>(\n *     { type: 'object', properties: { name: { type: 'string' } }, required: ['name'] },\n *     validator\n * );\n * // Use with server.registerTool('greet', { inputSchema }, handler)\n * ```\n */\nexport function fromJsonSchema<T = unknown>(schema: JsonSchemaType, validator: jsonSchemaValidator): StandardSchemaWithJSON<T, T> {\n    const check = validator.getValidator<T>(schema);\n    return {\n        '~standard': {\n            version: 1,\n            vendor: 'mcp',\n            jsonSchema: {\n                input: () => schema as Record<string, unknown>,\n                output: () => schema as Record<string, unknown>\n            },\n            validate: (data: unknown): StandardSchemaV1.Result<T> => {\n                const result = check(data);\n                return result.valid ? { value: result.data } : { issues: [{ message: result.errorMessage }] };\n            }\n        }\n    };\n}\n","\"use strict\";\nObject.defineProperty(exports, \"__esModule\", { value: true });\nexports.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;\n// eslint-disable-next-line @typescript-eslint/no-extraneous-class\nclass _CodeOrName {\n}\nexports._CodeOrName = _CodeOrName;\nexports.IDENTIFIER = /^[a-z$_][a-z$_0-9]*$/i;\nclass Name extends _CodeOrName {\n    constructor(s) {\n        super();\n        if (!exports.IDENTIFIER.test(s))\n            throw new Error(\"CodeGen: name must be a valid identifier\");\n        this.str = s;\n    }\n    toString() {\n        return this.str;\n    }\n    emptyStr() {\n        return false;\n    }\n    get names() {\n        return { [this.str]: 1 };\n    }\n}\nexports.Name = Name;\nclass _Code extends _CodeOrName {\n    constructor(code) {\n        super();\n        this._items = typeof code === \"string\" ? [code] : code;\n    }\n    toString() {\n        return this.str;\n    }\n    emptyStr() {\n        if (this._items.length > 1)\n            return false;\n        const item = this._items[0];\n        return item === \"\" || item === '\"\"';\n    }\n    get str() {\n        var _a;\n        return ((_a = this._str) !== null && _a !== void 0 ? _a : (this._str = this._items.reduce((s, c) => `${s}${c}`, \"\")));\n    }\n    get names() {\n        var _a;\n        return ((_a = this._names) !== null && _a !== void 0 ? _a : (this._names = this._items.reduce((names, c) => {\n            if (c instanceof Name)\n                names[c.str] = (names[c.str] || 0) + 1;\n            return names;\n        }, {})));\n    }\n}\nexports._Code = _Code;\nexports.nil = new _Code(\"\");\nfunction _(strs, ...args) {\n    const code = [strs[0]];\n    let i = 0;\n    while (i < args.length) {\n        addCodeArg(code, args[i]);\n        code.push(strs[++i]);\n    }\n    return new _Code(code);\n}\nexports._ = _;\nconst plus = new _Code(\"+\");\nfunction str(strs, ...args) {\n    const expr = [safeStringify(strs[0])];\n    let i = 0;\n    while (i < args.length) {\n        expr.push(plus);\n        addCodeArg(expr, args[i]);\n        expr.push(plus, safeStringify(strs[++i]));\n    }\n    optimize(expr);\n    return new _Code(expr);\n}\nexports.str = str;\nfunction addCodeArg(code, arg) {\n    if (arg instanceof _Code)\n        code.push(...arg._items);\n    else if (arg instanceof Name)\n        code.push(arg);\n    else\n        code.push(interpolate(arg));\n}\nexports.addCodeArg = addCodeArg;\nfunction optimize(expr) {\n    let i = 1;\n    while (i < expr.length - 1) {\n        if (expr[i] === plus) {\n            const res = mergeExprItems(expr[i - 1], expr[i + 1]);\n            if (res !== undefined) {\n                expr.splice(i - 1, 3, res);\n                continue;\n            }\n            expr[i++] = \"+\";\n        }\n        i++;\n    }\n}\nfunction mergeExprItems(a, b) {\n    if (b === '\"\"')\n        return a;\n    if (a === '\"\"')\n        return b;\n    if (typeof a == \"string\") {\n        if (b instanceof Name || a[a.length - 1] !== '\"')\n            return;\n        if (typeof b != \"string\")\n            return `${a.slice(0, -1)}${b}\"`;\n        if (b[0] === '\"')\n            return a.slice(0, -1) + b.slice(1);\n        return;\n    }\n    if (typeof b == \"string\" && b[0] === '\"' && !(a instanceof Name))\n        return `\"${a}${b.slice(1)}`;\n    return;\n}\nfunction strConcat(c1, c2) {\n    return c2.emptyStr() ? c1 : c1.emptyStr() ? c2 : str `${c1}${c2}`;\n}\nexports.strConcat = strConcat;\n// TODO do not allow arrays here\nfunction interpolate(x) {\n    return typeof x == \"number\" || typeof x == \"boolean\" || x === null\n        ? x\n        : safeStringify(Array.isArray(x) ? x.join(\",\") : x);\n}\nfunction stringify(x) {\n    return new _Code(safeStringify(x));\n}\nexports.stringify = stringify;\nfunction safeStringify(x) {\n    return JSON.stringify(x)\n        .replace(/\\u2028/g, \"\\\\u2028\")\n        .replace(/\\u2029/g, \"\\\\u2029\");\n}\nexports.safeStringify = safeStringify;\nfunction getProperty(key) {\n    return typeof key == \"string\" && exports.IDENTIFIER.test(key) ? new _Code(`.${key}`) : _ `[${key}]`;\n}\nexports.getProperty = getProperty;\n//Does best effort to format the name properly\nfunction getEsmExportName(key) {\n    if (typeof key == \"string\" && exports.IDENTIFIER.test(key)) {\n        return new _Code(`${key}`);\n    }\n    throw new Error(`CodeGen: invalid export name: ${key}, use explicit $id name mapping`);\n}\nexports.getEsmExportName = getEsmExportName;\nfunction regexpCode(rx) {\n    return new _Code(rx.toString());\n}\nexports.regexpCode = regexpCode;\n//# sourceMappingURL=code.js.map","\"use strict\";\nObject.defineProperty(exports, \"__esModule\", { value: true });\nexports.ValueScope = exports.ValueScopeName = exports.Scope = exports.varKinds = exports.UsedValueState = void 0;\nconst code_1 = require(\"./code\");\nclass ValueError extends Error {\n    constructor(name) {\n        super(`CodeGen: \"code\" for ${name} not defined`);\n        this.value = name.value;\n    }\n}\nvar UsedValueState;\n(function (UsedValueState) {\n    UsedValueState[UsedValueState[\"Started\"] = 0] = \"Started\";\n    UsedValueState[UsedValueState[\"Completed\"] = 1] = \"Completed\";\n})(UsedValueState || (exports.UsedValueState = UsedValueState = {}));\nexports.varKinds = {\n    const: new code_1.Name(\"const\"),\n    let: new code_1.Name(\"let\"),\n    var: new code_1.Name(\"var\"),\n};\nclass Scope {\n    constructor({ prefixes, parent } = {}) {\n        this._names = {};\n        this._prefixes = prefixes;\n        this._parent = parent;\n    }\n    toName(nameOrPrefix) {\n        return nameOrPrefix instanceof code_1.Name ? nameOrPrefix : this.name(nameOrPrefix);\n    }\n    name(prefix) {\n        return new code_1.Name(this._newName(prefix));\n    }\n    _newName(prefix) {\n        const ng = this._names[prefix] || this._nameGroup(prefix);\n        return `${prefix}${ng.index++}`;\n    }\n    _nameGroup(prefix) {\n        var _a, _b;\n        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))) {\n            throw new Error(`CodeGen: prefix \"${prefix}\" is not allowed in this scope`);\n        }\n        return (this._names[prefix] = { prefix, index: 0 });\n    }\n}\nexports.Scope = Scope;\nclass ValueScopeName extends code_1.Name {\n    constructor(prefix, nameStr) {\n        super(nameStr);\n        this.prefix = prefix;\n    }\n    setValue(value, { property, itemIndex }) {\n        this.value = value;\n        this.scopePath = (0, code_1._) `.${new code_1.Name(property)}[${itemIndex}]`;\n    }\n}\nexports.ValueScopeName = ValueScopeName;\nconst line = (0, code_1._) `\\n`;\nclass ValueScope extends Scope {\n    constructor(opts) {\n        super(opts);\n        this._values = {};\n        this._scope = opts.scope;\n        this.opts = { ...opts, _n: opts.lines ? line : code_1.nil };\n    }\n    get() {\n        return this._scope;\n    }\n    name(prefix) {\n        return new ValueScopeName(prefix, this._newName(prefix));\n    }\n    value(nameOrPrefix, value) {\n        var _a;\n        if (value.ref === undefined)\n            throw new Error(\"CodeGen: ref must be passed in value\");\n        const name = this.toName(nameOrPrefix);\n        const { prefix } = name;\n        const valueKey = (_a = value.key) !== null && _a !== void 0 ? _a : value.ref;\n        let vs = this._values[prefix];\n        if (vs) {\n            const _name = vs.get(valueKey);\n            if (_name)\n                return _name;\n        }\n        else {\n            vs = this._values[prefix] = new Map();\n        }\n        vs.set(valueKey, name);\n        const s = this._scope[prefix] || (this._scope[prefix] = []);\n        const itemIndex = s.length;\n        s[itemIndex] = value.ref;\n        name.setValue(value, { property: prefix, itemIndex });\n        return name;\n    }\n    getValue(prefix, keyOrRef) {\n        const vs = this._values[prefix];\n        if (!vs)\n            return;\n        return vs.get(keyOrRef);\n    }\n    scopeRefs(scopeName, values = this._values) {\n        return this._reduceValues(values, (name) => {\n            if (name.scopePath === undefined)\n                throw new Error(`CodeGen: name \"${name}\" has no value`);\n            return (0, code_1._) `${scopeName}${name.scopePath}`;\n        });\n    }\n    scopeCode(values = this._values, usedValues, getCode) {\n        return this._reduceValues(values, (name) => {\n            if (name.value === undefined)\n                throw new Error(`CodeGen: name \"${name}\" has no value`);\n            return name.value.code;\n        }, usedValues, getCode);\n    }\n    _reduceValues(values, valueCode, usedValues = {}, getCode) {\n        let code = code_1.nil;\n        for (const prefix in values) {\n            const vs = values[prefix];\n            if (!vs)\n                continue;\n            const nameSet = (usedValues[prefix] = usedValues[prefix] || new Map());\n            vs.forEach((name) => {\n                if (nameSet.has(name))\n                    return;\n                nameSet.set(name, UsedValueState.Started);\n                let c = valueCode(name);\n                if (c) {\n                    const def = this.opts.es5 ? exports.varKinds.var : exports.varKinds.const;\n                    code = (0, code_1._) `${code}${def} ${name} = ${c};${this.opts._n}`;\n                }\n                else if ((c = getCode === null || getCode === void 0 ? void 0 : getCode(name))) {\n                    code = (0, code_1._) `${code}${c}${this.opts._n}`;\n                }\n                else {\n                    throw new ValueError(name);\n                }\n                nameSet.set(name, UsedValueState.Completed);\n            });\n        }\n        return code;\n    }\n}\nexports.ValueScope = ValueScope;\n//# sourceMappingURL=scope.js.map","\"use strict\";\nObject.defineProperty(exports, \"__esModule\", { value: true });\nexports.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;\nconst code_1 = require(\"./code\");\nconst scope_1 = require(\"./scope\");\nvar code_2 = require(\"./code\");\nObject.defineProperty(exports, \"_\", { enumerable: true, get: function () { return code_2._; } });\nObject.defineProperty(exports, \"str\", { enumerable: true, get: function () { return code_2.str; } });\nObject.defineProperty(exports, \"strConcat\", { enumerable: true, get: function () { return code_2.strConcat; } });\nObject.defineProperty(exports, \"nil\", { enumerable: true, get: function () { return code_2.nil; } });\nObject.defineProperty(exports, \"getProperty\", { enumerable: true, get: function () { return code_2.getProperty; } });\nObject.defineProperty(exports, \"stringify\", { enumerable: true, get: function () { return code_2.stringify; } });\nObject.defineProperty(exports, \"regexpCode\", { enumerable: true, get: function () { return code_2.regexpCode; } });\nObject.defineProperty(exports, \"Name\", { enumerable: true, get: function () { return code_2.Name; } });\nvar scope_2 = require(\"./scope\");\nObject.defineProperty(exports, \"Scope\", { enumerable: true, get: function () { return scope_2.Scope; } });\nObject.defineProperty(exports, \"ValueScope\", { enumerable: true, get: function () { return scope_2.ValueScope; } });\nObject.defineProperty(exports, \"ValueScopeName\", { enumerable: true, get: function () { return scope_2.ValueScopeName; } });\nObject.defineProperty(exports, \"varKinds\", { enumerable: true, get: function () { return scope_2.varKinds; } });\nexports.operators = {\n    GT: new code_1._Code(\">\"),\n    GTE: new code_1._Code(\">=\"),\n    LT: new code_1._Code(\"<\"),\n    LTE: new code_1._Code(\"<=\"),\n    EQ: new code_1._Code(\"===\"),\n    NEQ: new code_1._Code(\"!==\"),\n    NOT: new code_1._Code(\"!\"),\n    OR: new code_1._Code(\"||\"),\n    AND: new code_1._Code(\"&&\"),\n    ADD: new code_1._Code(\"+\"),\n};\nclass Node {\n    optimizeNodes() {\n        return this;\n    }\n    optimizeNames(_names, _constants) {\n        return this;\n    }\n}\nclass Def extends Node {\n    constructor(varKind, name, rhs) {\n        super();\n        this.varKind = varKind;\n        this.name = name;\n        this.rhs = rhs;\n    }\n    render({ es5, _n }) {\n        const varKind = es5 ? scope_1.varKinds.var : this.varKind;\n        const rhs = this.rhs === undefined ? \"\" : ` = ${this.rhs}`;\n        return `${varKind} ${this.name}${rhs};` + _n;\n    }\n    optimizeNames(names, constants) {\n        if (!names[this.name.str])\n            return;\n        if (this.rhs)\n            this.rhs = optimizeExpr(this.rhs, names, constants);\n        return this;\n    }\n    get names() {\n        return this.rhs instanceof code_1._CodeOrName ? this.rhs.names : {};\n    }\n}\nclass Assign extends Node {\n    constructor(lhs, rhs, sideEffects) {\n        super();\n        this.lhs = lhs;\n        this.rhs = rhs;\n        this.sideEffects = sideEffects;\n    }\n    render({ _n }) {\n        return `${this.lhs} = ${this.rhs};` + _n;\n    }\n    optimizeNames(names, constants) {\n        if (this.lhs instanceof code_1.Name && !names[this.lhs.str] && !this.sideEffects)\n            return;\n        this.rhs = optimizeExpr(this.rhs, names, constants);\n        return this;\n    }\n    get names() {\n        const names = this.lhs instanceof code_1.Name ? {} : { ...this.lhs.names };\n        return addExprNames(names, this.rhs);\n    }\n}\nclass AssignOp extends Assign {\n    constructor(lhs, op, rhs, sideEffects) {\n        super(lhs, rhs, sideEffects);\n        this.op = op;\n    }\n    render({ _n }) {\n        return `${this.lhs} ${this.op}= ${this.rhs};` + _n;\n    }\n}\nclass Label extends Node {\n    constructor(label) {\n        super();\n        this.label = label;\n        this.names = {};\n    }\n    render({ _n }) {\n        return `${this.label}:` + _n;\n    }\n}\nclass Break extends Node {\n    constructor(label) {\n        super();\n        this.label = label;\n        this.names = {};\n    }\n    render({ _n }) {\n        const label = this.label ? ` ${this.label}` : \"\";\n        return `break${label};` + _n;\n    }\n}\nclass Throw extends Node {\n    constructor(error) {\n        super();\n        this.error = error;\n    }\n    render({ _n }) {\n        return `throw ${this.error};` + _n;\n    }\n    get names() {\n        return this.error.names;\n    }\n}\nclass AnyCode extends Node {\n    constructor(code) {\n        super();\n        this.code = code;\n    }\n    render({ _n }) {\n        return `${this.code};` + _n;\n    }\n    optimizeNodes() {\n        return `${this.code}` ? this : undefined;\n    }\n    optimizeNames(names, constants) {\n        this.code = optimizeExpr(this.code, names, constants);\n        return this;\n    }\n    get names() {\n        return this.code instanceof code_1._CodeOrName ? this.code.names : {};\n    }\n}\nclass ParentNode extends Node {\n    constructor(nodes = []) {\n        super();\n        this.nodes = nodes;\n    }\n    render(opts) {\n        return this.nodes.reduce((code, n) => code + n.render(opts), \"\");\n    }\n    optimizeNodes() {\n        const { nodes } = this;\n        let i = nodes.length;\n        while (i--) {\n            const n = nodes[i].optimizeNodes();\n            if (Array.isArray(n))\n                nodes.splice(i, 1, ...n);\n            else if (n)\n                nodes[i] = n;\n            else\n                nodes.splice(i, 1);\n        }\n        return nodes.length > 0 ? this : undefined;\n    }\n    optimizeNames(names, constants) {\n        const { nodes } = this;\n        let i = nodes.length;\n        while (i--) {\n            // iterating backwards improves 1-pass optimization\n            const n = nodes[i];\n            if (n.optimizeNames(names, constants))\n                continue;\n            subtractNames(names, n.names);\n            nodes.splice(i, 1);\n        }\n        return nodes.length > 0 ? this : undefined;\n    }\n    get names() {\n        return this.nodes.reduce((names, n) => addNames(names, n.names), {});\n    }\n}\nclass BlockNode extends ParentNode {\n    render(opts) {\n        return \"{\" + opts._n + super.render(opts) + \"}\" + opts._n;\n    }\n}\nclass Root extends ParentNode {\n}\nclass Else extends BlockNode {\n}\nElse.kind = \"else\";\nclass If extends BlockNode {\n    constructor(condition, nodes) {\n        super(nodes);\n        this.condition = condition;\n    }\n    render(opts) {\n        let code = `if(${this.condition})` + super.render(opts);\n        if (this.else)\n            code += \"else \" + this.else.render(opts);\n        return code;\n    }\n    optimizeNodes() {\n        super.optimizeNodes();\n        const cond = this.condition;\n        if (cond === true)\n            return this.nodes; // else is ignored here\n        let e = this.else;\n        if (e) {\n            const ns = e.optimizeNodes();\n            e = this.else = Array.isArray(ns) ? new Else(ns) : ns;\n        }\n        if (e) {\n            if (cond === false)\n                return e instanceof If ? e : e.nodes;\n            if (this.nodes.length)\n                return this;\n            return new If(not(cond), e instanceof If ? [e] : e.nodes);\n        }\n        if (cond === false || !this.nodes.length)\n            return undefined;\n        return this;\n    }\n    optimizeNames(names, constants) {\n        var _a;\n        this.else = (_a = this.else) === null || _a === void 0 ? void 0 : _a.optimizeNames(names, constants);\n        if (!(super.optimizeNames(names, constants) || this.else))\n            return;\n        this.condition = optimizeExpr(this.condition, names, constants);\n        return this;\n    }\n    get names() {\n        const names = super.names;\n        addExprNames(names, this.condition);\n        if (this.else)\n            addNames(names, this.else.names);\n        return names;\n    }\n}\nIf.kind = \"if\";\nclass For extends BlockNode {\n}\nFor.kind = \"for\";\nclass ForLoop extends For {\n    constructor(iteration) {\n        super();\n        this.iteration = iteration;\n    }\n    render(opts) {\n        return `for(${this.iteration})` + super.render(opts);\n    }\n    optimizeNames(names, constants) {\n        if (!super.optimizeNames(names, constants))\n            return;\n        this.iteration = optimizeExpr(this.iteration, names, constants);\n        return this;\n    }\n    get names() {\n        return addNames(super.names, this.iteration.names);\n    }\n}\nclass ForRange extends For {\n    constructor(varKind, name, from, to) {\n        super();\n        this.varKind = varKind;\n        this.name = name;\n        this.from = from;\n        this.to = to;\n    }\n    render(opts) {\n        const varKind = opts.es5 ? scope_1.varKinds.var : this.varKind;\n        const { name, from, to } = this;\n        return `for(${varKind} ${name}=${from}; ${name}<${to}; ${name}++)` + super.render(opts);\n    }\n    get names() {\n        const names = addExprNames(super.names, this.from);\n        return addExprNames(names, this.to);\n    }\n}\nclass ForIter extends For {\n    constructor(loop, varKind, name, iterable) {\n        super();\n        this.loop = loop;\n        this.varKind = varKind;\n        this.name = name;\n        this.iterable = iterable;\n    }\n    render(opts) {\n        return `for(${this.varKind} ${this.name} ${this.loop} ${this.iterable})` + super.render(opts);\n    }\n    optimizeNames(names, constants) {\n        if (!super.optimizeNames(names, constants))\n            return;\n        this.iterable = optimizeExpr(this.iterable, names, constants);\n        return this;\n    }\n    get names() {\n        return addNames(super.names, this.iterable.names);\n    }\n}\nclass Func extends BlockNode {\n    constructor(name, args, async) {\n        super();\n        this.name = name;\n        this.args = args;\n        this.async = async;\n    }\n    render(opts) {\n        const _async = this.async ? \"async \" : \"\";\n        return `${_async}function ${this.name}(${this.args})` + super.render(opts);\n    }\n}\nFunc.kind = \"func\";\nclass Return extends ParentNode {\n    render(opts) {\n        return \"return \" + super.render(opts);\n    }\n}\nReturn.kind = \"return\";\nclass Try extends BlockNode {\n    render(opts) {\n        let code = \"try\" + super.render(opts);\n        if (this.catch)\n            code += this.catch.render(opts);\n        if (this.finally)\n            code += this.finally.render(opts);\n        return code;\n    }\n    optimizeNodes() {\n        var _a, _b;\n        super.optimizeNodes();\n        (_a = this.catch) === null || _a === void 0 ? void 0 : _a.optimizeNodes();\n        (_b = this.finally) === null || _b === void 0 ? void 0 : _b.optimizeNodes();\n        return this;\n    }\n    optimizeNames(names, constants) {\n        var _a, _b;\n        super.optimizeNames(names, constants);\n        (_a = this.catch) === null || _a === void 0 ? void 0 : _a.optimizeNames(names, constants);\n        (_b = this.finally) === null || _b === void 0 ? void 0 : _b.optimizeNames(names, constants);\n        return this;\n    }\n    get names() {\n        const names = super.names;\n        if (this.catch)\n            addNames(names, this.catch.names);\n        if (this.finally)\n            addNames(names, this.finally.names);\n        return names;\n    }\n}\nclass Catch extends BlockNode {\n    constructor(error) {\n        super();\n        this.error = error;\n    }\n    render(opts) {\n        return `catch(${this.error})` + super.render(opts);\n    }\n}\nCatch.kind = \"catch\";\nclass Finally extends BlockNode {\n    render(opts) {\n        return \"finally\" + super.render(opts);\n    }\n}\nFinally.kind = \"finally\";\nclass CodeGen {\n    constructor(extScope, opts = {}) {\n        this._values = {};\n        this._blockStarts = [];\n        this._constants = {};\n        this.opts = { ...opts, _n: opts.lines ? \"\\n\" : \"\" };\n        this._extScope = extScope;\n        this._scope = new scope_1.Scope({ parent: extScope });\n        this._nodes = [new Root()];\n    }\n    toString() {\n        return this._root.render(this.opts);\n    }\n    // returns unique name in the internal scope\n    name(prefix) {\n        return this._scope.name(prefix);\n    }\n    // reserves unique name in the external scope\n    scopeName(prefix) {\n        return this._extScope.name(prefix);\n    }\n    // reserves unique name in the external scope and assigns value to it\n    scopeValue(prefixOrName, value) {\n        const name = this._extScope.value(prefixOrName, value);\n        const vs = this._values[name.prefix] || (this._values[name.prefix] = new Set());\n        vs.add(name);\n        return name;\n    }\n    getScopeValue(prefix, keyOrRef) {\n        return this._extScope.getValue(prefix, keyOrRef);\n    }\n    // return code that assigns values in the external scope to the names that are used internally\n    // (same names that were returned by gen.scopeName or gen.scopeValue)\n    scopeRefs(scopeName) {\n        return this._extScope.scopeRefs(scopeName, this._values);\n    }\n    scopeCode() {\n        return this._extScope.scopeCode(this._values);\n    }\n    _def(varKind, nameOrPrefix, rhs, constant) {\n        const name = this._scope.toName(nameOrPrefix);\n        if (rhs !== undefined && constant)\n            this._constants[name.str] = rhs;\n        this._leafNode(new Def(varKind, name, rhs));\n        return name;\n    }\n    // `const` declaration (`var` in es5 mode)\n    const(nameOrPrefix, rhs, _constant) {\n        return this._def(scope_1.varKinds.const, nameOrPrefix, rhs, _constant);\n    }\n    // `let` declaration with optional assignment (`var` in es5 mode)\n    let(nameOrPrefix, rhs, _constant) {\n        return this._def(scope_1.varKinds.let, nameOrPrefix, rhs, _constant);\n    }\n    // `var` declaration with optional assignment\n    var(nameOrPrefix, rhs, _constant) {\n        return this._def(scope_1.varKinds.var, nameOrPrefix, rhs, _constant);\n    }\n    // assignment code\n    assign(lhs, rhs, sideEffects) {\n        return this._leafNode(new Assign(lhs, rhs, sideEffects));\n    }\n    // `+=` code\n    add(lhs, rhs) {\n        return this._leafNode(new AssignOp(lhs, exports.operators.ADD, rhs));\n    }\n    // appends passed SafeExpr to code or executes Block\n    code(c) {\n        if (typeof c == \"function\")\n            c();\n        else if (c !== code_1.nil)\n            this._leafNode(new AnyCode(c));\n        return this;\n    }\n    // returns code for object literal for the passed argument list of key-value pairs\n    object(...keyValues) {\n        const code = [\"{\"];\n        for (const [key, value] of keyValues) {\n            if (code.length > 1)\n                code.push(\",\");\n            code.push(key);\n            if (key !== value || this.opts.es5) {\n                code.push(\":\");\n                (0, code_1.addCodeArg)(code, value);\n            }\n        }\n        code.push(\"}\");\n        return new code_1._Code(code);\n    }\n    // `if` clause (or statement if `thenBody` and, optionally, `elseBody` are passed)\n    if(condition, thenBody, elseBody) {\n        this._blockNode(new If(condition));\n        if (thenBody && elseBody) {\n            this.code(thenBody).else().code(elseBody).endIf();\n        }\n        else if (thenBody) {\n            this.code(thenBody).endIf();\n        }\n        else if (elseBody) {\n            throw new Error('CodeGen: \"else\" body without \"then\" body');\n        }\n        return this;\n    }\n    // `else if` clause - invalid without `if` or after `else` clauses\n    elseIf(condition) {\n        return this._elseNode(new If(condition));\n    }\n    // `else` clause - only valid after `if` or `else if` clauses\n    else() {\n        return this._elseNode(new Else());\n    }\n    // end `if` statement (needed if gen.if was used only with condition)\n    endIf() {\n        return this._endBlockNode(If, Else);\n    }\n    _for(node, forBody) {\n        this._blockNode(node);\n        if (forBody)\n            this.code(forBody).endFor();\n        return this;\n    }\n    // a generic `for` clause (or statement if `forBody` is passed)\n    for(iteration, forBody) {\n        return this._for(new ForLoop(iteration), forBody);\n    }\n    // `for` statement for a range of values\n    forRange(nameOrPrefix, from, to, forBody, varKind = this.opts.es5 ? scope_1.varKinds.var : scope_1.varKinds.let) {\n        const name = this._scope.toName(nameOrPrefix);\n        return this._for(new ForRange(varKind, name, from, to), () => forBody(name));\n    }\n    // `for-of` statement (in es5 mode replace with a normal for loop)\n    forOf(nameOrPrefix, iterable, forBody, varKind = scope_1.varKinds.const) {\n        const name = this._scope.toName(nameOrPrefix);\n        if (this.opts.es5) {\n            const arr = iterable instanceof code_1.Name ? iterable : this.var(\"_arr\", iterable);\n            return this.forRange(\"_i\", 0, (0, code_1._) `${arr}.length`, (i) => {\n                this.var(name, (0, code_1._) `${arr}[${i}]`);\n                forBody(name);\n            });\n        }\n        return this._for(new ForIter(\"of\", varKind, name, iterable), () => forBody(name));\n    }\n    // `for-in` statement.\n    // With option `ownProperties` replaced with a `for-of` loop for object keys\n    forIn(nameOrPrefix, obj, forBody, varKind = this.opts.es5 ? scope_1.varKinds.var : scope_1.varKinds.const) {\n        if (this.opts.ownProperties) {\n            return this.forOf(nameOrPrefix, (0, code_1._) `Object.keys(${obj})`, forBody);\n        }\n        const name = this._scope.toName(nameOrPrefix);\n        return this._for(new ForIter(\"in\", varKind, name, obj), () => forBody(name));\n    }\n    // end `for` loop\n    endFor() {\n        return this._endBlockNode(For);\n    }\n    // `label` statement\n    label(label) {\n        return this._leafNode(new Label(label));\n    }\n    // `break` statement\n    break(label) {\n        return this._leafNode(new Break(label));\n    }\n    // `return` statement\n    return(value) {\n        const node = new Return();\n        this._blockNode(node);\n        this.code(value);\n        if (node.nodes.length !== 1)\n            throw new Error('CodeGen: \"return\" should have one node');\n        return this._endBlockNode(Return);\n    }\n    // `try` statement\n    try(tryBody, catchCode, finallyCode) {\n        if (!catchCode && !finallyCode)\n            throw new Error('CodeGen: \"try\" without \"catch\" and \"finally\"');\n        const node = new Try();\n        this._blockNode(node);\n        this.code(tryBody);\n        if (catchCode) {\n            const error = this.name(\"e\");\n            this._currNode = node.catch = new Catch(error);\n            catchCode(error);\n        }\n        if (finallyCode) {\n            this._currNode = node.finally = new Finally();\n            this.code(finallyCode);\n        }\n        return this._endBlockNode(Catch, Finally);\n    }\n    // `throw` statement\n    throw(error) {\n        return this._leafNode(new Throw(error));\n    }\n    // start self-balancing block\n    block(body, nodeCount) {\n        this._blockStarts.push(this._nodes.length);\n        if (body)\n            this.code(body).endBlock(nodeCount);\n        return this;\n    }\n    // end the current self-balancing block\n    endBlock(nodeCount) {\n        const len = this._blockStarts.pop();\n        if (len === undefined)\n            throw new Error(\"CodeGen: not in self-balancing block\");\n        const toClose = this._nodes.length - len;\n        if (toClose < 0 || (nodeCount !== undefined && toClose !== nodeCount)) {\n            throw new Error(`CodeGen: wrong number of nodes: ${toClose} vs ${nodeCount} expected`);\n        }\n        this._nodes.length = len;\n        return this;\n    }\n    // `function` heading (or definition if funcBody is passed)\n    func(name, args = code_1.nil, async, funcBody) {\n        this._blockNode(new Func(name, args, async));\n        if (funcBody)\n            this.code(funcBody).endFunc();\n        return this;\n    }\n    // end function definition\n    endFunc() {\n        return this._endBlockNode(Func);\n    }\n    optimize(n = 1) {\n        while (n-- > 0) {\n            this._root.optimizeNodes();\n            this._root.optimizeNames(this._root.names, this._constants);\n        }\n    }\n    _leafNode(node) {\n        this._currNode.nodes.push(node);\n        return this;\n    }\n    _blockNode(node) {\n        this._currNode.nodes.push(node);\n        this._nodes.push(node);\n    }\n    _endBlockNode(N1, N2) {\n        const n = this._currNode;\n        if (n instanceof N1 || (N2 && n instanceof N2)) {\n            this._nodes.pop();\n            return this;\n        }\n        throw new Error(`CodeGen: not in block \"${N2 ? `${N1.kind}/${N2.kind}` : N1.kind}\"`);\n    }\n    _elseNode(node) {\n        const n = this._currNode;\n        if (!(n instanceof If)) {\n            throw new Error('CodeGen: \"else\" without \"if\"');\n        }\n        this._currNode = n.else = node;\n        return this;\n    }\n    get _root() {\n        return this._nodes[0];\n    }\n    get _currNode() {\n        const ns = this._nodes;\n        return ns[ns.length - 1];\n    }\n    set _currNode(node) {\n        const ns = this._nodes;\n        ns[ns.length - 1] = node;\n    }\n}\nexports.CodeGen = CodeGen;\nfunction addNames(names, from) {\n    for (const n in from)\n        names[n] = (names[n] || 0) + (from[n] || 0);\n    return names;\n}\nfunction addExprNames(names, from) {\n    return from instanceof code_1._CodeOrName ? addNames(names, from.names) : names;\n}\nfunction optimizeExpr(expr, names, constants) {\n    if (expr instanceof code_1.Name)\n        return replaceName(expr);\n    if (!canOptimize(expr))\n        return expr;\n    return new code_1._Code(expr._items.reduce((items, c) => {\n        if (c instanceof code_1.Name)\n            c = replaceName(c);\n        if (c instanceof code_1._Code)\n            items.push(...c._items);\n        else\n            items.push(c);\n        return items;\n    }, []));\n    function replaceName(n) {\n        const c = constants[n.str];\n        if (c === undefined || names[n.str] !== 1)\n            return n;\n        delete names[n.str];\n        return c;\n    }\n    function canOptimize(e) {\n        return (e instanceof code_1._Code &&\n            e._items.some((c) => c instanceof code_1.Name && names[c.str] === 1 && constants[c.str] !== undefined));\n    }\n}\nfunction subtractNames(names, from) {\n    for (const n in from)\n        names[n] = (names[n] || 0) - (from[n] || 0);\n}\nfunction not(x) {\n    return typeof x == \"boolean\" || typeof x == \"number\" || x === null ? !x : (0, code_1._) `!${par(x)}`;\n}\nexports.not = not;\nconst andCode = mappend(exports.operators.AND);\n// boolean AND (&&) expression with the passed arguments\nfunction and(...args) {\n    return args.reduce(andCode);\n}\nexports.and = and;\nconst orCode = mappend(exports.operators.OR);\n// boolean OR (||) expression with the passed arguments\nfunction or(...args) {\n    return args.reduce(orCode);\n}\nexports.or = or;\nfunction mappend(op) {\n    return (x, y) => (x === code_1.nil ? y : y === code_1.nil ? x : (0, code_1._) `${par(x)} ${op} ${par(y)}`);\n}\nfunction par(x) {\n    return x instanceof code_1.Name ? x : (0, code_1._) `(${x})`;\n}\n//# sourceMappingURL=index.js.map","\"use strict\";\nObject.defineProperty(exports, \"__esModule\", { value: true });\nexports.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;\nconst codegen_1 = require(\"./codegen\");\nconst code_1 = require(\"./codegen/code\");\n// TODO refactor to use Set\nfunction toHash(arr) {\n    const hash = {};\n    for (const item of arr)\n        hash[item] = true;\n    return hash;\n}\nexports.toHash = toHash;\nfunction alwaysValidSchema(it, schema) {\n    if (typeof schema == \"boolean\")\n        return schema;\n    if (Object.keys(schema).length === 0)\n        return true;\n    checkUnknownRules(it, schema);\n    return !schemaHasRules(schema, it.self.RULES.all);\n}\nexports.alwaysValidSchema = alwaysValidSchema;\nfunction checkUnknownRules(it, schema = it.schema) {\n    const { opts, self } = it;\n    if (!opts.strictSchema)\n        return;\n    if (typeof schema === \"boolean\")\n        return;\n    const rules = self.RULES.keywords;\n    for (const key in schema) {\n        if (!rules[key])\n            checkStrictMode(it, `unknown keyword: \"${key}\"`);\n    }\n}\nexports.checkUnknownRules = checkUnknownRules;\nfunction schemaHasRules(schema, rules) {\n    if (typeof schema == \"boolean\")\n        return !schema;\n    for (const key in schema)\n        if (rules[key])\n            return true;\n    return false;\n}\nexports.schemaHasRules = schemaHasRules;\nfunction schemaHasRulesButRef(schema, RULES) {\n    if (typeof schema == \"boolean\")\n        return !schema;\n    for (const key in schema)\n        if (key !== \"$ref\" && RULES.all[key])\n            return true;\n    return false;\n}\nexports.schemaHasRulesButRef = schemaHasRulesButRef;\nfunction schemaRefOrVal({ topSchemaRef, schemaPath }, schema, keyword, $data) {\n    if (!$data) {\n        if (typeof schema == \"number\" || typeof schema == \"boolean\")\n            return schema;\n        if (typeof schema == \"string\")\n            return (0, codegen_1._) `${schema}`;\n    }\n    return (0, codegen_1._) `${topSchemaRef}${schemaPath}${(0, codegen_1.getProperty)(keyword)}`;\n}\nexports.schemaRefOrVal = schemaRefOrVal;\nfunction unescapeFragment(str) {\n    return unescapeJsonPointer(decodeURIComponent(str));\n}\nexports.unescapeFragment = unescapeFragment;\nfunction escapeFragment(str) {\n    return encodeURIComponent(escapeJsonPointer(str));\n}\nexports.escapeFragment = escapeFragment;\nfunction escapeJsonPointer(str) {\n    if (typeof str == \"number\")\n        return `${str}`;\n    return str.replace(/~/g, \"~0\").replace(/\\//g, \"~1\");\n}\nexports.escapeJsonPointer = escapeJsonPointer;\nfunction unescapeJsonPointer(str) {\n    return str.replace(/~1/g, \"/\").replace(/~0/g, \"~\");\n}\nexports.unescapeJsonPointer = unescapeJsonPointer;\nfunction eachItem(xs, f) {\n    if (Array.isArray(xs)) {\n        for (const x of xs)\n            f(x);\n    }\n    else {\n        f(xs);\n    }\n}\nexports.eachItem = eachItem;\nfunction makeMergeEvaluated({ mergeNames, mergeToName, mergeValues, resultToName, }) {\n    return (gen, from, to, toName) => {\n        const res = to === undefined\n            ? from\n            : to instanceof codegen_1.Name\n                ? (from instanceof codegen_1.Name ? mergeNames(gen, from, to) : mergeToName(gen, from, to), to)\n                : from instanceof codegen_1.Name\n                    ? (mergeToName(gen, to, from), from)\n                    : mergeValues(from, to);\n        return toName === codegen_1.Name && !(res instanceof codegen_1.Name) ? resultToName(gen, res) : res;\n    };\n}\nexports.mergeEvaluated = {\n    props: makeMergeEvaluated({\n        mergeNames: (gen, from, to) => gen.if((0, codegen_1._) `${to} !== true && ${from} !== undefined`, () => {\n            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})`));\n        }),\n        mergeToName: (gen, from, to) => gen.if((0, codegen_1._) `${to} !== true`, () => {\n            if (from === true) {\n                gen.assign(to, true);\n            }\n            else {\n                gen.assign(to, (0, codegen_1._) `${to} || {}`);\n                setEvaluated(gen, to, from);\n            }\n        }),\n        mergeValues: (from, to) => (from === true ? true : { ...from, ...to }),\n        resultToName: evaluatedPropsToName,\n    }),\n    items: makeMergeEvaluated({\n        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}`)),\n        mergeToName: (gen, from, to) => gen.if((0, codegen_1._) `${to} !== true`, () => gen.assign(to, from === true ? true : (0, codegen_1._) `${to} > ${from} ? ${to} : ${from}`)),\n        mergeValues: (from, to) => (from === true ? true : Math.max(from, to)),\n        resultToName: (gen, items) => gen.var(\"items\", items),\n    }),\n};\nfunction evaluatedPropsToName(gen, ps) {\n    if (ps === true)\n        return gen.var(\"props\", true);\n    const props = gen.var(\"props\", (0, codegen_1._) `{}`);\n    if (ps !== undefined)\n        setEvaluated(gen, props, ps);\n    return props;\n}\nexports.evaluatedPropsToName = evaluatedPropsToName;\nfunction setEvaluated(gen, props, ps) {\n    Object.keys(ps).forEach((p) => gen.assign((0, codegen_1._) `${props}${(0, codegen_1.getProperty)(p)}`, true));\n}\nexports.setEvaluated = setEvaluated;\nconst snippets = {};\nfunction useFunc(gen, f) {\n    return gen.scopeValue(\"func\", {\n        ref: f,\n        code: snippets[f.code] || (snippets[f.code] = new code_1._Code(f.code)),\n    });\n}\nexports.useFunc = useFunc;\nvar Type;\n(function (Type) {\n    Type[Type[\"Num\"] = 0] = \"Num\";\n    Type[Type[\"Str\"] = 1] = \"Str\";\n})(Type || (exports.Type = Type = {}));\nfunction getErrorPath(dataProp, dataPropType, jsPropertySyntax) {\n    // let path\n    if (dataProp instanceof codegen_1.Name) {\n        const isNumber = dataPropType === Type.Num;\n        return jsPropertySyntax\n            ? isNumber\n                ? (0, codegen_1._) `\"[\" + ${dataProp} + \"]\"`\n                : (0, codegen_1._) `\"['\" + ${dataProp} + \"']\"`\n            : isNumber\n                ? (0, codegen_1._) `\"/\" + ${dataProp}`\n                : (0, codegen_1._) `\"/\" + ${dataProp}.replace(/~/g, \"~0\").replace(/\\\\//g, \"~1\")`; // TODO maybe use global escapePointer\n    }\n    return jsPropertySyntax ? (0, codegen_1.getProperty)(dataProp).toString() : \"/\" + escapeJsonPointer(dataProp);\n}\nexports.getErrorPath = getErrorPath;\nfunction checkStrictMode(it, msg, mode = it.opts.strictSchema) {\n    if (!mode)\n        return;\n    msg = `strict mode: ${msg}`;\n    if (mode === true)\n        throw new Error(msg);\n    it.self.logger.warn(msg);\n}\nexports.checkStrictMode = checkStrictMode;\n//# sourceMappingURL=util.js.map","\"use strict\";\nObject.defineProperty(exports, \"__esModule\", { value: true });\nconst codegen_1 = require(\"./codegen\");\nconst names = {\n    // validation function arguments\n    data: new codegen_1.Name(\"data\"), // data passed to validation function\n    // args passed from referencing schema\n    valCxt: new codegen_1.Name(\"valCxt\"), // validation/data context - should not be used directly, it is destructured to the names below\n    instancePath: new codegen_1.Name(\"instancePath\"),\n    parentData: new codegen_1.Name(\"parentData\"),\n    parentDataProperty: new codegen_1.Name(\"parentDataProperty\"),\n    rootData: new codegen_1.Name(\"rootData\"), // root data - same as the data passed to the first/top validation function\n    dynamicAnchors: new codegen_1.Name(\"dynamicAnchors\"), // used to support recursiveRef and dynamicRef\n    // function scoped variables\n    vErrors: new codegen_1.Name(\"vErrors\"), // null or array of validation errors\n    errors: new codegen_1.Name(\"errors\"), // counter of validation errors\n    this: new codegen_1.Name(\"this\"),\n    // \"globals\"\n    self: new codegen_1.Name(\"self\"),\n    scope: new codegen_1.Name(\"scope\"),\n    // JTD serialize/parse name for JSON string and position\n    json: new codegen_1.Name(\"json\"),\n    jsonPos: new codegen_1.Name(\"jsonPos\"),\n    jsonLen: new codegen_1.Name(\"jsonLen\"),\n    jsonPart: new codegen_1.Name(\"jsonPart\"),\n};\nexports.default = names;\n//# sourceMappingURL=names.js.map","\"use strict\";\nObject.defineProperty(exports, \"__esModule\", { value: true });\nexports.extendErrors = exports.resetErrorsCount = exports.reportExtraError = exports.reportError = exports.keyword$DataError = exports.keywordError = void 0;\nconst codegen_1 = require(\"./codegen\");\nconst util_1 = require(\"./util\");\nconst names_1 = require(\"./names\");\nexports.keywordError = {\n    message: ({ keyword }) => (0, codegen_1.str) `must pass \"${keyword}\" keyword validation`,\n};\nexports.keyword$DataError = {\n    message: ({ keyword, schemaType }) => schemaType\n        ? (0, codegen_1.str) `\"${keyword}\" keyword must be ${schemaType} ($data)`\n        : (0, codegen_1.str) `\"${keyword}\" keyword is invalid ($data)`,\n};\nfunction reportError(cxt, error = exports.keywordError, errorPaths, overrideAllErrors) {\n    const { it } = cxt;\n    const { gen, compositeRule, allErrors } = it;\n    const errObj = errorObjectCode(cxt, error, errorPaths);\n    if (overrideAllErrors !== null && overrideAllErrors !== void 0 ? overrideAllErrors : (compositeRule || allErrors)) {\n        addError(gen, errObj);\n    }\n    else {\n        returnErrors(it, (0, codegen_1._) `[${errObj}]`);\n    }\n}\nexports.reportError = reportError;\nfunction reportExtraError(cxt, error = exports.keywordError, errorPaths) {\n    const { it } = cxt;\n    const { gen, compositeRule, allErrors } = it;\n    const errObj = errorObjectCode(cxt, error, errorPaths);\n    addError(gen, errObj);\n    if (!(compositeRule || allErrors)) {\n        returnErrors(it, names_1.default.vErrors);\n    }\n}\nexports.reportExtraError = reportExtraError;\nfunction resetErrorsCount(gen, errsCount) {\n    gen.assign(names_1.default.errors, errsCount);\n    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)));\n}\nexports.resetErrorsCount = resetErrorsCount;\nfunction extendErrors({ gen, keyword, schemaValue, data, errsCount, it, }) {\n    /* istanbul ignore if */\n    if (errsCount === undefined)\n        throw new Error(\"ajv implementation error\");\n    const err = gen.name(\"err\");\n    gen.forRange(\"i\", errsCount, names_1.default.errors, (i) => {\n        gen.const(err, (0, codegen_1._) `${names_1.default.vErrors}[${i}]`);\n        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)));\n        gen.assign((0, codegen_1._) `${err}.schemaPath`, (0, codegen_1.str) `${it.errSchemaPath}/${keyword}`);\n        if (it.opts.verbose) {\n            gen.assign((0, codegen_1._) `${err}.schema`, schemaValue);\n            gen.assign((0, codegen_1._) `${err}.data`, data);\n        }\n    });\n}\nexports.extendErrors = extendErrors;\nfunction addError(gen, errObj) {\n    const err = gen.const(\"err\", errObj);\n    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})`);\n    gen.code((0, codegen_1._) `${names_1.default.errors}++`);\n}\nfunction returnErrors(it, errs) {\n    const { gen, validateName, schemaEnv } = it;\n    if (schemaEnv.$async) {\n        gen.throw((0, codegen_1._) `new ${it.ValidationError}(${errs})`);\n    }\n    else {\n        gen.assign((0, codegen_1._) `${validateName}.errors`, errs);\n        gen.return(false);\n    }\n}\nconst E = {\n    keyword: new codegen_1.Name(\"keyword\"),\n    schemaPath: new codegen_1.Name(\"schemaPath\"), // also used in JTD errors\n    params: new codegen_1.Name(\"params\"),\n    propertyName: new codegen_1.Name(\"propertyName\"),\n    message: new codegen_1.Name(\"message\"),\n    schema: new codegen_1.Name(\"schema\"),\n    parentSchema: new codegen_1.Name(\"parentSchema\"),\n};\nfunction errorObjectCode(cxt, error, errorPaths) {\n    const { createErrors } = cxt.it;\n    if (createErrors === false)\n        return (0, codegen_1._) `{}`;\n    return errorObject(cxt, error, errorPaths);\n}\nfunction errorObject(cxt, error, errorPaths = {}) {\n    const { gen, it } = cxt;\n    const keyValues = [\n        errorInstancePath(it, errorPaths),\n        errorSchemaPath(cxt, errorPaths),\n    ];\n    extraErrorProps(cxt, error, keyValues);\n    return gen.object(...keyValues);\n}\nfunction errorInstancePath({ errorPath }, { instancePath }) {\n    const instPath = instancePath\n        ? (0, codegen_1.str) `${errorPath}${(0, util_1.getErrorPath)(instancePath, util_1.Type.Str)}`\n        : errorPath;\n    return [names_1.default.instancePath, (0, codegen_1.strConcat)(names_1.default.instancePath, instPath)];\n}\nfunction errorSchemaPath({ keyword, it: { errSchemaPath } }, { schemaPath, parentSchema }) {\n    let schPath = parentSchema ? errSchemaPath : (0, codegen_1.str) `${errSchemaPath}/${keyword}`;\n    if (schemaPath) {\n        schPath = (0, codegen_1.str) `${schPath}${(0, util_1.getErrorPath)(schemaPath, util_1.Type.Str)}`;\n    }\n    return [E.schemaPath, schPath];\n}\nfunction extraErrorProps(cxt, { params, message }, keyValues) {\n    const { keyword, data, schemaValue, it } = cxt;\n    const { opts, propertyName, topSchemaRef, schemaPath } = it;\n    keyValues.push([E.keyword, keyword], [E.params, typeof params == \"function\" ? params(cxt) : params || (0, codegen_1._) `{}`]);\n    if (opts.messages) {\n        keyValues.push([E.message, typeof message == \"function\" ? message(cxt) : message]);\n    }\n    if (opts.verbose) {\n        keyValues.push([E.schema, schemaValue], [E.parentSchema, (0, codegen_1._) `${topSchemaRef}${schemaPath}`], [names_1.default.data, data]);\n    }\n    if (propertyName)\n        keyValues.push([E.propertyName, propertyName]);\n}\n//# sourceMappingURL=errors.js.map","\"use strict\";\nObject.defineProperty(exports, \"__esModule\", { value: true });\nexports.boolOrEmptySchema = exports.topBoolOrEmptySchema = void 0;\nconst errors_1 = require(\"../errors\");\nconst codegen_1 = require(\"../codegen\");\nconst names_1 = require(\"../names\");\nconst boolError = {\n    message: \"boolean schema is false\",\n};\nfunction topBoolOrEmptySchema(it) {\n    const { gen, schema, validateName } = it;\n    if (schema === false) {\n        falseSchemaError(it, false);\n    }\n    else if (typeof schema == \"object\" && schema.$async === true) {\n        gen.return(names_1.default.data);\n    }\n    else {\n        gen.assign((0, codegen_1._) `${validateName}.errors`, null);\n        gen.return(true);\n    }\n}\nexports.topBoolOrEmptySchema = topBoolOrEmptySchema;\nfunction boolOrEmptySchema(it, valid) {\n    const { gen, schema } = it;\n    if (schema === false) {\n        gen.var(valid, false); // TODO var\n        falseSchemaError(it);\n    }\n    else {\n        gen.var(valid, true); // TODO var\n    }\n}\nexports.boolOrEmptySchema = boolOrEmptySchema;\nfunction falseSchemaError(it, overrideAllErrors) {\n    const { gen, data } = it;\n    // TODO maybe some other interface should be used for non-keyword validation errors...\n    const cxt = {\n        gen,\n        keyword: \"false schema\",\n        data,\n        schema: false,\n        schemaCode: false,\n        schemaValue: false,\n        params: {},\n        it,\n    };\n    (0, errors_1.reportError)(cxt, boolError, undefined, overrideAllErrors);\n}\n//# sourceMappingURL=boolSchema.js.map","\"use strict\";\nObject.defineProperty(exports, \"__esModule\", { value: true });\nexports.getRules = exports.isJSONType = void 0;\nconst _jsonTypes = [\"string\", \"number\", \"integer\", \"boolean\", \"null\", \"object\", \"array\"];\nconst jsonTypes = new Set(_jsonTypes);\nfunction isJSONType(x) {\n    return typeof x == \"string\" && jsonTypes.has(x);\n}\nexports.isJSONType = isJSONType;\nfunction getRules() {\n    const groups = {\n        number: { type: \"number\", rules: [] },\n        string: { type: \"string\", rules: [] },\n        array: { type: \"array\", rules: [] },\n        object: { type: \"object\", rules: [] },\n    };\n    return {\n        types: { ...groups, integer: true, boolean: true, null: true },\n        rules: [{ rules: [] }, groups.number, groups.string, groups.array, groups.object],\n        post: { rules: [] },\n        all: {},\n        keywords: {},\n    };\n}\nexports.getRules = getRules;\n//# sourceMappingURL=rules.js.map","\"use strict\";\nObject.defineProperty(exports, \"__esModule\", { value: true });\nexports.shouldUseRule = exports.shouldUseGroup = exports.schemaHasRulesForType = void 0;\nfunction schemaHasRulesForType({ schema, self }, type) {\n    const group = self.RULES.types[type];\n    return group && group !== true && shouldUseGroup(schema, group);\n}\nexports.schemaHasRulesForType = schemaHasRulesForType;\nfunction shouldUseGroup(schema, group) {\n    return group.rules.some((rule) => shouldUseRule(schema, rule));\n}\nexports.shouldUseGroup = shouldUseGroup;\nfunction shouldUseRule(schema, rule) {\n    var _a;\n    return (schema[rule.keyword] !== undefined ||\n        ((_a = rule.definition.implements) === null || _a === void 0 ? void 0 : _a.some((kwd) => schema[kwd] !== undefined)));\n}\nexports.shouldUseRule = shouldUseRule;\n//# sourceMappingURL=applicability.js.map","\"use strict\";\nObject.defineProperty(exports, \"__esModule\", { value: true });\nexports.reportTypeError = exports.checkDataTypes = exports.checkDataType = exports.coerceAndCheckDataType = exports.getJSONTypes = exports.getSchemaTypes = exports.DataType = void 0;\nconst rules_1 = require(\"../rules\");\nconst applicability_1 = require(\"./applicability\");\nconst errors_1 = require(\"../errors\");\nconst codegen_1 = require(\"../codegen\");\nconst util_1 = require(\"../util\");\nvar DataType;\n(function (DataType) {\n    DataType[DataType[\"Correct\"] = 0] = \"Correct\";\n    DataType[DataType[\"Wrong\"] = 1] = \"Wrong\";\n})(DataType || (exports.DataType = DataType = {}));\nfunction getSchemaTypes(schema) {\n    const types = getJSONTypes(schema.type);\n    const hasNull = types.includes(\"null\");\n    if (hasNull) {\n        if (schema.nullable === false)\n            throw new Error(\"type: null contradicts nullable: false\");\n    }\n    else {\n        if (!types.length && schema.nullable !== undefined) {\n            throw new Error('\"nullable\" cannot be used without \"type\"');\n        }\n        if (schema.nullable === true)\n            types.push(\"null\");\n    }\n    return types;\n}\nexports.getSchemaTypes = getSchemaTypes;\n// eslint-disable-next-line @typescript-eslint/no-redundant-type-constituents\nfunction getJSONTypes(ts) {\n    const types = Array.isArray(ts) ? ts : ts ? [ts] : [];\n    if (types.every(rules_1.isJSONType))\n        return types;\n    throw new Error(\"type must be JSONType or JSONType[]: \" + types.join(\",\"));\n}\nexports.getJSONTypes = getJSONTypes;\nfunction coerceAndCheckDataType(it, types) {\n    const { gen, data, opts } = it;\n    const coerceTo = coerceToTypes(types, opts.coerceTypes);\n    const checkTypes = types.length > 0 &&\n        !(coerceTo.length === 0 && types.length === 1 && (0, applicability_1.schemaHasRulesForType)(it, types[0]));\n    if (checkTypes) {\n        const wrongType = checkDataTypes(types, data, opts.strictNumbers, DataType.Wrong);\n        gen.if(wrongType, () => {\n            if (coerceTo.length)\n                coerceData(it, types, coerceTo);\n            else\n                reportTypeError(it);\n        });\n    }\n    return checkTypes;\n}\nexports.coerceAndCheckDataType = coerceAndCheckDataType;\nconst COERCIBLE = new Set([\"string\", \"number\", \"integer\", \"boolean\", \"null\"]);\nfunction coerceToTypes(types, coerceTypes) {\n    return coerceTypes\n        ? types.filter((t) => COERCIBLE.has(t) || (coerceTypes === \"array\" && t === \"array\"))\n        : [];\n}\nfunction coerceData(it, types, coerceTo) {\n    const { gen, data, opts } = it;\n    const dataType = gen.let(\"dataType\", (0, codegen_1._) `typeof ${data}`);\n    const coerced = gen.let(\"coerced\", (0, codegen_1._) `undefined`);\n    if (opts.coerceTypes === \"array\") {\n        gen.if((0, codegen_1._) `${dataType} == 'object' && Array.isArray(${data}) && ${data}.length == 1`, () => gen\n            .assign(data, (0, codegen_1._) `${data}[0]`)\n            .assign(dataType, (0, codegen_1._) `typeof ${data}`)\n            .if(checkDataTypes(types, data, opts.strictNumbers), () => gen.assign(coerced, data)));\n    }\n    gen.if((0, codegen_1._) `${coerced} !== undefined`);\n    for (const t of coerceTo) {\n        if (COERCIBLE.has(t) || (t === \"array\" && opts.coerceTypes === \"array\")) {\n            coerceSpecificType(t);\n        }\n    }\n    gen.else();\n    reportTypeError(it);\n    gen.endIf();\n    gen.if((0, codegen_1._) `${coerced} !== undefined`, () => {\n        gen.assign(data, coerced);\n        assignParentData(it, coerced);\n    });\n    function coerceSpecificType(t) {\n        switch (t) {\n            case \"string\":\n                gen\n                    .elseIf((0, codegen_1._) `${dataType} == \"number\" || ${dataType} == \"boolean\"`)\n                    .assign(coerced, (0, codegen_1._) `\"\" + ${data}`)\n                    .elseIf((0, codegen_1._) `${data} === null`)\n                    .assign(coerced, (0, codegen_1._) `\"\"`);\n                return;\n            case \"number\":\n                gen\n                    .elseIf((0, codegen_1._) `${dataType} == \"boolean\" || ${data} === null\n              || (${dataType} == \"string\" && ${data} && ${data} == +${data})`)\n                    .assign(coerced, (0, codegen_1._) `+${data}`);\n                return;\n            case \"integer\":\n                gen\n                    .elseIf((0, codegen_1._) `${dataType} === \"boolean\" || ${data} === null\n              || (${dataType} === \"string\" && ${data} && ${data} == +${data} && !(${data} % 1))`)\n                    .assign(coerced, (0, codegen_1._) `+${data}`);\n                return;\n            case \"boolean\":\n                gen\n                    .elseIf((0, codegen_1._) `${data} === \"false\" || ${data} === 0 || ${data} === null`)\n                    .assign(coerced, false)\n                    .elseIf((0, codegen_1._) `${data} === \"true\" || ${data} === 1`)\n                    .assign(coerced, true);\n                return;\n            case \"null\":\n                gen.elseIf((0, codegen_1._) `${data} === \"\" || ${data} === 0 || ${data} === false`);\n                gen.assign(coerced, null);\n                return;\n            case \"array\":\n                gen\n                    .elseIf((0, codegen_1._) `${dataType} === \"string\" || ${dataType} === \"number\"\n              || ${dataType} === \"boolean\" || ${data} === null`)\n                    .assign(coerced, (0, codegen_1._) `[${data}]`);\n        }\n    }\n}\nfunction assignParentData({ gen, parentData, parentDataProperty }, expr) {\n    // TODO use gen.property\n    gen.if((0, codegen_1._) `${parentData} !== undefined`, () => gen.assign((0, codegen_1._) `${parentData}[${parentDataProperty}]`, expr));\n}\nfunction checkDataType(dataType, data, strictNums, correct = DataType.Correct) {\n    const EQ = correct === DataType.Correct ? codegen_1.operators.EQ : codegen_1.operators.NEQ;\n    let cond;\n    switch (dataType) {\n        case \"null\":\n            return (0, codegen_1._) `${data} ${EQ} null`;\n        case \"array\":\n            cond = (0, codegen_1._) `Array.isArray(${data})`;\n            break;\n        case \"object\":\n            cond = (0, codegen_1._) `${data} && typeof ${data} == \"object\" && !Array.isArray(${data})`;\n            break;\n        case \"integer\":\n            cond = numCond((0, codegen_1._) `!(${data} % 1) && !isNaN(${data})`);\n            break;\n        case \"number\":\n            cond = numCond();\n            break;\n        default:\n            return (0, codegen_1._) `typeof ${data} ${EQ} ${dataType}`;\n    }\n    return correct === DataType.Correct ? cond : (0, codegen_1.not)(cond);\n    function numCond(_cond = codegen_1.nil) {\n        return (0, codegen_1.and)((0, codegen_1._) `typeof ${data} == \"number\"`, _cond, strictNums ? (0, codegen_1._) `isFinite(${data})` : codegen_1.nil);\n    }\n}\nexports.checkDataType = checkDataType;\nfunction checkDataTypes(dataTypes, data, strictNums, correct) {\n    if (dataTypes.length === 1) {\n        return checkDataType(dataTypes[0], data, strictNums, correct);\n    }\n    let cond;\n    const types = (0, util_1.toHash)(dataTypes);\n    if (types.array && types.object) {\n        const notObj = (0, codegen_1._) `typeof ${data} != \"object\"`;\n        cond = types.null ? notObj : (0, codegen_1._) `!${data} || ${notObj}`;\n        delete types.null;\n        delete types.array;\n        delete types.object;\n    }\n    else {\n        cond = codegen_1.nil;\n    }\n    if (types.number)\n        delete types.integer;\n    for (const t in types)\n        cond = (0, codegen_1.and)(cond, checkDataType(t, data, strictNums, correct));\n    return cond;\n}\nexports.checkDataTypes = checkDataTypes;\nconst typeError = {\n    message: ({ schema }) => `must be ${schema}`,\n    params: ({ schema, schemaValue }) => typeof schema == \"string\" ? (0, codegen_1._) `{type: ${schema}}` : (0, codegen_1._) `{type: ${schemaValue}}`,\n};\nfunction reportTypeError(it) {\n    const cxt = getTypeErrorContext(it);\n    (0, errors_1.reportError)(cxt, typeError);\n}\nexports.reportTypeError = reportTypeError;\nfunction getTypeErrorContext(it) {\n    const { gen, data, schema } = it;\n    const schemaCode = (0, util_1.schemaRefOrVal)(it, schema, \"type\");\n    return {\n        gen,\n        keyword: \"type\",\n        data,\n        schema: schema.type,\n        schemaCode,\n        schemaValue: schemaCode,\n        parentSchema: schema,\n        params: {},\n        it,\n    };\n}\n//# sourceMappingURL=dataType.js.map","\"use strict\";\nObject.defineProperty(exports, \"__esModule\", { value: true });\nexports.assignDefaults = void 0;\nconst codegen_1 = require(\"../codegen\");\nconst util_1 = require(\"../util\");\nfunction assignDefaults(it, ty) {\n    const { properties, items } = it.schema;\n    if (ty === \"object\" && properties) {\n        for (const key in properties) {\n            assignDefault(it, key, properties[key].default);\n        }\n    }\n    else if (ty === \"array\" && Array.isArray(items)) {\n        items.forEach((sch, i) => assignDefault(it, i, sch.default));\n    }\n}\nexports.assignDefaults = assignDefaults;\nfunction assignDefault(it, prop, defaultValue) {\n    const { gen, compositeRule, data, opts } = it;\n    if (defaultValue === undefined)\n        return;\n    const childData = (0, codegen_1._) `${data}${(0, codegen_1.getProperty)(prop)}`;\n    if (compositeRule) {\n        (0, util_1.checkStrictMode)(it, `default is ignored for: ${childData}`);\n        return;\n    }\n    let condition = (0, codegen_1._) `${childData} === undefined`;\n    if (opts.useDefaults === \"empty\") {\n        condition = (0, codegen_1._) `${condition} || ${childData} === null || ${childData} === \"\"`;\n    }\n    // `${childData} === undefined` +\n    // (opts.useDefaults === \"empty\" ? ` || ${childData} === null || ${childData} === \"\"` : \"\")\n    gen.if(condition, (0, codegen_1._) `${childData} = ${(0, codegen_1.stringify)(defaultValue)}`);\n}\n//# sourceMappingURL=defaults.js.map","\"use strict\";\nObject.defineProperty(exports, \"__esModule\", { value: true });\nexports.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;\nconst codegen_1 = require(\"../compile/codegen\");\nconst util_1 = require(\"../compile/util\");\nconst names_1 = require(\"../compile/names\");\nconst util_2 = require(\"../compile/util\");\nfunction checkReportMissingProp(cxt, prop) {\n    const { gen, data, it } = cxt;\n    gen.if(noPropertyInData(gen, data, prop, it.opts.ownProperties), () => {\n        cxt.setParams({ missingProperty: (0, codegen_1._) `${prop}` }, true);\n        cxt.error();\n    });\n}\nexports.checkReportMissingProp = checkReportMissingProp;\nfunction checkMissingProp({ gen, data, it: { opts } }, properties, missing) {\n    return (0, codegen_1.or)(...properties.map((prop) => (0, codegen_1.and)(noPropertyInData(gen, data, prop, opts.ownProperties), (0, codegen_1._) `${missing} = ${prop}`)));\n}\nexports.checkMissingProp = checkMissingProp;\nfunction reportMissingProp(cxt, missing) {\n    cxt.setParams({ missingProperty: missing }, true);\n    cxt.error();\n}\nexports.reportMissingProp = reportMissingProp;\nfunction hasPropFunc(gen) {\n    return gen.scopeValue(\"func\", {\n        // eslint-disable-next-line @typescript-eslint/unbound-method\n        ref: Object.prototype.hasOwnProperty,\n        code: (0, codegen_1._) `Object.prototype.hasOwnProperty`,\n    });\n}\nexports.hasPropFunc = hasPropFunc;\nfunction isOwnProperty(gen, data, property) {\n    return (0, codegen_1._) `${hasPropFunc(gen)}.call(${data}, ${property})`;\n}\nexports.isOwnProperty = isOwnProperty;\nfunction propertyInData(gen, data, property, ownProperties) {\n    const cond = (0, codegen_1._) `${data}${(0, codegen_1.getProperty)(property)} !== undefined`;\n    return ownProperties ? (0, codegen_1._) `${cond} && ${isOwnProperty(gen, data, property)}` : cond;\n}\nexports.propertyInData = propertyInData;\nfunction noPropertyInData(gen, data, property, ownProperties) {\n    const cond = (0, codegen_1._) `${data}${(0, codegen_1.getProperty)(property)} === undefined`;\n    return ownProperties ? (0, codegen_1.or)(cond, (0, codegen_1.not)(isOwnProperty(gen, data, property))) : cond;\n}\nexports.noPropertyInData = noPropertyInData;\nfunction allSchemaProperties(schemaMap) {\n    return schemaMap ? Object.keys(schemaMap).filter((p) => p !== \"__proto__\") : [];\n}\nexports.allSchemaProperties = allSchemaProperties;\nfunction schemaProperties(it, schemaMap) {\n    return allSchemaProperties(schemaMap).filter((p) => !(0, util_1.alwaysValidSchema)(it, schemaMap[p]));\n}\nexports.schemaProperties = schemaProperties;\nfunction callValidateCode({ schemaCode, data, it: { gen, topSchemaRef, schemaPath, errorPath }, it }, func, context, passSchema) {\n    const dataAndSchema = passSchema ? (0, codegen_1._) `${schemaCode}, ${data}, ${topSchemaRef}${schemaPath}` : data;\n    const valCxt = [\n        [names_1.default.instancePath, (0, codegen_1.strConcat)(names_1.default.instancePath, errorPath)],\n        [names_1.default.parentData, it.parentData],\n        [names_1.default.parentDataProperty, it.parentDataProperty],\n        [names_1.default.rootData, names_1.default.rootData],\n    ];\n    if (it.opts.dynamicRef)\n        valCxt.push([names_1.default.dynamicAnchors, names_1.default.dynamicAnchors]);\n    const args = (0, codegen_1._) `${dataAndSchema}, ${gen.object(...valCxt)}`;\n    return context !== codegen_1.nil ? (0, codegen_1._) `${func}.call(${context}, ${args})` : (0, codegen_1._) `${func}(${args})`;\n}\nexports.callValidateCode = callValidateCode;\nconst newRegExp = (0, codegen_1._) `new RegExp`;\nfunction usePattern({ gen, it: { opts } }, pattern) {\n    const u = opts.unicodeRegExp ? \"u\" : \"\";\n    const { regExp } = opts.code;\n    const rx = regExp(pattern, u);\n    return gen.scopeValue(\"pattern\", {\n        key: rx.toString(),\n        ref: rx,\n        code: (0, codegen_1._) `${regExp.code === \"new RegExp\" ? newRegExp : (0, util_2.useFunc)(gen, regExp)}(${pattern}, ${u})`,\n    });\n}\nexports.usePattern = usePattern;\nfunction validateArray(cxt) {\n    const { gen, data, keyword, it } = cxt;\n    const valid = gen.name(\"valid\");\n    if (it.allErrors) {\n        const validArr = gen.let(\"valid\", true);\n        validateItems(() => gen.assign(validArr, false));\n        return validArr;\n    }\n    gen.var(valid, true);\n    validateItems(() => gen.break());\n    return valid;\n    function validateItems(notValid) {\n        const len = gen.const(\"len\", (0, codegen_1._) `${data}.length`);\n        gen.forRange(\"i\", 0, len, (i) => {\n            cxt.subschema({\n                keyword,\n                dataProp: i,\n                dataPropType: util_1.Type.Num,\n            }, valid);\n            gen.if((0, codegen_1.not)(valid), notValid);\n        });\n    }\n}\nexports.validateArray = validateArray;\nfunction validateUnion(cxt) {\n    const { gen, schema, keyword, it } = cxt;\n    /* istanbul ignore if */\n    if (!Array.isArray(schema))\n        throw new Error(\"ajv implementation error\");\n    const alwaysValid = schema.some((sch) => (0, util_1.alwaysValidSchema)(it, sch));\n    if (alwaysValid && !it.opts.unevaluated)\n        return;\n    const valid = gen.let(\"valid\", false);\n    const schValid = gen.name(\"_valid\");\n    gen.block(() => schema.forEach((_sch, i) => {\n        const schCxt = cxt.subschema({\n            keyword,\n            schemaProp: i,\n            compositeRule: true,\n        }, schValid);\n        gen.assign(valid, (0, codegen_1._) `${valid} || ${schValid}`);\n        const merged = cxt.mergeValidEvaluated(schCxt, schValid);\n        // can short-circuit if `unevaluatedProperties/Items` not supported (opts.unevaluated !== true)\n        // or if all properties and items were evaluated (it.props === true && it.items === true)\n        if (!merged)\n            gen.if((0, codegen_1.not)(valid));\n    }));\n    cxt.result(valid, () => cxt.reset(), () => cxt.error(true));\n}\nexports.validateUnion = validateUnion;\n//# sourceMappingURL=code.js.map","\"use strict\";\nObject.defineProperty(exports, \"__esModule\", { value: true });\nexports.validateKeywordUsage = exports.validSchemaType = exports.funcKeywordCode = exports.macroKeywordCode = void 0;\nconst codegen_1 = require(\"../codegen\");\nconst names_1 = require(\"../names\");\nconst code_1 = require(\"../../vocabularies/code\");\nconst errors_1 = require(\"../errors\");\nfunction macroKeywordCode(cxt, def) {\n    const { gen, keyword, schema, parentSchema, it } = cxt;\n    const macroSchema = def.macro.call(it.self, schema, parentSchema, it);\n    const schemaRef = useKeyword(gen, keyword, macroSchema);\n    if (it.opts.validateSchema !== false)\n        it.self.validateSchema(macroSchema, true);\n    const valid = gen.name(\"valid\");\n    cxt.subschema({\n        schema: macroSchema,\n        schemaPath: codegen_1.nil,\n        errSchemaPath: `${it.errSchemaPath}/${keyword}`,\n        topSchemaRef: schemaRef,\n        compositeRule: true,\n    }, valid);\n    cxt.pass(valid, () => cxt.error(true));\n}\nexports.macroKeywordCode = macroKeywordCode;\nfunction funcKeywordCode(cxt, def) {\n    var _a;\n    const { gen, keyword, schema, parentSchema, $data, it } = cxt;\n    checkAsyncKeyword(it, def);\n    const validate = !$data && def.compile ? def.compile.call(it.self, schema, parentSchema, it) : def.validate;\n    const validateRef = useKeyword(gen, keyword, validate);\n    const valid = gen.let(\"valid\");\n    cxt.block$data(valid, validateKeyword);\n    cxt.ok((_a = def.valid) !== null && _a !== void 0 ? _a : valid);\n    function validateKeyword() {\n        if (def.errors === false) {\n            assignValid();\n            if (def.modifying)\n                modifyData(cxt);\n            reportErrs(() => cxt.error());\n        }\n        else {\n            const ruleErrs = def.async ? validateAsync() : validateSync();\n            if (def.modifying)\n                modifyData(cxt);\n            reportErrs(() => addErrs(cxt, ruleErrs));\n        }\n    }\n    function validateAsync() {\n        const ruleErrs = gen.let(\"ruleErrs\", null);\n        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)));\n        return ruleErrs;\n    }\n    function validateSync() {\n        const validateErrs = (0, codegen_1._) `${validateRef}.errors`;\n        gen.assign(validateErrs, null);\n        assignValid(codegen_1.nil);\n        return validateErrs;\n    }\n    function assignValid(_await = def.async ? (0, codegen_1._) `await ` : codegen_1.nil) {\n        const passCxt = it.opts.passContext ? names_1.default.this : names_1.default.self;\n        const passSchema = !((\"compile\" in def && !$data) || def.schema === false);\n        gen.assign(valid, (0, codegen_1._) `${_await}${(0, code_1.callValidateCode)(cxt, validateRef, passCxt, passSchema)}`, def.modifying);\n    }\n    function reportErrs(errors) {\n        var _a;\n        gen.if((0, codegen_1.not)((_a = def.valid) !== null && _a !== void 0 ? _a : valid), errors);\n    }\n}\nexports.funcKeywordCode = funcKeywordCode;\nfunction modifyData(cxt) {\n    const { gen, data, it } = cxt;\n    gen.if(it.parentData, () => gen.assign(data, (0, codegen_1._) `${it.parentData}[${it.parentDataProperty}]`));\n}\nfunction addErrs(cxt, errs) {\n    const { gen } = cxt;\n    gen.if((0, codegen_1._) `Array.isArray(${errs})`, () => {\n        gen\n            .assign(names_1.default.vErrors, (0, codegen_1._) `${names_1.default.vErrors} === null ? ${errs} : ${names_1.default.vErrors}.concat(${errs})`)\n            .assign(names_1.default.errors, (0, codegen_1._) `${names_1.default.vErrors}.length`);\n        (0, errors_1.extendErrors)(cxt);\n    }, () => cxt.error());\n}\nfunction checkAsyncKeyword({ schemaEnv }, def) {\n    if (def.async && !schemaEnv.$async)\n        throw new Error(\"async keyword in sync schema\");\n}\nfunction useKeyword(gen, keyword, result) {\n    if (result === undefined)\n        throw new Error(`keyword \"${keyword}\" failed to compile`);\n    return gen.scopeValue(\"keyword\", typeof result == \"function\" ? { ref: result } : { ref: result, code: (0, codegen_1.stringify)(result) });\n}\nfunction validSchemaType(schema, schemaType, allowUndefined = false) {\n    // TODO add tests\n    return (!schemaType.length ||\n        schemaType.some((st) => st === \"array\"\n            ? Array.isArray(schema)\n            : st === \"object\"\n                ? schema && typeof schema == \"object\" && !Array.isArray(schema)\n                : typeof schema == st || (allowUndefined && typeof schema == \"undefined\")));\n}\nexports.validSchemaType = validSchemaType;\nfunction validateKeywordUsage({ schema, opts, self, errSchemaPath }, def, keyword) {\n    /* istanbul ignore if */\n    if (Array.isArray(def.keyword) ? !def.keyword.includes(keyword) : def.keyword !== keyword) {\n        throw new Error(\"ajv implementation error\");\n    }\n    const deps = def.dependencies;\n    if (deps === null || deps === void 0 ? void 0 : deps.some((kwd) => !Object.prototype.hasOwnProperty.call(schema, kwd))) {\n        throw new Error(`parent schema must have dependencies of ${keyword}: ${deps.join(\",\")}`);\n    }\n    if (def.validateSchema) {\n        const valid = def.validateSchema(schema[keyword]);\n        if (!valid) {\n            const msg = `keyword \"${keyword}\" value is invalid at path \"${errSchemaPath}\": ` +\n                self.errorsText(def.validateSchema.errors);\n            if (opts.validateSchema === \"log\")\n                self.logger.error(msg);\n            else\n                throw new Error(msg);\n        }\n    }\n}\nexports.validateKeywordUsage = validateKeywordUsage;\n//# sourceMappingURL=keyword.js.map","\"use strict\";\nObject.defineProperty(exports, \"__esModule\", { value: true });\nexports.extendSubschemaMode = exports.extendSubschemaData = exports.getSubschema = void 0;\nconst codegen_1 = require(\"../codegen\");\nconst util_1 = require(\"../util\");\nfunction getSubschema(it, { keyword, schemaProp, schema, schemaPath, errSchemaPath, topSchemaRef }) {\n    if (keyword !== undefined && schema !== undefined) {\n        throw new Error('both \"keyword\" and \"schema\" passed, only one allowed');\n    }\n    if (keyword !== undefined) {\n        const sch = it.schema[keyword];\n        return schemaProp === undefined\n            ? {\n                schema: sch,\n                schemaPath: (0, codegen_1._) `${it.schemaPath}${(0, codegen_1.getProperty)(keyword)}`,\n                errSchemaPath: `${it.errSchemaPath}/${keyword}`,\n            }\n            : {\n                schema: sch[schemaProp],\n                schemaPath: (0, codegen_1._) `${it.schemaPath}${(0, codegen_1.getProperty)(keyword)}${(0, codegen_1.getProperty)(schemaProp)}`,\n                errSchemaPath: `${it.errSchemaPath}/${keyword}/${(0, util_1.escapeFragment)(schemaProp)}`,\n            };\n    }\n    if (schema !== undefined) {\n        if (schemaPath === undefined || errSchemaPath === undefined || topSchemaRef === undefined) {\n            throw new Error('\"schemaPath\", \"errSchemaPath\" and \"topSchemaRef\" are required with \"schema\"');\n        }\n        return {\n            schema,\n            schemaPath,\n            topSchemaRef,\n            errSchemaPath,\n        };\n    }\n    throw new Error('either \"keyword\" or \"schema\" must be passed');\n}\nexports.getSubschema = getSubschema;\nfunction extendSubschemaData(subschema, it, { dataProp, dataPropType: dpType, data, dataTypes, propertyName }) {\n    if (data !== undefined && dataProp !== undefined) {\n        throw new Error('both \"data\" and \"dataProp\" passed, only one allowed');\n    }\n    const { gen } = it;\n    if (dataProp !== undefined) {\n        const { errorPath, dataPathArr, opts } = it;\n        const nextData = gen.let(\"data\", (0, codegen_1._) `${it.data}${(0, codegen_1.getProperty)(dataProp)}`, true);\n        dataContextProps(nextData);\n        subschema.errorPath = (0, codegen_1.str) `${errorPath}${(0, util_1.getErrorPath)(dataProp, dpType, opts.jsPropertySyntax)}`;\n        subschema.parentDataProperty = (0, codegen_1._) `${dataProp}`;\n        subschema.dataPathArr = [...dataPathArr, subschema.parentDataProperty];\n    }\n    if (data !== undefined) {\n        const nextData = data instanceof codegen_1.Name ? data : gen.let(\"data\", data, true); // replaceable if used once?\n        dataContextProps(nextData);\n        if (propertyName !== undefined)\n            subschema.propertyName = propertyName;\n        // TODO something is possibly wrong here with not changing parentDataProperty and not appending dataPathArr\n    }\n    if (dataTypes)\n        subschema.dataTypes = dataTypes;\n    function dataContextProps(_nextData) {\n        subschema.data = _nextData;\n        subschema.dataLevel = it.dataLevel + 1;\n        subschema.dataTypes = [];\n        it.definedProperties = new Set();\n        subschema.parentData = it.data;\n        subschema.dataNames = [...it.dataNames, _nextData];\n    }\n}\nexports.extendSubschemaData = extendSubschemaData;\nfunction extendSubschemaMode(subschema, { jtdDiscriminator, jtdMetadata, compositeRule, createErrors, allErrors }) {\n    if (compositeRule !== undefined)\n        subschema.compositeRule = compositeRule;\n    if (createErrors !== undefined)\n        subschema.createErrors = createErrors;\n    if (allErrors !== undefined)\n        subschema.allErrors = allErrors;\n    subschema.jtdDiscriminator = jtdDiscriminator; // not inherited\n    subschema.jtdMetadata = jtdMetadata; // not inherited\n}\nexports.extendSubschemaMode = extendSubschemaMode;\n//# sourceMappingURL=subschema.js.map","'use strict';\n\n// do not edit .js files directly - edit src/index.jst\n\n\n\nmodule.exports = function equal(a, b) {\n  if (a === b) return true;\n\n  if (a && b && typeof a == 'object' && typeof b == 'object') {\n    if (a.constructor !== b.constructor) return false;\n\n    var length, i, keys;\n    if (Array.isArray(a)) {\n      length = a.length;\n      if (length != b.length) return false;\n      for (i = length; i-- !== 0;)\n        if (!equal(a[i], b[i])) return false;\n      return true;\n    }\n\n\n\n    if (a.constructor === RegExp) return a.source === b.source && a.flags === b.flags;\n    if (a.valueOf !== Object.prototype.valueOf) return a.valueOf() === b.valueOf();\n    if (a.toString !== Object.prototype.toString) return a.toString() === b.toString();\n\n    keys = Object.keys(a);\n    length = keys.length;\n    if (length !== Object.keys(b).length) return false;\n\n    for (i = length; i-- !== 0;)\n      if (!Object.prototype.hasOwnProperty.call(b, keys[i])) return false;\n\n    for (i = length; i-- !== 0;) {\n      var key = keys[i];\n\n      if (!equal(a[key], b[key])) return false;\n    }\n\n    return true;\n  }\n\n  // true if both NaN, false otherwise\n  return a!==a && b!==b;\n};\n","'use strict';\n\nvar traverse = module.exports = function (schema, opts, cb) {\n  // Legacy support for v0.3.1 and earlier.\n  if (typeof opts == 'function') {\n    cb = opts;\n    opts = {};\n  }\n\n  cb = opts.cb || cb;\n  var pre = (typeof cb == 'function') ? cb : cb.pre || function() {};\n  var post = cb.post || function() {};\n\n  _traverse(opts, pre, post, schema, '', schema);\n};\n\n\ntraverse.keywords = {\n  additionalItems: true,\n  items: true,\n  contains: true,\n  additionalProperties: true,\n  propertyNames: true,\n  not: true,\n  if: true,\n  then: true,\n  else: true\n};\n\ntraverse.arrayKeywords = {\n  items: true,\n  allOf: true,\n  anyOf: true,\n  oneOf: true\n};\n\ntraverse.propsKeywords = {\n  $defs: true,\n  definitions: true,\n  properties: true,\n  patternProperties: true,\n  dependencies: true\n};\n\ntraverse.skipKeywords = {\n  default: true,\n  enum: true,\n  const: true,\n  required: true,\n  maximum: true,\n  minimum: true,\n  exclusiveMaximum: true,\n  exclusiveMinimum: true,\n  multipleOf: true,\n  maxLength: true,\n  minLength: true,\n  pattern: true,\n  format: true,\n  maxItems: true,\n  minItems: true,\n  uniqueItems: true,\n  maxProperties: true,\n  minProperties: true\n};\n\n\nfunction _traverse(opts, pre, post, schema, jsonPtr, rootSchema, parentJsonPtr, parentKeyword, parentSchema, keyIndex) {\n  if (schema && typeof schema == 'object' && !Array.isArray(schema)) {\n    pre(schema, jsonPtr, rootSchema, parentJsonPtr, parentKeyword, parentSchema, keyIndex);\n    for (var key in schema) {\n      var sch = schema[key];\n      if (Array.isArray(sch)) {\n        if (key in traverse.arrayKeywords) {\n          for (var i=0; i<sch.length; i++)\n            _traverse(opts, pre, post, sch[i], jsonPtr + '/' + key + '/' + i, rootSchema, jsonPtr, key, schema, i);\n        }\n      } else if (key in traverse.propsKeywords) {\n        if (sch && typeof sch == 'object') {\n          for (var prop in sch)\n            _traverse(opts, pre, post, sch[prop], jsonPtr + '/' + key + '/' + escapeJsonPtr(prop), rootSchema, jsonPtr, key, schema, prop);\n        }\n      } else if (key in traverse.keywords || (opts.allKeys && !(key in traverse.skipKeywords))) {\n        _traverse(opts, pre, post, sch, jsonPtr + '/' + key, rootSchema, jsonPtr, key, schema);\n      }\n    }\n    post(schema, jsonPtr, rootSchema, parentJsonPtr, parentKeyword, parentSchema, keyIndex);\n  }\n}\n\n\nfunction escapeJsonPtr(str) {\n  return str.replace(/~/g, '~0').replace(/\\//g, '~1');\n}\n","\"use strict\";\nObject.defineProperty(exports, \"__esModule\", { value: true });\nexports.getSchemaRefs = exports.resolveUrl = exports.normalizeId = exports._getFullPath = exports.getFullPath = exports.inlineRef = void 0;\nconst util_1 = require(\"./util\");\nconst equal = require(\"fast-deep-equal\");\nconst traverse = require(\"json-schema-traverse\");\n// TODO refactor to use keyword definitions\nconst SIMPLE_INLINED = new Set([\n    \"type\",\n    \"format\",\n    \"pattern\",\n    \"maxLength\",\n    \"minLength\",\n    \"maxProperties\",\n    \"minProperties\",\n    \"maxItems\",\n    \"minItems\",\n    \"maximum\",\n    \"minimum\",\n    \"uniqueItems\",\n    \"multipleOf\",\n    \"required\",\n    \"enum\",\n    \"const\",\n]);\nfunction inlineRef(schema, limit = true) {\n    if (typeof schema == \"boolean\")\n        return true;\n    if (limit === true)\n        return !hasRef(schema);\n    if (!limit)\n        return false;\n    return countKeys(schema) <= limit;\n}\nexports.inlineRef = inlineRef;\nconst REF_KEYWORDS = new Set([\n    \"$ref\",\n    \"$recursiveRef\",\n    \"$recursiveAnchor\",\n    \"$dynamicRef\",\n    \"$dynamicAnchor\",\n]);\nfunction hasRef(schema) {\n    for (const key in schema) {\n        if (REF_KEYWORDS.has(key))\n            return true;\n        const sch = schema[key];\n        if (Array.isArray(sch) && sch.some(hasRef))\n            return true;\n        if (typeof sch == \"object\" && hasRef(sch))\n            return true;\n    }\n    return false;\n}\nfunction countKeys(schema) {\n    let count = 0;\n    for (const key in schema) {\n        if (key === \"$ref\")\n            return Infinity;\n        count++;\n        if (SIMPLE_INLINED.has(key))\n            continue;\n        if (typeof schema[key] == \"object\") {\n            (0, util_1.eachItem)(schema[key], (sch) => (count += countKeys(sch)));\n        }\n        if (count === Infinity)\n            return Infinity;\n    }\n    return count;\n}\nfunction getFullPath(resolver, id = \"\", normalize) {\n    if (normalize !== false)\n        id = normalizeId(id);\n    const p = resolver.parse(id);\n    return _getFullPath(resolver, p);\n}\nexports.getFullPath = getFullPath;\nfunction _getFullPath(resolver, p) {\n    const serialized = resolver.serialize(p);\n    return serialized.split(\"#\")[0] + \"#\";\n}\nexports._getFullPath = _getFullPath;\nconst TRAILING_SLASH_HASH = /#\\/?$/;\nfunction normalizeId(id) {\n    return id ? id.replace(TRAILING_SLASH_HASH, \"\") : \"\";\n}\nexports.normalizeId = normalizeId;\nfunction resolveUrl(resolver, baseId, id) {\n    id = normalizeId(id);\n    return resolver.resolve(baseId, id);\n}\nexports.resolveUrl = resolveUrl;\nconst ANCHOR = /^[a-z_][-a-z0-9._]*$/i;\nfunction getSchemaRefs(schema, baseId) {\n    if (typeof schema == \"boolean\")\n        return {};\n    const { schemaId, uriResolver } = this.opts;\n    const schId = normalizeId(schema[schemaId] || baseId);\n    const baseIds = { \"\": schId };\n    const pathPrefix = getFullPath(uriResolver, schId, false);\n    const localRefs = {};\n    const schemaRefs = new Set();\n    traverse(schema, { allKeys: true }, (sch, jsonPtr, _, parentJsonPtr) => {\n        if (parentJsonPtr === undefined)\n            return;\n        const fullPath = pathPrefix + jsonPtr;\n        let innerBaseId = baseIds[parentJsonPtr];\n        if (typeof sch[schemaId] == \"string\")\n            innerBaseId = addRef.call(this, sch[schemaId]);\n        addAnchor.call(this, sch.$anchor);\n        addAnchor.call(this, sch.$dynamicAnchor);\n        baseIds[jsonPtr] = innerBaseId;\n        function addRef(ref) {\n            // eslint-disable-next-line @typescript-eslint/unbound-method\n            const _resolve = this.opts.uriResolver.resolve;\n            ref = normalizeId(innerBaseId ? _resolve(innerBaseId, ref) : ref);\n            if (schemaRefs.has(ref))\n                throw ambiguos(ref);\n            schemaRefs.add(ref);\n            let schOrRef = this.refs[ref];\n            if (typeof schOrRef == \"string\")\n                schOrRef = this.refs[schOrRef];\n            if (typeof schOrRef == \"object\") {\n                checkAmbiguosRef(sch, schOrRef.schema, ref);\n            }\n            else if (ref !== normalizeId(fullPath)) {\n                if (ref[0] === \"#\") {\n                    checkAmbiguosRef(sch, localRefs[ref], ref);\n                    localRefs[ref] = sch;\n                }\n                else {\n                    this.refs[ref] = fullPath;\n                }\n            }\n            return ref;\n        }\n        function addAnchor(anchor) {\n            if (typeof anchor == \"string\") {\n                if (!ANCHOR.test(anchor))\n                    throw new Error(`invalid anchor \"${anchor}\"`);\n                addRef.call(this, `#${anchor}`);\n            }\n        }\n    });\n    return localRefs;\n    function checkAmbiguosRef(sch1, sch2, ref) {\n        if (sch2 !== undefined && !equal(sch1, sch2))\n            throw ambiguos(ref);\n    }\n    function ambiguos(ref) {\n        return new Error(`reference \"${ref}\" resolves to more than one schema`);\n    }\n}\nexports.getSchemaRefs = getSchemaRefs;\n//# sourceMappingURL=resolve.js.map","\"use strict\";\nObject.defineProperty(exports, \"__esModule\", { value: true });\nexports.getData = exports.KeywordCxt = exports.validateFunctionCode = void 0;\nconst boolSchema_1 = require(\"./boolSchema\");\nconst dataType_1 = require(\"./dataType\");\nconst applicability_1 = require(\"./applicability\");\nconst dataType_2 = require(\"./dataType\");\nconst defaults_1 = require(\"./defaults\");\nconst keyword_1 = require(\"./keyword\");\nconst subschema_1 = require(\"./subschema\");\nconst codegen_1 = require(\"../codegen\");\nconst names_1 = require(\"../names\");\nconst resolve_1 = require(\"../resolve\");\nconst util_1 = require(\"../util\");\nconst errors_1 = require(\"../errors\");\n// schema compilation - generates validation function, subschemaCode (below) is used for subschemas\nfunction validateFunctionCode(it) {\n    if (isSchemaObj(it)) {\n        checkKeywords(it);\n        if (schemaCxtHasRules(it)) {\n            topSchemaObjCode(it);\n            return;\n        }\n    }\n    validateFunction(it, () => (0, boolSchema_1.topBoolOrEmptySchema)(it));\n}\nexports.validateFunctionCode = validateFunctionCode;\nfunction validateFunction({ gen, validateName, schema, schemaEnv, opts }, body) {\n    if (opts.code.es5) {\n        gen.func(validateName, (0, codegen_1._) `${names_1.default.data}, ${names_1.default.valCxt}`, schemaEnv.$async, () => {\n            gen.code((0, codegen_1._) `\"use strict\"; ${funcSourceUrl(schema, opts)}`);\n            destructureValCxtES5(gen, opts);\n            gen.code(body);\n        });\n    }\n    else {\n        gen.func(validateName, (0, codegen_1._) `${names_1.default.data}, ${destructureValCxt(opts)}`, schemaEnv.$async, () => gen.code(funcSourceUrl(schema, opts)).code(body));\n    }\n}\nfunction destructureValCxt(opts) {\n    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}}={}`;\n}\nfunction destructureValCxtES5(gen, opts) {\n    gen.if(names_1.default.valCxt, () => {\n        gen.var(names_1.default.instancePath, (0, codegen_1._) `${names_1.default.valCxt}.${names_1.default.instancePath}`);\n        gen.var(names_1.default.parentData, (0, codegen_1._) `${names_1.default.valCxt}.${names_1.default.parentData}`);\n        gen.var(names_1.default.parentDataProperty, (0, codegen_1._) `${names_1.default.valCxt}.${names_1.default.parentDataProperty}`);\n        gen.var(names_1.default.rootData, (0, codegen_1._) `${names_1.default.valCxt}.${names_1.default.rootData}`);\n        if (opts.dynamicRef)\n            gen.var(names_1.default.dynamicAnchors, (0, codegen_1._) `${names_1.default.valCxt}.${names_1.default.dynamicAnchors}`);\n    }, () => {\n        gen.var(names_1.default.instancePath, (0, codegen_1._) `\"\"`);\n        gen.var(names_1.default.parentData, (0, codegen_1._) `undefined`);\n        gen.var(names_1.default.parentDataProperty, (0, codegen_1._) `undefined`);\n        gen.var(names_1.default.rootData, names_1.default.data);\n        if (opts.dynamicRef)\n            gen.var(names_1.default.dynamicAnchors, (0, codegen_1._) `{}`);\n    });\n}\nfunction topSchemaObjCode(it) {\n    const { schema, opts, gen } = it;\n    validateFunction(it, () => {\n        if (opts.$comment && schema.$comment)\n            commentKeyword(it);\n        checkNoDefault(it);\n        gen.let(names_1.default.vErrors, null);\n        gen.let(names_1.default.errors, 0);\n        if (opts.unevaluated)\n            resetEvaluated(it);\n        typeAndKeywords(it);\n        returnResults(it);\n    });\n    return;\n}\nfunction resetEvaluated(it) {\n    // TODO maybe some hook to execute it in the end to check whether props/items are Name, as in assignEvaluated\n    const { gen, validateName } = it;\n    it.evaluated = gen.const(\"evaluated\", (0, codegen_1._) `${validateName}.evaluated`);\n    gen.if((0, codegen_1._) `${it.evaluated}.dynamicProps`, () => gen.assign((0, codegen_1._) `${it.evaluated}.props`, (0, codegen_1._) `undefined`));\n    gen.if((0, codegen_1._) `${it.evaluated}.dynamicItems`, () => gen.assign((0, codegen_1._) `${it.evaluated}.items`, (0, codegen_1._) `undefined`));\n}\nfunction funcSourceUrl(schema, opts) {\n    const schId = typeof schema == \"object\" && schema[opts.schemaId];\n    return schId && (opts.code.source || opts.code.process) ? (0, codegen_1._) `/*# sourceURL=${schId} */` : codegen_1.nil;\n}\n// schema compilation - this function is used recursively to generate code for sub-schemas\nfunction subschemaCode(it, valid) {\n    if (isSchemaObj(it)) {\n        checkKeywords(it);\n        if (schemaCxtHasRules(it)) {\n            subSchemaObjCode(it, valid);\n            return;\n        }\n    }\n    (0, boolSchema_1.boolOrEmptySchema)(it, valid);\n}\nfunction schemaCxtHasRules({ schema, self }) {\n    if (typeof schema == \"boolean\")\n        return !schema;\n    for (const key in schema)\n        if (self.RULES.all[key])\n            return true;\n    return false;\n}\nfunction isSchemaObj(it) {\n    return typeof it.schema != \"boolean\";\n}\nfunction subSchemaObjCode(it, valid) {\n    const { schema, gen, opts } = it;\n    if (opts.$comment && schema.$comment)\n        commentKeyword(it);\n    updateContext(it);\n    checkAsyncSchema(it);\n    const errsCount = gen.const(\"_errs\", names_1.default.errors);\n    typeAndKeywords(it, errsCount);\n    // TODO var\n    gen.var(valid, (0, codegen_1._) `${errsCount} === ${names_1.default.errors}`);\n}\nfunction checkKeywords(it) {\n    (0, util_1.checkUnknownRules)(it);\n    checkRefsAndKeywords(it);\n}\nfunction typeAndKeywords(it, errsCount) {\n    if (it.opts.jtd)\n        return schemaKeywords(it, [], false, errsCount);\n    const types = (0, dataType_1.getSchemaTypes)(it.schema);\n    const checkedTypes = (0, dataType_1.coerceAndCheckDataType)(it, types);\n    schemaKeywords(it, types, !checkedTypes, errsCount);\n}\nfunction checkRefsAndKeywords(it) {\n    const { schema, errSchemaPath, opts, self } = it;\n    if (schema.$ref && opts.ignoreKeywordsWithRef && (0, util_1.schemaHasRulesButRef)(schema, self.RULES)) {\n        self.logger.warn(`$ref: keywords ignored in schema at path \"${errSchemaPath}\"`);\n    }\n}\nfunction checkNoDefault(it) {\n    const { schema, opts } = it;\n    if (schema.default !== undefined && opts.useDefaults && opts.strictSchema) {\n        (0, util_1.checkStrictMode)(it, \"default is ignored in the schema root\");\n    }\n}\nfunction updateContext(it) {\n    const schId = it.schema[it.opts.schemaId];\n    if (schId)\n        it.baseId = (0, resolve_1.resolveUrl)(it.opts.uriResolver, it.baseId, schId);\n}\nfunction checkAsyncSchema(it) {\n    if (it.schema.$async && !it.schemaEnv.$async)\n        throw new Error(\"async schema in sync schema\");\n}\nfunction commentKeyword({ gen, schemaEnv, schema, errSchemaPath, opts }) {\n    const msg = schema.$comment;\n    if (opts.$comment === true) {\n        gen.code((0, codegen_1._) `${names_1.default.self}.logger.log(${msg})`);\n    }\n    else if (typeof opts.$comment == \"function\") {\n        const schemaPath = (0, codegen_1.str) `${errSchemaPath}/$comment`;\n        const rootName = gen.scopeValue(\"root\", { ref: schemaEnv.root });\n        gen.code((0, codegen_1._) `${names_1.default.self}.opts.$comment(${msg}, ${schemaPath}, ${rootName}.schema)`);\n    }\n}\nfunction returnResults(it) {\n    const { gen, schemaEnv, validateName, ValidationError, opts } = it;\n    if (schemaEnv.$async) {\n        // TODO assign unevaluated\n        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})`));\n    }\n    else {\n        gen.assign((0, codegen_1._) `${validateName}.errors`, names_1.default.vErrors);\n        if (opts.unevaluated)\n            assignEvaluated(it);\n        gen.return((0, codegen_1._) `${names_1.default.errors} === 0`);\n    }\n}\nfunction assignEvaluated({ gen, evaluated, props, items }) {\n    if (props instanceof codegen_1.Name)\n        gen.assign((0, codegen_1._) `${evaluated}.props`, props);\n    if (items instanceof codegen_1.Name)\n        gen.assign((0, codegen_1._) `${evaluated}.items`, items);\n}\nfunction schemaKeywords(it, types, typeErrors, errsCount) {\n    const { gen, schema, data, allErrors, opts, self } = it;\n    const { RULES } = self;\n    if (schema.$ref && (opts.ignoreKeywordsWithRef || !(0, util_1.schemaHasRulesButRef)(schema, RULES))) {\n        gen.block(() => keywordCode(it, \"$ref\", RULES.all.$ref.definition)); // TODO typecast\n        return;\n    }\n    if (!opts.jtd)\n        checkStrictTypes(it, types);\n    gen.block(() => {\n        for (const group of RULES.rules)\n            groupKeywords(group);\n        groupKeywords(RULES.post);\n    });\n    function groupKeywords(group) {\n        if (!(0, applicability_1.shouldUseGroup)(schema, group))\n            return;\n        if (group.type) {\n            gen.if((0, dataType_2.checkDataType)(group.type, data, opts.strictNumbers));\n            iterateKeywords(it, group);\n            if (types.length === 1 && types[0] === group.type && typeErrors) {\n                gen.else();\n                (0, dataType_2.reportTypeError)(it);\n            }\n            gen.endIf();\n        }\n        else {\n            iterateKeywords(it, group);\n        }\n        // TODO make it \"ok\" call?\n        if (!allErrors)\n            gen.if((0, codegen_1._) `${names_1.default.errors} === ${errsCount || 0}`);\n    }\n}\nfunction iterateKeywords(it, group) {\n    const { gen, schema, opts: { useDefaults }, } = it;\n    if (useDefaults)\n        (0, defaults_1.assignDefaults)(it, group.type);\n    gen.block(() => {\n        for (const rule of group.rules) {\n            if ((0, applicability_1.shouldUseRule)(schema, rule)) {\n                keywordCode(it, rule.keyword, rule.definition, group.type);\n            }\n        }\n    });\n}\nfunction checkStrictTypes(it, types) {\n    if (it.schemaEnv.meta || !it.opts.strictTypes)\n        return;\n    checkContextTypes(it, types);\n    if (!it.opts.allowUnionTypes)\n        checkMultipleTypes(it, types);\n    checkKeywordTypes(it, it.dataTypes);\n}\nfunction checkContextTypes(it, types) {\n    if (!types.length)\n        return;\n    if (!it.dataTypes.length) {\n        it.dataTypes = types;\n        return;\n    }\n    types.forEach((t) => {\n        if (!includesType(it.dataTypes, t)) {\n            strictTypesError(it, `type \"${t}\" not allowed by context \"${it.dataTypes.join(\",\")}\"`);\n        }\n    });\n    narrowSchemaTypes(it, types);\n}\nfunction checkMultipleTypes(it, ts) {\n    if (ts.length > 1 && !(ts.length === 2 && ts.includes(\"null\"))) {\n        strictTypesError(it, \"use allowUnionTypes to allow union type keyword\");\n    }\n}\nfunction checkKeywordTypes(it, ts) {\n    const rules = it.self.RULES.all;\n    for (const keyword in rules) {\n        const rule = rules[keyword];\n        if (typeof rule == \"object\" && (0, applicability_1.shouldUseRule)(it.schema, rule)) {\n            const { type } = rule.definition;\n            if (type.length && !type.some((t) => hasApplicableType(ts, t))) {\n                strictTypesError(it, `missing type \"${type.join(\",\")}\" for keyword \"${keyword}\"`);\n            }\n        }\n    }\n}\nfunction hasApplicableType(schTs, kwdT) {\n    return schTs.includes(kwdT) || (kwdT === \"number\" && schTs.includes(\"integer\"));\n}\nfunction includesType(ts, t) {\n    return ts.includes(t) || (t === \"integer\" && ts.includes(\"number\"));\n}\nfunction narrowSchemaTypes(it, withTypes) {\n    const ts = [];\n    for (const t of it.dataTypes) {\n        if (includesType(withTypes, t))\n            ts.push(t);\n        else if (withTypes.includes(\"integer\") && t === \"number\")\n            ts.push(\"integer\");\n    }\n    it.dataTypes = ts;\n}\nfunction strictTypesError(it, msg) {\n    const schemaPath = it.schemaEnv.baseId + it.errSchemaPath;\n    msg += ` at \"${schemaPath}\" (strictTypes)`;\n    (0, util_1.checkStrictMode)(it, msg, it.opts.strictTypes);\n}\nclass KeywordCxt {\n    constructor(it, def, keyword) {\n        (0, keyword_1.validateKeywordUsage)(it, def, keyword);\n        this.gen = it.gen;\n        this.allErrors = it.allErrors;\n        this.keyword = keyword;\n        this.data = it.data;\n        this.schema = it.schema[keyword];\n        this.$data = def.$data && it.opts.$data && this.schema && this.schema.$data;\n        this.schemaValue = (0, util_1.schemaRefOrVal)(it, this.schema, keyword, this.$data);\n        this.schemaType = def.schemaType;\n        this.parentSchema = it.schema;\n        this.params = {};\n        this.it = it;\n        this.def = def;\n        if (this.$data) {\n            this.schemaCode = it.gen.const(\"vSchema\", getData(this.$data, it));\n        }\n        else {\n            this.schemaCode = this.schemaValue;\n            if (!(0, keyword_1.validSchemaType)(this.schema, def.schemaType, def.allowUndefined)) {\n                throw new Error(`${keyword} value must be ${JSON.stringify(def.schemaType)}`);\n            }\n        }\n        if (\"code\" in def ? def.trackErrors : def.errors !== false) {\n            this.errsCount = it.gen.const(\"_errs\", names_1.default.errors);\n        }\n    }\n    result(condition, successAction, failAction) {\n        this.failResult((0, codegen_1.not)(condition), successAction, failAction);\n    }\n    failResult(condition, successAction, failAction) {\n        this.gen.if(condition);\n        if (failAction)\n            failAction();\n        else\n            this.error();\n        if (successAction) {\n            this.gen.else();\n            successAction();\n            if (this.allErrors)\n                this.gen.endIf();\n        }\n        else {\n            if (this.allErrors)\n                this.gen.endIf();\n            else\n                this.gen.else();\n        }\n    }\n    pass(condition, failAction) {\n        this.failResult((0, codegen_1.not)(condition), undefined, failAction);\n    }\n    fail(condition) {\n        if (condition === undefined) {\n            this.error();\n            if (!this.allErrors)\n                this.gen.if(false); // this branch will be removed by gen.optimize\n            return;\n        }\n        this.gen.if(condition);\n        this.error();\n        if (this.allErrors)\n            this.gen.endIf();\n        else\n            this.gen.else();\n    }\n    fail$data(condition) {\n        if (!this.$data)\n            return this.fail(condition);\n        const { schemaCode } = this;\n        this.fail((0, codegen_1._) `${schemaCode} !== undefined && (${(0, codegen_1.or)(this.invalid$data(), condition)})`);\n    }\n    error(append, errorParams, errorPaths) {\n        if (errorParams) {\n            this.setParams(errorParams);\n            this._error(append, errorPaths);\n            this.setParams({});\n            return;\n        }\n        this._error(append, errorPaths);\n    }\n    _error(append, errorPaths) {\n        ;\n        (append ? errors_1.reportExtraError : errors_1.reportError)(this, this.def.error, errorPaths);\n    }\n    $dataError() {\n        (0, errors_1.reportError)(this, this.def.$dataError || errors_1.keyword$DataError);\n    }\n    reset() {\n        if (this.errsCount === undefined)\n            throw new Error('add \"trackErrors\" to keyword definition');\n        (0, errors_1.resetErrorsCount)(this.gen, this.errsCount);\n    }\n    ok(cond) {\n        if (!this.allErrors)\n            this.gen.if(cond);\n    }\n    setParams(obj, assign) {\n        if (assign)\n            Object.assign(this.params, obj);\n        else\n            this.params = obj;\n    }\n    block$data(valid, codeBlock, $dataValid = codegen_1.nil) {\n        this.gen.block(() => {\n            this.check$data(valid, $dataValid);\n            codeBlock();\n        });\n    }\n    check$data(valid = codegen_1.nil, $dataValid = codegen_1.nil) {\n        if (!this.$data)\n            return;\n        const { gen, schemaCode, schemaType, def } = this;\n        gen.if((0, codegen_1.or)((0, codegen_1._) `${schemaCode} === undefined`, $dataValid));\n        if (valid !== codegen_1.nil)\n            gen.assign(valid, true);\n        if (schemaType.length || def.validateSchema) {\n            gen.elseIf(this.invalid$data());\n            this.$dataError();\n            if (valid !== codegen_1.nil)\n                gen.assign(valid, false);\n        }\n        gen.else();\n    }\n    invalid$data() {\n        const { gen, schemaCode, schemaType, def, it } = this;\n        return (0, codegen_1.or)(wrong$DataType(), invalid$DataSchema());\n        function wrong$DataType() {\n            if (schemaType.length) {\n                /* istanbul ignore if */\n                if (!(schemaCode instanceof codegen_1.Name))\n                    throw new Error(\"ajv implementation error\");\n                const st = Array.isArray(schemaType) ? schemaType : [schemaType];\n                return (0, codegen_1._) `${(0, dataType_2.checkDataTypes)(st, schemaCode, it.opts.strictNumbers, dataType_2.DataType.Wrong)}`;\n            }\n            return codegen_1.nil;\n        }\n        function invalid$DataSchema() {\n            if (def.validateSchema) {\n                const validateSchemaRef = gen.scopeValue(\"validate$data\", { ref: def.validateSchema }); // TODO value.code for standalone\n                return (0, codegen_1._) `!${validateSchemaRef}(${schemaCode})`;\n            }\n            return codegen_1.nil;\n        }\n    }\n    subschema(appl, valid) {\n        const subschema = (0, subschema_1.getSubschema)(this.it, appl);\n        (0, subschema_1.extendSubschemaData)(subschema, this.it, appl);\n        (0, subschema_1.extendSubschemaMode)(subschema, appl);\n        const nextContext = { ...this.it, ...subschema, items: undefined, props: undefined };\n        subschemaCode(nextContext, valid);\n        return nextContext;\n    }\n    mergeEvaluated(schemaCxt, toName) {\n        const { it, gen } = this;\n        if (!it.opts.unevaluated)\n            return;\n        if (it.props !== true && schemaCxt.props !== undefined) {\n            it.props = util_1.mergeEvaluated.props(gen, schemaCxt.props, it.props, toName);\n        }\n        if (it.items !== true && schemaCxt.items !== undefined) {\n            it.items = util_1.mergeEvaluated.items(gen, schemaCxt.items, it.items, toName);\n        }\n    }\n    mergeValidEvaluated(schemaCxt, valid) {\n        const { it, gen } = this;\n        if (it.opts.unevaluated && (it.props !== true || it.items !== true)) {\n            gen.if(valid, () => this.mergeEvaluated(schemaCxt, codegen_1.Name));\n            return true;\n        }\n    }\n}\nexports.KeywordCxt = KeywordCxt;\nfunction keywordCode(it, keyword, def, ruleType) {\n    const cxt = new KeywordCxt(it, def, keyword);\n    if (\"code\" in def) {\n        def.code(cxt, ruleType);\n    }\n    else if (cxt.$data && def.validate) {\n        (0, keyword_1.funcKeywordCode)(cxt, def);\n    }\n    else if (\"macro\" in def) {\n        (0, keyword_1.macroKeywordCode)(cxt, def);\n    }\n    else if (def.compile || def.validate) {\n        (0, keyword_1.funcKeywordCode)(cxt, def);\n    }\n}\nconst JSON_POINTER = /^\\/(?:[^~]|~0|~1)*$/;\nconst RELATIVE_JSON_POINTER = /^([0-9]+)(#|\\/(?:[^~]|~0|~1)*)?$/;\nfunction getData($data, { dataLevel, dataNames, dataPathArr }) {\n    let jsonPointer;\n    let data;\n    if ($data === \"\")\n        return names_1.default.rootData;\n    if ($data[0] === \"/\") {\n        if (!JSON_POINTER.test($data))\n            throw new Error(`Invalid JSON-pointer: ${$data}`);\n        jsonPointer = $data;\n        data = names_1.default.rootData;\n    }\n    else {\n        const matches = RELATIVE_JSON_POINTER.exec($data);\n        if (!matches)\n            throw new Error(`Invalid JSON-pointer: ${$data}`);\n        const up = +matches[1];\n        jsonPointer = matches[2];\n        if (jsonPointer === \"#\") {\n            if (up >= dataLevel)\n                throw new Error(errorMsg(\"property/index\", up));\n            return dataPathArr[dataLevel - up];\n        }\n        if (up > dataLevel)\n            throw new Error(errorMsg(\"data\", up));\n        data = dataNames[dataLevel - up];\n        if (!jsonPointer)\n            return data;\n    }\n    let expr = data;\n    const segments = jsonPointer.split(\"/\");\n    for (const segment of segments) {\n        if (segment) {\n            data = (0, codegen_1._) `${data}${(0, codegen_1.getProperty)((0, util_1.unescapeJsonPointer)(segment))}`;\n            expr = (0, codegen_1._) `${expr} && ${data}`;\n        }\n    }\n    return expr;\n    function errorMsg(pointerType, up) {\n        return `Cannot access ${pointerType} ${up} levels up, current level is ${dataLevel}`;\n    }\n}\nexports.getData = getData;\n//# sourceMappingURL=index.js.map","\"use strict\";\nObject.defineProperty(exports, \"__esModule\", { value: true });\nclass ValidationError extends Error {\n    constructor(errors) {\n        super(\"validation failed\");\n        this.errors = errors;\n        this.ajv = this.validation = true;\n    }\n}\nexports.default = ValidationError;\n//# sourceMappingURL=validation_error.js.map","\"use strict\";\nObject.defineProperty(exports, \"__esModule\", { value: true });\nconst resolve_1 = require(\"./resolve\");\nclass MissingRefError extends Error {\n    constructor(resolver, baseId, ref, msg) {\n        super(msg || `can't resolve reference ${ref} from id ${baseId}`);\n        this.missingRef = (0, resolve_1.resolveUrl)(resolver, baseId, ref);\n        this.missingSchema = (0, resolve_1.normalizeId)((0, resolve_1.getFullPath)(resolver, this.missingRef));\n    }\n}\nexports.default = MissingRefError;\n//# sourceMappingURL=ref_error.js.map","\"use strict\";\nObject.defineProperty(exports, \"__esModule\", { value: true });\nexports.resolveSchema = exports.getCompilingSchema = exports.resolveRef = exports.compileSchema = exports.SchemaEnv = void 0;\nconst codegen_1 = require(\"./codegen\");\nconst validation_error_1 = require(\"../runtime/validation_error\");\nconst names_1 = require(\"./names\");\nconst resolve_1 = require(\"./resolve\");\nconst util_1 = require(\"./util\");\nconst validate_1 = require(\"./validate\");\nclass SchemaEnv {\n    constructor(env) {\n        var _a;\n        this.refs = {};\n        this.dynamicAnchors = {};\n        let schema;\n        if (typeof env.schema == \"object\")\n            schema = env.schema;\n        this.schema = env.schema;\n        this.schemaId = env.schemaId;\n        this.root = env.root || this;\n        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\"]);\n        this.schemaPath = env.schemaPath;\n        this.localRefs = env.localRefs;\n        this.meta = env.meta;\n        this.$async = schema === null || schema === void 0 ? void 0 : schema.$async;\n        this.refs = {};\n    }\n}\nexports.SchemaEnv = SchemaEnv;\n// let codeSize = 0\n// let nodeCount = 0\n// Compiles schema in SchemaEnv\nfunction compileSchema(sch) {\n    // TODO refactor - remove compilations\n    const _sch = getCompilingSchema.call(this, sch);\n    if (_sch)\n        return _sch;\n    const rootId = (0, resolve_1.getFullPath)(this.opts.uriResolver, sch.root.baseId); // TODO if getFullPath removed 1 tests fails\n    const { es5, lines } = this.opts.code;\n    const { ownProperties } = this.opts;\n    const gen = new codegen_1.CodeGen(this.scope, { es5, lines, ownProperties });\n    let _ValidationError;\n    if (sch.$async) {\n        _ValidationError = gen.scopeValue(\"Error\", {\n            ref: validation_error_1.default,\n            code: (0, codegen_1._) `require(\"ajv/dist/runtime/validation_error\").default`,\n        });\n    }\n    const validateName = gen.scopeName(\"validate\");\n    sch.validateName = validateName;\n    const schemaCxt = {\n        gen,\n        allErrors: this.opts.allErrors,\n        data: names_1.default.data,\n        parentData: names_1.default.parentData,\n        parentDataProperty: names_1.default.parentDataProperty,\n        dataNames: [names_1.default.data],\n        dataPathArr: [codegen_1.nil], // TODO can its length be used as dataLevel if nil is removed?\n        dataLevel: 0,\n        dataTypes: [],\n        definedProperties: new Set(),\n        topSchemaRef: gen.scopeValue(\"schema\", this.opts.code.source === true\n            ? { ref: sch.schema, code: (0, codegen_1.stringify)(sch.schema) }\n            : { ref: sch.schema }),\n        validateName,\n        ValidationError: _ValidationError,\n        schema: sch.schema,\n        schemaEnv: sch,\n        rootId,\n        baseId: sch.baseId || rootId,\n        schemaPath: codegen_1.nil,\n        errSchemaPath: sch.schemaPath || (this.opts.jtd ? \"\" : \"#\"),\n        errorPath: (0, codegen_1._) `\"\"`,\n        opts: this.opts,\n        self: this,\n    };\n    let sourceCode;\n    try {\n        this._compilations.add(sch);\n        (0, validate_1.validateFunctionCode)(schemaCxt);\n        gen.optimize(this.opts.code.optimize);\n        // gen.optimize(1)\n        const validateCode = gen.toString();\n        sourceCode = `${gen.scopeRefs(names_1.default.scope)}return ${validateCode}`;\n        // console.log((codeSize += sourceCode.length), (nodeCount += gen.nodeCount))\n        if (this.opts.code.process)\n            sourceCode = this.opts.code.process(sourceCode, sch);\n        // console.log(\"\\n\\n\\n *** \\n\", sourceCode)\n        const makeValidate = new Function(`${names_1.default.self}`, `${names_1.default.scope}`, sourceCode);\n        const validate = makeValidate(this, this.scope.get());\n        this.scope.value(validateName, { ref: validate });\n        validate.errors = null;\n        validate.schema = sch.schema;\n        validate.schemaEnv = sch;\n        if (sch.$async)\n            validate.$async = true;\n        if (this.opts.code.source === true) {\n            validate.source = { validateName, validateCode, scopeValues: gen._values };\n        }\n        if (this.opts.unevaluated) {\n            const { props, items } = schemaCxt;\n            validate.evaluated = {\n                props: props instanceof codegen_1.Name ? undefined : props,\n                items: items instanceof codegen_1.Name ? undefined : items,\n                dynamicProps: props instanceof codegen_1.Name,\n                dynamicItems: items instanceof codegen_1.Name,\n            };\n            if (validate.source)\n                validate.source.evaluated = (0, codegen_1.stringify)(validate.evaluated);\n        }\n        sch.validate = validate;\n        return sch;\n    }\n    catch (e) {\n        delete sch.validate;\n        delete sch.validateName;\n        if (sourceCode)\n            this.logger.error(\"Error compiling schema, function code:\", sourceCode);\n        // console.log(\"\\n\\n\\n *** \\n\", sourceCode, this.opts)\n        throw e;\n    }\n    finally {\n        this._compilations.delete(sch);\n    }\n}\nexports.compileSchema = compileSchema;\nfunction resolveRef(root, baseId, ref) {\n    var _a;\n    ref = (0, resolve_1.resolveUrl)(this.opts.uriResolver, baseId, ref);\n    const schOrFunc = root.refs[ref];\n    if (schOrFunc)\n        return schOrFunc;\n    let _sch = resolve.call(this, root, ref);\n    if (_sch === undefined) {\n        const schema = (_a = root.localRefs) === null || _a === void 0 ? void 0 : _a[ref]; // TODO maybe localRefs should hold SchemaEnv\n        const { schemaId } = this.opts;\n        if (schema)\n            _sch = new SchemaEnv({ schema, schemaId, root, baseId });\n    }\n    if (_sch === undefined)\n        return;\n    return (root.refs[ref] = inlineOrCompile.call(this, _sch));\n}\nexports.resolveRef = resolveRef;\nfunction inlineOrCompile(sch) {\n    if ((0, resolve_1.inlineRef)(sch.schema, this.opts.inlineRefs))\n        return sch.schema;\n    return sch.validate ? sch : compileSchema.call(this, sch);\n}\n// Index of schema compilation in the currently compiled list\nfunction getCompilingSchema(schEnv) {\n    for (const sch of this._compilations) {\n        if (sameSchemaEnv(sch, schEnv))\n            return sch;\n    }\n}\nexports.getCompilingSchema = getCompilingSchema;\nfunction sameSchemaEnv(s1, s2) {\n    return s1.schema === s2.schema && s1.root === s2.root && s1.baseId === s2.baseId;\n}\n// resolve and compile the references ($ref)\n// TODO returns AnySchemaObject (if the schema can be inlined) or validation function\nfunction resolve(root, // information about the root schema for the current schema\nref // reference to resolve\n) {\n    let sch;\n    while (typeof (sch = this.refs[ref]) == \"string\")\n        ref = sch;\n    return sch || this.schemas[ref] || resolveSchema.call(this, root, ref);\n}\n// Resolve schema, its root and baseId\nfunction resolveSchema(root, // root object with properties schema, refs TODO below SchemaEnv is assigned to it\nref // reference to resolve\n) {\n    const p = this.opts.uriResolver.parse(ref);\n    const refPath = (0, resolve_1._getFullPath)(this.opts.uriResolver, p);\n    let baseId = (0, resolve_1.getFullPath)(this.opts.uriResolver, root.baseId, undefined);\n    // TODO `Object.keys(root.schema).length > 0` should not be needed - but removing breaks 2 tests\n    if (Object.keys(root.schema).length > 0 && refPath === baseId) {\n        return getJsonPointer.call(this, p, root);\n    }\n    const id = (0, resolve_1.normalizeId)(refPath);\n    const schOrRef = this.refs[id] || this.schemas[id];\n    if (typeof schOrRef == \"string\") {\n        const sch = resolveSchema.call(this, root, schOrRef);\n        if (typeof (sch === null || sch === void 0 ? void 0 : sch.schema) !== \"object\")\n            return;\n        return getJsonPointer.call(this, p, sch);\n    }\n    if (typeof (schOrRef === null || schOrRef === void 0 ? void 0 : schOrRef.schema) !== \"object\")\n        return;\n    if (!schOrRef.validate)\n        compileSchema.call(this, schOrRef);\n    if (id === (0, resolve_1.normalizeId)(ref)) {\n        const { schema } = schOrRef;\n        const { schemaId } = this.opts;\n        const schId = schema[schemaId];\n        if (schId)\n            baseId = (0, resolve_1.resolveUrl)(this.opts.uriResolver, baseId, schId);\n        return new SchemaEnv({ schema, schemaId, root, baseId });\n    }\n    return getJsonPointer.call(this, p, schOrRef);\n}\nexports.resolveSchema = resolveSchema;\nconst PREVENT_SCOPE_CHANGE = new Set([\n    \"properties\",\n    \"patternProperties\",\n    \"enum\",\n    \"dependencies\",\n    \"definitions\",\n]);\nfunction getJsonPointer(parsedRef, { baseId, schema, root }) {\n    var _a;\n    if (((_a = parsedRef.fragment) === null || _a === void 0 ? void 0 : _a[0]) !== \"/\")\n        return;\n    for (const part of parsedRef.fragment.slice(1).split(\"/\")) {\n        if (typeof schema === \"boolean\")\n            return;\n        const partSchema = schema[(0, util_1.unescapeFragment)(part)];\n        if (partSchema === undefined)\n            return;\n        schema = partSchema;\n        // TODO PREVENT_SCOPE_CHANGE could be defined in keyword def?\n        const schId = typeof schema === \"object\" && schema[this.opts.schemaId];\n        if (!PREVENT_SCOPE_CHANGE.has(part) && schId) {\n            baseId = (0, resolve_1.resolveUrl)(this.opts.uriResolver, baseId, schId);\n        }\n    }\n    let env;\n    if (typeof schema != \"boolean\" && schema.$ref && !(0, util_1.schemaHasRulesButRef)(schema, this.RULES)) {\n        const $ref = (0, resolve_1.resolveUrl)(this.opts.uriResolver, baseId, schema.$ref);\n        env = resolveSchema.call(this, root, $ref);\n    }\n    // even though resolution failed we need to return SchemaEnv to throw exception\n    // so that compileAsync loads missing schema.\n    const { schemaId } = this.opts;\n    env = env || new SchemaEnv({ schema, schemaId, root, baseId });\n    if (env.schema !== env.root.schema)\n        return env;\n    return undefined;\n}\n//# sourceMappingURL=index.js.map","","'use strict'\n\n/** @type {(value: string) => boolean} */\nconst isUUID = RegExp.prototype.test.bind(/^[\\da-f]{8}-[\\da-f]{4}-[\\da-f]{4}-[\\da-f]{4}-[\\da-f]{12}$/iu)\n\n/** @type {(value: string) => boolean} */\nconst 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)\n\n/** @type {(value: string) => boolean} */\nconst isPort = RegExp.prototype.test.bind(/^\\d*$/u)\n\n/** @type {(value: string) => boolean} */\nconst isHexPair = RegExp.prototype.test.bind(/^[\\da-f]{2}$/iu)\n\n/** @type {(value: string) => boolean} */\nconst isUnreserved = RegExp.prototype.test.bind(/^[\\da-z\\-._~]$/iu)\n\n/** @type {(value: string) => boolean} */\nconst isPathCharacter = RegExp.prototype.test.bind(/^[A-Za-z0-9\\-._~!$&'()*+,;=:@/]$/u)\n\n/** @type {(value: string) => boolean} */\nconst isQueryFragmentCharacter = RegExp.prototype.test.bind(/^[A-Za-z0-9\\-._~!$&'()*+,;=:@/?]$/u)\n\n/** @type {(value: string) => boolean} */\nconst isUserinfoCharacter = RegExp.prototype.test.bind(/^[A-Za-z0-9\\-._~!$&'()*+,;=:]$/u)\n\nconst BYTE_HEX = new Array(256)\n{\n  const HEX_DIGITS = '0123456789ABCDEF'\n  for (let i = 0; i < 256; i++) {\n    BYTE_HEX[i] = '%' + HEX_DIGITS[i >> 4] + HEX_DIGITS[i & 0xF]\n  }\n}\nfunction percentEncodeNonAscii (cp) {\n  if (cp < 0x800) {\n    return BYTE_HEX[0xC0 | (cp >> 6)] +\n           BYTE_HEX[0x80 | (cp & 0x3F)]\n  }\n  if (cp < 0x10000) {\n    return BYTE_HEX[0xE0 | (cp >> 12)] +\n           BYTE_HEX[0x80 | ((cp >> 6) & 0x3F)] +\n           BYTE_HEX[0x80 | (cp & 0x3F)]\n  }\n  return BYTE_HEX[0xF0 | (cp >> 18)] +\n         BYTE_HEX[0x80 | ((cp >> 12) & 0x3F)] +\n         BYTE_HEX[0x80 | ((cp >> 6) & 0x3F)] +\n         BYTE_HEX[0x80 | (cp & 0x3F)]\n}\n\n/**\n * @param {Array<string>} input\n * @returns {string}\n */\nfunction stringArrayToHexStripped (input) {\n  let acc = ''\n  let code = 0\n  let i = 0\n\n  for (i = 0; i < input.length; i++) {\n    code = input[i].charCodeAt(0)\n    if (code === 48) {\n      continue\n    }\n    if (!((code >= 48 && code <= 57) || (code >= 65 && code <= 70) || (code >= 97 && code <= 102))) {\n      return ''\n    }\n    acc += input[i]\n    break\n  }\n\n  for (i += 1; i < input.length; i++) {\n    code = input[i].charCodeAt(0)\n    if (!((code >= 48 && code <= 57) || (code >= 65 && code <= 70) || (code >= 97 && code <= 102))) {\n      return ''\n    }\n    acc += input[i]\n  }\n  return acc\n}\n\n/** @type {(value: string) => boolean} */\nconst isHextet = RegExp.prototype.test.bind(/^[\\dA-Fa-f]{1,4}$/)\n\n/** @type {(value: string) => boolean} */\nconst isIPvFuture = RegExp.prototype.test.bind(/^[vV][\\dA-Fa-f]+\\.[A-Za-z\\d\\-._~!$&'()*+,;=:]+$/)\n\n/** @type {(value: string) => boolean} */\nconst isZoneCharacter = RegExp.prototype.test.bind(/^[A-Za-z\\d\\-._~]$/)\n\n/**\n * @param {string} value\n * @returns {boolean}\n */\nconst nonSimpleDomain = RegExp.prototype.test.bind(/[^!\"$&'()*+,\\-.;=_`a-z{}~]/u)\n\n/**\n * @param {string} zone\n * @returns {boolean}\n */\nfunction isZoneIdentifier (zone) {\n  if (zone.length === 0) return false\n\n  for (let i = 0; i < zone.length; i++) {\n    if (isZoneCharacter(zone[i])) continue\n    if (zone[i] === '%' && i + 2 < zone.length && isHexPair(zone.slice(i + 1, i + 3))) {\n      i += 2\n      continue\n    }\n    return false\n  }\n\n  return true\n}\n\n/**\n * Compresses the longest run of zero hextets to \"::\" per RFC 5952. A run of a\n * single zero hextet is left uncompressed. On ties the leftmost run wins.\n *\n * @param {string[]} hextets\n * @returns {string}\n */\nfunction compressIPv6ZeroRun (hextets) {\n  let bestStart = -1\n  let bestLength = 0\n  let runStart = -1\n  let runLength = 0\n  for (let i = 0; i < hextets.length; i++) {\n    if (hextets[i] === '0') {\n      if (runStart === -1) runStart = i\n      runLength++\n      if (runLength > bestLength) {\n        bestLength = runLength\n        bestStart = runStart\n      }\n    } else {\n      runStart = -1\n      runLength = 0\n    }\n  }\n\n  if (bestLength < 2) return hextets.join(':')\n\n  const head = hextets.slice(0, bestStart).join(':')\n  const tail = hextets.slice(bestStart + bestLength).join(':')\n  return head + '::' + tail\n}\n\n/**\n * Validates an IPv6 address against the alternatives in RFC 3986 section\n * 3.2.2 and returns the same address with leading hextet zeroes removed.\n * An embedded IPv4 address counts as two hextets and is only valid at the end.\n *\n * @param {string} input\n * @returns {string|undefined}\n */\nfunction normalizeIPv6Address (input) {\n  const compression = input.indexOf('::')\n  if (compression !== -1 && input.indexOf('::', compression + 1) !== -1) return undefined\n\n  const left = compression === -1 ? input.split(':') : input.slice(0, compression).split(':')\n  const right = compression === -1 ? [] : input.slice(compression + 2).split(':')\n  if (compression !== -1) {\n    if (left.length === 1 && left[0] === '') left.length = 0\n    if (right.length === 1 && right[0] === '') right.length = 0\n  }\n\n  const parts = left.concat(right)\n  let hextetCount = 0\n  for (let i = 0; i < parts.length; i++) {\n    const part = parts[i]\n    if (part === '') return undefined\n\n    if (part.indexOf('.') !== -1) {\n      if (i !== parts.length - 1 || (compression !== -1 && right.length === 0) || !isIPv4(part)) return undefined\n      hextetCount += 2\n      continue\n    }\n\n    if (!isHextet(part)) return undefined\n    parts[i] = parseInt(part, 16).toString(16)\n    hextetCount++\n  }\n\n  if (compression === -1) {\n    if (hextetCount !== 8) return undefined\n    return compressIPv6ZeroRun(parts)\n  }\n  if (hextetCount >= 8) return undefined\n\n  // expand \"::\" then re-compress the longest run for a canonical result\n  const expanded = parts.slice(0, left.length)\n  for (let i = hextetCount; i < 8; i++) expanded.push('0')\n  for (let i = left.length; i < parts.length; i++) expanded.push(parts[i])\n  return compressIPv6ZeroRun(expanded)\n}\n\n/**\n * @typedef {Object} NormalizeIPv6Result\n * @property {string} host - The normalized host.\n * @property {string} [escapedHost] - The escaped host.\n * @property {boolean} isIPV6 - Indicates if the host is an IPv6 address.\n * @property {boolean} [isIPVFuture] - Indicates if the host is an IPvFuture literal.\n * @property {boolean} [error] - Indicates if a bracketed IP literal is malformed.\n */\n\n/**\n * Validates and normalizes a bracketed IP literal. Raw zone separators remain\n * accepted for backwards compatibility, while encoded separators and zone\n * contents follow RFC 6874.\n *\n * @param {string} host\n * @returns {NormalizeIPv6Result}\n */\nfunction normalizeIPv6 (host) {\n  const bracketed = host[0] === '[' && host[host.length - 1] === ']'\n  const hasBracket = host[0] === '[' || host[host.length - 1] === ']'\n  if (hasBracket && !bracketed) return { host, isIPV6: false, error: true }\n\n  let input = bracketed ? host.slice(1, -1) : host\n  if (bracketed && isIPvFuture(input)) {\n    input = input.toLowerCase()\n    return { host: `[${input}]`, escapedHost: input, isIPV6: false, isIPVFuture: true }\n  }\n\n  if (findToken(input, ':') < 2) {\n    return { host, isIPV6: false, error: bracketed }\n  }\n\n  let zoneIdentifier = ''\n  const zoneSeparator = input.indexOf('%')\n  if (zoneSeparator !== -1) {\n    const separatorLength = input.slice(zoneSeparator, zoneSeparator + 3).toLowerCase() === '%25' ? 3 : 1\n    zoneIdentifier = input.slice(zoneSeparator + separatorLength)\n    if (!isZoneIdentifier(zoneIdentifier)) return { host, isIPV6: false, error: true }\n    input = input.slice(0, zoneSeparator)\n  }\n\n  const address = normalizeIPv6Address(input)\n  if (address === undefined) return { host, isIPV6: false, error: true }\n\n  return {\n    host: address + (zoneIdentifier ? '%' + zoneIdentifier : ''),\n    escapedHost: address + (zoneIdentifier ? '%25' + zoneIdentifier : ''),\n    isIPV6: true\n  }\n}\n\n/**\n * @param {string} str\n * @param {string} token\n * @returns {number}\n */\nfunction findToken (str, token) {\n  let ind = 0\n  for (let i = 0; i < str.length; i++) {\n    if (str[i] === token) ind++\n  }\n  return ind\n}\n\n/**\n * @param {string} path\n * @returns {string}\n *\n * @see https://datatracker.ietf.org/doc/html/rfc3986#section-5.2.4\n */\nfunction removeDotSegments (path) {\n  let input = path\n  const output = []\n  let nextSlash = -1\n  let len = 0\n\n  // eslint-disable-next-line no-cond-assign\n  while (len = input.length) {\n    if (len === 1) {\n      if (input === '.') {\n        break\n      } else if (input === '/') {\n        output.push('/')\n        break\n      } else {\n        output.push(input)\n        break\n      }\n    } else if (len === 2) {\n      if (input[0] === '.') {\n        if (input[1] === '.') {\n          break\n        } else if (input[1] === '/') {\n          input = input.slice(2)\n          continue\n        }\n      } else if (input[0] === '/') {\n        if (input[1] === '.' || input[1] === '/') {\n          output.push('/')\n          break\n        }\n      }\n    } else if (len === 3) {\n      if (input === '/..') {\n        if (output.length !== 0) {\n          output.pop()\n        }\n        output.push('/')\n        break\n      }\n    }\n    if (input[0] === '.') {\n      if (input[1] === '.') {\n        if (input[2] === '/') {\n          input = input.slice(3)\n          continue\n        }\n      } else if (input[1] === '/') {\n        input = input.slice(2)\n        continue\n      }\n    } else if (input[0] === '/') {\n      if (input[1] === '.') {\n        if (input[2] === '/') {\n          input = input.slice(2)\n          continue\n        } else if (input[2] === '.') {\n          if (input[3] === '/') {\n            input = input.slice(3)\n            if (output.length !== 0) {\n              output.pop()\n            }\n            continue\n          }\n        }\n      }\n    }\n\n    // Rule 2E: Move normal path segment to output\n    if ((nextSlash = input.indexOf('/', 1)) === -1) {\n      output.push(input)\n      break\n    } else {\n      output.push(input.slice(0, nextSlash))\n      input = input.slice(nextSlash)\n    }\n  }\n\n  return output.join('')\n}\n\n/**\n * Re-escape RFC 3986 gen-delims that must not appear literally in the host.\n * After the URI regex parses, these characters cannot be literal in the host\n * field, so any that appear after decoding came from percent-encoding and\n * must be restored to prevent authority structure changes.\n *\n * @param {string} host\n * @param {boolean} isIP - true for IPv4/IPv6 hosts (skip colon re-escaping)\n * @returns {string}\n */\nconst HOST_DELIMS = { '@': '%40', '/': '%2F', '?': '%3F', '#': '%23', ':': '%3A' }\nconst HOST_DELIM_RE = /[@/?#:]/g\nconst HOST_DELIM_NO_COLON_RE = /[@/?#]/g\n\nfunction reescapeHostDelimiters (host, isIP) {\n  const re = isIP ? HOST_DELIM_NO_COLON_RE : HOST_DELIM_RE\n  re.lastIndex = 0\n  return host.replace(re, (ch) => HOST_DELIMS[ch])\n}\n\n/**\n * Normalizes percent escapes and optionally decodes only unreserved ASCII bytes.\n * Reserved delimiters such as `%2F` stay escaped; `%2E` is unreserved.\n *\n * @param {string} input\n * @param {boolean} [decodeUnreserved=false]\n * @returns {string}\n */\nfunction normalizePercentEncoding (input, decodeUnreserved = false) {\n  if (input.indexOf('%') === -1) {\n    return input\n  }\n\n  let output = ''\n\n  for (let i = 0; i < input.length; i++) {\n    if (input[i] === '%' && i + 2 < input.length) {\n      const hex = input.slice(i + 1, i + 3)\n      if (isHexPair(hex)) {\n        const normalizedHex = hex.toUpperCase()\n        const decoded = String.fromCharCode(parseInt(normalizedHex, 16))\n\n        if (decodeUnreserved && isUnreserved(decoded)) {\n          output += decoded\n        } else {\n          output += '%' + normalizedHex\n        }\n\n        i += 2\n        continue\n      }\n    }\n\n    output += input[i]\n  }\n\n  return output\n}\n\n/**\n * Normalizes path data without turning reserved escapes into live path syntax.\n * Valid escapes are uppercased, raw unsafe characters are escaped, and only\n * unreserved bytes that are not `.` are decoded.\n *\n * @param {string} input\n * @returns {string}\n */\nfunction normalizePathEncoding (input) {\n  let output = ''\n\n  for (let i = 0; i < input.length; i++) {\n    const ch = input[i]\n    if (ch === '%' && i + 2 < input.length) {\n      const hex = input.slice(i + 1, i + 3)\n      if (isHexPair(hex)) {\n        const normalizedHex = hex.toUpperCase()\n        const decoded = String.fromCharCode(parseInt(normalizedHex, 16))\n\n        if (decoded !== '.' && isUnreserved(decoded)) {\n          output += decoded\n        } else {\n          output += '%' + normalizedHex\n        }\n\n        i += 2\n        continue\n      }\n    }\n\n    if (isPathCharacter(ch)) {\n      output += ch\n    } else {\n      const code = input.charCodeAt(i)\n      if (code < 0x80) {\n        output += isEscapeSafe(code) ? ch : BYTE_HEX[code]\n      } else if (code < 0xD800 || code > 0xDFFF) {\n        output += percentEncodeNonAscii(code)\n      } else if (code <= 0xDBFF && i + 1 < input.length) {\n        const low = input.charCodeAt(i + 1)\n        if (low >= 0xDC00 && low <= 0xDFFF) {\n          output += percentEncodeNonAscii(0x10000 + ((code - 0xD800) << 10) + (low - 0xDC00))\n          i++\n        } else {\n          output += percentEncodeNonAscii(0xFFFD)\n        }\n      } else {\n        output += percentEncodeNonAscii(0xFFFD)\n      }\n    }\n  }\n\n  return output\n}\n\n/**\n * Serializes a path without rewriting reserved data. Raw RFC 3986 path\n * characters remain literal, valid escapes are preserved and uppercased, and\n * everything else is UTF-8 percent-encoded. In a path-noscheme, a colon in the\n * first segment must be escaped so the result cannot be parsed as a scheme.\n *\n * @param {string} input\n * @param {boolean} [pathNoScheme=false]\n * @returns {string}\n */\nfunction serializePathEncoding (input, pathNoScheme = false) {\n  let output = ''\n  let firstSegment = pathNoScheme && input[0] !== '/'\n\n  for (let i = 0; i < input.length; i++) {\n    const ch = input[i]\n    if (ch === '%' && i + 2 < input.length) {\n      const hex = input.slice(i + 1, i + 3)\n      if (isHexPair(hex)) {\n        output += '%' + hex.toUpperCase()\n        i += 2\n        continue\n      }\n    }\n\n    if (ch === '/') {\n      firstSegment = false\n    }\n\n    if (isPathCharacter(ch) && (ch !== ':' || !firstSegment)) {\n      output += ch\n    } else {\n      const code = input.charCodeAt(i)\n      if (code < 0x80) {\n        output += BYTE_HEX[code]\n      } else if (code < 0xD800 || code > 0xDFFF) {\n        output += percentEncodeNonAscii(code)\n      } else if (code <= 0xDBFF && i + 1 < input.length) {\n        const low = input.charCodeAt(i + 1)\n        if (low >= 0xDC00 && low <= 0xDFFF) {\n          output += percentEncodeNonAscii(0x10000 + ((code - 0xD800) << 10) + (low - 0xDC00))\n          i++\n        } else {\n          output += percentEncodeNonAscii(0xFFFD)\n        }\n      } else {\n        output += percentEncodeNonAscii(0xFFFD)\n      }\n    }\n  }\n\n  return output\n}\n\n/**\n * Percent-encodes a URI component using its RFC 3986 literal character set.\n * Existing valid escapes are preserved and normalized to uppercase hex.\n *\n * @param {string} input\n * @param {(value: string) => boolean} isAllowed\n * @returns {string}\n */\nfunction encodeComponent (input, isAllowed) {\n  let output = ''\n\n  for (let i = 0; i < input.length; i++) {\n    const ch = input[i]\n    if (ch === '%' && i + 2 < input.length) {\n      const hex = input.slice(i + 1, i + 3)\n      if (isHexPair(hex)) {\n        output += '%' + hex.toUpperCase()\n        i += 2\n        continue\n      }\n    }\n\n    if (isAllowed(ch)) {\n      output += ch\n    } else {\n      const code = input.charCodeAt(i)\n      if (code < 0x80) {\n        output += BYTE_HEX[code]\n      } else if (code < 0xD800 || code > 0xDFFF) {\n        output += percentEncodeNonAscii(code)\n      } else if (code <= 0xDBFF && i + 1 < input.length) {\n        const low = input.charCodeAt(i + 1)\n        if (low >= 0xDC00 && low <= 0xDFFF) {\n          output += percentEncodeNonAscii(0x10000 + ((code - 0xD800) << 10) + (low - 0xDC00))\n          i++\n        } else {\n          output += percentEncodeNonAscii(0xFFFD)\n        }\n      } else {\n        output += percentEncodeNonAscii(0xFFFD)\n      }\n    }\n  }\n\n  return output\n}\n\n/**\n * Encodes userinfo while preserving its RFC 3986 §3.2.1 literal characters.\n * In particular, authority delimiters such as `@`, `/`, `?`, and `#` are data.\n *\n * @param {string} input\n * @returns {string}\n */\nfunction encodeUserinfo (input) {\n  return encodeComponent(input, isUserinfoCharacter)\n}\n\n/**\n * Encodes query data using the RFC 3986 §3.4 grammar. A literal `#` must be\n * escaped because it would otherwise begin the fragment component.\n *\n * @param {string} input\n * @returns {string}\n */\nfunction encodeQuery (input) {\n  return encodeComponent(input, isQueryFragmentCharacter)\n}\n\n/**\n * Encodes fragment data using the RFC 3986 §3.5 grammar.\n *\n * @param {string} input\n * @returns {string}\n */\nfunction encodeFragment (input) {\n  return encodeComponent(input, isQueryFragmentCharacter)\n}\n\nfunction isEscapeSafe (cp) {\n  return (\n    (cp >= 0x30 && cp <= 0x39) ||\n    (cp >= 0x41 && cp <= 0x5A) ||\n    (cp >= 0x61 && cp <= 0x7A) ||\n    cp === 0x2A || cp === 0x2B || cp === 0x2D || cp === 0x2E ||\n    cp === 0x2F || cp === 0x40 || cp === 0x5F\n  )\n}\n\n/**\n * Normalizes the percent-encoding of a query or fragment component.\n *\n * Like `normalizePathEncoding`, but uses the query/fragment character set\n * (which additionally allows `?`) and decodes `.` since it has no dot-segment\n * meaning outside of a path.\n *\n * @param {string} input\n * @returns {string}\n */\nfunction normalizeQueryFragmentEncoding (input) {\n  let output = ''\n\n  for (let i = 0; i < input.length; i++) {\n    const ch = input[i]\n    if (ch === '%' && i + 2 < input.length) {\n      const hex = input.slice(i + 1, i + 3)\n      if (isHexPair(hex)) {\n        const normalizedHex = hex.toUpperCase()\n        const decoded = String.fromCharCode(parseInt(normalizedHex, 16))\n\n        if (isUnreserved(decoded)) {\n          output += decoded\n        } else {\n          output += '%' + normalizedHex\n        }\n\n        i += 2\n        continue\n      }\n    }\n\n    if (isQueryFragmentCharacter(ch)) {\n      output += ch\n    } else {\n      const code = input.charCodeAt(i)\n      if (code < 0x80) {\n        output += isEscapeSafe(code) ? ch : BYTE_HEX[code]\n      } else if (code < 0xD800 || code > 0xDFFF) {\n        output += percentEncodeNonAscii(code)\n      } else if (code <= 0xDBFF && i + 1 < input.length) {\n        const low = input.charCodeAt(i + 1)\n        if (low >= 0xDC00 && low <= 0xDFFF) {\n          output += percentEncodeNonAscii(0x10000 + ((code - 0xD800) << 10) + (low - 0xDC00))\n          i++\n        } else {\n          output += percentEncodeNonAscii(0xFFFD)\n        }\n      } else {\n        output += percentEncodeNonAscii(0xFFFD)\n      }\n    }\n  }\n\n  return output\n}\n\n/**\n * Escapes a component while preserving existing valid percent escapes.\n *\n * @param {string} input\n * @returns {string}\n */\nfunction escapePreservingEscapes (input) {\n  let output = ''\n\n  for (let i = 0; i < input.length; i++) {\n    if (input[i] === '%' && i + 2 < input.length) {\n      const hex = input.slice(i + 1, i + 3)\n      if (isHexPair(hex)) {\n        output += '%' + hex.toUpperCase()\n        i += 2\n        continue\n      }\n    }\n\n    output += escape(input[i])\n  }\n\n  return output\n}\n\n/**\n * @param {import('../types/index').URIComponent} component\n * @returns {string|undefined}\n */\nfunction recomposeAuthority (component) {\n  const uriTokens = []\n\n  if (component.userinfo !== undefined) {\n    uriTokens.push(encodeUserinfo(component.userinfo))\n    uriTokens.push('@')\n  }\n\n  if (component.host !== undefined) {\n    let host = component.host\n    if (!isIPv4(host)) {\n      let ipV6res = normalizeIPv6(host)\n      if (ipV6res.isIPV6 !== true && ipV6res.isIPVFuture !== true) {\n        // Decode only unreserved bytes, once. In particular, keep %25 encoded\n        // so it cannot introduce a second escape during recomposition.\n        host = normalizePercentEncoding(host, true)\n        ipV6res = normalizeIPv6(host)\n      }\n      if (ipV6res.isIPV6 === true || ipV6res.isIPVFuture === true) {\n        host = `[${ipV6res.escapedHost}]`\n      } else {\n        host = reescapeHostDelimiters(host, false)\n      }\n    }\n    uriTokens.push(host)\n  }\n\n  if (typeof component.port === 'number' || typeof component.port === 'string') {\n    const port = String(component.port)\n    if (!isPort(port)) {\n      throw new TypeError('URI port is malformed.')\n    }\n    uriTokens.push(':')\n    uriTokens.push(port)\n  }\n\n  return uriTokens.length ? uriTokens.join('') : undefined\n};\n\nmodule.exports = {\n  nonSimpleDomain,\n  recomposeAuthority,\n  reescapeHostDelimiters,\n  normalizePercentEncoding,\n  normalizePathEncoding,\n  serializePathEncoding,\n  normalizeQueryFragmentEncoding,\n  encodeUserinfo,\n  encodeQuery,\n  encodeFragment,\n  escapePreservingEscapes,\n  removeDotSegments,\n  isIPv4,\n  isUUID,\n  normalizeIPv6,\n  stringArrayToHexStripped\n}\n","'use strict'\n\nconst { isUUID } = require('./utils')\nconst URN_REG = /^([\\da-z][\\d\\-a-z]{0,31}):((?:[\\w!$'()*+,\\-./:;=@]|%[\\da-f]{2})+)$/iu\n\nconst supportedSchemeNames = /** @type {const} */ (['http', 'https', 'ws',\n  'wss', 'urn', 'urn:uuid'])\n\n/** @typedef {supportedSchemeNames[number]} SchemeName */\n\n/**\n * @param {string} name\n * @returns {name is SchemeName}\n */\nfunction isValidSchemeName (name) {\n  return supportedSchemeNames.indexOf(/** @type {*} */ (name)) !== -1\n}\n\n/**\n * @callback SchemeFn\n * @param {import('../types/index').URIComponent} component\n * @param {import('../types/index').Options} options\n * @returns {import('../types/index').URIComponent}\n */\n\n/**\n * @typedef {Object} SchemeHandler\n * @property {SchemeName} scheme - The scheme name.\n * @property {boolean} [domainHost] - Indicates if the scheme supports domain hosts.\n * @property {SchemeFn} parse - Function to parse the URI component for this scheme.\n * @property {SchemeFn} serialize - Function to serialize the URI component for this scheme.\n * @property {boolean} [skipNormalize] - Indicates if normalization should be skipped for this scheme.\n * @property {boolean} [absolutePath] - Indicates if the scheme uses absolute paths.\n * @property {boolean} [unicodeSupport] - Indicates if the scheme supports Unicode.\n */\n\n/**\n * @param {import('../types/index').URIComponent} wsComponent\n * @returns {boolean}\n */\nfunction wsIsSecure (wsComponent) {\n  if (wsComponent.secure === true) {\n    return true\n  } else if (wsComponent.secure === false) {\n    return false\n  } else if (wsComponent.scheme) {\n    return (\n      wsComponent.scheme.length === 3 &&\n      (wsComponent.scheme[0] === 'w' || wsComponent.scheme[0] === 'W') &&\n      (wsComponent.scheme[1] === 's' || wsComponent.scheme[1] === 'S') &&\n      (wsComponent.scheme[2] === 's' || wsComponent.scheme[2] === 'S')\n    )\n  } else {\n    return false\n  }\n}\n\n/** @type {SchemeFn} */\nfunction httpParse (component) {\n  if (!component.host) {\n    component.error = component.error || 'HTTP URIs must have a host.'\n  }\n\n  return component\n}\n\n/** @type {SchemeFn} */\nfunction httpSerialize (component) {\n  const secure = String(component.scheme).toLowerCase() === 'https'\n\n  // normalize the default port\n  if (component.port === (secure ? 443 : 80) || component.port === '') {\n    component.port = undefined\n  }\n\n  // normalize the empty path\n  if (!component.path) {\n    component.path = '/'\n  }\n\n  // NOTE: We do not parse query strings for HTTP URIs\n  // as WWW Form Url Encoded query strings are part of the HTML4+ spec,\n  // and not the HTTP spec.\n\n  return component\n}\n\n/** @type {SchemeFn} */\nfunction wsParse (wsComponent) {\n// indicate if the secure flag is set\n  wsComponent.secure = wsIsSecure(wsComponent)\n\n  // construct resouce name\n  wsComponent.resourceName = (wsComponent.path || '/') + (wsComponent.query ? '?' + wsComponent.query : '')\n  wsComponent.path = undefined\n  wsComponent.query = undefined\n\n  return wsComponent\n}\n\n/** @type {SchemeFn} */\nfunction wsSerialize (wsComponent) {\n// normalize the default port\n  if (wsComponent.port === (wsIsSecure(wsComponent) ? 443 : 80) || wsComponent.port === '') {\n    wsComponent.port = undefined\n  }\n\n  // ensure scheme matches secure flag\n  if (typeof wsComponent.secure === 'boolean') {\n    wsComponent.scheme = (wsComponent.secure ? 'wss' : 'ws')\n    wsComponent.secure = undefined\n  }\n\n  // reconstruct path from resource name\n  if (wsComponent.resourceName) {\n    const queryIndex = wsComponent.resourceName.indexOf('?')\n    const path = queryIndex === -1\n      ? wsComponent.resourceName\n      : wsComponent.resourceName.slice(0, queryIndex)\n    wsComponent.path = (path && path !== '/' ? path : undefined)\n    wsComponent.query = queryIndex === -1\n      ? undefined\n      : wsComponent.resourceName.slice(queryIndex + 1)\n    wsComponent.resourceName = undefined\n  }\n\n  // forbid fragment component\n  wsComponent.fragment = undefined\n\n  return wsComponent\n}\n\n/** @type {SchemeFn} */\nfunction urnParse (urnComponent, options) {\n  if (!urnComponent.path) {\n    urnComponent.error = 'URN can not be parsed'\n    return urnComponent\n  }\n  const matches = urnComponent.path.match(URN_REG)\n  if (matches && matches[0] === urnComponent.path) {\n    const scheme = options.scheme || urnComponent.scheme || 'urn'\n    urnComponent.nid = matches[1].toLowerCase()\n    urnComponent.nss = matches[2]\n    const urnScheme = `${scheme}:${options.nid || urnComponent.nid}`\n    const schemeHandler = getSchemeHandler(urnScheme)\n    urnComponent.path = undefined\n\n    if (schemeHandler) {\n      urnComponent = schemeHandler.parse(urnComponent, options)\n    }\n  } else {\n    urnComponent.error = urnComponent.error || 'URN can not be parsed.'\n  }\n\n  return urnComponent\n}\n\n/** @type {SchemeFn} */\nfunction urnSerialize (urnComponent, options) {\n  if (urnComponent.nid === undefined) {\n    throw new Error('URN without nid cannot be serialized')\n  }\n  const scheme = options.scheme || urnComponent.scheme || 'urn'\n  const nid = urnComponent.nid.toLowerCase()\n  const urnScheme = `${scheme}:${options.nid || nid}`\n  const schemeHandler = getSchemeHandler(urnScheme)\n\n  if (schemeHandler) {\n    urnComponent = schemeHandler.serialize(urnComponent, options)\n  }\n\n  const uriComponent = urnComponent\n  const nss = urnComponent.nss\n  uriComponent.path = `${nid || options.nid}:${nss}`\n\n  options.skipEscape = true\n  return uriComponent\n}\n\n/** @type {SchemeFn} */\nfunction urnuuidParse (urnComponent, options) {\n  const uuidComponent = urnComponent\n  uuidComponent.uuid = uuidComponent.nss\n  uuidComponent.nss = undefined\n\n  if (!options.tolerant && (!uuidComponent.uuid || !isUUID(uuidComponent.uuid))) {\n    uuidComponent.error = uuidComponent.error || 'UUID is not valid.'\n  }\n\n  return uuidComponent\n}\n\n/** @type {SchemeFn} */\nfunction urnuuidSerialize (uuidComponent) {\n  const urnComponent = uuidComponent\n  // normalize UUID\n  urnComponent.nss = (uuidComponent.uuid || '').toLowerCase()\n  return urnComponent\n}\n\nconst http = /** @type {SchemeHandler} */ ({\n  scheme: 'http',\n  domainHost: true,\n  parse: httpParse,\n  serialize: httpSerialize\n})\n\nconst https = /** @type {SchemeHandler} */ ({\n  scheme: 'https',\n  domainHost: http.domainHost,\n  parse: httpParse,\n  serialize: httpSerialize\n})\n\nconst ws = /** @type {SchemeHandler} */ ({\n  scheme: 'ws',\n  domainHost: true,\n  parse: wsParse,\n  serialize: wsSerialize\n})\n\nconst wss = /** @type {SchemeHandler} */ ({\n  scheme: 'wss',\n  domainHost: ws.domainHost,\n  parse: ws.parse,\n  serialize: ws.serialize\n})\n\nconst urn = /** @type {SchemeHandler} */ ({\n  scheme: 'urn',\n  parse: urnParse,\n  serialize: urnSerialize,\n  skipNormalize: true\n})\n\nconst urnuuid = /** @type {SchemeHandler} */ ({\n  scheme: 'urn:uuid',\n  parse: urnuuidParse,\n  serialize: urnuuidSerialize,\n  skipNormalize: true\n})\n\nconst SCHEMES = /** @type {Record<SchemeName, SchemeHandler>} */ ({\n  http,\n  https,\n  ws,\n  wss,\n  urn,\n  'urn:uuid': urnuuid\n})\n\nObject.setPrototypeOf(SCHEMES, null)\n\n/**\n * @param {string|undefined} scheme\n * @returns {SchemeHandler|undefined}\n */\nfunction getSchemeHandler (scheme) {\n  return (\n    scheme && (\n      SCHEMES[/** @type {SchemeName} */ (scheme)] ||\n      SCHEMES[/** @type {SchemeName} */(scheme.toLowerCase())])\n  ) ||\n    undefined\n}\n\nmodule.exports = {\n  wsIsSecure,\n  SCHEMES,\n  isValidSchemeName,\n  getSchemeHandler,\n}\n","'use strict'\n\nconst { normalizeIPv6, removeDotSegments, recomposeAuthority, normalizePercentEncoding, normalizePathEncoding, serializePathEncoding, normalizeQueryFragmentEncoding, encodeQuery, encodeFragment, reescapeHostDelimiters, isIPv4, nonSimpleDomain } = require('./lib/utils')\nconst { SCHEMES, getSchemeHandler } = require('./lib/schemes')\n\nconst VALID_SCHEME = /^[A-Za-z][A-Za-z0-9+.-]*$/u\nconst MALFORMED_SCHEME_ERROR = 'URI scheme is malformed.'\n\n/**\n * @param {string} scheme\n * @returns {string}\n */\nfunction decodeValidScheme (scheme) {\n  const decodedScheme = unescape(String(scheme))\n  if (!VALID_SCHEME.test(decodedScheme)) {\n    throw new TypeError(MALFORMED_SCHEME_ERROR)\n  }\n  return decodedScheme\n}\n\n/**\n * @template {import('./types/index').URIComponent|string} T\n * @param {T} uri\n * @param {import('./types/index').Options} [options]\n * @returns {T}\n */\nfunction normalize (uri, options) {\n  if (typeof uri === 'string') {\n    uri = /** @type {T} */ (normalizeString(uri, options))\n  } else if (typeof uri === 'object') {\n    uri = /** @type {T} */ (parse(serialize(uri, options), options))\n  }\n  return uri\n}\n\n/**\n * @param {string} baseURI\n * @param {string} relativeURI\n * @param {import('./types/index').Options} [options]\n * @returns {string}\n */\nfunction resolve (baseURI, relativeURI, options) {\n  const schemelessOptions = options ? Object.assign({ scheme: 'null' }, options) : { scheme: 'null' }\n  const {\n    parsed: baseParsed,\n    malformedAuthorityOrPort: baseMalformed,\n    malformedPercentEncoding: baseMalformedPercentEncoding,\n    malformedSchemeSpecific: baseMalformedSchemeSpecific,\n    malformedHost: baseMalformedHost,\n    malformedScheme: baseMalformedScheme\n  } = parseWithStatus(baseURI, schemelessOptions)\n  const {\n    parsed: relativeParsed,\n    malformedAuthorityOrPort: relativeMalformed,\n    malformedPercentEncoding: relativeMalformedPercentEncoding,\n    malformedSchemeSpecific: relativeMalformedSchemeSpecific,\n    malformedHost: relativeMalformedHost,\n    malformedScheme: relativeMalformedScheme\n  } = parseWithStatus(relativeURI, schemelessOptions)\n  if (\n    baseMalformed ||\n    relativeMalformed ||\n    baseMalformedPercentEncoding ||\n    relativeMalformedPercentEncoding ||\n    baseMalformedSchemeSpecific ||\n    relativeMalformedSchemeSpecific ||\n    baseMalformedHost ||\n    relativeMalformedHost ||\n    baseMalformedScheme ||\n    relativeMalformedScheme\n  ) {\n    throw new Error(baseParsed.error || relativeParsed.error || 'URI is malformed.')\n  }\n  const resolved = resolveComponent(baseParsed, relativeParsed, schemelessOptions, true)\n  const resolvedSchemeHandler = getSchemeHandler((options && options.scheme) || resolved.scheme)\n  const resolvedHost = resolved.host\n  const resolvedHostIsIP = resolvedHost !== undefined && resolvedHost !== '' &&\n    (isIPv4(resolvedHost) || normalizeIPv6(resolvedHost).isIPV6)\n  canonicalizeHost(resolved, options || {}, resolvedSchemeHandler, resolvedHostIsIP)\n  // Percent escapes in an ASCII reg-name are encoded data. The WHATWG hostname\n  // parser can reject them even though fast-uri preserves them safely as RFC\n  // 3986 data. A raw non-ASCII host must still fail closed if conversion fails.\n  const encodedASCIIHost = resolvedHost && resolvedHost.indexOf('%') !== -1 &&\n    !/\\P{ASCII}/u.test(resolvedHost)\n  if (resolved.error && !encodedASCIIHost) {\n    throw new Error(resolved.error)\n  }\n  schemelessOptions.skipEscape = true\n  return serialize(resolved, schemelessOptions)\n}\n\n/**\n * @param {import ('./types/index').URIComponent} base\n * @param {import ('./types/index').URIComponent} relative\n * @param {import('./types/index').Options} [options]\n * @param {boolean} [skipNormalization=false]\n * @returns {import ('./types/index').URIComponent}\n */\nfunction resolveComponent (base, relative, options, skipNormalization) {\n  /** @type {import('./types/index').URIComponent} */\n  const target = {}\n  if (!skipNormalization) {\n    base = parse(serialize(base, options), options) // normalize base component\n    relative = parse(serialize(relative, options), options) // normalize relative component\n  }\n  options = options || {}\n\n  if (!options.tolerant && relative.scheme) {\n    target.scheme = relative.scheme\n    // target.authority = relative.authority;\n    target.userinfo = relative.userinfo\n    target.host = relative.host\n    target.port = relative.port\n    target.path = removeDotSegments(relative.path || '')\n    target.query = relative.query\n  } else {\n    if (relative.userinfo !== undefined || relative.host !== undefined || relative.port !== undefined) {\n      // target.authority = relative.authority;\n      target.userinfo = relative.userinfo\n      target.host = relative.host\n      target.port = relative.port\n      target.path = removeDotSegments(relative.path || '')\n      target.query = relative.query\n    } else {\n      if (!relative.path) {\n        target.path = base.path\n        if (relative.query !== undefined) {\n          target.query = relative.query\n        } else {\n          target.query = base.query\n        }\n      } else {\n        if (relative.path[0] === '/') {\n          target.path = removeDotSegments(relative.path)\n        } else {\n          if ((base.userinfo !== undefined || base.host !== undefined || base.port !== undefined) && !base.path) {\n            target.path = '/' + relative.path\n          } else if (!base.path) {\n            target.path = relative.path\n          } else {\n            target.path = base.path.slice(0, base.path.lastIndexOf('/') + 1) + relative.path\n          }\n          target.path = removeDotSegments(target.path)\n        }\n        target.query = relative.query\n      }\n      // target.authority = base.authority;\n      target.userinfo = base.userinfo\n      target.host = base.host\n      target.port = base.port\n    }\n    target.scheme = base.scheme\n  }\n\n  target.fragment = relative.fragment\n\n  return target\n}\n\n/**\n * @param {import ('./types/index').URIComponent|string} uriA\n * @param {import ('./types/index').URIComponent|string} uriB\n * @param {import ('./types/index').Options} options\n * @returns {boolean}\n */\nfunction equal (uriA, uriB, options) {\n  const normalizedA = normalizeComparableURI(uriA, options)\n  const normalizedB = normalizeComparableURI(uriB, options)\n\n  return normalizedA !== undefined && normalizedB !== undefined && normalizedA === normalizedB\n}\n\n/**\n * @param {Readonly<import('./types/index').URIComponent>} cmpts\n * @param {import('./types/index').Options} [opts]\n * @returns {string}\n */\nfunction serialize (cmpts, opts) {\n  const component = {\n    host: cmpts.host,\n    scheme: cmpts.scheme,\n    userinfo: cmpts.userinfo,\n    port: cmpts.port,\n    path: cmpts.path,\n    query: cmpts.query,\n    nid: cmpts.nid,\n    nss: cmpts.nss,\n    uuid: cmpts.uuid,\n    fragment: cmpts.fragment,\n    reference: cmpts.reference,\n    resourceName: cmpts.resourceName,\n    secure: cmpts.secure,\n    error: ''\n  }\n  const options = Object.assign({}, opts)\n  const uriTokens = []\n\n  if (component.scheme) {\n    component.scheme = decodeValidScheme(component.scheme)\n  }\n\n  // find scheme handler\n  const schemeHandler = getSchemeHandler(options.scheme || component.scheme)\n\n  // perform scheme specific serialization\n  if (schemeHandler && schemeHandler.serialize) schemeHandler.serialize(component, options)\n\n  const hasAuthority = component.userinfo !== undefined || component.host !== undefined || component.port !== undefined\n  const pathNoScheme = !options.skipEscape && component.scheme === undefined && !hasAuthority\n\n  if (component.path !== undefined) {\n    if (!options.skipEscape) {\n      component.path = serializePathEncoding(component.path, pathNoScheme)\n    } else {\n      component.path = normalizePercentEncoding(component.path)\n    }\n  }\n\n  if (options.reference !== 'suffix' && component.scheme) {\n    // Scheme handlers may replace the scheme during serialization.\n    component.scheme = decodeValidScheme(component.scheme)\n    uriTokens.push(component.scheme, ':')\n  }\n\n  const authority = recomposeAuthority(component)\n  if (authority !== undefined) {\n    if (options.reference !== 'suffix') {\n      uriTokens.push('//')\n    }\n\n    uriTokens.push(authority)\n\n    if (component.path && component.path[0] !== '/') {\n      uriTokens.push('/')\n    }\n  }\n  if (component.path !== undefined) {\n    let s = component.path\n\n    if (!options.absolutePath && (!schemeHandler || !schemeHandler.absolutePath)) {\n      s = removeDotSegments(s)\n    }\n\n    // Dot-segment removal can expose a colon that was not originally in the\n    // first segment (for example, \"./a:b\"). Reapply path-noscheme encoding so\n    // the serialized relative reference cannot be reparsed as a URI scheme.\n    if (pathNoScheme) {\n      s = serializePathEncoding(s, true)\n    }\n\n    if (\n      authority === undefined &&\n      s[0] === '/' &&\n      s[1] === '/'\n    ) {\n      // don't allow the path to start with \"//\"\n      s = '/%2F' + s.slice(2)\n    }\n\n    uriTokens.push(s)\n  }\n\n  if (component.query !== undefined) {\n    uriTokens.push('?', encodeQuery(component.query))\n  }\n\n  if (component.fragment !== undefined) {\n    uriTokens.push('#', encodeFragment(component.fragment))\n  }\n  return uriTokens.join('')\n}\n\nconst URI_PARSE = /^(?:([^#/:?]+):)?(?:\\/\\/((?:([^#/?@]*)@)?(\\[[^#/?\\]]+\\]|[^#/:?]*)(?::(\\d*))?))?([^#?]*)(?:\\?([^#]*))?(?:#((?:.|[\\n\\r])*))?/u\n\n// Captures the authority component (between \"//\" and the next \"/\", \"?\" or \"#\"),\n// with or without a scheme prefix, for the literal-backslash rejection below.\nconst AUTHORITY_PREFIX = /^(?:[^#/:?]+:)?\\/\\/([^/?#]*)/\n\n// Captures the leading authority-introducer region after an optional scheme: a\n// run of forward slashes, backslashes, and the characters the WHATWG URL parser\n// removes before parsing (TAB U+0009, LF U+000A, CR U+000D). A valid introducer\n// is exactly \"//\". Node treats \"\\\" as \"/\" on special schemes and strips those\n// characters first, so forms like \"\\\\\", \"/\\\", \"\\/\", \"/<TAB>/\", or a leading\n// \"<TAB>//\" reach an authority in Node while fast-uri's URI_PARSE folds them into\n// the path group (host confusion / SSRF / redirect bypass).\nconst AUTHORITY_INTRODUCER_REGION = /^(?:[^#/:?]+:)?([/\\\\\\t\\n\\r]*)/\n\n/**\n * @param {import('./types/index').URIComponent} parsed\n * @param {RegExpMatchArray} matches\n * @returns {string|undefined}\n */\nfunction getParseError (parsed, matches) {\n  if (matches[2] !== undefined && parsed.path && parsed.path[0] !== '/') {\n    return 'URI path must start with \"/\" when authority is present.'\n  }\n\n  if (typeof parsed.port === 'number' && (parsed.port < 0 || parsed.port > 65535)) {\n    return 'URI port is malformed.'\n  }\n\n  return undefined\n}\n\n/**\n * Checks percent syntax without decoding the represented octets. RFC 3986\n * percent-encoding is byte-oriented, so sequences such as `%FF` are valid even\n * though they are not independently valid UTF-8.\n *\n * @param {string|undefined} component\n * @returns {boolean}\n */\nfunction hasMalformedPercentEncoding (component) {\n  if (component === undefined) return false\n\n  let percent = component.indexOf('%')\n  while (percent !== -1) {\n    if (percent + 2 >= component.length || !/^[\\da-f]{2}$/iu.test(component.slice(percent + 1, percent + 3))) {\n      return true\n    }\n    percent = component.indexOf('%', percent + 3)\n  }\n\n  return false\n}\n\n/**\n * Whether the host is a bracketed IP literal (RFC 3986 `IP-literal`).\n * An unterminated `[` is not a literal, so it must still be validated as a\n * reg-name instead of being waved through as an IP.\n *\n * @param {string} host\n * @returns {boolean}\n */\nfunction isIPLiteral (host) {\n  return host[0] === '[' && host[host.length - 1] === ']'\n}\n\n/**\n * @param {RegExpMatchArray} matches\n * @returns {boolean}\n */\nfunction hasMalformedComponentPercentEncoding (matches) {\n  // Bracketed IP literals use a raw \"%\" as the zone separator for historical\n  // compatibility. Their parsing is intentionally left to normalizeIPv6.\n  const host = matches[4]\n  return hasMalformedPercentEncoding(matches[3]) ||\n    (host !== undefined && !isIPLiteral(host) && hasMalformedPercentEncoding(host)) ||\n    hasMalformedPercentEncoding(matches[6]) ||\n    hasMalformedPercentEncoding(matches[7]) ||\n    hasMalformedPercentEncoding(matches[8])\n}\n\n/**\n * @param {import('./types/index').URIComponent} parsed\n * @param {import('./types/index').Options} options\n * @param {{ domainHost?: boolean, unicodeSupport?: boolean }|undefined} schemeHandler\n * @param {boolean} isIP\n * @returns {boolean} whether host conversion failed\n */\nfunction canonicalizeHost (parsed, options, schemeHandler, isIP) {\n  if (\n    !options.unicodeSupport &&\n    (!schemeHandler || !schemeHandler.unicodeSupport) &&\n    parsed.host &&\n    !isIPLiteral(parsed.host) &&\n    (options.domainHost || (schemeHandler && schemeHandler.domainHost)) &&\n    isIP === false &&\n    nonSimpleDomain(parsed.host)\n  ) {\n    try {\n      parsed.host = new URL('http://' + parsed.host).hostname\n    } catch (e) {\n      parsed.error = parsed.error || \"Host's domain name can not be converted to ASCII: \" + e\n      return true\n    }\n  }\n  return false\n}\n\n/**\n * @param {string} uri\n * @param {import('./types/index').Options} [opts]\n * @returns {{ parsed: import('./types/index').URIComponent, malformedAuthorityOrPort: boolean, malformedPercentEncoding: boolean, malformedSchemeSpecific: boolean, malformedHost: boolean, malformedScheme: boolean }}\n */\nfunction parseWithStatus (uri, opts) {\n  const options = Object.assign({}, opts)\n  /** @type {import('./types/index').URIComponent} */\n  const parsed = {\n    scheme: undefined,\n    userinfo: undefined,\n    host: '',\n    port: undefined,\n    path: '',\n    query: undefined,\n    fragment: undefined\n  }\n\n  let malformedAuthorityOrPort = false\n  let malformedPercentEncoding = false\n  let malformedSchemeSpecific = false\n  let malformedHost = false\n  let malformedIPLiteral = false\n  let malformedScheme = false\n\n  let isIP = false\n  if (options.reference === 'suffix') {\n    if (options.scheme) {\n      uri = options.scheme + ':' + uri\n    } else {\n      uri = '//' + uri\n    }\n  }\n\n  // A literal backslash (U+005C) is not a valid RFC 3986 URI character and is\n  // not an authority delimiter. Reject it in the authority rather than\n  // rewriting it: normalizing \"\\\" -> \"/\" (WHATWG error recovery) could silently\n  // change the resource identified by an otherwise-invalid input, and lets \"\\\"\n  // act as a host delimiter here while Node's native URL parses a different\n  // host (SSRF / redirect / origin-allowlist bypass). Percent-encoded %5C is\n  // untouched and remains valid encoded data.\n  const authorityMatch = uri.match(AUTHORITY_PREFIX)\n  if (authorityMatch !== null && authorityMatch[1].indexOf('\\\\') !== -1) {\n    parsed.error = 'URI authority must not contain a literal backslash.'\n    malformedAuthorityOrPort = true\n  }\n\n  // Reject a malformed or whitespace-smuggled authority introducer. fast-uri\n  // only recognizes a literal \"//\"; anything else in the leading separator run\n  // (a backslash, or a \"//\" that appears only after removing the TAB/LF/CR that\n  // Node strips) means the authority fast-uri parses differs from the one Node's\n  // URL resolves. Reject rather than rewrite, mirroring the literal-backslash\n  // guard above. Percent-encoded forms (%5C, %09) are untouched, valid data.\n  const introducerMatch = uri.match(AUTHORITY_INTRODUCER_REGION)\n  if (introducerMatch !== null) {\n    const region = introducerMatch[1]\n    const normalizedRegion = region.replace(/[\\t\\n\\r]/g, '')\n    // Two or more leading separators introduce an authority.\n    if (normalizedRegion.length >= 2) {\n      if (normalizedRegion.slice(0, 2) !== '//') {\n        parsed.error = parsed.error || 'URI authority must not contain a literal backslash.'\n        malformedAuthorityOrPort = true\n      } else if (region.length !== normalizedRegion.length) {\n        parsed.error = parsed.error || 'URI authority introducer must not contain whitespace.'\n        malformedAuthorityOrPort = true\n      }\n    }\n  }\n\n  const matches = uri.match(URI_PARSE)\n\n  if (matches) {\n    // store each component\n    parsed.scheme = matches[1]\n    parsed.userinfo = matches[3]\n    parsed.host = matches[4]\n    parsed.port = parseInt(matches[5], 10)\n    parsed.path = matches[6] || ''\n    parsed.query = matches[7]\n    parsed.fragment = matches[8]\n\n    if (parsed.scheme !== undefined) {\n      const decodedScheme = unescape(parsed.scheme)\n      if (VALID_SCHEME.test(decodedScheme)) {\n        parsed.scheme = decodedScheme.toLowerCase()\n      } else {\n        parsed.error = parsed.error || MALFORMED_SCHEME_ERROR\n        malformedScheme = true\n      }\n    }\n\n    malformedPercentEncoding = hasMalformedComponentPercentEncoding(matches)\n    if (malformedPercentEncoding) {\n      parsed.error = parsed.error || 'URI contains malformed percent-encoding.'\n    }\n\n    // fix port number\n    if (isNaN(parsed.port)) {\n      parsed.port = matches[5]\n    }\n\n    const parseError = getParseError(parsed, matches)\n    if (parseError !== undefined) {\n      parsed.error = parsed.error || parseError\n      malformedAuthorityOrPort = true\n    }\n\n    if (parsed.host) {\n      const ipv4result = isIPv4(parsed.host)\n      if (ipv4result === false) {\n        const bracketedIPLiteral = isIPLiteral(parsed.host)\n        const hasIPLiteralBracket = parsed.host.indexOf('[') !== -1 || parsed.host.indexOf(']') !== -1\n        const ipv6result = normalizeIPv6(parsed.host)\n        isIP = ipv6result.isIPV6 || ipv6result.isIPVFuture === true\n        malformedIPLiteral = hasIPLiteralBracket && (!bracketedIPLiteral || ipv6result.error === true)\n        parsed.host = isIP ? ipv6result.host : ipv6result.host.toLowerCase()\n\n        if (malformedIPLiteral) {\n          parsed.error = parsed.error || 'URI host is malformed.'\n          malformedAuthorityOrPort = true\n        }\n      } else {\n        isIP = true\n      }\n    }\n    if (parsed.scheme === undefined && parsed.userinfo === undefined && parsed.host === undefined && parsed.port === undefined && parsed.query === undefined && !parsed.path) {\n      parsed.reference = 'same-document'\n    } else if (parsed.scheme === undefined) {\n      parsed.reference = 'relative'\n    } else if (parsed.fragment === undefined) {\n      parsed.reference = 'absolute'\n    } else {\n      parsed.reference = 'uri'\n    }\n\n    // check for reference errors\n    if (options.reference && options.reference !== 'suffix' && options.reference !== parsed.reference) {\n      parsed.error = parsed.error || 'URI is not a ' + options.reference + ' reference.'\n    }\n\n    // find scheme handler\n    const schemeHandler = getSchemeHandler(options.scheme || parsed.scheme)\n\n    // convert Unicode IDN -> ASCII IDN when the effective scheme uses domain hosts\n    if (!malformedIPLiteral) {\n      malformedHost = canonicalizeHost(parsed, options, schemeHandler, isIP)\n    }\n\n    if (uri.indexOf('%') !== -1 && parsed.host !== undefined && !malformedIPLiteral) {\n      let host = isIP ? parsed.host : normalizePercentEncoding(parsed.host, true)\n      if (!isIP) {\n        // Fold reg-name case after decoding unreserved octets. The second\n        // pass only restores uppercase hex in escapes that remain encoded.\n        host = normalizePercentEncoding(host.toLowerCase())\n      }\n      parsed.host = reescapeHostDelimiters(host, isIP)\n    }\n\n    if (!schemeHandler || (schemeHandler && !schemeHandler.skipNormalize)) {\n      if (parsed.path) {\n        parsed.path = normalizePathEncoding(parsed.path)\n      }\n      if (parsed.query) {\n        parsed.query = normalizeQueryFragmentEncoding(parsed.query)\n      }\n      if (parsed.fragment) {\n        parsed.fragment = normalizeQueryFragmentEncoding(parsed.fragment)\n      }\n    }\n\n    // perform scheme specific parsing\n    if (schemeHandler && schemeHandler.parse) {\n      schemeHandler.parse(parsed, options)\n      if (schemeHandler === SCHEMES.urn && parsed.nid === undefined) {\n        malformedSchemeSpecific = true\n      }\n    }\n  } else {\n    parsed.error = parsed.error || 'URI can not be parsed.'\n  }\n  return { parsed, malformedAuthorityOrPort, malformedPercentEncoding, malformedSchemeSpecific, malformedHost, malformedScheme }\n}\n\n/**\n * @param {string} uri\n * @param {import('./types/index').Options} [opts]\n * @returns\n */\nfunction parse (uri, opts) {\n  return parseWithStatus(uri, opts).parsed\n}\n\n/**\n * @param {string} uri\n * @param {import('./types/index').Options} [opts]\n * @returns {string}\n */\nfunction normalizeString (uri, opts) {\n  return normalizeStringWithStatus(uri, opts).normalized\n}\n\n/**\n * @param {string} uri\n * @param {import('./types/index').Options} [opts]\n * @returns {{ normalized: string, malformedAuthorityOrPort: boolean, malformedPercentEncoding: boolean, malformedSchemeSpecific: boolean, malformedHost: boolean, malformedScheme: boolean }}\n */\nfunction normalizeStringWithStatus (uri, opts) {\n  const { parsed, malformedAuthorityOrPort, malformedPercentEncoding, malformedSchemeSpecific, malformedHost, malformedScheme } = parseWithStatus(uri, opts)\n  return {\n    normalized: malformedAuthorityOrPort || malformedPercentEncoding || malformedSchemeSpecific || malformedHost || malformedScheme ? uri : serialize(parsed, opts),\n    malformedAuthorityOrPort,\n    malformedPercentEncoding,\n    malformedSchemeSpecific,\n    malformedHost,\n    malformedScheme\n  }\n}\n\n/**\n * @param {import ('./types/index').URIComponent|string} uri\n * @param {import('./types/index').Options} [opts]\n * @returns {string|undefined}\n */\nfunction normalizeComparableURI (uri, opts) {\n  if (typeof uri !== 'string' && typeof uri !== 'object') {\n    return undefined\n  }\n\n  let value\n  try {\n    value = typeof uri === 'string' ? uri : serialize(uri, opts)\n  } catch {\n    return undefined\n  }\n  const { normalized, malformedAuthorityOrPort, malformedPercentEncoding, malformedSchemeSpecific, malformedHost, malformedScheme } = normalizeStringWithStatus(value, opts)\n  return malformedAuthorityOrPort || malformedPercentEncoding || malformedSchemeSpecific || malformedHost || malformedScheme ? undefined : normalized\n}\n\nconst fastUri = {\n  SCHEMES,\n  normalize,\n  resolve,\n  resolveComponent,\n  equal,\n  serialize,\n  parse\n}\n\nmodule.exports = fastUri\nmodule.exports.default = fastUri\nmodule.exports.fastUri = fastUri\n","\"use strict\";\nObject.defineProperty(exports, \"__esModule\", { value: true });\nconst uri = require(\"fast-uri\");\nuri.code = 'require(\"ajv/dist/runtime/uri\").default';\nexports.default = uri;\n//# sourceMappingURL=uri.js.map","\"use strict\";\nObject.defineProperty(exports, \"__esModule\", { value: true });\nexports.CodeGen = exports.Name = exports.nil = exports.stringify = exports.str = exports._ = exports.KeywordCxt = void 0;\nvar validate_1 = require(\"./compile/validate\");\nObject.defineProperty(exports, \"KeywordCxt\", { enumerable: true, get: function () { return validate_1.KeywordCxt; } });\nvar codegen_1 = require(\"./compile/codegen\");\nObject.defineProperty(exports, \"_\", { enumerable: true, get: function () { return codegen_1._; } });\nObject.defineProperty(exports, \"str\", { enumerable: true, get: function () { return codegen_1.str; } });\nObject.defineProperty(exports, \"stringify\", { enumerable: true, get: function () { return codegen_1.stringify; } });\nObject.defineProperty(exports, \"nil\", { enumerable: true, get: function () { return codegen_1.nil; } });\nObject.defineProperty(exports, \"Name\", { enumerable: true, get: function () { return codegen_1.Name; } });\nObject.defineProperty(exports, \"CodeGen\", { enumerable: true, get: function () { return codegen_1.CodeGen; } });\nconst validation_error_1 = require(\"./runtime/validation_error\");\nconst ref_error_1 = require(\"./compile/ref_error\");\nconst rules_1 = require(\"./compile/rules\");\nconst compile_1 = require(\"./compile\");\nconst codegen_2 = require(\"./compile/codegen\");\nconst resolve_1 = require(\"./compile/resolve\");\nconst dataType_1 = require(\"./compile/validate/dataType\");\nconst util_1 = require(\"./compile/util\");\nconst $dataRefSchema = require(\"./refs/data.json\");\nconst uri_1 = require(\"./runtime/uri\");\nconst defaultRegExp = (str, flags) => new RegExp(str, flags);\ndefaultRegExp.code = \"new RegExp\";\nconst META_IGNORE_OPTIONS = [\"removeAdditional\", \"useDefaults\", \"coerceTypes\"];\nconst EXT_SCOPE_NAMES = new Set([\n    \"validate\",\n    \"serialize\",\n    \"parse\",\n    \"wrapper\",\n    \"root\",\n    \"schema\",\n    \"keyword\",\n    \"pattern\",\n    \"formats\",\n    \"validate$data\",\n    \"func\",\n    \"obj\",\n    \"Error\",\n]);\nconst removedOptions = {\n    errorDataPath: \"\",\n    format: \"`validateFormats: false` can be used instead.\",\n    nullable: '\"nullable\" keyword is supported by default.',\n    jsonPointers: \"Deprecated jsPropertySyntax can be used instead.\",\n    extendRefs: \"Deprecated ignoreKeywordsWithRef can be used instead.\",\n    missingRefs: \"Pass empty schema with $id that should be ignored to ajv.addSchema.\",\n    processCode: \"Use option `code: {process: (code, schemaEnv: object) => string}`\",\n    sourceCode: \"Use option `code: {source: true}`\",\n    strictDefaults: \"It is default now, see option `strict`.\",\n    strictKeywords: \"It is default now, see option `strict`.\",\n    uniqueItems: '\"uniqueItems\" keyword is always validated.',\n    unknownFormats: \"Disable strict mode or pass `true` to `ajv.addFormat` (or `formats` option).\",\n    cache: \"Map is used as cache, schema object as key.\",\n    serialize: \"Map is used as cache, schema object as key.\",\n    ajvErrors: \"It is default now.\",\n};\nconst deprecatedOptions = {\n    ignoreKeywordsWithRef: \"\",\n    jsPropertySyntax: \"\",\n    unicode: '\"minLength\"/\"maxLength\" account for unicode characters by default.',\n};\nconst MAX_EXPRESSION = 200;\n// eslint-disable-next-line complexity\nfunction requiredOptions(o) {\n    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;\n    const s = o.strict;\n    const _optz = (_a = o.code) === null || _a === void 0 ? void 0 : _a.optimize;\n    const optimize = _optz === true || _optz === undefined ? 1 : _optz || 0;\n    const regExp = (_c = (_b = o.code) === null || _b === void 0 ? void 0 : _b.regExp) !== null && _c !== void 0 ? _c : defaultRegExp;\n    const uriResolver = (_d = o.uriResolver) !== null && _d !== void 0 ? _d : uri_1.default;\n    return {\n        strictSchema: (_f = (_e = o.strictSchema) !== null && _e !== void 0 ? _e : s) !== null && _f !== void 0 ? _f : true,\n        strictNumbers: (_h = (_g = o.strictNumbers) !== null && _g !== void 0 ? _g : s) !== null && _h !== void 0 ? _h : true,\n        strictTypes: (_k = (_j = o.strictTypes) !== null && _j !== void 0 ? _j : s) !== null && _k !== void 0 ? _k : \"log\",\n        strictTuples: (_m = (_l = o.strictTuples) !== null && _l !== void 0 ? _l : s) !== null && _m !== void 0 ? _m : \"log\",\n        strictRequired: (_p = (_o = o.strictRequired) !== null && _o !== void 0 ? _o : s) !== null && _p !== void 0 ? _p : false,\n        code: o.code ? { ...o.code, optimize, regExp } : { optimize, regExp },\n        loopRequired: (_q = o.loopRequired) !== null && _q !== void 0 ? _q : MAX_EXPRESSION,\n        loopEnum: (_r = o.loopEnum) !== null && _r !== void 0 ? _r : MAX_EXPRESSION,\n        meta: (_s = o.meta) !== null && _s !== void 0 ? _s : true,\n        messages: (_t = o.messages) !== null && _t !== void 0 ? _t : true,\n        inlineRefs: (_u = o.inlineRefs) !== null && _u !== void 0 ? _u : true,\n        schemaId: (_v = o.schemaId) !== null && _v !== void 0 ? _v : \"$id\",\n        addUsedSchema: (_w = o.addUsedSchema) !== null && _w !== void 0 ? _w : true,\n        validateSchema: (_x = o.validateSchema) !== null && _x !== void 0 ? _x : true,\n        validateFormats: (_y = o.validateFormats) !== null && _y !== void 0 ? _y : true,\n        unicodeRegExp: (_z = o.unicodeRegExp) !== null && _z !== void 0 ? _z : true,\n        int32range: (_0 = o.int32range) !== null && _0 !== void 0 ? _0 : true,\n        uriResolver: uriResolver,\n    };\n}\nclass Ajv {\n    constructor(opts = {}) {\n        this.schemas = {};\n        this.refs = {};\n        this.formats = {};\n        this._compilations = new Set();\n        this._loading = {};\n        this._cache = new Map();\n        opts = this.opts = { ...opts, ...requiredOptions(opts) };\n        const { es5, lines } = this.opts.code;\n        this.scope = new codegen_2.ValueScope({ scope: {}, prefixes: EXT_SCOPE_NAMES, es5, lines });\n        this.logger = getLogger(opts.logger);\n        const formatOpt = opts.validateFormats;\n        opts.validateFormats = false;\n        this.RULES = (0, rules_1.getRules)();\n        checkOptions.call(this, removedOptions, opts, \"NOT SUPPORTED\");\n        checkOptions.call(this, deprecatedOptions, opts, \"DEPRECATED\", \"warn\");\n        this._metaOpts = getMetaSchemaOptions.call(this);\n        if (opts.formats)\n            addInitialFormats.call(this);\n        this._addVocabularies();\n        this._addDefaultMetaSchema();\n        if (opts.keywords)\n            addInitialKeywords.call(this, opts.keywords);\n        if (typeof opts.meta == \"object\")\n            this.addMetaSchema(opts.meta);\n        addInitialSchemas.call(this);\n        opts.validateFormats = formatOpt;\n    }\n    _addVocabularies() {\n        this.addKeyword(\"$async\");\n    }\n    _addDefaultMetaSchema() {\n        const { $data, meta, schemaId } = this.opts;\n        let _dataRefSchema = $dataRefSchema;\n        if (schemaId === \"id\") {\n            _dataRefSchema = { ...$dataRefSchema };\n            _dataRefSchema.id = _dataRefSchema.$id;\n            delete _dataRefSchema.$id;\n        }\n        if (meta && $data)\n            this.addMetaSchema(_dataRefSchema, _dataRefSchema[schemaId], false);\n    }\n    defaultMeta() {\n        const { meta, schemaId } = this.opts;\n        return (this.opts.defaultMeta = typeof meta == \"object\" ? meta[schemaId] || meta : undefined);\n    }\n    validate(schemaKeyRef, // key, ref or schema object\n    // eslint-disable-next-line @typescript-eslint/no-redundant-type-constituents\n    data // to be validated\n    ) {\n        let v;\n        if (typeof schemaKeyRef == \"string\") {\n            v = this.getSchema(schemaKeyRef);\n            if (!v)\n                throw new Error(`no schema with key or ref \"${schemaKeyRef}\"`);\n        }\n        else {\n            v = this.compile(schemaKeyRef);\n        }\n        const valid = v(data);\n        if (!(\"$async\" in v))\n            this.errors = v.errors;\n        return valid;\n    }\n    compile(schema, _meta) {\n        const sch = this._addSchema(schema, _meta);\n        return (sch.validate || this._compileSchemaEnv(sch));\n    }\n    compileAsync(schema, meta) {\n        if (typeof this.opts.loadSchema != \"function\") {\n            throw new Error(\"options.loadSchema should be a function\");\n        }\n        const { loadSchema } = this.opts;\n        return runCompileAsync.call(this, schema, meta);\n        async function runCompileAsync(_schema, _meta) {\n            await loadMetaSchema.call(this, _schema.$schema);\n            const sch = this._addSchema(_schema, _meta);\n            return sch.validate || _compileAsync.call(this, sch);\n        }\n        async function loadMetaSchema($ref) {\n            if ($ref && !this.getSchema($ref)) {\n                await runCompileAsync.call(this, { $ref }, true);\n            }\n        }\n        async function _compileAsync(sch) {\n            try {\n                return this._compileSchemaEnv(sch);\n            }\n            catch (e) {\n                if (!(e instanceof ref_error_1.default))\n                    throw e;\n                checkLoaded.call(this, e);\n                await loadMissingSchema.call(this, e.missingSchema);\n                return _compileAsync.call(this, sch);\n            }\n        }\n        function checkLoaded({ missingSchema: ref, missingRef }) {\n            if (this.refs[ref]) {\n                throw new Error(`AnySchema ${ref} is loaded but ${missingRef} cannot be resolved`);\n            }\n        }\n        async function loadMissingSchema(ref) {\n            const _schema = await _loadSchema.call(this, ref);\n            if (!this.refs[ref])\n                await loadMetaSchema.call(this, _schema.$schema);\n            if (!this.refs[ref])\n                this.addSchema(_schema, ref, meta);\n        }\n        async function _loadSchema(ref) {\n            const p = this._loading[ref];\n            if (p)\n                return p;\n            try {\n                return await (this._loading[ref] = loadSchema(ref));\n            }\n            finally {\n                delete this._loading[ref];\n            }\n        }\n    }\n    // Adds schema to the instance\n    addSchema(schema, // If array is passed, `key` will be ignored\n    key, // Optional schema key. Can be passed to `validate` method instead of schema object or id/ref. One schema per instance can have empty `id` and `key`.\n    _meta, // true if schema is a meta-schema. Used internally, addMetaSchema should be used instead.\n    _validateSchema = this.opts.validateSchema // false to skip schema validation. Used internally, option validateSchema should be used instead.\n    ) {\n        if (Array.isArray(schema)) {\n            for (const sch of schema)\n                this.addSchema(sch, undefined, _meta, _validateSchema);\n            return this;\n        }\n        let id;\n        if (typeof schema === \"object\") {\n            const { schemaId } = this.opts;\n            id = schema[schemaId];\n            if (id !== undefined && typeof id != \"string\") {\n                throw new Error(`schema ${schemaId} must be string`);\n            }\n        }\n        key = (0, resolve_1.normalizeId)(key || id);\n        this._checkUnique(key);\n        this.schemas[key] = this._addSchema(schema, _meta, key, _validateSchema, true);\n        return this;\n    }\n    // Add schema that will be used to validate other schemas\n    // options in META_IGNORE_OPTIONS are alway set to false\n    addMetaSchema(schema, key, // schema key\n    _validateSchema = this.opts.validateSchema // false to skip schema validation, can be used to override validateSchema option for meta-schema\n    ) {\n        this.addSchema(schema, key, true, _validateSchema);\n        return this;\n    }\n    //  Validate schema against its meta-schema\n    validateSchema(schema, throwOrLogError) {\n        if (typeof schema == \"boolean\")\n            return true;\n        let $schema;\n        $schema = schema.$schema;\n        if ($schema !== undefined && typeof $schema != \"string\") {\n            throw new Error(\"$schema must be a string\");\n        }\n        $schema = $schema || this.opts.defaultMeta || this.defaultMeta();\n        if (!$schema) {\n            this.logger.warn(\"meta-schema not available\");\n            this.errors = null;\n            return true;\n        }\n        const valid = this.validate($schema, schema);\n        if (!valid && throwOrLogError) {\n            const message = \"schema is invalid: \" + this.errorsText();\n            if (this.opts.validateSchema === \"log\")\n                this.logger.error(message);\n            else\n                throw new Error(message);\n        }\n        return valid;\n    }\n    // Get compiled schema by `key` or `ref`.\n    // (`key` that was passed to `addSchema` or full schema reference - `schema.$id` or resolved id)\n    getSchema(keyRef) {\n        let sch;\n        while (typeof (sch = getSchEnv.call(this, keyRef)) == \"string\")\n            keyRef = sch;\n        if (sch === undefined) {\n            const { schemaId } = this.opts;\n            const root = new compile_1.SchemaEnv({ schema: {}, schemaId });\n            sch = compile_1.resolveSchema.call(this, root, keyRef);\n            if (!sch)\n                return;\n            this.refs[keyRef] = sch;\n        }\n        return (sch.validate || this._compileSchemaEnv(sch));\n    }\n    // Remove cached schema(s).\n    // If no parameter is passed all schemas but meta-schemas are removed.\n    // If RegExp is passed all schemas with key/id matching pattern but meta-schemas are removed.\n    // Even if schema is referenced by other schemas it still can be removed as other schemas have local references.\n    removeSchema(schemaKeyRef) {\n        if (schemaKeyRef instanceof RegExp) {\n            this._removeAllSchemas(this.schemas, schemaKeyRef);\n            this._removeAllSchemas(this.refs, schemaKeyRef);\n            return this;\n        }\n        switch (typeof schemaKeyRef) {\n            case \"undefined\":\n                this._removeAllSchemas(this.schemas);\n                this._removeAllSchemas(this.refs);\n                this._cache.clear();\n                return this;\n            case \"string\": {\n                const sch = getSchEnv.call(this, schemaKeyRef);\n                if (typeof sch == \"object\")\n                    this._cache.delete(sch.schema);\n                delete this.schemas[schemaKeyRef];\n                delete this.refs[schemaKeyRef];\n                return this;\n            }\n            case \"object\": {\n                const cacheKey = schemaKeyRef;\n                this._cache.delete(cacheKey);\n                let id = schemaKeyRef[this.opts.schemaId];\n                if (id) {\n                    id = (0, resolve_1.normalizeId)(id);\n                    delete this.schemas[id];\n                    delete this.refs[id];\n                }\n                return this;\n            }\n            default:\n                throw new Error(\"ajv.removeSchema: invalid parameter\");\n        }\n    }\n    // add \"vocabulary\" - a collection of keywords\n    addVocabulary(definitions) {\n        for (const def of definitions)\n            this.addKeyword(def);\n        return this;\n    }\n    addKeyword(kwdOrDef, def // deprecated\n    ) {\n        let keyword;\n        if (typeof kwdOrDef == \"string\") {\n            keyword = kwdOrDef;\n            if (typeof def == \"object\") {\n                this.logger.warn(\"these parameters are deprecated, see docs for addKeyword\");\n                def.keyword = keyword;\n            }\n        }\n        else if (typeof kwdOrDef == \"object\" && def === undefined) {\n            def = kwdOrDef;\n            keyword = def.keyword;\n            if (Array.isArray(keyword) && !keyword.length) {\n                throw new Error(\"addKeywords: keyword must be string or non-empty array\");\n            }\n        }\n        else {\n            throw new Error(\"invalid addKeywords parameters\");\n        }\n        checkKeyword.call(this, keyword, def);\n        if (!def) {\n            (0, util_1.eachItem)(keyword, (kwd) => addRule.call(this, kwd));\n            return this;\n        }\n        keywordMetaschema.call(this, def);\n        const definition = {\n            ...def,\n            type: (0, dataType_1.getJSONTypes)(def.type),\n            schemaType: (0, dataType_1.getJSONTypes)(def.schemaType),\n        };\n        (0, util_1.eachItem)(keyword, definition.type.length === 0\n            ? (k) => addRule.call(this, k, definition)\n            : (k) => definition.type.forEach((t) => addRule.call(this, k, definition, t)));\n        return this;\n    }\n    getKeyword(keyword) {\n        const rule = this.RULES.all[keyword];\n        return typeof rule == \"object\" ? rule.definition : !!rule;\n    }\n    // Remove keyword\n    removeKeyword(keyword) {\n        // TODO return type should be Ajv\n        const { RULES } = this;\n        delete RULES.keywords[keyword];\n        delete RULES.all[keyword];\n        for (const group of RULES.rules) {\n            const i = group.rules.findIndex((rule) => rule.keyword === keyword);\n            if (i >= 0)\n                group.rules.splice(i, 1);\n        }\n        return this;\n    }\n    // Add format\n    addFormat(name, format) {\n        if (typeof format == \"string\")\n            format = new RegExp(format);\n        this.formats[name] = format;\n        return this;\n    }\n    errorsText(errors = this.errors, // optional array of validation errors\n    { separator = \", \", dataVar = \"data\" } = {} // optional options with properties `separator` and `dataVar`\n    ) {\n        if (!errors || errors.length === 0)\n            return \"No errors\";\n        return errors\n            .map((e) => `${dataVar}${e.instancePath} ${e.message}`)\n            .reduce((text, msg) => text + separator + msg);\n    }\n    $dataMetaSchema(metaSchema, keywordsJsonPointers) {\n        const rules = this.RULES.all;\n        metaSchema = JSON.parse(JSON.stringify(metaSchema));\n        for (const jsonPointer of keywordsJsonPointers) {\n            const segments = jsonPointer.split(\"/\").slice(1); // first segment is an empty string\n            let keywords = metaSchema;\n            for (const seg of segments)\n                keywords = keywords[seg];\n            for (const key in rules) {\n                const rule = rules[key];\n                if (typeof rule != \"object\")\n                    continue;\n                const { $data } = rule.definition;\n                const schema = keywords[key];\n                if ($data && schema)\n                    keywords[key] = schemaOrData(schema);\n            }\n        }\n        return metaSchema;\n    }\n    _removeAllSchemas(schemas, regex) {\n        for (const keyRef in schemas) {\n            const sch = schemas[keyRef];\n            if (!regex || regex.test(keyRef)) {\n                if (typeof sch == \"string\") {\n                    delete schemas[keyRef];\n                }\n                else if (sch && !sch.meta) {\n                    this._cache.delete(sch.schema);\n                    delete schemas[keyRef];\n                }\n            }\n        }\n    }\n    _addSchema(schema, meta, baseId, validateSchema = this.opts.validateSchema, addSchema = this.opts.addUsedSchema) {\n        let id;\n        const { schemaId } = this.opts;\n        if (typeof schema == \"object\") {\n            id = schema[schemaId];\n        }\n        else {\n            if (this.opts.jtd)\n                throw new Error(\"schema must be object\");\n            else if (typeof schema != \"boolean\")\n                throw new Error(\"schema must be object or boolean\");\n        }\n        let sch = this._cache.get(schema);\n        if (sch !== undefined)\n            return sch;\n        baseId = (0, resolve_1.normalizeId)(id || baseId);\n        const localRefs = resolve_1.getSchemaRefs.call(this, schema, baseId);\n        sch = new compile_1.SchemaEnv({ schema, schemaId, meta, baseId, localRefs });\n        this._cache.set(sch.schema, sch);\n        if (addSchema && !baseId.startsWith(\"#\")) {\n            // TODO atm it is allowed to overwrite schemas without id (instead of not adding them)\n            if (baseId)\n                this._checkUnique(baseId);\n            this.refs[baseId] = sch;\n        }\n        if (validateSchema)\n            this.validateSchema(schema, true);\n        return sch;\n    }\n    _checkUnique(id) {\n        if (this.schemas[id] || this.refs[id]) {\n            throw new Error(`schema with key or id \"${id}\" already exists`);\n        }\n    }\n    _compileSchemaEnv(sch) {\n        if (sch.meta)\n            this._compileMetaSchema(sch);\n        else\n            compile_1.compileSchema.call(this, sch);\n        /* istanbul ignore if */\n        if (!sch.validate)\n            throw new Error(\"ajv implementation error\");\n        return sch.validate;\n    }\n    _compileMetaSchema(sch) {\n        const currentOpts = this.opts;\n        this.opts = this._metaOpts;\n        try {\n            compile_1.compileSchema.call(this, sch);\n        }\n        finally {\n            this.opts = currentOpts;\n        }\n    }\n}\nAjv.ValidationError = validation_error_1.default;\nAjv.MissingRefError = ref_error_1.default;\nexports.default = Ajv;\nfunction checkOptions(checkOpts, options, msg, log = \"error\") {\n    for (const key in checkOpts) {\n        const opt = key;\n        if (opt in options)\n            this.logger[log](`${msg}: option ${key}. ${checkOpts[opt]}`);\n    }\n}\nfunction getSchEnv(keyRef) {\n    keyRef = (0, resolve_1.normalizeId)(keyRef); // TODO tests fail without this line\n    return this.schemas[keyRef] || this.refs[keyRef];\n}\nfunction addInitialSchemas() {\n    const optsSchemas = this.opts.schemas;\n    if (!optsSchemas)\n        return;\n    if (Array.isArray(optsSchemas))\n        this.addSchema(optsSchemas);\n    else\n        for (const key in optsSchemas)\n            this.addSchema(optsSchemas[key], key);\n}\nfunction addInitialFormats() {\n    for (const name in this.opts.formats) {\n        const format = this.opts.formats[name];\n        if (format)\n            this.addFormat(name, format);\n    }\n}\nfunction addInitialKeywords(defs) {\n    if (Array.isArray(defs)) {\n        this.addVocabulary(defs);\n        return;\n    }\n    this.logger.warn(\"keywords option as map is deprecated, pass array\");\n    for (const keyword in defs) {\n        const def = defs[keyword];\n        if (!def.keyword)\n            def.keyword = keyword;\n        this.addKeyword(def);\n    }\n}\nfunction getMetaSchemaOptions() {\n    const metaOpts = { ...this.opts };\n    for (const opt of META_IGNORE_OPTIONS)\n        delete metaOpts[opt];\n    return metaOpts;\n}\nconst noLogs = { log() { }, warn() { }, error() { } };\nfunction getLogger(logger) {\n    if (logger === false)\n        return noLogs;\n    if (logger === undefined)\n        return console;\n    if (logger.log && logger.warn && logger.error)\n        return logger;\n    throw new Error(\"logger must implement log, warn and error methods\");\n}\nconst KEYWORD_NAME = /^[a-z_$][a-z0-9_$:-]*$/i;\nfunction checkKeyword(keyword, def) {\n    const { RULES } = this;\n    (0, util_1.eachItem)(keyword, (kwd) => {\n        if (RULES.keywords[kwd])\n            throw new Error(`Keyword ${kwd} is already defined`);\n        if (!KEYWORD_NAME.test(kwd))\n            throw new Error(`Keyword ${kwd} has invalid name`);\n    });\n    if (!def)\n        return;\n    if (def.$data && !(\"code\" in def || \"validate\" in def)) {\n        throw new Error('$data keyword must have \"code\" or \"validate\" function');\n    }\n}\nfunction addRule(keyword, definition, dataType) {\n    var _a;\n    const post = definition === null || definition === void 0 ? void 0 : definition.post;\n    if (dataType && post)\n        throw new Error('keyword with \"post\" flag cannot have \"type\"');\n    const { RULES } = this;\n    let ruleGroup = post ? RULES.post : RULES.rules.find(({ type: t }) => t === dataType);\n    if (!ruleGroup) {\n        ruleGroup = { type: dataType, rules: [] };\n        RULES.rules.push(ruleGroup);\n    }\n    RULES.keywords[keyword] = true;\n    if (!definition)\n        return;\n    const rule = {\n        keyword,\n        definition: {\n            ...definition,\n            type: (0, dataType_1.getJSONTypes)(definition.type),\n            schemaType: (0, dataType_1.getJSONTypes)(definition.schemaType),\n        },\n    };\n    if (definition.before)\n        addBeforeRule.call(this, ruleGroup, rule, definition.before);\n    else\n        ruleGroup.rules.push(rule);\n    RULES.all[keyword] = rule;\n    (_a = definition.implements) === null || _a === void 0 ? void 0 : _a.forEach((kwd) => this.addKeyword(kwd));\n}\nfunction addBeforeRule(ruleGroup, rule, before) {\n    const i = ruleGroup.rules.findIndex((_rule) => _rule.keyword === before);\n    if (i >= 0) {\n        ruleGroup.rules.splice(i, 0, rule);\n    }\n    else {\n        ruleGroup.rules.push(rule);\n        this.logger.warn(`rule ${before} is not defined`);\n    }\n}\nfunction keywordMetaschema(def) {\n    let { metaSchema } = def;\n    if (metaSchema === undefined)\n        return;\n    if (def.$data && this.opts.$data)\n        metaSchema = schemaOrData(metaSchema);\n    def.validateSchema = this.compile(metaSchema, true);\n}\nconst $dataRef = {\n    $ref: \"https://raw.githubusercontent.com/ajv-validator/ajv/master/lib/refs/data.json#\",\n};\nfunction schemaOrData(schema) {\n    return { anyOf: [schema, $dataRef] };\n}\n//# sourceMappingURL=core.js.map","\"use strict\";\nObject.defineProperty(exports, \"__esModule\", { value: true });\nconst def = {\n    keyword: \"id\",\n    code() {\n        throw new Error('NOT SUPPORTED: keyword \"id\", use \"$id\" for schema ID');\n    },\n};\nexports.default = def;\n//# sourceMappingURL=id.js.map","\"use strict\";\nObject.defineProperty(exports, \"__esModule\", { value: true });\nexports.callRef = exports.getValidate = void 0;\nconst ref_error_1 = require(\"../../compile/ref_error\");\nconst code_1 = require(\"../code\");\nconst codegen_1 = require(\"../../compile/codegen\");\nconst names_1 = require(\"../../compile/names\");\nconst compile_1 = require(\"../../compile\");\nconst util_1 = require(\"../../compile/util\");\nconst def = {\n    keyword: \"$ref\",\n    schemaType: \"string\",\n    code(cxt) {\n        const { gen, schema: $ref, it } = cxt;\n        const { baseId, schemaEnv: env, validateName, opts, self } = it;\n        const { root } = env;\n        if (($ref === \"#\" || $ref === \"#/\") && baseId === root.baseId)\n            return callRootRef();\n        const schOrEnv = compile_1.resolveRef.call(self, root, baseId, $ref);\n        if (schOrEnv === undefined)\n            throw new ref_error_1.default(it.opts.uriResolver, baseId, $ref);\n        if (schOrEnv instanceof compile_1.SchemaEnv)\n            return callValidate(schOrEnv);\n        return inlineRefSchema(schOrEnv);\n        function callRootRef() {\n            if (env === root)\n                return callRef(cxt, validateName, env, env.$async);\n            const rootName = gen.scopeValue(\"root\", { ref: root });\n            return callRef(cxt, (0, codegen_1._) `${rootName}.validate`, root, root.$async);\n        }\n        function callValidate(sch) {\n            const v = getValidate(cxt, sch);\n            callRef(cxt, v, sch, sch.$async);\n        }\n        function inlineRefSchema(sch) {\n            const schName = gen.scopeValue(\"schema\", opts.code.source === true ? { ref: sch, code: (0, codegen_1.stringify)(sch) } : { ref: sch });\n            const valid = gen.name(\"valid\");\n            const schCxt = cxt.subschema({\n                schema: sch,\n                dataTypes: [],\n                schemaPath: codegen_1.nil,\n                topSchemaRef: schName,\n                errSchemaPath: $ref,\n            }, valid);\n            cxt.mergeEvaluated(schCxt);\n            cxt.ok(valid);\n        }\n    },\n};\nfunction getValidate(cxt, sch) {\n    const { gen } = cxt;\n    return sch.validate\n        ? gen.scopeValue(\"validate\", { ref: sch.validate })\n        : (0, codegen_1._) `${gen.scopeValue(\"wrapper\", { ref: sch })}.validate`;\n}\nexports.getValidate = getValidate;\nfunction callRef(cxt, v, sch, $async) {\n    const { gen, it } = cxt;\n    const { allErrors, schemaEnv: env, opts } = it;\n    const passCxt = opts.passContext ? names_1.default.this : codegen_1.nil;\n    if ($async)\n        callAsyncRef();\n    else\n        callSyncRef();\n    function callAsyncRef() {\n        if (!env.$async)\n            throw new Error(\"async schema referenced by sync schema\");\n        const valid = gen.let(\"valid\");\n        gen.try(() => {\n            gen.code((0, codegen_1._) `await ${(0, code_1.callValidateCode)(cxt, v, passCxt)}`);\n            addEvaluatedFrom(v); // TODO will not work with async, it has to be returned with the result\n            if (!allErrors)\n                gen.assign(valid, true);\n        }, (e) => {\n            gen.if((0, codegen_1._) `!(${e} instanceof ${it.ValidationError})`, () => gen.throw(e));\n            addErrorsFrom(e);\n            if (!allErrors)\n                gen.assign(valid, false);\n        });\n        cxt.ok(valid);\n    }\n    function callSyncRef() {\n        cxt.result((0, code_1.callValidateCode)(cxt, v, passCxt), () => addEvaluatedFrom(v), () => addErrorsFrom(v));\n    }\n    function addErrorsFrom(source) {\n        const errs = (0, codegen_1._) `${source}.errors`;\n        gen.assign(names_1.default.vErrors, (0, codegen_1._) `${names_1.default.vErrors} === null ? ${errs} : ${names_1.default.vErrors}.concat(${errs})`); // TODO tagged\n        gen.assign(names_1.default.errors, (0, codegen_1._) `${names_1.default.vErrors}.length`);\n    }\n    function addEvaluatedFrom(source) {\n        var _a;\n        if (!it.opts.unevaluated)\n            return;\n        const schEvaluated = (_a = sch === null || sch === void 0 ? void 0 : sch.validate) === null || _a === void 0 ? void 0 : _a.evaluated;\n        // TODO refactor\n        if (it.props !== true) {\n            if (schEvaluated && !schEvaluated.dynamicProps) {\n                if (schEvaluated.props !== undefined) {\n                    it.props = util_1.mergeEvaluated.props(gen, schEvaluated.props, it.props);\n                }\n            }\n            else {\n                const props = gen.var(\"props\", (0, codegen_1._) `${source}.evaluated.props`);\n                it.props = util_1.mergeEvaluated.props(gen, props, it.props, codegen_1.Name);\n            }\n        }\n        if (it.items !== true) {\n            if (schEvaluated && !schEvaluated.dynamicItems) {\n                if (schEvaluated.items !== undefined) {\n                    it.items = util_1.mergeEvaluated.items(gen, schEvaluated.items, it.items);\n                }\n            }\n            else {\n                const items = gen.var(\"items\", (0, codegen_1._) `${source}.evaluated.items`);\n                it.items = util_1.mergeEvaluated.items(gen, items, it.items, codegen_1.Name);\n            }\n        }\n    }\n}\nexports.callRef = callRef;\nexports.default = def;\n//# sourceMappingURL=ref.js.map","\"use strict\";\nObject.defineProperty(exports, \"__esModule\", { value: true });\nconst id_1 = require(\"./id\");\nconst ref_1 = require(\"./ref\");\nconst core = [\n    \"$schema\",\n    \"$id\",\n    \"$defs\",\n    \"$vocabulary\",\n    { keyword: \"$comment\" },\n    \"definitions\",\n    id_1.default,\n    ref_1.default,\n];\nexports.default = core;\n//# sourceMappingURL=index.js.map","\"use strict\";\nObject.defineProperty(exports, \"__esModule\", { value: true });\nconst codegen_1 = require(\"../../compile/codegen\");\nconst ops = codegen_1.operators;\nconst KWDs = {\n    maximum: { okStr: \"<=\", ok: ops.LTE, fail: ops.GT },\n    minimum: { okStr: \">=\", ok: ops.GTE, fail: ops.LT },\n    exclusiveMaximum: { okStr: \"<\", ok: ops.LT, fail: ops.GTE },\n    exclusiveMinimum: { okStr: \">\", ok: ops.GT, fail: ops.LTE },\n};\nconst error = {\n    message: ({ keyword, schemaCode }) => (0, codegen_1.str) `must be ${KWDs[keyword].okStr} ${schemaCode}`,\n    params: ({ keyword, schemaCode }) => (0, codegen_1._) `{comparison: ${KWDs[keyword].okStr}, limit: ${schemaCode}}`,\n};\nconst def = {\n    keyword: Object.keys(KWDs),\n    type: \"number\",\n    schemaType: \"number\",\n    $data: true,\n    error,\n    code(cxt) {\n        const { keyword, data, schemaCode } = cxt;\n        cxt.fail$data((0, codegen_1._) `${data} ${KWDs[keyword].fail} ${schemaCode} || isNaN(${data})`);\n    },\n};\nexports.default = def;\n//# sourceMappingURL=limitNumber.js.map","\"use strict\";\nObject.defineProperty(exports, \"__esModule\", { value: true });\nconst codegen_1 = require(\"../../compile/codegen\");\nconst error = {\n    message: ({ schemaCode }) => (0, codegen_1.str) `must be multiple of ${schemaCode}`,\n    params: ({ schemaCode }) => (0, codegen_1._) `{multipleOf: ${schemaCode}}`,\n};\nconst def = {\n    keyword: \"multipleOf\",\n    type: \"number\",\n    schemaType: \"number\",\n    $data: true,\n    error,\n    code(cxt) {\n        const { gen, data, schemaCode, it } = cxt;\n        // const bdt = bad$DataType(schemaCode, <string>def.schemaType, $data)\n        const prec = it.opts.multipleOfPrecision;\n        const res = gen.let(\"res\");\n        const invalid = prec\n            ? (0, codegen_1._) `Math.abs(Math.round(${res}) - ${res}) > 1e-${prec}`\n            : (0, codegen_1._) `${res} !== parseInt(${res})`;\n        cxt.fail$data((0, codegen_1._) `(${schemaCode} === 0 || (${res} = ${data}/${schemaCode}, ${invalid}))`);\n    },\n};\nexports.default = def;\n//# sourceMappingURL=multipleOf.js.map","\"use strict\";\nObject.defineProperty(exports, \"__esModule\", { value: true });\n// https://mathiasbynens.be/notes/javascript-encoding\n// https://github.com/bestiejs/punycode.js - punycode.ucs2.decode\nfunction ucs2length(str) {\n    const len = str.length;\n    let length = 0;\n    let pos = 0;\n    let value;\n    while (pos < len) {\n        length++;\n        value = str.charCodeAt(pos++);\n        if (value >= 0xd800 && value <= 0xdbff && pos < len) {\n            // high surrogate, and there is a next character\n            value = str.charCodeAt(pos);\n            if ((value & 0xfc00) === 0xdc00)\n                pos++; // low surrogate\n        }\n    }\n    return length;\n}\nexports.default = ucs2length;\nucs2length.code = 'require(\"ajv/dist/runtime/ucs2length\").default';\n//# sourceMappingURL=ucs2length.js.map","\"use strict\";\nObject.defineProperty(exports, \"__esModule\", { value: true });\nconst codegen_1 = require(\"../../compile/codegen\");\nconst util_1 = require(\"../../compile/util\");\nconst ucs2length_1 = require(\"../../runtime/ucs2length\");\nconst error = {\n    message({ keyword, schemaCode }) {\n        const comp = keyword === \"maxLength\" ? \"more\" : \"fewer\";\n        return (0, codegen_1.str) `must NOT have ${comp} than ${schemaCode} characters`;\n    },\n    params: ({ schemaCode }) => (0, codegen_1._) `{limit: ${schemaCode}}`,\n};\nconst def = {\n    keyword: [\"maxLength\", \"minLength\"],\n    type: \"string\",\n    schemaType: \"number\",\n    $data: true,\n    error,\n    code(cxt) {\n        const { keyword, data, schemaCode, it } = cxt;\n        const op = keyword === \"maxLength\" ? codegen_1.operators.GT : codegen_1.operators.LT;\n        const len = it.opts.unicode === false ? (0, codegen_1._) `${data}.length` : (0, codegen_1._) `${(0, util_1.useFunc)(cxt.gen, ucs2length_1.default)}(${data})`;\n        cxt.fail$data((0, codegen_1._) `${len} ${op} ${schemaCode}`);\n    },\n};\nexports.default = def;\n//# sourceMappingURL=limitLength.js.map","\"use strict\";\nObject.defineProperty(exports, \"__esModule\", { value: true });\nconst code_1 = require(\"../code\");\nconst util_1 = require(\"../../compile/util\");\nconst codegen_1 = require(\"../../compile/codegen\");\nconst error = {\n    message: ({ schemaCode }) => (0, codegen_1.str) `must match pattern \"${schemaCode}\"`,\n    params: ({ schemaCode }) => (0, codegen_1._) `{pattern: ${schemaCode}}`,\n};\nconst def = {\n    keyword: \"pattern\",\n    type: \"string\",\n    schemaType: \"string\",\n    $data: true,\n    error,\n    code(cxt) {\n        const { gen, data, $data, schema, schemaCode, it } = cxt;\n        const u = it.opts.unicodeRegExp ? \"u\" : \"\";\n        if ($data) {\n            const { regExp } = it.opts.code;\n            const regExpCode = regExp.code === \"new RegExp\" ? (0, codegen_1._) `new RegExp` : (0, util_1.useFunc)(gen, regExp);\n            const valid = gen.let(\"valid\");\n            gen.try(() => gen.assign(valid, (0, codegen_1._) `${regExpCode}(${schemaCode}, ${u}).test(${data})`), () => gen.assign(valid, false));\n            cxt.fail$data((0, codegen_1._) `!${valid}`);\n        }\n        else {\n            const regExp = (0, code_1.usePattern)(cxt, schema);\n            cxt.fail$data((0, codegen_1._) `!${regExp}.test(${data})`);\n        }\n    },\n};\nexports.default = def;\n//# sourceMappingURL=pattern.js.map","\"use strict\";\nObject.defineProperty(exports, \"__esModule\", { value: true });\nconst codegen_1 = require(\"../../compile/codegen\");\nconst error = {\n    message({ keyword, schemaCode }) {\n        const comp = keyword === \"maxProperties\" ? \"more\" : \"fewer\";\n        return (0, codegen_1.str) `must NOT have ${comp} than ${schemaCode} properties`;\n    },\n    params: ({ schemaCode }) => (0, codegen_1._) `{limit: ${schemaCode}}`,\n};\nconst def = {\n    keyword: [\"maxProperties\", \"minProperties\"],\n    type: \"object\",\n    schemaType: \"number\",\n    $data: true,\n    error,\n    code(cxt) {\n        const { keyword, data, schemaCode } = cxt;\n        const op = keyword === \"maxProperties\" ? codegen_1.operators.GT : codegen_1.operators.LT;\n        cxt.fail$data((0, codegen_1._) `Object.keys(${data}).length ${op} ${schemaCode}`);\n    },\n};\nexports.default = def;\n//# sourceMappingURL=limitProperties.js.map","\"use strict\";\nObject.defineProperty(exports, \"__esModule\", { value: true });\nconst code_1 = require(\"../code\");\nconst codegen_1 = require(\"../../compile/codegen\");\nconst util_1 = require(\"../../compile/util\");\nconst error = {\n    message: ({ params: { missingProperty } }) => (0, codegen_1.str) `must have required property '${missingProperty}'`,\n    params: ({ params: { missingProperty } }) => (0, codegen_1._) `{missingProperty: ${missingProperty}}`,\n};\nconst def = {\n    keyword: \"required\",\n    type: \"object\",\n    schemaType: \"array\",\n    $data: true,\n    error,\n    code(cxt) {\n        const { gen, schema, schemaCode, data, $data, it } = cxt;\n        const { opts } = it;\n        if (!$data && schema.length === 0)\n            return;\n        const useLoop = schema.length >= opts.loopRequired;\n        if (it.allErrors)\n            allErrorsMode();\n        else\n            exitOnErrorMode();\n        if (opts.strictRequired) {\n            const props = cxt.parentSchema.properties;\n            const { definedProperties } = cxt.it;\n            for (const requiredKey of schema) {\n                if ((props === null || props === void 0 ? void 0 : props[requiredKey]) === undefined && !definedProperties.has(requiredKey)) {\n                    const schemaPath = it.schemaEnv.baseId + it.errSchemaPath;\n                    const msg = `required property \"${requiredKey}\" is not defined at \"${schemaPath}\" (strictRequired)`;\n                    (0, util_1.checkStrictMode)(it, msg, it.opts.strictRequired);\n                }\n            }\n        }\n        function allErrorsMode() {\n            if (useLoop || $data) {\n                cxt.block$data(codegen_1.nil, loopAllRequired);\n            }\n            else {\n                for (const prop of schema) {\n                    (0, code_1.checkReportMissingProp)(cxt, prop);\n                }\n            }\n        }\n        function exitOnErrorMode() {\n            const missing = gen.let(\"missing\");\n            if (useLoop || $data) {\n                const valid = gen.let(\"valid\", true);\n                cxt.block$data(valid, () => loopUntilMissing(missing, valid));\n                cxt.ok(valid);\n            }\n            else {\n                gen.if((0, code_1.checkMissingProp)(cxt, schema, missing));\n                (0, code_1.reportMissingProp)(cxt, missing);\n                gen.else();\n            }\n        }\n        function loopAllRequired() {\n            gen.forOf(\"prop\", schemaCode, (prop) => {\n                cxt.setParams({ missingProperty: prop });\n                gen.if((0, code_1.noPropertyInData)(gen, data, prop, opts.ownProperties), () => cxt.error());\n            });\n        }\n        function loopUntilMissing(missing, valid) {\n            cxt.setParams({ missingProperty: missing });\n            gen.forOf(missing, schemaCode, () => {\n                gen.assign(valid, (0, code_1.propertyInData)(gen, data, missing, opts.ownProperties));\n                gen.if((0, codegen_1.not)(valid), () => {\n                    cxt.error();\n                    gen.break();\n                });\n            }, codegen_1.nil);\n        }\n    },\n};\nexports.default = def;\n//# sourceMappingURL=required.js.map","\"use strict\";\nObject.defineProperty(exports, \"__esModule\", { value: true });\nconst codegen_1 = require(\"../../compile/codegen\");\nconst error = {\n    message({ keyword, schemaCode }) {\n        const comp = keyword === \"maxItems\" ? \"more\" : \"fewer\";\n        return (0, codegen_1.str) `must NOT have ${comp} than ${schemaCode} items`;\n    },\n    params: ({ schemaCode }) => (0, codegen_1._) `{limit: ${schemaCode}}`,\n};\nconst def = {\n    keyword: [\"maxItems\", \"minItems\"],\n    type: \"array\",\n    schemaType: \"number\",\n    $data: true,\n    error,\n    code(cxt) {\n        const { keyword, data, schemaCode } = cxt;\n        const op = keyword === \"maxItems\" ? codegen_1.operators.GT : codegen_1.operators.LT;\n        cxt.fail$data((0, codegen_1._) `${data}.length ${op} ${schemaCode}`);\n    },\n};\nexports.default = def;\n//# sourceMappingURL=limitItems.js.map","\"use strict\";\nObject.defineProperty(exports, \"__esModule\", { value: true });\n// https://github.com/ajv-validator/ajv/issues/889\nconst equal = require(\"fast-deep-equal\");\nequal.code = 'require(\"ajv/dist/runtime/equal\").default';\nexports.default = equal;\n//# sourceMappingURL=equal.js.map","\"use strict\";\nObject.defineProperty(exports, \"__esModule\", { value: true });\nconst dataType_1 = require(\"../../compile/validate/dataType\");\nconst codegen_1 = require(\"../../compile/codegen\");\nconst util_1 = require(\"../../compile/util\");\nconst equal_1 = require(\"../../runtime/equal\");\nconst error = {\n    message: ({ params: { i, j } }) => (0, codegen_1.str) `must NOT have duplicate items (items ## ${j} and ${i} are identical)`,\n    params: ({ params: { i, j } }) => (0, codegen_1._) `{i: ${i}, j: ${j}}`,\n};\nconst def = {\n    keyword: \"uniqueItems\",\n    type: \"array\",\n    schemaType: \"boolean\",\n    $data: true,\n    error,\n    code(cxt) {\n        const { gen, data, $data, schema, parentSchema, schemaCode, it } = cxt;\n        if (!$data && !schema)\n            return;\n        const valid = gen.let(\"valid\");\n        const itemTypes = parentSchema.items ? (0, dataType_1.getSchemaTypes)(parentSchema.items) : [];\n        cxt.block$data(valid, validateUniqueItems, (0, codegen_1._) `${schemaCode} === false`);\n        cxt.ok(valid);\n        function validateUniqueItems() {\n            const i = gen.let(\"i\", (0, codegen_1._) `${data}.length`);\n            const j = gen.let(\"j\");\n            cxt.setParams({ i, j });\n            gen.assign(valid, true);\n            gen.if((0, codegen_1._) `${i} > 1`, () => (canOptimize() ? loopN : loopN2)(i, j));\n        }\n        function canOptimize() {\n            return itemTypes.length > 0 && !itemTypes.some((t) => t === \"object\" || t === \"array\");\n        }\n        function loopN(i, j) {\n            const item = gen.name(\"item\");\n            const wrongType = (0, dataType_1.checkDataTypes)(itemTypes, item, it.opts.strictNumbers, dataType_1.DataType.Wrong);\n            const indices = gen.const(\"indices\", (0, codegen_1._) `{}`);\n            gen.for((0, codegen_1._) `;${i}--;`, () => {\n                gen.let(item, (0, codegen_1._) `${data}[${i}]`);\n                gen.if(wrongType, (0, codegen_1._) `continue`);\n                if (itemTypes.length > 1)\n                    gen.if((0, codegen_1._) `typeof ${item} == \"string\"`, (0, codegen_1._) `${item} += \"_\"`);\n                gen\n                    .if((0, codegen_1._) `typeof ${indices}[${item}] == \"number\"`, () => {\n                    gen.assign(j, (0, codegen_1._) `${indices}[${item}]`);\n                    cxt.error();\n                    gen.assign(valid, false).break();\n                })\n                    .code((0, codegen_1._) `${indices}[${item}] = ${i}`);\n            });\n        }\n        function loopN2(i, j) {\n            const eql = (0, util_1.useFunc)(gen, equal_1.default);\n            const outer = gen.name(\"outer\");\n            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}])`, () => {\n                cxt.error();\n                gen.assign(valid, false).break(outer);\n            })));\n        }\n    },\n};\nexports.default = def;\n//# sourceMappingURL=uniqueItems.js.map","\"use strict\";\nObject.defineProperty(exports, \"__esModule\", { value: true });\nconst codegen_1 = require(\"../../compile/codegen\");\nconst util_1 = require(\"../../compile/util\");\nconst equal_1 = require(\"../../runtime/equal\");\nconst error = {\n    message: \"must be equal to constant\",\n    params: ({ schemaCode }) => (0, codegen_1._) `{allowedValue: ${schemaCode}}`,\n};\nconst def = {\n    keyword: \"const\",\n    $data: true,\n    error,\n    code(cxt) {\n        const { gen, data, $data, schemaCode, schema } = cxt;\n        if ($data || (schema && typeof schema == \"object\")) {\n            cxt.fail$data((0, codegen_1._) `!${(0, util_1.useFunc)(gen, equal_1.default)}(${data}, ${schemaCode})`);\n        }\n        else {\n            cxt.fail((0, codegen_1._) `${schema} !== ${data}`);\n        }\n    },\n};\nexports.default = def;\n//# sourceMappingURL=const.js.map","\"use strict\";\nObject.defineProperty(exports, \"__esModule\", { value: true });\nconst codegen_1 = require(\"../../compile/codegen\");\nconst util_1 = require(\"../../compile/util\");\nconst equal_1 = require(\"../../runtime/equal\");\nconst error = {\n    message: \"must be equal to one of the allowed values\",\n    params: ({ schemaCode }) => (0, codegen_1._) `{allowedValues: ${schemaCode}}`,\n};\nconst def = {\n    keyword: \"enum\",\n    schemaType: \"array\",\n    $data: true,\n    error,\n    code(cxt) {\n        const { gen, data, $data, schema, schemaCode, it } = cxt;\n        if (!$data && schema.length === 0)\n            throw new Error(\"enum must have non-empty array\");\n        const useLoop = schema.length >= it.opts.loopEnum;\n        let eql;\n        const getEql = () => (eql !== null && eql !== void 0 ? eql : (eql = (0, util_1.useFunc)(gen, equal_1.default)));\n        let valid;\n        if (useLoop || $data) {\n            valid = gen.let(\"valid\");\n            cxt.block$data(valid, loopEnum);\n        }\n        else {\n            /* istanbul ignore if */\n            if (!Array.isArray(schema))\n                throw new Error(\"ajv implementation error\");\n            const vSchema = gen.const(\"vSchema\", schemaCode);\n            valid = (0, codegen_1.or)(...schema.map((_x, i) => equalCode(vSchema, i)));\n        }\n        cxt.pass(valid);\n        function loopEnum() {\n            gen.assign(valid, false);\n            gen.forOf(\"v\", schemaCode, (v) => gen.if((0, codegen_1._) `${getEql()}(${data}, ${v})`, () => gen.assign(valid, true).break()));\n        }\n        function equalCode(vSchema, i) {\n            const sch = schema[i];\n            return typeof sch === \"object\" && sch !== null\n                ? (0, codegen_1._) `${getEql()}(${data}, ${vSchema}[${i}])`\n                : (0, codegen_1._) `${data} === ${sch}`;\n        }\n    },\n};\nexports.default = def;\n//# sourceMappingURL=enum.js.map","\"use strict\";\nObject.defineProperty(exports, \"__esModule\", { value: true });\nconst limitNumber_1 = require(\"./limitNumber\");\nconst multipleOf_1 = require(\"./multipleOf\");\nconst limitLength_1 = require(\"./limitLength\");\nconst pattern_1 = require(\"./pattern\");\nconst limitProperties_1 = require(\"./limitProperties\");\nconst required_1 = require(\"./required\");\nconst limitItems_1 = require(\"./limitItems\");\nconst uniqueItems_1 = require(\"./uniqueItems\");\nconst const_1 = require(\"./const\");\nconst enum_1 = require(\"./enum\");\nconst validation = [\n    // number\n    limitNumber_1.default,\n    multipleOf_1.default,\n    // string\n    limitLength_1.default,\n    pattern_1.default,\n    // object\n    limitProperties_1.default,\n    required_1.default,\n    // array\n    limitItems_1.default,\n    uniqueItems_1.default,\n    // any\n    { keyword: \"type\", schemaType: [\"string\", \"array\"] },\n    { keyword: \"nullable\", schemaType: \"boolean\" },\n    const_1.default,\n    enum_1.default,\n];\nexports.default = validation;\n//# sourceMappingURL=index.js.map","\"use strict\";\nObject.defineProperty(exports, \"__esModule\", { value: true });\nexports.validateAdditionalItems = void 0;\nconst codegen_1 = require(\"../../compile/codegen\");\nconst util_1 = require(\"../../compile/util\");\nconst error = {\n    message: ({ params: { len } }) => (0, codegen_1.str) `must NOT have more than ${len} items`,\n    params: ({ params: { len } }) => (0, codegen_1._) `{limit: ${len}}`,\n};\nconst def = {\n    keyword: \"additionalItems\",\n    type: \"array\",\n    schemaType: [\"boolean\", \"object\"],\n    before: \"uniqueItems\",\n    error,\n    code(cxt) {\n        const { parentSchema, it } = cxt;\n        const { items } = parentSchema;\n        if (!Array.isArray(items)) {\n            (0, util_1.checkStrictMode)(it, '\"additionalItems\" is ignored when \"items\" is not an array of schemas');\n            return;\n        }\n        validateAdditionalItems(cxt, items);\n    },\n};\nfunction validateAdditionalItems(cxt, items) {\n    const { gen, schema, data, keyword, it } = cxt;\n    it.items = true;\n    const len = gen.const(\"len\", (0, codegen_1._) `${data}.length`);\n    if (schema === false) {\n        cxt.setParams({ len: items.length });\n        cxt.pass((0, codegen_1._) `${len} <= ${items.length}`);\n    }\n    else if (typeof schema == \"object\" && !(0, util_1.alwaysValidSchema)(it, schema)) {\n        const valid = gen.var(\"valid\", (0, codegen_1._) `${len} <= ${items.length}`); // TODO var\n        gen.if((0, codegen_1.not)(valid), () => validateItems(valid));\n        cxt.ok(valid);\n    }\n    function validateItems(valid) {\n        gen.forRange(\"i\", items.length, len, (i) => {\n            cxt.subschema({ keyword, dataProp: i, dataPropType: util_1.Type.Num }, valid);\n            if (!it.allErrors)\n                gen.if((0, codegen_1.not)(valid), () => gen.break());\n        });\n    }\n}\nexports.validateAdditionalItems = validateAdditionalItems;\nexports.default = def;\n//# sourceMappingURL=additionalItems.js.map","\"use strict\";\nObject.defineProperty(exports, \"__esModule\", { value: true });\nexports.validateTuple = void 0;\nconst codegen_1 = require(\"../../compile/codegen\");\nconst util_1 = require(\"../../compile/util\");\nconst code_1 = require(\"../code\");\nconst def = {\n    keyword: \"items\",\n    type: \"array\",\n    schemaType: [\"object\", \"array\", \"boolean\"],\n    before: \"uniqueItems\",\n    code(cxt) {\n        const { schema, it } = cxt;\n        if (Array.isArray(schema))\n            return validateTuple(cxt, \"additionalItems\", schema);\n        it.items = true;\n        if ((0, util_1.alwaysValidSchema)(it, schema))\n            return;\n        cxt.ok((0, code_1.validateArray)(cxt));\n    },\n};\nfunction validateTuple(cxt, extraItems, schArr = cxt.schema) {\n    const { gen, parentSchema, data, keyword, it } = cxt;\n    checkStrictTuple(parentSchema);\n    if (it.opts.unevaluated && schArr.length && it.items !== true) {\n        it.items = util_1.mergeEvaluated.items(gen, schArr.length, it.items);\n    }\n    const valid = gen.name(\"valid\");\n    const len = gen.const(\"len\", (0, codegen_1._) `${data}.length`);\n    schArr.forEach((sch, i) => {\n        if ((0, util_1.alwaysValidSchema)(it, sch))\n            return;\n        gen.if((0, codegen_1._) `${len} > ${i}`, () => cxt.subschema({\n            keyword,\n            schemaProp: i,\n            dataProp: i,\n        }, valid));\n        cxt.ok(valid);\n    });\n    function checkStrictTuple(sch) {\n        const { opts, errSchemaPath } = it;\n        const l = schArr.length;\n        const fullTuple = l === sch.minItems && (l === sch.maxItems || sch[extraItems] === false);\n        if (opts.strictTuples && !fullTuple) {\n            const msg = `\"${keyword}\" is ${l}-tuple, but minItems or maxItems/${extraItems} are not specified or different at path \"${errSchemaPath}\"`;\n            (0, util_1.checkStrictMode)(it, msg, opts.strictTuples);\n        }\n    }\n}\nexports.validateTuple = validateTuple;\nexports.default = def;\n//# sourceMappingURL=items.js.map","\"use strict\";\nObject.defineProperty(exports, \"__esModule\", { value: true });\nconst items_1 = require(\"./items\");\nconst def = {\n    keyword: \"prefixItems\",\n    type: \"array\",\n    schemaType: [\"array\"],\n    before: \"uniqueItems\",\n    code: (cxt) => (0, items_1.validateTuple)(cxt, \"items\"),\n};\nexports.default = def;\n//# sourceMappingURL=prefixItems.js.map","\"use strict\";\nObject.defineProperty(exports, \"__esModule\", { value: true });\nconst codegen_1 = require(\"../../compile/codegen\");\nconst util_1 = require(\"../../compile/util\");\nconst code_1 = require(\"../code\");\nconst additionalItems_1 = require(\"./additionalItems\");\nconst error = {\n    message: ({ params: { len } }) => (0, codegen_1.str) `must NOT have more than ${len} items`,\n    params: ({ params: { len } }) => (0, codegen_1._) `{limit: ${len}}`,\n};\nconst def = {\n    keyword: \"items\",\n    type: \"array\",\n    schemaType: [\"object\", \"boolean\"],\n    before: \"uniqueItems\",\n    error,\n    code(cxt) {\n        const { schema, parentSchema, it } = cxt;\n        const { prefixItems } = parentSchema;\n        it.items = true;\n        if ((0, util_1.alwaysValidSchema)(it, schema))\n            return;\n        if (prefixItems)\n            (0, additionalItems_1.validateAdditionalItems)(cxt, prefixItems);\n        else\n            cxt.ok((0, code_1.validateArray)(cxt));\n    },\n};\nexports.default = def;\n//# sourceMappingURL=items2020.js.map","\"use strict\";\nObject.defineProperty(exports, \"__esModule\", { value: true });\nconst codegen_1 = require(\"../../compile/codegen\");\nconst util_1 = require(\"../../compile/util\");\nconst error = {\n    message: ({ params: { min, max } }) => max === undefined\n        ? (0, codegen_1.str) `must contain at least ${min} valid item(s)`\n        : (0, codegen_1.str) `must contain at least ${min} and no more than ${max} valid item(s)`,\n    params: ({ params: { min, max } }) => max === undefined ? (0, codegen_1._) `{minContains: ${min}}` : (0, codegen_1._) `{minContains: ${min}, maxContains: ${max}}`,\n};\nconst def = {\n    keyword: \"contains\",\n    type: \"array\",\n    schemaType: [\"object\", \"boolean\"],\n    before: \"uniqueItems\",\n    trackErrors: true,\n    error,\n    code(cxt) {\n        const { gen, schema, parentSchema, data, it } = cxt;\n        let min;\n        let max;\n        const { minContains, maxContains } = parentSchema;\n        if (it.opts.next) {\n            min = minContains === undefined ? 1 : minContains;\n            max = maxContains;\n        }\n        else {\n            min = 1;\n        }\n        const len = gen.const(\"len\", (0, codegen_1._) `${data}.length`);\n        cxt.setParams({ min, max });\n        if (max === undefined && min === 0) {\n            (0, util_1.checkStrictMode)(it, `\"minContains\" == 0 without \"maxContains\": \"contains\" keyword ignored`);\n            return;\n        }\n        if (max !== undefined && min > max) {\n            (0, util_1.checkStrictMode)(it, `\"minContains\" > \"maxContains\" is always invalid`);\n            cxt.fail();\n            return;\n        }\n        if ((0, util_1.alwaysValidSchema)(it, schema)) {\n            let cond = (0, codegen_1._) `${len} >= ${min}`;\n            if (max !== undefined)\n                cond = (0, codegen_1._) `${cond} && ${len} <= ${max}`;\n            cxt.pass(cond);\n            return;\n        }\n        it.items = true;\n        const valid = gen.name(\"valid\");\n        if (max === undefined && min === 1) {\n            validateItems(valid, () => gen.if(valid, () => gen.break()));\n        }\n        else if (min === 0) {\n            gen.let(valid, true);\n            if (max !== undefined)\n                gen.if((0, codegen_1._) `${data}.length > 0`, validateItemsWithCount);\n        }\n        else {\n            gen.let(valid, false);\n            validateItemsWithCount();\n        }\n        cxt.result(valid, () => cxt.reset());\n        function validateItemsWithCount() {\n            const schValid = gen.name(\"_valid\");\n            const count = gen.let(\"count\", 0);\n            validateItems(schValid, () => gen.if(schValid, () => checkLimits(count)));\n        }\n        function validateItems(_valid, block) {\n            gen.forRange(\"i\", 0, len, (i) => {\n                cxt.subschema({\n                    keyword: \"contains\",\n                    dataProp: i,\n                    dataPropType: util_1.Type.Num,\n                    compositeRule: true,\n                }, _valid);\n                block();\n            });\n        }\n        function checkLimits(count) {\n            gen.code((0, codegen_1._) `${count}++`);\n            if (max === undefined) {\n                gen.if((0, codegen_1._) `${count} >= ${min}`, () => gen.assign(valid, true).break());\n            }\n            else {\n                gen.if((0, codegen_1._) `${count} > ${max}`, () => gen.assign(valid, false).break());\n                if (min === 1)\n                    gen.assign(valid, true);\n                else\n                    gen.if((0, codegen_1._) `${count} >= ${min}`, () => gen.assign(valid, true));\n            }\n        }\n    },\n};\nexports.default = def;\n//# sourceMappingURL=contains.js.map","\"use strict\";\nObject.defineProperty(exports, \"__esModule\", { value: true });\nexports.validateSchemaDeps = exports.validatePropertyDeps = exports.error = void 0;\nconst codegen_1 = require(\"../../compile/codegen\");\nconst util_1 = require(\"../../compile/util\");\nconst code_1 = require(\"../code\");\nexports.error = {\n    message: ({ params: { property, depsCount, deps } }) => {\n        const property_ies = depsCount === 1 ? \"property\" : \"properties\";\n        return (0, codegen_1.str) `must have ${property_ies} ${deps} when property ${property} is present`;\n    },\n    params: ({ params: { property, depsCount, deps, missingProperty } }) => (0, codegen_1._) `{property: ${property},\n    missingProperty: ${missingProperty},\n    depsCount: ${depsCount},\n    deps: ${deps}}`, // TODO change to reference\n};\nconst def = {\n    keyword: \"dependencies\",\n    type: \"object\",\n    schemaType: \"object\",\n    error: exports.error,\n    code(cxt) {\n        const [propDeps, schDeps] = splitDependencies(cxt);\n        validatePropertyDeps(cxt, propDeps);\n        validateSchemaDeps(cxt, schDeps);\n    },\n};\nfunction splitDependencies({ schema }) {\n    const propertyDeps = {};\n    const schemaDeps = {};\n    for (const key in schema) {\n        if (key === \"__proto__\")\n            continue;\n        const deps = Array.isArray(schema[key]) ? propertyDeps : schemaDeps;\n        deps[key] = schema[key];\n    }\n    return [propertyDeps, schemaDeps];\n}\nfunction validatePropertyDeps(cxt, propertyDeps = cxt.schema) {\n    const { gen, data, it } = cxt;\n    if (Object.keys(propertyDeps).length === 0)\n        return;\n    const missing = gen.let(\"missing\");\n    for (const prop in propertyDeps) {\n        const deps = propertyDeps[prop];\n        if (deps.length === 0)\n            continue;\n        const hasProperty = (0, code_1.propertyInData)(gen, data, prop, it.opts.ownProperties);\n        cxt.setParams({\n            property: prop,\n            depsCount: deps.length,\n            deps: deps.join(\", \"),\n        });\n        if (it.allErrors) {\n            gen.if(hasProperty, () => {\n                for (const depProp of deps) {\n                    (0, code_1.checkReportMissingProp)(cxt, depProp);\n                }\n            });\n        }\n        else {\n            gen.if((0, codegen_1._) `${hasProperty} && (${(0, code_1.checkMissingProp)(cxt, deps, missing)})`);\n            (0, code_1.reportMissingProp)(cxt, missing);\n            gen.else();\n        }\n    }\n}\nexports.validatePropertyDeps = validatePropertyDeps;\nfunction validateSchemaDeps(cxt, schemaDeps = cxt.schema) {\n    const { gen, data, keyword, it } = cxt;\n    const valid = gen.name(\"valid\");\n    for (const prop in schemaDeps) {\n        if ((0, util_1.alwaysValidSchema)(it, schemaDeps[prop]))\n            continue;\n        gen.if((0, code_1.propertyInData)(gen, data, prop, it.opts.ownProperties), () => {\n            const schCxt = cxt.subschema({ keyword, schemaProp: prop }, valid);\n            cxt.mergeValidEvaluated(schCxt, valid);\n        }, () => gen.var(valid, true) // TODO var\n        );\n        cxt.ok(valid);\n    }\n}\nexports.validateSchemaDeps = validateSchemaDeps;\nexports.default = def;\n//# sourceMappingURL=dependencies.js.map","\"use strict\";\nObject.defineProperty(exports, \"__esModule\", { value: true });\nconst codegen_1 = require(\"../../compile/codegen\");\nconst util_1 = require(\"../../compile/util\");\nconst error = {\n    message: \"property name must be valid\",\n    params: ({ params }) => (0, codegen_1._) `{propertyName: ${params.propertyName}}`,\n};\nconst def = {\n    keyword: \"propertyNames\",\n    type: \"object\",\n    schemaType: [\"object\", \"boolean\"],\n    error,\n    code(cxt) {\n        const { gen, schema, data, it } = cxt;\n        if ((0, util_1.alwaysValidSchema)(it, schema))\n            return;\n        const valid = gen.name(\"valid\");\n        gen.forIn(\"key\", data, (key) => {\n            cxt.setParams({ propertyName: key });\n            cxt.subschema({\n                keyword: \"propertyNames\",\n                data: key,\n                dataTypes: [\"string\"],\n                propertyName: key,\n                compositeRule: true,\n            }, valid);\n            gen.if((0, codegen_1.not)(valid), () => {\n                cxt.error(true);\n                if (!it.allErrors)\n                    gen.break();\n            });\n        });\n        cxt.ok(valid);\n    },\n};\nexports.default = def;\n//# sourceMappingURL=propertyNames.js.map","\"use strict\";\nObject.defineProperty(exports, \"__esModule\", { value: true });\nconst code_1 = require(\"../code\");\nconst codegen_1 = require(\"../../compile/codegen\");\nconst names_1 = require(\"../../compile/names\");\nconst util_1 = require(\"../../compile/util\");\nconst error = {\n    message: \"must NOT have additional properties\",\n    params: ({ params }) => (0, codegen_1._) `{additionalProperty: ${params.additionalProperty}}`,\n};\nconst def = {\n    keyword: \"additionalProperties\",\n    type: [\"object\"],\n    schemaType: [\"boolean\", \"object\"],\n    allowUndefined: true,\n    trackErrors: true,\n    error,\n    code(cxt) {\n        const { gen, schema, parentSchema, data, errsCount, it } = cxt;\n        /* istanbul ignore if */\n        if (!errsCount)\n            throw new Error(\"ajv implementation error\");\n        const { allErrors, opts } = it;\n        it.props = true;\n        if (opts.removeAdditional !== \"all\" && (0, util_1.alwaysValidSchema)(it, schema))\n            return;\n        const props = (0, code_1.allSchemaProperties)(parentSchema.properties);\n        const patProps = (0, code_1.allSchemaProperties)(parentSchema.patternProperties);\n        checkAdditionalProperties();\n        cxt.ok((0, codegen_1._) `${errsCount} === ${names_1.default.errors}`);\n        function checkAdditionalProperties() {\n            gen.forIn(\"key\", data, (key) => {\n                if (!props.length && !patProps.length)\n                    additionalPropertyCode(key);\n                else\n                    gen.if(isAdditional(key), () => additionalPropertyCode(key));\n            });\n        }\n        function isAdditional(key) {\n            let definedProp;\n            if (props.length > 8) {\n                // TODO maybe an option instead of hard-coded 8?\n                const propsSchema = (0, util_1.schemaRefOrVal)(it, parentSchema.properties, \"properties\");\n                definedProp = (0, code_1.isOwnProperty)(gen, propsSchema, key);\n            }\n            else if (props.length) {\n                definedProp = (0, codegen_1.or)(...props.map((p) => (0, codegen_1._) `${key} === ${p}`));\n            }\n            else {\n                definedProp = codegen_1.nil;\n            }\n            if (patProps.length) {\n                definedProp = (0, codegen_1.or)(definedProp, ...patProps.map((p) => (0, codegen_1._) `${(0, code_1.usePattern)(cxt, p)}.test(${key})`));\n            }\n            return (0, codegen_1.not)(definedProp);\n        }\n        function deleteAdditional(key) {\n            gen.code((0, codegen_1._) `delete ${data}[${key}]`);\n        }\n        function additionalPropertyCode(key) {\n            if (opts.removeAdditional === \"all\" || (opts.removeAdditional && schema === false)) {\n                deleteAdditional(key);\n                return;\n            }\n            if (schema === false) {\n                cxt.setParams({ additionalProperty: key });\n                cxt.error();\n                if (!allErrors)\n                    gen.break();\n                return;\n            }\n            if (typeof schema == \"object\" && !(0, util_1.alwaysValidSchema)(it, schema)) {\n                const valid = gen.name(\"valid\");\n                if (opts.removeAdditional === \"failing\") {\n                    applyAdditionalSchema(key, valid, false);\n                    gen.if((0, codegen_1.not)(valid), () => {\n                        cxt.reset();\n                        deleteAdditional(key);\n                    });\n                }\n                else {\n                    applyAdditionalSchema(key, valid);\n                    if (!allErrors)\n                        gen.if((0, codegen_1.not)(valid), () => gen.break());\n                }\n            }\n        }\n        function applyAdditionalSchema(key, valid, errors) {\n            const subschema = {\n                keyword: \"additionalProperties\",\n                dataProp: key,\n                dataPropType: util_1.Type.Str,\n            };\n            if (errors === false) {\n                Object.assign(subschema, {\n                    compositeRule: true,\n                    createErrors: false,\n                    allErrors: false,\n                });\n            }\n            cxt.subschema(subschema, valid);\n        }\n    },\n};\nexports.default = def;\n//# sourceMappingURL=additionalProperties.js.map","\"use strict\";\nObject.defineProperty(exports, \"__esModule\", { value: true });\nconst validate_1 = require(\"../../compile/validate\");\nconst code_1 = require(\"../code\");\nconst util_1 = require(\"../../compile/util\");\nconst additionalProperties_1 = require(\"./additionalProperties\");\nconst def = {\n    keyword: \"properties\",\n    type: \"object\",\n    schemaType: \"object\",\n    code(cxt) {\n        const { gen, schema, parentSchema, data, it } = cxt;\n        if (it.opts.removeAdditional === \"all\" && parentSchema.additionalProperties === undefined) {\n            additionalProperties_1.default.code(new validate_1.KeywordCxt(it, additionalProperties_1.default, \"additionalProperties\"));\n        }\n        const allProps = (0, code_1.allSchemaProperties)(schema);\n        for (const prop of allProps) {\n            it.definedProperties.add(prop);\n        }\n        if (it.opts.unevaluated && allProps.length && it.props !== true) {\n            it.props = util_1.mergeEvaluated.props(gen, (0, util_1.toHash)(allProps), it.props);\n        }\n        const properties = allProps.filter((p) => !(0, util_1.alwaysValidSchema)(it, schema[p]));\n        if (properties.length === 0)\n            return;\n        const valid = gen.name(\"valid\");\n        for (const prop of properties) {\n            if (hasDefault(prop)) {\n                applyPropertySchema(prop);\n            }\n            else {\n                gen.if((0, code_1.propertyInData)(gen, data, prop, it.opts.ownProperties));\n                applyPropertySchema(prop);\n                if (!it.allErrors)\n                    gen.else().var(valid, true);\n                gen.endIf();\n            }\n            cxt.it.definedProperties.add(prop);\n            cxt.ok(valid);\n        }\n        function hasDefault(prop) {\n            return it.opts.useDefaults && !it.compositeRule && schema[prop].default !== undefined;\n        }\n        function applyPropertySchema(prop) {\n            cxt.subschema({\n                keyword: \"properties\",\n                schemaProp: prop,\n                dataProp: prop,\n            }, valid);\n        }\n    },\n};\nexports.default = def;\n//# sourceMappingURL=properties.js.map","\"use strict\";\nObject.defineProperty(exports, \"__esModule\", { value: true });\nconst code_1 = require(\"../code\");\nconst codegen_1 = require(\"../../compile/codegen\");\nconst util_1 = require(\"../../compile/util\");\nconst util_2 = require(\"../../compile/util\");\nconst def = {\n    keyword: \"patternProperties\",\n    type: \"object\",\n    schemaType: \"object\",\n    code(cxt) {\n        const { gen, schema, data, parentSchema, it } = cxt;\n        const { opts } = it;\n        const patterns = (0, code_1.allSchemaProperties)(schema);\n        const alwaysValidPatterns = patterns.filter((p) => (0, util_1.alwaysValidSchema)(it, schema[p]));\n        if (patterns.length === 0 ||\n            (alwaysValidPatterns.length === patterns.length &&\n                (!it.opts.unevaluated || it.props === true))) {\n            return;\n        }\n        const checkProperties = opts.strictSchema && !opts.allowMatchingProperties && parentSchema.properties;\n        const valid = gen.name(\"valid\");\n        if (it.props !== true && !(it.props instanceof codegen_1.Name)) {\n            it.props = (0, util_2.evaluatedPropsToName)(gen, it.props);\n        }\n        const { props } = it;\n        validatePatternProperties();\n        function validatePatternProperties() {\n            for (const pat of patterns) {\n                if (checkProperties)\n                    checkMatchingProperties(pat);\n                if (it.allErrors) {\n                    validateProperties(pat);\n                }\n                else {\n                    gen.var(valid, true); // TODO var\n                    validateProperties(pat);\n                    gen.if(valid);\n                }\n            }\n        }\n        function checkMatchingProperties(pat) {\n            for (const prop in checkProperties) {\n                if (new RegExp(pat).test(prop)) {\n                    (0, util_1.checkStrictMode)(it, `property ${prop} matches pattern ${pat} (use allowMatchingProperties)`);\n                }\n            }\n        }\n        function validateProperties(pat) {\n            gen.forIn(\"key\", data, (key) => {\n                gen.if((0, codegen_1._) `${(0, code_1.usePattern)(cxt, pat)}.test(${key})`, () => {\n                    const alwaysValid = alwaysValidPatterns.includes(pat);\n                    if (!alwaysValid) {\n                        cxt.subschema({\n                            keyword: \"patternProperties\",\n                            schemaProp: pat,\n                            dataProp: key,\n                            dataPropType: util_2.Type.Str,\n                        }, valid);\n                    }\n                    if (it.opts.unevaluated && props !== true) {\n                        gen.assign((0, codegen_1._) `${props}[${key}]`, true);\n                    }\n                    else if (!alwaysValid && !it.allErrors) {\n                        // can short-circuit if `unevaluatedProperties` is not supported (opts.next === false)\n                        // or if all properties were evaluated (props === true)\n                        gen.if((0, codegen_1.not)(valid), () => gen.break());\n                    }\n                });\n            });\n        }\n    },\n};\nexports.default = def;\n//# sourceMappingURL=patternProperties.js.map","\"use strict\";\nObject.defineProperty(exports, \"__esModule\", { value: true });\nconst util_1 = require(\"../../compile/util\");\nconst def = {\n    keyword: \"not\",\n    schemaType: [\"object\", \"boolean\"],\n    trackErrors: true,\n    code(cxt) {\n        const { gen, schema, it } = cxt;\n        if ((0, util_1.alwaysValidSchema)(it, schema)) {\n            cxt.fail();\n            return;\n        }\n        const valid = gen.name(\"valid\");\n        cxt.subschema({\n            keyword: \"not\",\n            compositeRule: true,\n            createErrors: false,\n            allErrors: false,\n        }, valid);\n        cxt.failResult(valid, () => cxt.reset(), () => cxt.error());\n    },\n    error: { message: \"must NOT be valid\" },\n};\nexports.default = def;\n//# sourceMappingURL=not.js.map","\"use strict\";\nObject.defineProperty(exports, \"__esModule\", { value: true });\nconst code_1 = require(\"../code\");\nconst def = {\n    keyword: \"anyOf\",\n    schemaType: \"array\",\n    trackErrors: true,\n    code: code_1.validateUnion,\n    error: { message: \"must match a schema in anyOf\" },\n};\nexports.default = def;\n//# sourceMappingURL=anyOf.js.map","\"use strict\";\nObject.defineProperty(exports, \"__esModule\", { value: true });\nconst codegen_1 = require(\"../../compile/codegen\");\nconst util_1 = require(\"../../compile/util\");\nconst error = {\n    message: \"must match exactly one schema in oneOf\",\n    params: ({ params }) => (0, codegen_1._) `{passingSchemas: ${params.passing}}`,\n};\nconst def = {\n    keyword: \"oneOf\",\n    schemaType: \"array\",\n    trackErrors: true,\n    error,\n    code(cxt) {\n        const { gen, schema, parentSchema, it } = cxt;\n        /* istanbul ignore if */\n        if (!Array.isArray(schema))\n            throw new Error(\"ajv implementation error\");\n        if (it.opts.discriminator && parentSchema.discriminator)\n            return;\n        const schArr = schema;\n        const valid = gen.let(\"valid\", false);\n        const passing = gen.let(\"passing\", null);\n        const schValid = gen.name(\"_valid\");\n        cxt.setParams({ passing });\n        // TODO possibly fail straight away (with warning or exception) if there are two empty always valid schemas\n        gen.block(validateOneOf);\n        cxt.result(valid, () => cxt.reset(), () => cxt.error(true));\n        function validateOneOf() {\n            schArr.forEach((sch, i) => {\n                let schCxt;\n                if ((0, util_1.alwaysValidSchema)(it, sch)) {\n                    gen.var(schValid, true);\n                }\n                else {\n                    schCxt = cxt.subschema({\n                        keyword: \"oneOf\",\n                        schemaProp: i,\n                        compositeRule: true,\n                    }, schValid);\n                }\n                if (i > 0) {\n                    gen\n                        .if((0, codegen_1._) `${schValid} && ${valid}`)\n                        .assign(valid, false)\n                        .assign(passing, (0, codegen_1._) `[${passing}, ${i}]`)\n                        .else();\n                }\n                gen.if(schValid, () => {\n                    gen.assign(valid, true);\n                    gen.assign(passing, i);\n                    if (schCxt)\n                        cxt.mergeEvaluated(schCxt, codegen_1.Name);\n                });\n            });\n        }\n    },\n};\nexports.default = def;\n//# sourceMappingURL=oneOf.js.map","\"use strict\";\nObject.defineProperty(exports, \"__esModule\", { value: true });\nconst util_1 = require(\"../../compile/util\");\nconst def = {\n    keyword: \"allOf\",\n    schemaType: \"array\",\n    code(cxt) {\n        const { gen, schema, it } = cxt;\n        /* istanbul ignore if */\n        if (!Array.isArray(schema))\n            throw new Error(\"ajv implementation error\");\n        const valid = gen.name(\"valid\");\n        schema.forEach((sch, i) => {\n            if ((0, util_1.alwaysValidSchema)(it, sch))\n                return;\n            const schCxt = cxt.subschema({ keyword: \"allOf\", schemaProp: i }, valid);\n            cxt.ok(valid);\n            cxt.mergeEvaluated(schCxt);\n        });\n    },\n};\nexports.default = def;\n//# sourceMappingURL=allOf.js.map","\"use strict\";\nObject.defineProperty(exports, \"__esModule\", { value: true });\nconst codegen_1 = require(\"../../compile/codegen\");\nconst util_1 = require(\"../../compile/util\");\nconst error = {\n    message: ({ params }) => (0, codegen_1.str) `must match \"${params.ifClause}\" schema`,\n    params: ({ params }) => (0, codegen_1._) `{failingKeyword: ${params.ifClause}}`,\n};\nconst def = {\n    keyword: \"if\",\n    schemaType: [\"object\", \"boolean\"],\n    trackErrors: true,\n    error,\n    code(cxt) {\n        const { gen, parentSchema, it } = cxt;\n        if (parentSchema.then === undefined && parentSchema.else === undefined) {\n            (0, util_1.checkStrictMode)(it, '\"if\" without \"then\" and \"else\" is ignored');\n        }\n        const hasThen = hasSchema(it, \"then\");\n        const hasElse = hasSchema(it, \"else\");\n        if (!hasThen && !hasElse)\n            return;\n        const valid = gen.let(\"valid\", true);\n        const schValid = gen.name(\"_valid\");\n        validateIf();\n        cxt.reset();\n        if (hasThen && hasElse) {\n            const ifClause = gen.let(\"ifClause\");\n            cxt.setParams({ ifClause });\n            gen.if(schValid, validateClause(\"then\", ifClause), validateClause(\"else\", ifClause));\n        }\n        else if (hasThen) {\n            gen.if(schValid, validateClause(\"then\"));\n        }\n        else {\n            gen.if((0, codegen_1.not)(schValid), validateClause(\"else\"));\n        }\n        cxt.pass(valid, () => cxt.error(true));\n        function validateIf() {\n            const schCxt = cxt.subschema({\n                keyword: \"if\",\n                compositeRule: true,\n                createErrors: false,\n                allErrors: false,\n            }, schValid);\n            cxt.mergeEvaluated(schCxt);\n        }\n        function validateClause(keyword, ifClause) {\n            return () => {\n                const schCxt = cxt.subschema({ keyword }, schValid);\n                gen.assign(valid, schValid);\n                cxt.mergeValidEvaluated(schCxt, valid);\n                if (ifClause)\n                    gen.assign(ifClause, (0, codegen_1._) `${keyword}`);\n                else\n                    cxt.setParams({ ifClause: keyword });\n            };\n        }\n    },\n};\nfunction hasSchema(it, keyword) {\n    const schema = it.schema[keyword];\n    return schema !== undefined && !(0, util_1.alwaysValidSchema)(it, schema);\n}\nexports.default = def;\n//# sourceMappingURL=if.js.map","\"use strict\";\nObject.defineProperty(exports, \"__esModule\", { value: true });\nconst util_1 = require(\"../../compile/util\");\nconst def = {\n    keyword: [\"then\", \"else\"],\n    schemaType: [\"object\", \"boolean\"],\n    code({ keyword, parentSchema, it }) {\n        if (parentSchema.if === undefined)\n            (0, util_1.checkStrictMode)(it, `\"${keyword}\" without \"if\" is ignored`);\n    },\n};\nexports.default = def;\n//# sourceMappingURL=thenElse.js.map","\"use strict\";\nObject.defineProperty(exports, \"__esModule\", { value: true });\nconst additionalItems_1 = require(\"./additionalItems\");\nconst prefixItems_1 = require(\"./prefixItems\");\nconst items_1 = require(\"./items\");\nconst items2020_1 = require(\"./items2020\");\nconst contains_1 = require(\"./contains\");\nconst dependencies_1 = require(\"./dependencies\");\nconst propertyNames_1 = require(\"./propertyNames\");\nconst additionalProperties_1 = require(\"./additionalProperties\");\nconst properties_1 = require(\"./properties\");\nconst patternProperties_1 = require(\"./patternProperties\");\nconst not_1 = require(\"./not\");\nconst anyOf_1 = require(\"./anyOf\");\nconst oneOf_1 = require(\"./oneOf\");\nconst allOf_1 = require(\"./allOf\");\nconst if_1 = require(\"./if\");\nconst thenElse_1 = require(\"./thenElse\");\nfunction getApplicator(draft2020 = false) {\n    const applicator = [\n        // any\n        not_1.default,\n        anyOf_1.default,\n        oneOf_1.default,\n        allOf_1.default,\n        if_1.default,\n        thenElse_1.default,\n        // object\n        propertyNames_1.default,\n        additionalProperties_1.default,\n        dependencies_1.default,\n        properties_1.default,\n        patternProperties_1.default,\n    ];\n    // array\n    if (draft2020)\n        applicator.push(prefixItems_1.default, items2020_1.default);\n    else\n        applicator.push(additionalItems_1.default, items_1.default);\n    applicator.push(contains_1.default);\n    return applicator;\n}\nexports.default = getApplicator;\n//# sourceMappingURL=index.js.map","\"use strict\";\nObject.defineProperty(exports, \"__esModule\", { value: true });\nconst codegen_1 = require(\"../../compile/codegen\");\nconst error = {\n    message: ({ schemaCode }) => (0, codegen_1.str) `must match format \"${schemaCode}\"`,\n    params: ({ schemaCode }) => (0, codegen_1._) `{format: ${schemaCode}}`,\n};\nconst def = {\n    keyword: \"format\",\n    type: [\"number\", \"string\"],\n    schemaType: \"string\",\n    $data: true,\n    error,\n    code(cxt, ruleType) {\n        const { gen, data, $data, schema, schemaCode, it } = cxt;\n        const { opts, errSchemaPath, schemaEnv, self } = it;\n        if (!opts.validateFormats)\n            return;\n        if ($data)\n            validate$DataFormat();\n        else\n            validateFormat();\n        function validate$DataFormat() {\n            const fmts = gen.scopeValue(\"formats\", {\n                ref: self.formats,\n                code: opts.code.formats,\n            });\n            const fDef = gen.const(\"fDef\", (0, codegen_1._) `${fmts}[${schemaCode}]`);\n            const fType = gen.let(\"fType\");\n            const format = gen.let(\"format\");\n            // TODO simplify\n            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));\n            cxt.fail$data((0, codegen_1.or)(unknownFmt(), invalidFmt()));\n            function unknownFmt() {\n                if (opts.strictSchema === false)\n                    return codegen_1.nil;\n                return (0, codegen_1._) `${schemaCode} && !${format}`;\n            }\n            function invalidFmt() {\n                const callFormat = schemaEnv.$async\n                    ? (0, codegen_1._) `(${fDef}.async ? await ${format}(${data}) : ${format}(${data}))`\n                    : (0, codegen_1._) `${format}(${data})`;\n                const validData = (0, codegen_1._) `(typeof ${format} == \"function\" ? ${callFormat} : ${format}.test(${data}))`;\n                return (0, codegen_1._) `${format} && ${format} !== true && ${fType} === ${ruleType} && !${validData}`;\n            }\n        }\n        function validateFormat() {\n            const formatDef = self.formats[schema];\n            if (!formatDef) {\n                unknownFormat();\n                return;\n            }\n            if (formatDef === true)\n                return;\n            const [fmtType, format, fmtRef] = getFormat(formatDef);\n            if (fmtType === ruleType)\n                cxt.pass(validCondition());\n            function unknownFormat() {\n                if (opts.strictSchema === false) {\n                    self.logger.warn(unknownMsg());\n                    return;\n                }\n                throw new Error(unknownMsg());\n                function unknownMsg() {\n                    return `unknown format \"${schema}\" ignored in schema at path \"${errSchemaPath}\"`;\n                }\n            }\n            function getFormat(fmtDef) {\n                const code = fmtDef instanceof RegExp\n                    ? (0, codegen_1.regexpCode)(fmtDef)\n                    : opts.code.formats\n                        ? (0, codegen_1._) `${opts.code.formats}${(0, codegen_1.getProperty)(schema)}`\n                        : undefined;\n                const fmt = gen.scopeValue(\"formats\", { key: schema, ref: fmtDef, code });\n                if (typeof fmtDef == \"object\" && !(fmtDef instanceof RegExp)) {\n                    return [fmtDef.type || \"string\", fmtDef.validate, (0, codegen_1._) `${fmt}.validate`];\n                }\n                return [\"string\", fmtDef, fmt];\n            }\n            function validCondition() {\n                if (typeof formatDef == \"object\" && !(formatDef instanceof RegExp) && formatDef.async) {\n                    if (!schemaEnv.$async)\n                        throw new Error(\"async format in sync schema\");\n                    return (0, codegen_1._) `await ${fmtRef}(${data})`;\n                }\n                return typeof format == \"function\" ? (0, codegen_1._) `${fmtRef}(${data})` : (0, codegen_1._) `${fmtRef}.test(${data})`;\n            }\n        }\n    },\n};\nexports.default = def;\n//# sourceMappingURL=format.js.map","\"use strict\";\nObject.defineProperty(exports, \"__esModule\", { value: true });\nconst format_1 = require(\"./format\");\nconst format = [format_1.default];\nexports.default = format;\n//# sourceMappingURL=index.js.map","\"use strict\";\nObject.defineProperty(exports, \"__esModule\", { value: true });\nexports.contentVocabulary = exports.metadataVocabulary = void 0;\nexports.metadataVocabulary = [\n    \"title\",\n    \"description\",\n    \"default\",\n    \"deprecated\",\n    \"readOnly\",\n    \"writeOnly\",\n    \"examples\",\n];\nexports.contentVocabulary = [\n    \"contentMediaType\",\n    \"contentEncoding\",\n    \"contentSchema\",\n];\n//# sourceMappingURL=metadata.js.map","\"use strict\";\nObject.defineProperty(exports, \"__esModule\", { value: true });\nconst core_1 = require(\"./core\");\nconst validation_1 = require(\"./validation\");\nconst applicator_1 = require(\"./applicator\");\nconst format_1 = require(\"./format\");\nconst metadata_1 = require(\"./metadata\");\nconst draft7Vocabularies = [\n    core_1.default,\n    validation_1.default,\n    (0, applicator_1.default)(),\n    format_1.default,\n    metadata_1.metadataVocabulary,\n    metadata_1.contentVocabulary,\n];\nexports.default = draft7Vocabularies;\n//# sourceMappingURL=draft7.js.map","\"use strict\";\nObject.defineProperty(exports, \"__esModule\", { value: true });\nexports.DiscrError = void 0;\nvar DiscrError;\n(function (DiscrError) {\n    DiscrError[\"Tag\"] = \"tag\";\n    DiscrError[\"Mapping\"] = \"mapping\";\n})(DiscrError || (exports.DiscrError = DiscrError = {}));\n//# sourceMappingURL=types.js.map","\"use strict\";\nObject.defineProperty(exports, \"__esModule\", { value: true });\nconst codegen_1 = require(\"../../compile/codegen\");\nconst types_1 = require(\"../discriminator/types\");\nconst compile_1 = require(\"../../compile\");\nconst ref_error_1 = require(\"../../compile/ref_error\");\nconst util_1 = require(\"../../compile/util\");\nconst error = {\n    message: ({ params: { discrError, tagName } }) => discrError === types_1.DiscrError.Tag\n        ? `tag \"${tagName}\" must be string`\n        : `value of tag \"${tagName}\" must be in oneOf`,\n    params: ({ params: { discrError, tag, tagName } }) => (0, codegen_1._) `{error: ${discrError}, tag: ${tagName}, tagValue: ${tag}}`,\n};\nconst def = {\n    keyword: \"discriminator\",\n    type: \"object\",\n    schemaType: \"object\",\n    error,\n    code(cxt) {\n        const { gen, data, schema, parentSchema, it } = cxt;\n        const { oneOf } = parentSchema;\n        if (!it.opts.discriminator) {\n            throw new Error(\"discriminator: requires discriminator option\");\n        }\n        const tagName = schema.propertyName;\n        if (typeof tagName != \"string\")\n            throw new Error(\"discriminator: requires propertyName\");\n        if (schema.mapping)\n            throw new Error(\"discriminator: mapping is not supported\");\n        if (!oneOf)\n            throw new Error(\"discriminator: requires oneOf keyword\");\n        const valid = gen.let(\"valid\", false);\n        const tag = gen.const(\"tag\", (0, codegen_1._) `${data}${(0, codegen_1.getProperty)(tagName)}`);\n        gen.if((0, codegen_1._) `typeof ${tag} == \"string\"`, () => validateMapping(), () => cxt.error(false, { discrError: types_1.DiscrError.Tag, tag, tagName }));\n        cxt.ok(valid);\n        function validateMapping() {\n            const mapping = getMapping();\n            gen.if(false);\n            for (const tagValue in mapping) {\n                gen.elseIf((0, codegen_1._) `${tag} === ${tagValue}`);\n                gen.assign(valid, applyTagSchema(mapping[tagValue]));\n            }\n            gen.else();\n            cxt.error(false, { discrError: types_1.DiscrError.Mapping, tag, tagName });\n            gen.endIf();\n        }\n        function applyTagSchema(schemaProp) {\n            const _valid = gen.name(\"valid\");\n            const schCxt = cxt.subschema({ keyword: \"oneOf\", schemaProp }, _valid);\n            cxt.mergeEvaluated(schCxt, codegen_1.Name);\n            return _valid;\n        }\n        function getMapping() {\n            var _a;\n            const oneOfMapping = {};\n            const topRequired = hasRequired(parentSchema);\n            let tagRequired = true;\n            for (let i = 0; i < oneOf.length; i++) {\n                let sch = oneOf[i];\n                if ((sch === null || sch === void 0 ? void 0 : sch.$ref) && !(0, util_1.schemaHasRulesButRef)(sch, it.self.RULES)) {\n                    const ref = sch.$ref;\n                    sch = compile_1.resolveRef.call(it.self, it.schemaEnv.root, it.baseId, ref);\n                    if (sch instanceof compile_1.SchemaEnv)\n                        sch = sch.schema;\n                    if (sch === undefined)\n                        throw new ref_error_1.default(it.opts.uriResolver, it.baseId, ref);\n                }\n                const propSch = (_a = sch === null || sch === void 0 ? void 0 : sch.properties) === null || _a === void 0 ? void 0 : _a[tagName];\n                if (typeof propSch != \"object\") {\n                    throw new Error(`discriminator: oneOf subschemas (or referenced schemas) must have \"properties/${tagName}\"`);\n                }\n                tagRequired = tagRequired && (topRequired || hasRequired(sch));\n                addMappings(propSch, i);\n            }\n            if (!tagRequired)\n                throw new Error(`discriminator: \"${tagName}\" must be required`);\n            return oneOfMapping;\n            function hasRequired({ required }) {\n                return Array.isArray(required) && required.includes(tagName);\n            }\n            function addMappings(sch, i) {\n                if (sch.const) {\n                    addMapping(sch.const, i);\n                }\n                else if (sch.enum) {\n                    for (const tagValue of sch.enum) {\n                        addMapping(tagValue, i);\n                    }\n                }\n                else {\n                    throw new Error(`discriminator: \"properties/${tagName}\" must have \"const\" or \"enum\"`);\n                }\n            }\n            function addMapping(tagValue, i) {\n                if (typeof tagValue != \"string\" || tagValue in oneOfMapping) {\n                    throw new Error(`discriminator: \"${tagName}\" values must be unique strings`);\n                }\n                oneOfMapping[tagValue] = i;\n            }\n        }\n    },\n};\nexports.default = def;\n//# sourceMappingURL=index.js.map","","\"use strict\";\nObject.defineProperty(exports, \"__esModule\", { value: true });\nexports.MissingRefError = exports.ValidationError = exports.CodeGen = exports.Name = exports.nil = exports.stringify = exports.str = exports._ = exports.KeywordCxt = exports.Ajv = void 0;\nconst core_1 = require(\"./core\");\nconst draft7_1 = require(\"./vocabularies/draft7\");\nconst discriminator_1 = require(\"./vocabularies/discriminator\");\nconst draft7MetaSchema = require(\"./refs/json-schema-draft-07.json\");\nconst META_SUPPORT_DATA = [\"/properties\"];\nconst META_SCHEMA_ID = \"http://json-schema.org/draft-07/schema\";\nclass Ajv extends core_1.default {\n    _addVocabularies() {\n        super._addVocabularies();\n        draft7_1.default.forEach((v) => this.addVocabulary(v));\n        if (this.opts.discriminator)\n            this.addKeyword(discriminator_1.default);\n    }\n    _addDefaultMetaSchema() {\n        super._addDefaultMetaSchema();\n        if (!this.opts.meta)\n            return;\n        const metaSchema = this.opts.$data\n            ? this.$dataMetaSchema(draft7MetaSchema, META_SUPPORT_DATA)\n            : draft7MetaSchema;\n        this.addMetaSchema(metaSchema, META_SCHEMA_ID, false);\n        this.refs[\"http://json-schema.org/schema\"] = META_SCHEMA_ID;\n    }\n    defaultMeta() {\n        return (this.opts.defaultMeta =\n            super.defaultMeta() || (this.getSchema(META_SCHEMA_ID) ? META_SCHEMA_ID : undefined));\n    }\n}\nexports.Ajv = Ajv;\nmodule.exports = exports = Ajv;\nmodule.exports.Ajv = Ajv;\nObject.defineProperty(exports, \"__esModule\", { value: true });\nexports.default = Ajv;\nvar validate_1 = require(\"./compile/validate\");\nObject.defineProperty(exports, \"KeywordCxt\", { enumerable: true, get: function () { return validate_1.KeywordCxt; } });\nvar codegen_1 = require(\"./compile/codegen\");\nObject.defineProperty(exports, \"_\", { enumerable: true, get: function () { return codegen_1._; } });\nObject.defineProperty(exports, \"str\", { enumerable: true, get: function () { return codegen_1.str; } });\nObject.defineProperty(exports, \"stringify\", { enumerable: true, get: function () { return codegen_1.stringify; } });\nObject.defineProperty(exports, \"nil\", { enumerable: true, get: function () { return codegen_1.nil; } });\nObject.defineProperty(exports, \"Name\", { enumerable: true, get: function () { return codegen_1.Name; } });\nObject.defineProperty(exports, \"CodeGen\", { enumerable: true, get: function () { return codegen_1.CodeGen; } });\nvar validation_error_1 = require(\"./runtime/validation_error\");\nObject.defineProperty(exports, \"ValidationError\", { enumerable: true, get: function () { return validation_error_1.default; } });\nvar ref_error_1 = require(\"./compile/ref_error\");\nObject.defineProperty(exports, \"MissingRefError\", { enumerable: true, get: function () { return ref_error_1.default; } });\n//# sourceMappingURL=ajv.js.map","\"use strict\";\nObject.defineProperty(exports, \"__esModule\", { value: true });\nexports.dynamicAnchor = void 0;\nconst codegen_1 = require(\"../../compile/codegen\");\nconst names_1 = require(\"../../compile/names\");\nconst compile_1 = require(\"../../compile\");\nconst ref_1 = require(\"../core/ref\");\nconst def = {\n    keyword: \"$dynamicAnchor\",\n    schemaType: \"string\",\n    code: (cxt) => dynamicAnchor(cxt, cxt.schema),\n};\nfunction dynamicAnchor(cxt, anchor) {\n    const { gen, it } = cxt;\n    it.schemaEnv.root.dynamicAnchors[anchor] = true;\n    const v = (0, codegen_1._) `${names_1.default.dynamicAnchors}${(0, codegen_1.getProperty)(anchor)}`;\n    const validate = it.errSchemaPath === \"#\" ? it.validateName : _getValidate(cxt);\n    gen.if((0, codegen_1._) `!${v}`, () => gen.assign(v, validate));\n}\nexports.dynamicAnchor = dynamicAnchor;\nfunction _getValidate(cxt) {\n    const { schemaEnv, schema, self } = cxt.it;\n    const { root, baseId, localRefs, meta } = schemaEnv.root;\n    const { schemaId } = self.opts;\n    const sch = new compile_1.SchemaEnv({ schema, schemaId, root, baseId, localRefs, meta });\n    compile_1.compileSchema.call(self, sch);\n    return (0, ref_1.getValidate)(cxt, sch);\n}\nexports.default = def;\n//# sourceMappingURL=dynamicAnchor.js.map","\"use strict\";\nObject.defineProperty(exports, \"__esModule\", { value: true });\nexports.dynamicRef = void 0;\nconst codegen_1 = require(\"../../compile/codegen\");\nconst names_1 = require(\"../../compile/names\");\nconst ref_1 = require(\"../core/ref\");\nconst def = {\n    keyword: \"$dynamicRef\",\n    schemaType: \"string\",\n    code: (cxt) => dynamicRef(cxt, cxt.schema),\n};\nfunction dynamicRef(cxt, ref) {\n    const { gen, keyword, it } = cxt;\n    if (ref[0] !== \"#\")\n        throw new Error(`\"${keyword}\" only supports hash fragment reference`);\n    const anchor = ref.slice(1);\n    if (it.allErrors) {\n        _dynamicRef();\n    }\n    else {\n        const valid = gen.let(\"valid\", false);\n        _dynamicRef(valid);\n        cxt.ok(valid);\n    }\n    function _dynamicRef(valid) {\n        // TODO the assumption here is that `recursiveRef: #` always points to the root\n        // of the schema object, which is not correct, because there may be $id that\n        // makes # point to it, and the target schema may not contain dynamic/recursiveAnchor.\n        // Because of that 2 tests in recursiveRef.json fail.\n        // This is a similar problem to #815 (`$id` doesn't alter resolution scope for `{ \"$ref\": \"#\" }`).\n        // (This problem is not tested in JSON-Schema-Test-Suite)\n        if (it.schemaEnv.root.dynamicAnchors[anchor]) {\n            const v = gen.let(\"_v\", (0, codegen_1._) `${names_1.default.dynamicAnchors}${(0, codegen_1.getProperty)(anchor)}`);\n            gen.if(v, _callRef(v, valid), _callRef(it.validateName, valid));\n        }\n        else {\n            _callRef(it.validateName, valid)();\n        }\n    }\n    function _callRef(validate, valid) {\n        return valid\n            ? () => gen.block(() => {\n                (0, ref_1.callRef)(cxt, validate);\n                gen.let(valid, true);\n            })\n            : () => (0, ref_1.callRef)(cxt, validate);\n    }\n}\nexports.dynamicRef = dynamicRef;\nexports.default = def;\n//# sourceMappingURL=dynamicRef.js.map","\"use strict\";\nObject.defineProperty(exports, \"__esModule\", { value: true });\nconst dynamicAnchor_1 = require(\"./dynamicAnchor\");\nconst util_1 = require(\"../../compile/util\");\nconst def = {\n    keyword: \"$recursiveAnchor\",\n    schemaType: \"boolean\",\n    code(cxt) {\n        if (cxt.schema)\n            (0, dynamicAnchor_1.dynamicAnchor)(cxt, \"\");\n        else\n            (0, util_1.checkStrictMode)(cxt.it, \"$recursiveAnchor: false is ignored\");\n    },\n};\nexports.default = def;\n//# sourceMappingURL=recursiveAnchor.js.map","\"use strict\";\nObject.defineProperty(exports, \"__esModule\", { value: true });\nconst dynamicRef_1 = require(\"./dynamicRef\");\nconst def = {\n    keyword: \"$recursiveRef\",\n    schemaType: \"string\",\n    code: (cxt) => (0, dynamicRef_1.dynamicRef)(cxt, cxt.schema),\n};\nexports.default = def;\n//# sourceMappingURL=recursiveRef.js.map","\"use strict\";\nObject.defineProperty(exports, \"__esModule\", { value: true });\nconst dynamicAnchor_1 = require(\"./dynamicAnchor\");\nconst dynamicRef_1 = require(\"./dynamicRef\");\nconst recursiveAnchor_1 = require(\"./recursiveAnchor\");\nconst recursiveRef_1 = require(\"./recursiveRef\");\nconst dynamic = [dynamicAnchor_1.default, dynamicRef_1.default, recursiveAnchor_1.default, recursiveRef_1.default];\nexports.default = dynamic;\n//# sourceMappingURL=index.js.map","\"use strict\";\nObject.defineProperty(exports, \"__esModule\", { value: true });\nconst dependencies_1 = require(\"../applicator/dependencies\");\nconst def = {\n    keyword: \"dependentRequired\",\n    type: \"object\",\n    schemaType: \"object\",\n    error: dependencies_1.error,\n    code: (cxt) => (0, dependencies_1.validatePropertyDeps)(cxt),\n};\nexports.default = def;\n//# sourceMappingURL=dependentRequired.js.map","\"use strict\";\nObject.defineProperty(exports, \"__esModule\", { value: true });\nconst dependencies_1 = require(\"./dependencies\");\nconst def = {\n    keyword: \"dependentSchemas\",\n    type: \"object\",\n    schemaType: \"object\",\n    code: (cxt) => (0, dependencies_1.validateSchemaDeps)(cxt),\n};\nexports.default = def;\n//# sourceMappingURL=dependentSchemas.js.map","\"use strict\";\nObject.defineProperty(exports, \"__esModule\", { value: true });\nconst util_1 = require(\"../../compile/util\");\nconst def = {\n    keyword: [\"maxContains\", \"minContains\"],\n    type: \"array\",\n    schemaType: \"number\",\n    code({ keyword, parentSchema, it }) {\n        if (parentSchema.contains === undefined) {\n            (0, util_1.checkStrictMode)(it, `\"${keyword}\" without \"contains\" is ignored`);\n        }\n    },\n};\nexports.default = def;\n//# sourceMappingURL=limitContains.js.map","\"use strict\";\nObject.defineProperty(exports, \"__esModule\", { value: true });\nconst dependentRequired_1 = require(\"./validation/dependentRequired\");\nconst dependentSchemas_1 = require(\"./applicator/dependentSchemas\");\nconst limitContains_1 = require(\"./validation/limitContains\");\nconst next = [dependentRequired_1.default, dependentSchemas_1.default, limitContains_1.default];\nexports.default = next;\n//# sourceMappingURL=next.js.map","\"use strict\";\nObject.defineProperty(exports, \"__esModule\", { value: true });\nconst codegen_1 = require(\"../../compile/codegen\");\nconst util_1 = require(\"../../compile/util\");\nconst names_1 = require(\"../../compile/names\");\nconst error = {\n    message: \"must NOT have unevaluated properties\",\n    params: ({ params }) => (0, codegen_1._) `{unevaluatedProperty: ${params.unevaluatedProperty}}`,\n};\nconst def = {\n    keyword: \"unevaluatedProperties\",\n    type: \"object\",\n    schemaType: [\"boolean\", \"object\"],\n    trackErrors: true,\n    error,\n    code(cxt) {\n        const { gen, schema, data, errsCount, it } = cxt;\n        /* istanbul ignore if */\n        if (!errsCount)\n            throw new Error(\"ajv implementation error\");\n        const { allErrors, props } = it;\n        if (props instanceof codegen_1.Name) {\n            gen.if((0, codegen_1._) `${props} !== true`, () => gen.forIn(\"key\", data, (key) => gen.if(unevaluatedDynamic(props, key), () => unevaluatedPropCode(key))));\n        }\n        else if (props !== true) {\n            gen.forIn(\"key\", data, (key) => props === undefined\n                ? unevaluatedPropCode(key)\n                : gen.if(unevaluatedStatic(props, key), () => unevaluatedPropCode(key)));\n        }\n        it.props = true;\n        cxt.ok((0, codegen_1._) `${errsCount} === ${names_1.default.errors}`);\n        function unevaluatedPropCode(key) {\n            if (schema === false) {\n                cxt.setParams({ unevaluatedProperty: key });\n                cxt.error();\n                if (!allErrors)\n                    gen.break();\n                return;\n            }\n            if (!(0, util_1.alwaysValidSchema)(it, schema)) {\n                const valid = gen.name(\"valid\");\n                cxt.subschema({\n                    keyword: \"unevaluatedProperties\",\n                    dataProp: key,\n                    dataPropType: util_1.Type.Str,\n                }, valid);\n                if (!allErrors)\n                    gen.if((0, codegen_1.not)(valid), () => gen.break());\n            }\n        }\n        function unevaluatedDynamic(evaluatedProps, key) {\n            return (0, codegen_1._) `!${evaluatedProps} || !${evaluatedProps}[${key}]`;\n        }\n        function unevaluatedStatic(evaluatedProps, key) {\n            const ps = [];\n            for (const p in evaluatedProps) {\n                if (evaluatedProps[p] === true)\n                    ps.push((0, codegen_1._) `${key} !== ${p}`);\n            }\n            return (0, codegen_1.and)(...ps);\n        }\n    },\n};\nexports.default = def;\n//# sourceMappingURL=unevaluatedProperties.js.map","\"use strict\";\nObject.defineProperty(exports, \"__esModule\", { value: true });\nconst codegen_1 = require(\"../../compile/codegen\");\nconst util_1 = require(\"../../compile/util\");\nconst error = {\n    message: ({ params: { len } }) => (0, codegen_1.str) `must NOT have more than ${len} items`,\n    params: ({ params: { len } }) => (0, codegen_1._) `{limit: ${len}}`,\n};\nconst def = {\n    keyword: \"unevaluatedItems\",\n    type: \"array\",\n    schemaType: [\"boolean\", \"object\"],\n    error,\n    code(cxt) {\n        const { gen, schema, data, it } = cxt;\n        const items = it.items || 0;\n        if (items === true)\n            return;\n        const len = gen.const(\"len\", (0, codegen_1._) `${data}.length`);\n        if (schema === false) {\n            cxt.setParams({ len: items });\n            cxt.fail((0, codegen_1._) `${len} > ${items}`);\n        }\n        else if (typeof schema == \"object\" && !(0, util_1.alwaysValidSchema)(it, schema)) {\n            const valid = gen.var(\"valid\", (0, codegen_1._) `${len} <= ${items}`);\n            gen.if((0, codegen_1.not)(valid), () => validateItems(valid, items));\n            cxt.ok(valid);\n        }\n        it.items = true;\n        function validateItems(valid, from) {\n            gen.forRange(\"i\", from, len, (i) => {\n                cxt.subschema({ keyword: \"unevaluatedItems\", dataProp: i, dataPropType: util_1.Type.Num }, valid);\n                if (!it.allErrors)\n                    gen.if((0, codegen_1.not)(valid), () => gen.break());\n            });\n        }\n    },\n};\nexports.default = def;\n//# sourceMappingURL=unevaluatedItems.js.map","\"use strict\";\nObject.defineProperty(exports, \"__esModule\", { value: true });\nconst unevaluatedProperties_1 = require(\"./unevaluatedProperties\");\nconst unevaluatedItems_1 = require(\"./unevaluatedItems\");\nconst unevaluated = [unevaluatedProperties_1.default, unevaluatedItems_1.default];\nexports.default = unevaluated;\n//# sourceMappingURL=index.js.map","","","","","","","","\"use strict\";\nObject.defineProperty(exports, \"__esModule\", { value: true });\nconst metaSchema = require(\"./schema.json\");\nconst applicator = require(\"./meta/applicator.json\");\nconst content = require(\"./meta/content.json\");\nconst core = require(\"./meta/core.json\");\nconst format = require(\"./meta/format.json\");\nconst metadata = require(\"./meta/meta-data.json\");\nconst validation = require(\"./meta/validation.json\");\nconst META_SUPPORT_DATA = [\"/properties\"];\nfunction addMetaSchema2019($data) {\n    ;\n    [\n        metaSchema,\n        applicator,\n        content,\n        core,\n        with$data(this, format),\n        metadata,\n        with$data(this, validation),\n    ].forEach((sch) => this.addMetaSchema(sch, undefined, false));\n    return this;\n    function with$data(ajv, sch) {\n        return $data ? ajv.$dataMetaSchema(sch, META_SUPPORT_DATA) : sch;\n    }\n}\nexports.default = addMetaSchema2019;\n//# sourceMappingURL=index.js.map","\"use strict\";\nObject.defineProperty(exports, \"__esModule\", { value: true });\nexports.MissingRefError = exports.ValidationError = exports.CodeGen = exports.Name = exports.nil = exports.stringify = exports.str = exports._ = exports.KeywordCxt = exports.Ajv2019 = void 0;\nconst core_1 = require(\"./core\");\nconst draft7_1 = require(\"./vocabularies/draft7\");\nconst dynamic_1 = require(\"./vocabularies/dynamic\");\nconst next_1 = require(\"./vocabularies/next\");\nconst unevaluated_1 = require(\"./vocabularies/unevaluated\");\nconst discriminator_1 = require(\"./vocabularies/discriminator\");\nconst json_schema_2019_09_1 = require(\"./refs/json-schema-2019-09\");\nconst META_SCHEMA_ID = \"https://json-schema.org/draft/2019-09/schema\";\nclass Ajv2019 extends core_1.default {\n    constructor(opts = {}) {\n        super({\n            ...opts,\n            dynamicRef: true,\n            next: true,\n            unevaluated: true,\n        });\n    }\n    _addVocabularies() {\n        super._addVocabularies();\n        this.addVocabulary(dynamic_1.default);\n        draft7_1.default.forEach((v) => this.addVocabulary(v));\n        this.addVocabulary(next_1.default);\n        this.addVocabulary(unevaluated_1.default);\n        if (this.opts.discriminator)\n            this.addKeyword(discriminator_1.default);\n    }\n    _addDefaultMetaSchema() {\n        super._addDefaultMetaSchema();\n        const { $data, meta } = this.opts;\n        if (!meta)\n            return;\n        json_schema_2019_09_1.default.call(this, $data);\n        this.refs[\"http://json-schema.org/schema\"] = META_SCHEMA_ID;\n    }\n    defaultMeta() {\n        return (this.opts.defaultMeta =\n            super.defaultMeta() || (this.getSchema(META_SCHEMA_ID) ? META_SCHEMA_ID : undefined));\n    }\n}\nexports.Ajv2019 = Ajv2019;\nmodule.exports = exports = Ajv2019;\nmodule.exports.Ajv2019 = Ajv2019;\nObject.defineProperty(exports, \"__esModule\", { value: true });\nexports.default = Ajv2019;\nvar validate_1 = require(\"./compile/validate\");\nObject.defineProperty(exports, \"KeywordCxt\", { enumerable: true, get: function () { return validate_1.KeywordCxt; } });\nvar codegen_1 = require(\"./compile/codegen\");\nObject.defineProperty(exports, \"_\", { enumerable: true, get: function () { return codegen_1._; } });\nObject.defineProperty(exports, \"str\", { enumerable: true, get: function () { return codegen_1.str; } });\nObject.defineProperty(exports, \"stringify\", { enumerable: true, get: function () { return codegen_1.stringify; } });\nObject.defineProperty(exports, \"nil\", { enumerable: true, get: function () { return codegen_1.nil; } });\nObject.defineProperty(exports, \"Name\", { enumerable: true, get: function () { return codegen_1.Name; } });\nObject.defineProperty(exports, \"CodeGen\", { enumerable: true, get: function () { return codegen_1.CodeGen; } });\nvar validation_error_1 = require(\"./runtime/validation_error\");\nObject.defineProperty(exports, \"ValidationError\", { enumerable: true, get: function () { return validation_error_1.default; } });\nvar ref_error_1 = require(\"./compile/ref_error\");\nObject.defineProperty(exports, \"MissingRefError\", { enumerable: true, get: function () { return ref_error_1.default; } });\n//# sourceMappingURL=2019.js.map","\"use strict\";\nObject.defineProperty(exports, \"__esModule\", { value: true });\nconst core_1 = require(\"./core\");\nconst validation_1 = require(\"./validation\");\nconst applicator_1 = require(\"./applicator\");\nconst dynamic_1 = require(\"./dynamic\");\nconst next_1 = require(\"./next\");\nconst unevaluated_1 = require(\"./unevaluated\");\nconst format_1 = require(\"./format\");\nconst metadata_1 = require(\"./metadata\");\nconst draft2020Vocabularies = [\n    dynamic_1.default,\n    core_1.default,\n    validation_1.default,\n    (0, applicator_1.default)(true),\n    format_1.default,\n    metadata_1.metadataVocabulary,\n    metadata_1.contentVocabulary,\n    next_1.default,\n    unevaluated_1.default,\n];\nexports.default = draft2020Vocabularies;\n//# sourceMappingURL=draft2020.js.map","","","","","","","","","\"use strict\";\nObject.defineProperty(exports, \"__esModule\", { value: true });\nconst metaSchema = require(\"./schema.json\");\nconst applicator = require(\"./meta/applicator.json\");\nconst unevaluated = require(\"./meta/unevaluated.json\");\nconst content = require(\"./meta/content.json\");\nconst core = require(\"./meta/core.json\");\nconst format = require(\"./meta/format-annotation.json\");\nconst metadata = require(\"./meta/meta-data.json\");\nconst validation = require(\"./meta/validation.json\");\nconst META_SUPPORT_DATA = [\"/properties\"];\nfunction addMetaSchema2020($data) {\n    ;\n    [\n        metaSchema,\n        applicator,\n        unevaluated,\n        content,\n        core,\n        with$data(this, format),\n        metadata,\n        with$data(this, validation),\n    ].forEach((sch) => this.addMetaSchema(sch, undefined, false));\n    return this;\n    function with$data(ajv, sch) {\n        return $data ? ajv.$dataMetaSchema(sch, META_SUPPORT_DATA) : sch;\n    }\n}\nexports.default = addMetaSchema2020;\n//# sourceMappingURL=index.js.map","\"use strict\";\nObject.defineProperty(exports, \"__esModule\", { value: true });\nexports.MissingRefError = exports.ValidationError = exports.CodeGen = exports.Name = exports.nil = exports.stringify = exports.str = exports._ = exports.KeywordCxt = exports.Ajv2020 = void 0;\nconst core_1 = require(\"./core\");\nconst draft2020_1 = require(\"./vocabularies/draft2020\");\nconst discriminator_1 = require(\"./vocabularies/discriminator\");\nconst json_schema_2020_12_1 = require(\"./refs/json-schema-2020-12\");\nconst META_SCHEMA_ID = \"https://json-schema.org/draft/2020-12/schema\";\nclass Ajv2020 extends core_1.default {\n    constructor(opts = {}) {\n        super({\n            ...opts,\n            dynamicRef: true,\n            next: true,\n            unevaluated: true,\n        });\n    }\n    _addVocabularies() {\n        super._addVocabularies();\n        draft2020_1.default.forEach((v) => this.addVocabulary(v));\n        if (this.opts.discriminator)\n            this.addKeyword(discriminator_1.default);\n    }\n    _addDefaultMetaSchema() {\n        super._addDefaultMetaSchema();\n        const { $data, meta } = this.opts;\n        if (!meta)\n            return;\n        json_schema_2020_12_1.default.call(this, $data);\n        this.refs[\"http://json-schema.org/schema\"] = META_SCHEMA_ID;\n    }\n    defaultMeta() {\n        return (this.opts.defaultMeta =\n            super.defaultMeta() || (this.getSchema(META_SCHEMA_ID) ? META_SCHEMA_ID : undefined));\n    }\n}\nexports.Ajv2020 = Ajv2020;\nmodule.exports = exports = Ajv2020;\nmodule.exports.Ajv2020 = Ajv2020;\nObject.defineProperty(exports, \"__esModule\", { value: true });\nexports.default = Ajv2020;\nvar validate_1 = require(\"./compile/validate\");\nObject.defineProperty(exports, \"KeywordCxt\", { enumerable: true, get: function () { return validate_1.KeywordCxt; } });\nvar codegen_1 = require(\"./compile/codegen\");\nObject.defineProperty(exports, \"_\", { enumerable: true, get: function () { return codegen_1._; } });\nObject.defineProperty(exports, \"str\", { enumerable: true, get: function () { return codegen_1.str; } });\nObject.defineProperty(exports, \"stringify\", { enumerable: true, get: function () { return codegen_1.stringify; } });\nObject.defineProperty(exports, \"nil\", { enumerable: true, get: function () { return codegen_1.nil; } });\nObject.defineProperty(exports, \"Name\", { enumerable: true, get: function () { return codegen_1.Name; } });\nObject.defineProperty(exports, \"CodeGen\", { enumerable: true, get: function () { return codegen_1.CodeGen; } });\nvar validation_error_1 = require(\"./runtime/validation_error\");\nObject.defineProperty(exports, \"ValidationError\", { enumerable: true, get: function () { return validation_error_1.default; } });\nvar ref_error_1 = require(\"./compile/ref_error\");\nObject.defineProperty(exports, \"MissingRefError\", { enumerable: true, get: function () { return ref_error_1.default; } });\n//# sourceMappingURL=2020.js.map","\"use strict\";\nObject.defineProperty(exports, \"__esModule\", { value: true });\nexports.formatNames = exports.fastFormats = exports.fullFormats = void 0;\nfunction fmtDef(validate, compare) {\n    return { validate, compare };\n}\nexports.fullFormats = {\n    // date: http://tools.ietf.org/html/rfc3339#section-5.6\n    date: fmtDef(date, compareDate),\n    // date-time: http://tools.ietf.org/html/rfc3339#section-5.6\n    time: fmtDef(getTime(true), compareTime),\n    \"date-time\": fmtDef(getDateTime(true), compareDateTime),\n    \"iso-time\": fmtDef(getTime(), compareIsoTime),\n    \"iso-date-time\": fmtDef(getDateTime(), compareIsoDateTime),\n    // duration: https://tools.ietf.org/html/rfc3339#appendix-A\n    duration: /^P(?!$)((\\d+Y)?(\\d+M)?(\\d+D)?(T(?=\\d)(\\d+H)?(\\d+M)?(\\d+S)?)?|(\\d+W)?)$/,\n    uri,\n    \"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,\n    // uri-template: https://tools.ietf.org/html/rfc6570\n    \"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,\n    // For the source: https://gist.github.com/dperini/729294\n    // For test cases: https://mathiasbynens.be/demo/url-regex\n    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,\n    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,\n    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,\n    // optimized https://www.safaribooksonline.com/library/view/regular-expressions-cookbook/9780596802837/ch07s16.html\n    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)$/,\n    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,\n    regex,\n    // uuid: http://tools.ietf.org/html/rfc4122\n    uuid: /^(?:urn:uuid:)?[0-9a-f]{8}-(?:[0-9a-f]{4}-){3}[0-9a-f]{12}$/i,\n    // JSON-pointer: https://tools.ietf.org/html/rfc6901\n    // uri fragment: https://tools.ietf.org/html/rfc3986#appendix-A\n    \"json-pointer\": /^(?:\\/(?:[^~/]|~0|~1)*)*$/,\n    \"json-pointer-uri-fragment\": /^#(?:\\/(?:[a-z0-9_\\-.!$&'()*+,;:=@]|%[0-9a-f]{2}|~0|~1)*)*$/i,\n    // relative JSON-pointer: http://tools.ietf.org/html/draft-luff-relative-json-pointer-00\n    \"relative-json-pointer\": /^(?:0|[1-9][0-9]*)(?:#|(?:\\/(?:[^~/]|~0|~1)*)*)$/,\n    // the following formats are used by the openapi specification: https://spec.openapis.org/oas/v3.0.0#data-types\n    // byte: https://github.com/miguelmota/is-base64\n    byte,\n    // signed 32 bit integer\n    int32: { type: \"number\", validate: validateInt32 },\n    // signed 64 bit integer\n    int64: { type: \"number\", validate: validateInt64 },\n    // C-type float\n    float: { type: \"number\", validate: validateNumber },\n    // C-type double\n    double: { type: \"number\", validate: validateNumber },\n    // hint to the UI to hide input strings\n    password: true,\n    // unchecked string payload\n    binary: true,\n};\nexports.fastFormats = {\n    ...exports.fullFormats,\n    date: fmtDef(/^\\d\\d\\d\\d-[0-1]\\d-[0-3]\\d$/, compareDate),\n    time: fmtDef(/^(?:[0-2]\\d:[0-5]\\d:[0-5]\\d|23:59:60)(?:\\.\\d+)?(?:z|[+-]\\d\\d(?::?\\d\\d)?)$/i, compareTime),\n    \"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),\n    \"iso-time\": fmtDef(/^(?:[0-2]\\d:[0-5]\\d:[0-5]\\d|23:59:60)(?:\\.\\d+)?(?:z|[+-]\\d\\d(?::?\\d\\d)?)?$/i, compareIsoTime),\n    \"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),\n    // uri: https://github.com/mafintosh/is-my-json-valid/blob/master/formats.js\n    uri: /^(?:[a-z][a-z0-9+\\-.]*:)(?:\\/?\\/)?[^\\s]*$/i,\n    \"uri-reference\": /^(?:(?:[a-z][a-z0-9+\\-.]*:)?\\/?\\/)?(?:[^\\\\\\s#][^\\s#]*)?(?:#[^\\\\\\s]*)?$/i,\n    // email (sources from jsen validator):\n    // http://stackoverflow.com/questions/201323/using-a-regular-expression-to-validate-an-email-address#answer-8829363\n    // http://www.w3.org/TR/html5/forms.html#valid-e-mail-address (search for 'wilful violation')\n    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,\n};\nexports.formatNames = Object.keys(exports.fullFormats);\nfunction isLeapYear(year) {\n    // https://tools.ietf.org/html/rfc3339#appendix-C\n    return year % 4 === 0 && (year % 100 !== 0 || year % 400 === 0);\n}\nconst DATE = /^(\\d\\d\\d\\d)-(\\d\\d)-(\\d\\d)$/;\nconst DAYS = [0, 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31];\nfunction date(str) {\n    // full-date from http://tools.ietf.org/html/rfc3339#section-5.6\n    const matches = DATE.exec(str);\n    if (!matches)\n        return false;\n    const year = +matches[1];\n    const month = +matches[2];\n    const day = +matches[3];\n    return (month >= 1 &&\n        month <= 12 &&\n        day >= 1 &&\n        day <= (month === 2 && isLeapYear(year) ? 29 : DAYS[month]));\n}\nfunction compareDate(d1, d2) {\n    if (!(d1 && d2))\n        return undefined;\n    if (d1 > d2)\n        return 1;\n    if (d1 < d2)\n        return -1;\n    return 0;\n}\nconst TIME = /^(\\d\\d):(\\d\\d):(\\d\\d(?:\\.\\d+)?)(z|([+-])(\\d\\d)(?::?(\\d\\d))?)?$/i;\nfunction getTime(strictTimeZone) {\n    return function time(str) {\n        const matches = TIME.exec(str);\n        if (!matches)\n            return false;\n        const hr = +matches[1];\n        const min = +matches[2];\n        const sec = +matches[3];\n        const tz = matches[4];\n        const tzSign = matches[5] === \"-\" ? -1 : 1;\n        const tzH = +(matches[6] || 0);\n        const tzM = +(matches[7] || 0);\n        if (tzH > 23 || tzM > 59 || (strictTimeZone && !tz))\n            return false;\n        if (hr <= 23 && min <= 59 && sec < 60)\n            return true;\n        // leap second\n        const utcMin = min - tzM * tzSign;\n        const utcHr = hr - tzH * tzSign - (utcMin < 0 ? 1 : 0);\n        return (utcHr === 23 || utcHr === -1) && (utcMin === 59 || utcMin === -1) && sec < 61;\n    };\n}\nfunction compareTime(s1, s2) {\n    if (!(s1 && s2))\n        return undefined;\n    const t1 = new Date(\"2020-01-01T\" + s1).valueOf();\n    const t2 = new Date(\"2020-01-01T\" + s2).valueOf();\n    if (!(t1 && t2))\n        return undefined;\n    return t1 - t2;\n}\nfunction compareIsoTime(t1, t2) {\n    if (!(t1 && t2))\n        return undefined;\n    const a1 = TIME.exec(t1);\n    const a2 = TIME.exec(t2);\n    if (!(a1 && a2))\n        return undefined;\n    t1 = a1[1] + a1[2] + a1[3];\n    t2 = a2[1] + a2[2] + a2[3];\n    if (t1 > t2)\n        return 1;\n    if (t1 < t2)\n        return -1;\n    return 0;\n}\nconst DATE_TIME_SEPARATOR = /t|\\s/i;\nfunction getDateTime(strictTimeZone) {\n    const time = getTime(strictTimeZone);\n    return function date_time(str) {\n        // http://tools.ietf.org/html/rfc3339#section-5.6\n        const dateTime = str.split(DATE_TIME_SEPARATOR);\n        return dateTime.length === 2 && date(dateTime[0]) && time(dateTime[1]);\n    };\n}\nfunction compareDateTime(dt1, dt2) {\n    if (!(dt1 && dt2))\n        return undefined;\n    const d1 = new Date(dt1).valueOf();\n    const d2 = new Date(dt2).valueOf();\n    if (!(d1 && d2))\n        return undefined;\n    return d1 - d2;\n}\nfunction compareIsoDateTime(dt1, dt2) {\n    if (!(dt1 && dt2))\n        return undefined;\n    const [d1, t1] = dt1.split(DATE_TIME_SEPARATOR);\n    const [d2, t2] = dt2.split(DATE_TIME_SEPARATOR);\n    const res = compareDate(d1, d2);\n    if (res === undefined)\n        return undefined;\n    return res || compareTime(t1, t2);\n}\nconst NOT_URI_FRAGMENT = /\\/|:/;\nconst 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;\nfunction uri(str) {\n    // http://jmrware.com/articles/2009/uri_regexp/URI_regex.html + optional protocol + required \".\"\n    return NOT_URI_FRAGMENT.test(str) && URI.test(str);\n}\nconst BYTE = /^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/gm;\nfunction byte(str) {\n    BYTE.lastIndex = 0;\n    return BYTE.test(str);\n}\nconst MIN_INT32 = -(2 ** 31);\nconst MAX_INT32 = 2 ** 31 - 1;\nfunction validateInt32(value) {\n    return Number.isInteger(value) && value <= MAX_INT32 && value >= MIN_INT32;\n}\nfunction validateInt64(value) {\n    // JSON and javascript max Int is 2**53, so any int that passes isInteger is valid for Int64\n    return Number.isInteger(value);\n}\nfunction validateNumber() {\n    return true;\n}\nconst Z_ANCHOR = /[^\\\\]\\\\Z/;\nfunction regex(str) {\n    if (Z_ANCHOR.test(str))\n        return false;\n    try {\n        new RegExp(str);\n        return true;\n    }\n    catch (e) {\n        return false;\n    }\n}\n//# sourceMappingURL=formats.js.map","\"use strict\";\nObject.defineProperty(exports, \"__esModule\", { value: true });\nexports.formatLimitDefinition = void 0;\nconst ajv_1 = require(\"ajv\");\nconst codegen_1 = require(\"ajv/dist/compile/codegen\");\nconst ops = codegen_1.operators;\nconst KWDs = {\n    formatMaximum: { okStr: \"<=\", ok: ops.LTE, fail: ops.GT },\n    formatMinimum: { okStr: \">=\", ok: ops.GTE, fail: ops.LT },\n    formatExclusiveMaximum: { okStr: \"<\", ok: ops.LT, fail: ops.GTE },\n    formatExclusiveMinimum: { okStr: \">\", ok: ops.GT, fail: ops.LTE },\n};\nconst error = {\n    message: ({ keyword, schemaCode }) => (0, codegen_1.str) `should be ${KWDs[keyword].okStr} ${schemaCode}`,\n    params: ({ keyword, schemaCode }) => (0, codegen_1._) `{comparison: ${KWDs[keyword].okStr}, limit: ${schemaCode}}`,\n};\nexports.formatLimitDefinition = {\n    keyword: Object.keys(KWDs),\n    type: \"string\",\n    schemaType: \"string\",\n    $data: true,\n    error,\n    code(cxt) {\n        const { gen, data, schemaCode, keyword, it } = cxt;\n        const { opts, self } = it;\n        if (!opts.validateFormats)\n            return;\n        const fCxt = new ajv_1.KeywordCxt(it, self.RULES.all.format.definition, \"format\");\n        if (fCxt.$data)\n            validate$DataFormat();\n        else\n            validateFormat();\n        function validate$DataFormat() {\n            const fmts = gen.scopeValue(\"formats\", {\n                ref: self.formats,\n                code: opts.code.formats,\n            });\n            const fmt = gen.const(\"fmt\", (0, codegen_1._) `${fmts}[${fCxt.schemaCode}]`);\n            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)));\n        }\n        function validateFormat() {\n            const format = fCxt.schema;\n            const fmtDef = self.formats[format];\n            if (!fmtDef || fmtDef === true)\n                return;\n            if (typeof fmtDef != \"object\" ||\n                fmtDef instanceof RegExp ||\n                typeof fmtDef.compare != \"function\") {\n                throw new Error(`\"${keyword}\": format \"${format}\" does not define \"compare\" function`);\n            }\n            const fmt = gen.scopeValue(\"formats\", {\n                key: format,\n                ref: fmtDef,\n                code: opts.code.formats ? (0, codegen_1._) `${opts.code.formats}${(0, codegen_1.getProperty)(format)}` : undefined,\n            });\n            cxt.fail$data(compareCode(fmt));\n        }\n        function compareCode(fmt) {\n            return (0, codegen_1._) `${fmt}.compare(${data}, ${schemaCode}) ${KWDs[keyword].fail} 0`;\n        }\n    },\n    dependencies: [\"format\"],\n};\nconst formatLimitPlugin = (ajv) => {\n    ajv.addKeyword(exports.formatLimitDefinition);\n    return ajv;\n};\nexports.default = formatLimitPlugin;\n//# sourceMappingURL=limit.js.map","\"use strict\";\nObject.defineProperty(exports, \"__esModule\", { value: true });\nconst formats_1 = require(\"./formats\");\nconst limit_1 = require(\"./limit\");\nconst codegen_1 = require(\"ajv/dist/compile/codegen\");\nconst fullName = new codegen_1.Name(\"fullFormats\");\nconst fastName = new codegen_1.Name(\"fastFormats\");\nconst formatsPlugin = (ajv, opts = { keywords: true }) => {\n    if (Array.isArray(opts)) {\n        addFormats(ajv, opts, formats_1.fullFormats, fullName);\n        return ajv;\n    }\n    const [formats, exportName] = opts.mode === \"fast\" ? [formats_1.fastFormats, fastName] : [formats_1.fullFormats, fullName];\n    const list = opts.formats || formats_1.formatNames;\n    addFormats(ajv, list, formats, exportName);\n    if (opts.keywords)\n        (0, limit_1.default)(ajv);\n    return ajv;\n};\nformatsPlugin.get = (name, mode = \"full\") => {\n    const formats = mode === \"fast\" ? formats_1.fastFormats : formats_1.fullFormats;\n    const f = formats[name];\n    if (!f)\n        throw new Error(`Unknown format \"${name}\"`);\n    return f;\n};\nfunction addFormats(ajv, list, fs, exportName) {\n    var _a;\n    var _b;\n    (_a = (_b = ajv.opts.code).formats) !== null && _a !== void 0 ? _a : (_b.formats = (0, codegen_1._) `require(\"ajv-formats/dist/formats\").${exportName}`);\n    for (const f of list)\n        ajv.addFormat(f, fs[f]);\n}\nmodule.exports = exports = formatsPlugin;\nObject.defineProperty(exports, \"__esModule\", { value: true });\nexports.default = formatsPlugin;\n//# sourceMappingURL=index.js.map","/**\n * AJV-based JSON Schema validator provider\n */\n\nimport { Ajv as Draft7Ajv } from 'ajv';\nimport { Ajv2019 } from 'ajv/dist/2019.js';\nimport { Ajv2020 } from 'ajv/dist/2020.js';\nimport _addFormats from 'ajv-formats';\n\nimport { declaredDialect } from './dialects';\nimport type { JsonSchemaType, JsonSchemaValidator, jsonSchemaValidator, JsonSchemaValidatorResult } from './types';\n\n/** Structural subset of the AJV interface used by {@link AjvJsonSchemaValidator}. */\ninterface AjvLike {\n    compile: (schema: unknown) => AjvValidateFunction;\n    getSchema: (keyRef: string) => AjvValidateFunction | undefined;\n    // eslint-disable-next-line @typescript-eslint/no-explicit-any\n    errorsText: (errors?: any) => string;\n}\n\ninterface AjvValidateFunction {\n    (input: unknown): boolean;\n    // eslint-disable-next-line @typescript-eslint/no-explicit-any\n    errors?: any;\n}\n\n/** `ajv-formats` default export, normalised through the CJS/ESM interop wrapper. */\nconst addFormats = _addFormats as unknown as typeof _addFormats.default;\n\nfunction createDefaultAjvInstance(engineClass: typeof Ajv2020 | typeof Ajv2019 | typeof Draft7Ajv): AjvLike {\n    const ajv = new engineClass({\n        strict: false,\n        validateFormats: true,\n        validateSchema: false,\n        allErrors: true\n    });\n    addFormats(ajv);\n    return ajv;\n}\n\n/**\n * AJV-backed JSON Schema validator. See `@modelcontextprotocol/{client,server}/validators/ajv`\n * for the customisation entry point (re-exports `Ajv` and `addFormats` from the bundled copy).\n *\n * Default dispatches on the schema's declared dialect: no `$schema` or 2020-12 → `Ajv2020`\n * (SEP-1613); 2019-09 → `Ajv2019`; draft-07 or draft-06 → the classic draft-07 `Ajv` class\n * (draft-07's changes over draft-06 are additive, so one engine covers both). Known draft-07 deviation: classic Ajv\n * evaluates keywords adjacent to `$ref` (stricter than draft-07's ignore-siblings rule, matching\n * v1's default engine), while the cfworker provider ignores them per spec.\n * Schemas declaring any other `$schema` are\n * rejected with a plain `Error`; pass a pre-configured Ajv instance to validate\n * other dialects. The SDK bundles ajv internally but does not re-export `Ajv2020` (its type\n * graph tips downstream declaration bundling — see #2339). To construct a custom 2020-12\n * instance, add `ajv` to your own dependencies (matching the SDK's pinned version) and\n * `import { Ajv2020 } from 'ajv/dist/2020.js'` — `new Ajv(...)` is the draft-07 class and would\n * silently downgrade dialect.\n *\n * @example Use with default configuration\n * ```ts source=\"./ajvProvider.examples.ts#AjvJsonSchemaValidator_default\"\n * const validator = new AjvJsonSchemaValidator();\n * ```\n *\n * @example Use with a custom AJV instance\n * ```ts source=\"./ajvProvider.examples.ts#AjvJsonSchemaValidator_customInstance\"\n * // import { Ajv2020 } from 'ajv/dist/2020.js';\n * const ajv = new Ajv2020({ strict: false, validateSchema: false, allErrors: true });\n * const validator = new AjvJsonSchemaValidator(ajv);\n * ```\n *\n * @example Register ajv-formats\n * ```ts source=\"./ajvProvider.examples.ts#AjvJsonSchemaValidator_withFormats\"\n * // import { Ajv2020 } from 'ajv/dist/2020.js';\n * const ajv = new Ajv2020({ strict: false, validateSchema: false, allErrors: true });\n * addFormats(ajv);\n * const validator = new AjvJsonSchemaValidator(ajv);\n * ```\n */\nexport class AjvJsonSchemaValidator implements jsonSchemaValidator {\n    private _ajv: AjvLike | undefined;\n    /** Lazy classic (draft-07) engine, built on the first draft-07/draft-06-declared schema. */\n    private _ajvDraft7: AjvLike | undefined;\n    /** Lazy 2019-09 engine, built on the first 2019-09-declared schema. */\n    private _ajv2019: AjvLike | undefined;\n    /** True iff the constructor received a caller-supplied engine; the `$schema` dispatch is skipped. */\n    private readonly _userAjv: boolean;\n\n    /**\n     * @param ajv - Optional pre-configured AJV-compatible instance. When supplied, this instance is\n     * used for **every** schema regardless of its declared `$schema` (the caller owns dialect\n     * choice). When omitted, the provider constructs per-dialect engines (`Ajv2020`, `Ajv2019`,\n     * and the classic draft-07 `Ajv` for draft-07/06-declared schemas) with\n     * `strict: false`, `validateFormats: true`, `validateSchema: false`, `allErrors: true`, and\n     * `ajv-formats` registered — **lazily, on the first {@linkcode getValidator} call needing each**, so\n     * constructing the provider (e.g. as the default validator of a `Client`/`Server` that never\n     * validates a JSON Schema) does not pay the ajv + ajv-formats instantiation cost. The parameter\n     * is typed structurally so consumers who don't pass an instance need not have `ajv` installed.\n     */\n    constructor(ajv?: AjvLike) {\n        this._userAjv = ajv !== undefined;\n        this._ajv = ajv;\n    }\n\n    /** The underlying 2020-12 engine — the default instance is created on first use. */\n    private get ajv(): AjvLike {\n        return (this._ajv ??= createDefaultAjvInstance(Ajv2020));\n    }\n\n    /**\n     * Pick the engine for a schema's declared dialect. A caller-supplied engine is used for\n     * every schema — do not second-guess by `$schema` (bring-your-own-validator means\n     * bring-your-own-dialect). Otherwise: no `$schema` or 2020-12 → `Ajv2020`; 2019-09 →\n     * `Ajv2019`; draft-07 or draft-06 → classic `Ajv`; anything else → `Error`.\n     */\n    private _engineFor(schema: JsonSchemaType): AjvLike {\n        if (this._userAjv) {\n            return this.ajv;\n        }\n        const dialect = declaredDialect(\n            schema,\n            'pass a pre-configured Ajv instance to AjvJsonSchemaValidator(ajv) to validate other dialects.'\n        );\n        if (dialect === '2020-12') {\n            return this.ajv;\n        }\n        if (dialect === '2019-09') {\n            return (this._ajv2019 ??= createDefaultAjvInstance(Ajv2019));\n        }\n        return (this._ajvDraft7 ??= createDefaultAjvInstance(Draft7Ajv));\n    }\n\n    getValidator<T>(schema: JsonSchemaType): JsonSchemaValidator<T> {\n        const engine = this._engineFor(schema);\n        const ajvValidator =\n            '$id' in schema && typeof schema.$id === 'string'\n                ? (engine.getSchema(schema.$id) ?? engine.compile(schema))\n                : engine.compile(schema);\n\n        return (input: unknown): JsonSchemaValidatorResult<T> => {\n            const valid = ajvValidator(input);\n\n            return valid\n                ? {\n                      valid: true,\n                      data: input as T,\n                      errorMessage: undefined\n                  }\n                : {\n                      valid: false,\n                      data: undefined,\n                      errorMessage: engine.errorsText(ajvValidator.errors)\n                  };\n        };\n    }\n}\n\n/**\n * Draft-07 AJV class, re-exported for consumers who need to opt back to the pre-SEP-1613 default.\n * The full v1-equivalent construction is:\n *\n * ```ts\n * const ajv = new Ajv({ strict: false, validateFormats: true, validateSchema: false, allErrors: true });\n * addFormats(ajv);\n * new AjvJsonSchemaValidator(ajv);\n * ```\n *\n * (omitting `validateSchema: false` makes a 2020-12-stamped `$schema` fail with an opaque\n * \"no schema with key or ref …\" engine error; omitting `addFormats` silently drops `format`\n * validation that the v1 default had).\n *\n * The SDK bundles ajv internally but does not re-export `Ajv2020` (its type graph tips downstream\n * declaration bundling — see #2339). To construct a custom 2020-12 instance, add `ajv` to your own\n * dependencies (matching the SDK's pinned version) and `import { Ajv2020 } from 'ajv/dist/2020.js'`.\n */\nconst Ajv = Draft7Ajv;\n\nexport { addFormats, Ajv };\n","/**\n * Node.js runtime shims for client package\n *\n * This file is selected via package.json export conditions when running in Node.js.\n */\nexport { AjvJsonSchemaValidator as DefaultJsonSchemaValidator } from '@modelcontextprotocol/core-internal/validators/ajv';\n\n/**\n * Whether `fetch()` may throw `TypeError` due to CORS. CORS is a browser-only concept —\n * in Node.js, a `TypeError` from `fetch` is always a real network/configuration error\n * (DNS resolution, connection refused, invalid URL), never a CORS error.\n */\nexport const CORS_IS_POSSIBLE = false;\n","let crypto;\ncrypto =\n    globalThis.crypto?.webcrypto ?? // Node.js [18-16] REPL\n        globalThis.crypto ?? // Node.js >18\n        import(\"node:crypto\").then(m => m.webcrypto); // Node.js <18 Non-REPL\n/**\n * Creates an array of length `size` of random bytes\n * @param size\n * @returns Array of random ints (0 to 255)\n */\nasync function getRandomValues(size) {\n    return (await crypto).getRandomValues(new Uint8Array(size));\n}\n/** Generate cryptographically strong random string\n * @param size The desired length of the string\n * @returns The random string\n */\nasync function random(size) {\n    const mask = \"abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789-._~\";\n    const evenDistCutoff = Math.pow(2, 8) - Math.pow(2, 8) % mask.length;\n    let result = \"\";\n    while (result.length < size) {\n        const randomBytes = await getRandomValues(size - result.length);\n        for (const randomByte of randomBytes) {\n            if (randomByte < evenDistCutoff) {\n                result += mask[randomByte % mask.length];\n            }\n        }\n    }\n    return result;\n}\n/** Generate a PKCE challenge verifier\n * @param length Length of the verifier\n * @returns A random verifier `length` characters long\n */\nasync function generateVerifier(length) {\n    return await random(length);\n}\n/** Generate a PKCE code challenge from a code verifier\n * @param code_verifier\n * @returns The base64 url encoded code challenge\n */\nexport async function generateChallenge(code_verifier) {\n    const buffer = await (await crypto).subtle.digest(\"SHA-256\", new TextEncoder().encode(code_verifier));\n    // Generate base64url string\n    // btoa is deprecated in Node.js but is used here for web browser compatibility\n    // (which has no good replacement yet, see also https://github.com/whatwg/html/issues/6811)\n    return btoa(String.fromCharCode(...new Uint8Array(buffer)))\n        .replace(/\\//g, '_')\n        .replace(/\\+/g, '-')\n        .replace(/=/g, '');\n}\n/** Generate a PKCE challenge pair\n * @param length Length of the verifer (between 43-128). Defaults to 43.\n * @returns PKCE challenge pair\n */\nexport default async function pkceChallenge(length) {\n    if (!length)\n        length = 43;\n    if (length < 43 || length > 128) {\n        throw `Expected a length between 43 and 128. Received ${length}.`;\n    }\n    const verifier = await generateVerifier(length);\n    const challenge = await generateChallenge(verifier);\n    return {\n        code_verifier: verifier,\n        code_challenge: challenge,\n    };\n}\n/** Verify that a code_verifier produces the expected code challenge\n * @param code_verifier\n * @param expectedChallenge The code challenge to verify\n * @returns True if challenges are equal. False otherwise.\n */\nexport async function verifyChallenge(code_verifier, expectedChallenge) {\n    const actualChallenge = await generateChallenge(code_verifier);\n    return actualChallenge === expectedChallenge;\n}\n","/**\n * Error classes thrown by the OAuth client flow ({@linkcode auth} and helpers).\n *\n * Each behavior change in the 2026-07-28 authorization requirements adds its\n * dedicated error class to this module so callers can `instanceof`-dispatch on\n * the failure mode without string-matching messages.\n */\n\nimport type { OAuthClientMetadata } from '@modelcontextprotocol/core-internal';\nimport { brandedHasInstance, stampErrorBrands } from '@modelcontextprotocol/core-internal';\n\n/**\n * Base class for the OAuth-client-flow error family. Concrete subclasses are\n * added to this module alongside the SEP-2468/837/2207/2350/2352 behavior\n * changes that throw them, so callers can catch the whole family with a single\n * `instanceof OAuthClientFlowError` guard once those land.\n *\n * @remarks Nothing in the SDK throws this base class directly. In the release\n * that introduces it no subclass exists yet — the guard is a forward-compat\n * hook and will not match anything until the first behavior change ships.\n */\nexport class OAuthClientFlowError extends Error {\n    static {\n        Object.defineProperty(this, 'mcpBrand', { value: 'mcp.OAuthClientFlowError' });\n    }\n\n    static override [Symbol.hasInstance](value: unknown): boolean {\n        return brandedHasInstance(this, value);\n    }\n\n    /**\n     * Brand-based type guard: equivalent to `value instanceof this`, as an\n     * explicit static predicate (the axios/AWS-SDK `isInstance` style). Reads\n     * the caller's own brand via `this`, so every branded subclass gets a\n     * correctly-scoped guard by inheritance. Must be invoked on the class —\n     * in callback position write `v => SdkError.isInstance(v)`, not\n     * `.filter(SdkError.isInstance)` (detached calls throw rather than\n     * silently matching nothing).\n     */\n    static isInstance<T extends abstract new (...args: never[]) => unknown>(this: T, value: unknown): value is InstanceType<T> {\n        if (typeof this !== 'function') {\n            throw new TypeError(\n                'isInstance must be called on the class (e.g. `SdkError.isInstance(value)`); for callbacks use `v => SdkError.isInstance(v)`'\n            );\n        }\n        return brandedHasInstance(this, value);\n    }\n\n    constructor(message: string) {\n        super(message);\n        this.name = new.target.name;\n        stampErrorBrands(this, new.target);\n    }\n}\n\n/**\n * Thrown when an authorization-server issuer identifier fails validation.\n *\n * Two checks raise this error, distinguished by {@linkcode IssuerMismatchError.kind | kind}:\n * - `'metadata'` — the `issuer` in fetched authorization-server metadata does\n *   not match the issuer identifier the well-known URL was constructed from\n *   (RFC 8414 §3.3 / OpenID Connect Discovery §4.3).\n * - `'authorization_response'` — the `iss` parameter on the authorization\n *   callback failed RFC 9207 §2.4 validation against the recorded issuer.\n *\n * Intentionally does **not** extend `OAuthError`: the `auth()`\n * orchestrator's `OAuthError` retry block must not swallow this — a mix-up\n * indication is fatal for the flow, not a retryable credential problem.\n *\n * On the `'authorization_response'` path the {@linkcode IssuerMismatchError.received | received}\n * value is attacker-controllable in a mix-up attack; callers **MUST NOT** display\n * it (or any `error`/`error_description`/`error_uri` from the same callback) to\n * end users. The values are JSON-encoded in the message to neutralize log-injection.\n */\nexport class IssuerMismatchError extends OAuthClientFlowError {\n    static {\n        Object.defineProperty(this, 'mcpBrand', { value: 'mcp.IssuerMismatchError' });\n    }\n\n    /** Which check failed — metadata echo (RFC 8414 §3.3) or authorization-response `iss` (RFC 9207). */\n    readonly kind: 'metadata' | 'authorization_response';\n    /** The issuer the client expected (from validated metadata / discovery input). */\n    readonly expected: string | undefined;\n    /** The issuer value that was received. Attacker-controllable on the `'authorization_response'` path. */\n    readonly received: string | undefined;\n\n    constructor(kind: 'metadata' | 'authorization_response', expected: string | undefined, received: string | undefined) {\n        const where = kind === 'metadata' ? 'authorization server metadata (RFC 8414 §3.3)' : 'authorization response (RFC 9207)';\n        // JSON-stringify embedded values so attacker-supplied control characters cannot forge log lines.\n        super(`Issuer mismatch in ${where}: expected ${JSON.stringify(expected)}, received ${JSON.stringify(received)}`);\n        this.kind = kind;\n        this.expected = expected;\n        this.received = received;\n    }\n}\n\n/**\n * Thrown by `registerClient()` when the authorization server rejects a\n * Dynamic Client Registration request. Carries the HTTP status, the raw\n * response body, and the metadata that was submitted, so callers can inspect\n * the AS's `error` / `error_description` and retry with adjusted metadata\n * (for example a different `application_type`) per SEP-837.\n *\n * The `body` is the raw RFC 7591 error JSON; compare `JSON.parse(body).error`\n * against `OAuthErrorCode` (e.g. `OAuthErrorCode.InvalidRedirectUri`,\n * `OAuthErrorCode.InvalidClientMetadata`).\n *\n * Intentionally does **not** extend `OAuthError`: registration rejection is\n * not a recoverable-by-credential-invalidation condition, and staying outside\n * that hierarchy keeps it from being caught by `auth()`'s `OAuthError` retry\n * path.\n */\nexport class RegistrationRejectedError extends OAuthClientFlowError {\n    static {\n        Object.defineProperty(this, 'mcpBrand', { value: 'mcp.RegistrationRejectedError' });\n    }\n\n    /** HTTP status code returned by the registration endpoint. */\n    public readonly status: number;\n    /** Raw response body text (typically an RFC 7591 error JSON document). */\n    public readonly body: string;\n    /** The exact client metadata that was POSTed (after SDK defaults were applied). */\n    public readonly submittedMetadata: OAuthClientMetadata;\n\n    constructor(args: { status: number; body: string; submittedMetadata: OAuthClientMetadata }) {\n        super(`Dynamic Client Registration rejected (HTTP ${args.status}): ${args.body}`);\n        this.status = args.status;\n        this.body = args.body;\n        this.submittedMetadata = args.submittedMetadata;\n    }\n}\n\n/**\n * Thrown by the token-exchange and refresh paths when the resolved token\n * endpoint is not `https:` and is not a loopback host. The MCP authorization\n * specification requires authorization server endpoints to use HTTPS; loopback\n * hosts are exempt here for local development. This is a configuration error —\n * re-authorizing cannot fix it — so it intentionally does **not** extend\n * `OAuthError` and `auth()`'s refresh branch rethrows it instead of falling\n * through to a fresh `/authorize` redirect.\n */\nexport class InsecureTokenEndpointError extends OAuthClientFlowError {\n    static {\n        Object.defineProperty(this, 'mcpBrand', { value: 'mcp.InsecureTokenEndpointError' });\n    }\n\n    /** The token endpoint URL that was rejected. */\n    public readonly tokenEndpoint: string;\n\n    constructor(tokenEndpoint: string) {\n        super(\n            `Refusing to send credentials to non-https token endpoint '${tokenEndpoint}'. ` +\n                `OAuth token requests MUST use TLS (localhost / *.localhost / 127.0.0.1 / ::1 are exempt).`\n        );\n        this.tokenEndpoint = tokenEndpoint;\n    }\n}\n\n/**\n * Thrown by the HTTP client transport when the server responds with\n * `403 Forbidden` and `WWW-Authenticate: Bearer error=\"insufficient_scope\"`,\n * and either (a) the transport's `onInsufficientScope` option is `'throw'`, or\n * (b) `onInsufficientScope` is the default `'reauthorize'` but the transport\n * has no {@linkcode index.OAuthClientProvider | OAuthClientProvider} to drive\n * step-up (e.g. a minimal `AuthProvider`, `requestInit`-only headers, or no\n * `authProvider`).\n *\n * Carries the challenge parameters so the host can decide whether to initiate\n * step-up authorization itself (e.g., behind a UX gate) or surface the error.\n *\n * Does **not** extend `OAuthError`: that class represents OAuth protocol errors\n * from the authorization server; this is a resource-server challenge surfaced\n * at the transport layer.\n *\n * All fields originate from the resource server's `WWW-Authenticate` header;\n * treat them as untrusted input when displaying or logging (this includes\n * `requiredScope`, which appears in the error message).\n */\n/**\n * Thrown by `auth()` and `fetchToken()` when the authorization server in use differs\n * from the one a credential is bound to and the flow cannot simply start over:\n *\n * - on the authorization-code callback leg, when it differs from the one recorded\n *   in `discoveryState()` at redirect time — the `authorization_code` and PKCE\n *   `code_verifier` are bound to the AS that minted the code (RFC 7636);\n * - for client information whose `issuer` stamp names a different authorization\n *   server on a provider that cannot re-register (no `saveClientInformation()`,\n *   e.g. the bundled static-credential providers); `fetchToken()` throws for any provider.\n *\n * Stored tokens and re-registrable client information are protected structurally\n * by the `issuer` stamp instead (they read back as absent).\n */\nexport class AuthorizationServerMismatchError extends OAuthClientFlowError {\n    static {\n        Object.defineProperty(this, 'mcpBrand', { value: 'mcp.AuthorizationServerMismatchError' });\n    }\n\n    constructor(\n        /** The issuer the credential is bound to (recorded in `discoveryState()` at redirect time, or stamped on the client information). */\n        public readonly recordedIssuer: string,\n        /** The issuer resolved by discovery on this call. */\n        public readonly currentIssuer: string\n    ) {\n        super(\n            `Authorization server mismatch: credentials are bound to ${JSON.stringify(recordedIssuer)} ` +\n                `but this call resolved ${JSON.stringify(currentIssuer)}; refusing to present them to a different authorization server`\n        );\n    }\n}\n\nexport class InsufficientScopeError extends OAuthClientFlowError {\n    static {\n        Object.defineProperty(this, 'mcpBrand', { value: 'mcp.InsufficientScopeError' });\n    }\n\n    /** The `scope` value from the `WWW-Authenticate` challenge — the scopes the resource server says are required. */\n    readonly requiredScope?: string;\n    /** The `resource_metadata` URL from the `WWW-Authenticate` challenge, if present. */\n    readonly resourceMetadataUrl?: URL;\n    /** The `error_description` from the `WWW-Authenticate` challenge, if present. */\n    readonly errorDescription?: string;\n\n    constructor(init: { requiredScope?: string; resourceMetadataUrl?: URL; errorDescription?: string }) {\n        super(`Insufficient scope${init.requiredScope ? `: required \"${init.requiredScope}\"` : ''}`);\n        this.requiredScope = init.requiredScope;\n        this.resourceMetadataUrl = init.resourceMetadataUrl;\n        this.errorDescription = init.errorDescription;\n    }\n}\n","import { CORS_IS_POSSIBLE } from '@modelcontextprotocol/client/_shims';\nimport type {\n    AuthorizationServerMetadata,\n    FetchLike,\n    OAuthClientInformation,\n    OAuthClientInformationFull,\n    OAuthClientInformationMixed,\n    OAuthClientMetadata,\n    OAuthMetadata,\n    OAuthProtectedResourceMetadata,\n    OAuthTokens,\n    StoredOAuthClientInformation,\n    StoredOAuthTokens\n} from '@modelcontextprotocol/core-internal';\nimport {\n    brandedHasInstance,\n    checkResourceAllowed,\n    fetchWithinOrigin,\n    LATEST_PROTOCOL_VERSION,\n    OAuthClientInformationFullSchema,\n    OAuthError,\n    OAuthErrorCode,\n    OAuthErrorResponseSchema,\n    OAuthMetadataSchema,\n    OAuthProtectedResourceMetadataSchema,\n    OAuthTokensSchema,\n    OpenIdProviderDiscoveryMetadataSchema,\n    resourceUrlFromServerUrl,\n    stampErrorBrands,\n    withoutIssuer\n} from '@modelcontextprotocol/core-internal';\nimport pkceChallenge from 'pkce-challenge';\n\nimport { AuthorizationServerMismatchError, InsecureTokenEndpointError, IssuerMismatchError, RegistrationRejectedError } from './authErrors';\nimport type { DpopSession } from './dpop';\n// eslint-disable-next-line @typescript-eslint/no-unused-vars -- referenced in JSDoc {@linkcode}\nimport type { withDpopFromProvider, withOAuth } from './middleware';\n\n// Re-exported for back-compat — the canonical home is ./authErrors.js.\nexport { AuthorizationServerMismatchError, InsecureTokenEndpointError, IssuerMismatchError, RegistrationRejectedError } from './authErrors';\n\n/**\n * Function type for adding client authentication to token requests.\n */\nexport type AddClientAuthentication = (\n    headers: Headers,\n    params: URLSearchParams,\n    url: string | URL,\n    metadata?: AuthorizationServerMetadata\n) => void | Promise<void>;\n\n/**\n * Context passed to {@linkcode AuthProvider.onUnauthorized} when the server\n * responds with 401. Provides everything needed to refresh credentials.\n */\nexport interface UnauthorizedContext {\n    /** The 401 response — inspect `WWW-Authenticate` for resource metadata, scope, etc. */\n    response: Response;\n    /** The MCP server URL, for passing to {@linkcode auth} or discovery helpers. */\n    serverUrl: URL;\n    /** Fetch function configured with the transport's `requestInit`, for making auth requests. */\n    fetchFn: FetchLike;\n}\n\n/**\n * Minimal interface for authenticating MCP client transports with bearer tokens.\n *\n * Transports call {@linkcode AuthProvider.token | token()} before every request\n * to obtain the current token, and {@linkcode AuthProvider.onUnauthorized | onUnauthorized()}\n * (if provided) when the server responds with 401, giving the provider a chance\n * to refresh credentials before the transport retries once.\n *\n * For simple cases (API keys, gateway-managed tokens), implement only `token()`:\n * ```typescript\n * const authProvider: AuthProvider = { token: async () => process.env.API_KEY };\n * ```\n *\n * For OAuth flows, pass an {@linkcode OAuthClientProvider} directly — transports\n * accept either shape and adapt OAuth providers automatically via {@linkcode adaptOAuthProvider}.\n */\nexport interface AuthProvider {\n    /**\n     * Returns the current bearer token, or `undefined` if no token is available.\n     * Called before every request.\n     */\n    token(): Promise<string | undefined>;\n\n    /**\n     * Called when the server responds with 401. If provided, the transport will\n     * await this, then retry the request once. If the retry also gets 401, the\n     * transport throws `SdkHttpError` (`SdkErrorCode.ClientHttpAuthentication`). If\n     * this method is not provided, the transport throws {@linkcode UnauthorizedError}.\n     *\n     * Implementations should refresh tokens, re-authenticate, etc. — whatever is\n     * needed so the next `token()` call returns a valid token.\n     */\n    onUnauthorized?(ctx: UnauthorizedContext): Promise<void>;\n}\n\n/**\n * Context passed to the credential-persistence methods on\n * {@linkcode OAuthClientProvider} — `clientInformation` / `saveClientInformation`\n * and `tokens` / `saveTokens`. Carries the resolved authorization-server `issuer`\n * so provider implementations can key persisted credentials per authorization\n * server (RFC 6749 §2.2 — client identifiers are unique to the AS that issued\n * them). Providers that store a single credential set may ignore it.\n */\nexport interface OAuthClientInformationContext {\n    /**\n     * The authorization server's `issuer` identifier from its validated metadata\n     * document, used as the binding key for persisted credentials.\n     */\n    issuer: string;\n}\n\n/**\n * SEP-2352 stamp check: returns `stored` only when its `issuer` stamp matches the\n * resolved authorization server. A stamp that names a *different* issuer reads back\n * as `undefined`, so a credential issued by one authorization server is never reused\n * at another — the flow falls through to re-registration / re-authorization exactly\n * as if nothing were stored. An unstamped value (legacy provider or pre-SEP-2352\n * storage) is returned as-is with a `console.warn`; {@linkcode auth} writes the\n * stamp back on first use so the window closes after one call.\n *\n * {@linkcode auth} stamps every value it writes via `saveTokens` / `saveClientInformation`,\n * so a provider that round-trips the stored object verbatim is protected with no extra\n * code. Providers that hold credentials for multiple authorization servers key their\n * storage on `ctx.issuer` instead.\n *\n * @param opts.canPersistStamp - When `false`, suppresses the unstamped-credential\n *   warning: the caller cannot back-stamp (no `saveClientInformation`), so the\n *   \"binding on first use\" claim would be false and would fire on every call.\n */\nexport function discardIfIssuerMismatch<T extends { issuer?: string }>(\n    stored: T | null | undefined,\n    issuer: string,\n    opts?: { canPersistStamp?: boolean }\n): T | undefined {\n    // Nothing stored (`null` from a `JSON.parse(storage.getItem(...))`-style getter included).\n    if (!stored) return undefined;\n    // A stamp that is not a string (raw storage) counts as no stamp.\n    if (typeof stored.issuer !== 'string') {\n        if (opts?.canPersistStamp !== false) {\n            console.warn(\n                `[mcp-sdk] SEP-2352: stored OAuth credential has no 'issuer' stamp (pre-upgrade storage or ` +\n                    `provider not round-tripping the value). SEP-2352 isolation is inactive for this read; ` +\n                    `ensure your provider round-trips the issuer field.`\n            );\n        }\n        return stored.issuer === undefined ? stored : { ...stored, issuer: undefined };\n    }\n    return issuersMatch(stored.issuer, issuer) ? stored : undefined;\n}\n\n/**\n * SEP-2352 issuer-identity comparison. Tolerates a single trailing `/` difference,\n * mirroring the RFC 8414 §3.3 \"one narrow tolerance\" applied at metadata-echo\n * validation in {@linkcode discoverAuthorizationServerMetadata}: when the SDK\n * derives an issuer from `String(new URL(...))` (always slash-suffixed) and the AS\n * publishes a slash-free `metadata.issuer`, the two name the same authorization\n * server.\n */\nfunction issuersMatch(a: string, b: string): boolean {\n    return a === b || (a.endsWith('/') && a.slice(0, -1) === b) || (b.endsWith('/') && b.slice(0, -1) === a);\n}\n\n/**\n * Type guard distinguishing `OAuthClientProvider` from a minimal `AuthProvider`.\n * Transports use this at construction time to classify the `authProvider` option.\n *\n * Checks for `tokens()` + `clientInformation()` — two required `OAuthClientProvider`\n * methods that a minimal `AuthProvider` `{ token: ... }` would never have.\n */\nexport function isOAuthClientProvider(provider: AuthProvider | OAuthClientProvider | undefined): provider is OAuthClientProvider {\n    if (provider == null) return false;\n    const p = provider as OAuthClientProvider;\n    return typeof p.tokens === 'function' && typeof p.clientInformation === 'function';\n}\n\n/**\n * Standard `onUnauthorized` behavior for OAuth providers: extracts\n * `WWW-Authenticate` parameters from the 401 response and runs {@linkcode auth}.\n * Used by {@linkcode adaptOAuthProvider} to bridge `OAuthClientProvider` to `AuthProvider`.\n */\nexport async function handleOAuthUnauthorized(\n    provider: OAuthClientProvider,\n    ctx: UnauthorizedContext,\n    extraAuthOptions?: Pick<AuthOptions, 'skipIssuerMetadataValidation'>\n): Promise<void> {\n    const { resourceMetadataUrl, scope } = extractWWWAuthenticateParams(ctx.response);\n    const result = await auth(provider, {\n        serverUrl: ctx.serverUrl,\n        resourceMetadataUrl,\n        scope,\n        fetchFn: ctx.fetchFn,\n        ...extraAuthOptions\n    });\n    if (result !== 'AUTHORIZED') {\n        throw new UnauthorizedError();\n    }\n}\n\n/**\n * Adapts an `OAuthClientProvider` to the minimal `AuthProvider` interface that\n * transports consume. Called once at transport construction — the transport stores\n * the adapted provider for `_commonHeaders()` and 401 handling, while keeping the\n * original `OAuthClientProvider` for OAuth-specific paths (`finishAuth()`, 403 `insufficient_scope` step-up).\n *\n * SEP-2352 note: `token()` here is the per-request `Authorization: Bearer …` read for\n * the *resource server* (the MCP transport URL), not an authorization server. No OAuth\n * discovery has run at this layer, so there is no `issuer` to pass as `ctx` and no\n * {@linkcode discardIfIssuerMismatch} check to apply — the access token is sent only to\n * the resource server, never to an AS, so the SEP-2352 cross-AS isolation invariant is\n * not in scope. Providers that key storage on `ctx.issuer` MUST treat `ctx === undefined`\n * as \"return the most-recently-saved token set\" (the only consumer is the resource server\n * the token was minted for); providers that round-trip a single blob need no change.\n *\n * SEP-1932 (DPoP) note: DPoP request-signing is deliberately *not* done here. When the provider\n * implements {@linkcode OAuthClientProvider.dpop | dpop()}, the transports wrap their\n * resource-server `fetch` with {@linkcode withDpopFromProvider}, which upgrades the `Bearer` header\n * this adapter produces to `DPoP` + proof for DPoP-bound tokens and handles nonce challenges — at\n * the one layer that sees the real method, URL and response of every request.\n */\nexport function adaptOAuthProvider(\n    provider: OAuthClientProvider,\n    extraAuthOptions?: Pick<AuthOptions, 'skipIssuerMetadataValidation'>\n): AuthProvider {\n    return {\n        token: async () => {\n            const tokens = await provider.tokens();\n            return tokens?.access_token;\n        },\n        onUnauthorized: async ctx => handleOAuthUnauthorized(provider, ctx, extraAuthOptions)\n    };\n}\n\n/**\n * Implements an end-to-end OAuth client to be used with one MCP server.\n *\n * This client relies upon a concept of an authorized \"session,\" the exact\n * meaning of which is application-defined. Tokens, authorization codes, and\n * code verifiers should not cross different sessions.\n *\n * Transports accept `OAuthClientProvider` directly via the `authProvider` option —\n * they adapt it to {@linkcode AuthProvider} internally via {@linkcode adaptOAuthProvider}.\n * No changes are needed to existing implementations.\n */\nexport interface OAuthClientProvider {\n    /**\n     * The URL to redirect the user agent to after authorization.\n     * Return `undefined` for non-interactive flows that don't require user interaction\n     * (e.g., `client_credentials`, `jwt-bearer`).\n     */\n    get redirectUrl(): string | URL | undefined;\n\n    /**\n     * External URL the server should use to fetch client metadata document\n     */\n    clientMetadataUrl?: string;\n\n    /**\n     * Metadata about this OAuth client.\n     */\n    get clientMetadata(): OAuthClientMetadata;\n\n    /**\n     * Returns an OAuth2 state parameter.\n     */\n    state?(): string | Promise<string>;\n\n    /**\n     * Loads information about this OAuth client, as registered already with the\n     * server, or returns `undefined` if the client is not registered with the\n     * server.\n     *\n     * @param ctx - Carries the resolved authorization-server `issuer`. Providers\n     *   that persist credentials per authorization server should return the entry\n     *   keyed by `ctx.issuer`. Providers with a single credential set may ignore it.\n     */\n    clientInformation(\n        ctx?: OAuthClientInformationContext\n    ): StoredOAuthClientInformation | undefined | Promise<StoredOAuthClientInformation | undefined>;\n\n    /**\n     * If implemented, this permits the OAuth client to dynamically register with\n     * the server. Client information saved this way should later be read via\n     * {@linkcode OAuthClientProvider.clientInformation | clientInformation()}.\n     *\n     * This method is not required to be implemented if client information is\n     * statically known (e.g., pre-registered).\n     *\n     * @param ctx - Carries the resolved authorization-server `issuer`. Providers\n     *   that persist credentials per authorization server should store the entry\n     *   keyed by `ctx.issuer`.\n     */\n    saveClientInformation?(clientInformation: StoredOAuthClientInformation, ctx?: OAuthClientInformationContext): void | Promise<void>;\n\n    /**\n     * Loads any existing OAuth tokens for the current session, or returns\n     * `undefined` if there are no saved tokens.\n     *\n     * @param ctx - Carries the resolved authorization-server `issuer`. Providers\n     *   that persist tokens per authorization server should return the entry\n     *   keyed by `ctx.issuer`. Providers with a single token set may ignore it.\n     *   When called with no `ctx` — the transport's per-request bearer-token\n     *   read — return the most-recently-saved token set; do not return\n     *   `undefined` for `ctx === undefined`.\n     */\n    tokens(ctx?: OAuthClientInformationContext): StoredOAuthTokens | undefined | Promise<StoredOAuthTokens | undefined>;\n\n    /**\n     * Stores new OAuth tokens for the current session, after a successful\n     * authorization.\n     *\n     * @param ctx - Carries the resolved authorization-server `issuer`. Providers\n     *   that persist tokens per authorization server should store the entry\n     *   keyed by `ctx.issuer`.\n     */\n    saveTokens(tokens: StoredOAuthTokens, ctx?: OAuthClientInformationContext): void | Promise<void>;\n\n    /**\n     * Invoked to redirect the user agent to the given URL to begin the authorization flow.\n     */\n    redirectToAuthorization(authorizationUrl: URL): void | Promise<void>;\n\n    /**\n     * Saves a PKCE code verifier for the current session, before redirecting to\n     * the authorization flow.\n     */\n    saveCodeVerifier(codeVerifier: string): void | Promise<void>;\n\n    /**\n     * Loads the PKCE code verifier for the current session, necessary to validate\n     * the authorization result.\n     */\n    codeVerifier(): string | Promise<string>;\n\n    /**\n     * Adds custom client authentication to OAuth token requests.\n     *\n     * This optional method allows implementations to customize how client credentials\n     * are included in token exchange and refresh requests. When provided, this method\n     * is called instead of the default authentication logic, giving full control over\n     * the authentication mechanism.\n     *\n     * Common use cases include:\n     * - Supporting authentication methods beyond the standard OAuth 2.0 methods\n     * - Adding custom headers for proprietary authentication schemes\n     * - Implementing client assertion-based authentication (e.g., JWT bearer tokens)\n     *\n     * @param headers - The request headers (can be modified to add authentication)\n     * @param params - The request body parameters (can be modified to add credentials)\n     * @param url - The token endpoint URL being called\n     * @param metadata - Optional OAuth metadata for the server, which may include supported authentication methods\n     */\n    addClientAuthentication?: AddClientAuthentication;\n\n    /**\n     * Enables DPoP (RFC 9449 / SEP-1932) sender-constrained tokens when implemented. When this\n     * resolves to a {@linkcode DpopSession}, {@linkcode auth} signs a DPoP proof into the token\n     * request, and the transports (and {@linkcode withOAuth}) present a resulting `token_type: DPoP`\n     * access token with the `DPoP` Authorization scheme plus a fresh per-request proof instead of\n     * `Bearer`, by wrapping their resource-server `fetch` with {@linkcode withDpopFromProvider}.\n     *\n     * Return the *same* session across calls — the AS/RS nonce state and signing key it holds are\n     * meant to persist for the life of this client registration. A minimal implementation:\n     * ```typescript\n     * class MyProvider implements OAuthClientProvider {\n     *     private _dpop = DpopSession.create();\n     *     dpop() { return this._dpop; }\n     *     // ...\n     * }\n     * ```\n     *\n     * Left undefined (the default), the provider behaves exactly as before this option existed:\n     * plain Bearer tokens throughout.\n     */\n    dpop?(): DpopSession | undefined | Promise<DpopSession | undefined>;\n\n    /**\n     * If defined, overrides the selection and validation of the\n     * RFC 8707 Resource Indicator. If left undefined, default\n     * validation behavior will be used.\n     *\n     * Implementations must verify the returned resource matches the MCP server.\n     */\n    validateResourceURL?(serverUrl: string | URL, resource?: string): Promise<URL | undefined>;\n\n    /**\n     * Returns the `scope` that {@linkcode auth} sends on a refresh-token request. Left undefined\n     * (the default), or when it returns `undefined` or `''`, the request carries no `scope`, which\n     * asks for the scope already granted (RFC 6749 §6).\n     *\n     * Implement it only for an authorization server that rejects a refresh without `scope`:\n     * other servers may reject or narrow a refresh that carries one. The returned value must\n     * not include a scope that was not originally granted.\n     *\n     * @param tokens - The stored tokens being refreshed; `tokens.scope` is the scope last saved with them.\n     */\n    scopeForRefresh?(tokens: StoredOAuthTokens): string | undefined | Promise<string | undefined>;\n\n    /**\n     * If implemented, provides a way for the client to invalidate (e.g. delete) the specified\n     * credentials, in the case where the server has indicated that they are no longer valid.\n     * This avoids requiring the user to intervene manually.\n     */\n    invalidateCredentials?(scope: 'all' | 'client' | 'tokens' | 'verifier' | 'discovery'): void | Promise<void>;\n\n    /**\n     * Prepares grant-specific parameters for a token request.\n     *\n     * This optional method allows providers to customize the token request based on\n     * the grant type they support. When implemented, it returns the grant type and\n     * any grant-specific parameters needed for the token exchange.\n     *\n     * If not implemented, the default behavior depends on the flow:\n     * - For authorization code flow: uses `code`, `code_verifier`, and `redirect_uri`\n     * - For `client_credentials`: detected via `grant_types` in {@linkcode OAuthClientProvider.clientMetadata | clientMetadata}\n     *\n     * @param scope - Optional scope to request\n     * @returns Grant type and parameters, or `undefined` to use default behavior\n     *\n     * @example\n     * // For client_credentials grant:\n     * prepareTokenRequest(scope) {\n     *   return {\n     *     grantType: 'client_credentials',\n     *     params: scope ? { scope } : {}\n     *   };\n     * }\n     *\n     * @example\n     * // For authorization_code grant (default behavior):\n     * async prepareTokenRequest() {\n     *   return {\n     *     grantType: 'authorization_code',\n     *     params: {\n     *       code: this.authorizationCode,\n     *       code_verifier: await this.codeVerifier(),\n     *       redirect_uri: String(this.redirectUrl)\n     *     }\n     *   };\n     * }\n     */\n    prepareTokenRequest?(scope?: string): URLSearchParams | Promise<URLSearchParams | undefined> | undefined;\n\n    /**\n     * Saves the resolved authorization-server **issuer**. Called after a successful\n     * token exchange (timing changed in v2: was post-discovery, now post-`saveTokens`).\n     *\n     * @deprecated Superseded by the `issuer` stamp on stored tokens / client credentials\n     * (SEP-2352). {@linkcode auth} still **writes** this for back-compat with providers\n     * that read it (e.g. Cross-App Access), but the SDK never reads it. Prefer reading\n     * the `issuer` field on the value passed to {@linkcode saveTokens} /\n     * {@linkcode saveClientInformation}, or the `ctx.issuer` argument.\n     */\n    saveAuthorizationServerUrl?(authorizationServerUrl: string): void | Promise<void>;\n\n    /**\n     * Returns the previously saved authorization server URL, if available.\n     *\n     * @deprecated Superseded by the `issuer` stamp on stored tokens / client credentials\n     * (SEP-2352). The SDK never reads this method; it remains for provider implementations\n     * that consume the value internally (e.g. Cross-App Access).\n     */\n    authorizationServerUrl?(): string | undefined | Promise<string | undefined>;\n\n    /**\n     * Saves the resource URL after RFC 9728 discovery.\n     * This method is called by {@linkcode auth} after successful discovery of the\n     * resource metadata.\n     *\n     * Providers implementing Cross-App Access or other flows that need access to\n     * the discovered resource URL should implement this method.\n     *\n     * @param resourceUrl - The resource URL discovered via RFC 9728\n     */\n    saveResourceUrl?(resourceUrl: string): void | Promise<void>;\n\n    /**\n     * Returns the previously saved resource URL, if available.\n     *\n     * Providers implementing Cross-App Access can use this to access the\n     * resource URL discovered during the OAuth flow.\n     *\n     * @returns The resource URL, or `undefined` if not available\n     */\n    resourceUrl?(): string | undefined | Promise<string | undefined>;\n\n    /**\n     * Saves the OAuth discovery state after RFC 9728 and authorization server metadata\n     * discovery. Providers can persist this state to avoid redundant discovery requests\n     * on subsequent {@linkcode auth} calls.\n     *\n     * This state can also be provided out-of-band (e.g., from a previous session or\n     * external configuration) to bootstrap the OAuth flow without discovery.\n     *\n     * Called by {@linkcode auth} after successful discovery.\n     *\n     * MUST persist with the same durability as `codeVerifier` (survives the redirect\n     * round-trip).\n     */\n    saveDiscoveryState?(state: OAuthDiscoveryState): void | Promise<void>;\n\n    /**\n     * Returns previously saved discovery state, or `undefined` if none is cached.\n     *\n     * When available, {@linkcode auth} restores the discovery state (authorization server\n     * URL, resource metadata, etc.) instead of performing RFC 9728 discovery, reducing\n     * latency on subsequent calls.\n     *\n     * Hosts should call {@linkcode invalidateCredentials} with scope `'discovery'`\n     * on repeated 401s so a changed `authorization_servers` list is picked up; the\n     * SDK does not invoke that scope itself.\n     *\n     * MUST persist with the same durability as `codeVerifier` (survives the redirect\n     * round-trip).\n     */\n    discoveryState?(): OAuthDiscoveryState | undefined | Promise<OAuthDiscoveryState | undefined>;\n}\n\n/**\n * Discovery state that can be persisted across sessions by an {@linkcode OAuthClientProvider}.\n *\n * Contains the results of RFC 9728 protected resource metadata discovery and\n * authorization server metadata discovery. Persisting this state avoids\n * redundant discovery HTTP requests on subsequent {@linkcode auth} calls.\n */\n// TODO: Consider adding `authorizationServerMetadataUrl` to capture the exact well-known URL\n// at which authorization server metadata was discovered. This would require\n// `discoverAuthorizationServerMetadata()` to return the successful discovery URL.\nexport interface OAuthDiscoveryState extends OAuthServerInfo {\n    /** The URL at which the protected resource metadata was found, if available. */\n    resourceMetadataUrl?: string;\n}\n\nexport type AuthResult = 'AUTHORIZED' | 'REDIRECT';\n\nexport class UnauthorizedError extends Error {\n    static {\n        Object.defineProperty(this, 'mcpBrand', { value: 'mcp.UnauthorizedError' });\n    }\n\n    static override [Symbol.hasInstance](value: unknown): boolean {\n        return brandedHasInstance(this, value);\n    }\n\n    /**\n     * Brand-based type guard: equivalent to `value instanceof this`, as an\n     * explicit static predicate (the axios/AWS-SDK `isInstance` style). Reads\n     * the caller's own brand via `this`, so every branded subclass gets a\n     * correctly-scoped guard by inheritance. Must be invoked on the class —\n     * in callback position write `v => SdkError.isInstance(v)`, not\n     * `.filter(SdkError.isInstance)` (detached calls throw rather than\n     * silently matching nothing).\n     */\n    static isInstance<T extends abstract new (...args: never[]) => unknown>(this: T, value: unknown): value is InstanceType<T> {\n        if (typeof this !== 'function') {\n            throw new TypeError(\n                'isInstance must be called on the class (e.g. `SdkError.isInstance(value)`); for callbacks use `v => SdkError.isInstance(v)`'\n            );\n        }\n        return brandedHasInstance(this, value);\n    }\n\n    constructor(message?: string) {\n        super(message ?? 'Unauthorized');\n        this.name = 'UnauthorizedError';\n        stampErrorBrands(this, new.target);\n    }\n}\n\n/**\n * Validates the `iss` parameter from an authorization response against the\n * issuer recorded from the authorization server's validated metadata, per\n * RFC 9207 §2.4 and the MCP specification's four-row decision table.\n *\n * | `issParameterSupported` | `iss`   | Action                                           |\n * | ----------------------- | ------- | ------------------------------------------------ |\n * | `true`                  | present | compare; throw {@linkcode IssuerMismatchError} on mismatch |\n * | `true`                  | absent  | throw {@linkcode IssuerMismatchError}            |\n * | `false`                 | present | compare; throw {@linkcode IssuerMismatchError} on mismatch |\n * | `false`                 | absent  | proceed (no-op)                                  |\n *\n * Comparison is **simple string equality** (RFC 3986 §6.2.1). Scheme/host case\n * folding, default-port elision, trailing-slash, and percent-encoding\n * normalization are explicitly **not** applied — any difference is a mismatch.\n *\n * When `expectedIssuer` is `undefined` (no validated metadata document exists),\n * the check has no authentic baseline and degenerates to a no-op.\n *\n * @throws {IssuerMismatchError} with `kind: 'authorization_response'`\n */\n/**\n * Reads RFC 9207's `authorization_response_iss_parameter_supported` from\n * authorization-server metadata. Only a literal `true` counts as advertised;\n * absent, `false`, or a non-boolean wire value (coerced to `undefined` by the\n * schema) means not advertised.\n */\nfunction isIssParameterSupported(metadata: AuthorizationServerMetadata | undefined): boolean {\n    return metadata?.authorization_response_iss_parameter_supported === true;\n}\n\nexport function validateAuthorizationResponseIssuer({\n    iss,\n    expectedIssuer,\n    issParameterSupported\n}: {\n    /** The form-urldecoded `iss` query parameter from the authorization callback, or `undefined` if absent. */\n    iss: string | undefined;\n    /** The `issuer` value from the authorization server's validated metadata document. */\n    expectedIssuer: string | undefined;\n    /** Whether the metadata advertised `authorization_response_iss_parameter_supported: true`. */\n    issParameterSupported: boolean;\n}): void {\n    if (expectedIssuer === undefined) {\n        // No validated metadata document → no recorded issuer → no comparison (table row 4).\n        return;\n    }\n    if (iss === undefined) {\n        if (issParameterSupported) {\n            // Row 2: AS advertised that it always sends `iss`; absence is a stripped-parameter attack indicator.\n            throw new IssuerMismatchError('authorization_response', expectedIssuer, undefined);\n        }\n        // Row 4: not advertised, not present → proceed.\n        return;\n    }\n    // Rows 1 & 3: present → compare with simple string comparison only.\n    if (iss !== expectedIssuer) {\n        throw new IssuerMismatchError('authorization_response', expectedIssuer, iss);\n    }\n}\n\n/**\n * Computes the union of one or more OAuth `scope` strings.\n *\n * Each argument is a space-delimited scope string per RFC 6749 §3.3, or\n * `undefined`. The result is a single space-delimited string containing each\n * distinct scope token exactly once, in first-seen order, or `undefined` if\n * every input is empty/undefined.\n *\n * No hierarchical deduplication is performed: a union may contain semantically\n * redundant entries (e.g., a broad scope alongside a narrower one it implies).\n * Authorization servers normalize such redundancy during token issuance; the\n * spec's step-up flow does not require clients to.\n *\n * Used by the transport's `403 insufficient_scope` step-up path to accumulate\n * previously-requested scopes with newly-challenged scopes so re-authorization\n * does not lose previously-granted permissions.\n */\nexport function computeScopeUnion(...scopes: ReadonlyArray<string | undefined>): string | undefined {\n    const seen = new Set<string>();\n    for (const scope of scopes) {\n        if (!scope) continue;\n        for (const token of scope.split(/\\s+/)) {\n            if (token) seen.add(token);\n        }\n    }\n    return seen.size > 0 ? [...seen].join(' ') : undefined;\n}\n\n/**\n * Whether `union` contains at least one scope token not present in `current`.\n * Both arguments are space-delimited scope strings per RFC 6749 §3.3.\n *\n * Used to gate the step-up refresh bypass: when the union of previously-requested\n * and newly-challenged scopes is a strict superset of the current token's\n * granted scope, refreshing cannot widen the grant (RFC 6749 §6), so the\n * transport must force a fresh authorization request instead. When the current\n * token already covers the union, refresh remains valid.\n *\n * An undefined or empty `current` is treated as the empty set, so any non-empty\n * `union` is a strict superset. Note that per RFC 6749 §3.3 an authorization\n * server MAY omit the token's `scope` field when it equals the requested scope;\n * this helper is conservative and treats an absent token `scope` as empty, so\n * step-up always forces a fresh authorization request in that case rather than\n * risking a refresh that silently drops the widened scope.\n */\nexport function isStrictScopeSuperset(union: string | undefined, current: string | undefined): boolean {\n    if (!union) return false;\n    const currentSet = new Set((current ?? '').split(/\\s+/).filter(Boolean));\n    for (const token of union.split(/\\s+/)) {\n        if (token && !currentSet.has(token)) return true;\n    }\n    return false;\n}\n\n/**\n * Shared `finishAuth` resolver for the `(code, iss?)` and `(URLSearchParams)` overloads.\n *\n * For the `URLSearchParams` form, only `iss` and `code` are read up front. When a `code` is\n * present the returned values flow into {@linkcode auth}, which runs\n * {@linkcode validateAuthorizationResponseIssuer} against freshly-discovered metadata before\n * the code is redeemed — so on mismatch the thrown {@linkcode IssuerMismatchError} carries no\n * `error`/`error_description`/`error_uri` text from the callback (those are attacker-controlled\n * in a mix-up). When no `code` is present (an error-shaped callback), `iss` is validated here\n * against the provider's recorded discovery state — or, when the provider does not implement\n * `discoveryState`, against freshly-discovered metadata mirroring what {@linkcode auth} does on\n * the code-present path — **before** the callback's error parameters are read; only after that\n * passes are they surfaced as an {@linkcode OAuthError}. When no issuer baseline can be\n * obtained either way, a generic {@linkcode UnauthorizedError} is thrown without surfacing the\n * callback's `error`/`error_description`/`error_uri`.\n *\n * @internal Exported for the transport `finishAuth` overloads; not part of the public barrel.\n */\nexport async function resolveAuthorizationCallbackParams(\n    codeOrParams: string | URLSearchParams,\n    iss: string | undefined,\n    provider: OAuthClientProvider,\n    serverUrl: string | URL,\n    opts?: { fetchFn?: FetchLike; resourceMetadataUrl?: URL }\n): Promise<{ authorizationCode: string; iss: string | undefined }> {\n    if (typeof codeOrParams === 'string') {\n        return { authorizationCode: codeOrParams, iss };\n    }\n    const issParam = codeOrParams.get('iss') ?? undefined;\n    const code = codeOrParams.get('code');\n    if (code) {\n        return { authorizationCode: code, iss: issParam };\n    }\n    // No code → error response. Gate the (potentially attacker-supplied) error params on the\n    // issuer first. Prefer the provider's recorded discovery state; when absent, mirror auth()'s\n    // code-present path and run a fresh discovery so the iss gate has an authentic baseline.\n    const discoveryState = await provider.discoveryState?.();\n    let metadata = discoveryState?.authorizationServerMetadata;\n    if (!metadata) {\n        try {\n            const serverInfo = await discoverOAuthServerInfo(serverUrl, opts);\n            metadata = serverInfo.authorizationServerMetadata;\n        } catch {\n            metadata = undefined;\n        }\n    }\n    if (!metadata) {\n        // No authentic baseline → cannot prove the error params came from our AS. Do NOT surface\n        // attacker-controllable `error`/`error_description`/`error_uri` here.\n        throw new UnauthorizedError('Authorization callback failed and the issuer could not be verified');\n    }\n    validateAuthorizationResponseIssuer({\n        iss: issParam,\n        expectedIssuer: metadata.issuer,\n        issParameterSupported: isIssParameterSupported(metadata)\n    });\n    const error = codeOrParams.get('error');\n    if (error) {\n        throw new OAuthError(error, codeOrParams.get('error_description') ?? error, codeOrParams.get('error_uri') ?? undefined);\n    }\n    throw new UnauthorizedError('Authorization callback contained neither `code` nor `error`');\n}\n\nexport type ClientAuthMethod = 'client_secret_basic' | 'client_secret_post' | 'none';\n\nfunction isClientAuthMethod(method: string): method is ClientAuthMethod {\n    return ['client_secret_basic', 'client_secret_post', 'none'].includes(method);\n}\n\nconst AUTHORIZATION_CODE_RESPONSE_TYPE = 'code';\nconst AUTHORIZATION_CODE_CHALLENGE_METHOD = 'S256';\n\n/**\n * Determines the best client authentication method to use based on server support and client configuration.\n *\n * Priority order (highest to lowest):\n * 1. `client_secret_basic` (if client secret is available)\n * 2. `client_secret_post` (if client secret is available)\n * 3. `none` (for public clients)\n *\n * @param clientInformation - OAuth client information containing credentials\n * @param supportedMethods - Authentication methods supported by the authorization server\n * @returns The selected authentication method\n */\nexport function selectClientAuthMethod(clientInformation: OAuthClientInformationMixed, supportedMethods: string[]): ClientAuthMethod {\n    const hasClientSecret = clientInformation.client_secret !== undefined;\n\n    // Prefer the method returned by the server during client registration, if valid.\n    // When server metadata is present we also require the method to be listed as supported;\n    // when supportedMethods is empty (metadata omitted the field) the DCR hint stands alone.\n    if (\n        'token_endpoint_auth_method' in clientInformation &&\n        clientInformation.token_endpoint_auth_method &&\n        isClientAuthMethod(clientInformation.token_endpoint_auth_method) &&\n        (supportedMethods.length === 0 || supportedMethods.includes(clientInformation.token_endpoint_auth_method))\n    ) {\n        return clientInformation.token_endpoint_auth_method;\n    }\n\n    // If server metadata omits token_endpoint_auth_methods_supported, RFC 8414 §2 says the\n    // default is client_secret_basic. RFC 6749 §2.3.1 also requires servers to support HTTP\n    // Basic authentication for clients with a secret, making it the safest default.\n    if (supportedMethods.length === 0) {\n        return hasClientSecret ? 'client_secret_basic' : 'none';\n    }\n\n    // Try methods in priority order (most secure first)\n    if (hasClientSecret && supportedMethods.includes('client_secret_basic')) {\n        return 'client_secret_basic';\n    }\n\n    if (hasClientSecret && supportedMethods.includes('client_secret_post')) {\n        return 'client_secret_post';\n    }\n\n    if (supportedMethods.includes('none')) {\n        return 'none';\n    }\n\n    // Fallback: use what we have\n    return hasClientSecret ? 'client_secret_post' : 'none';\n}\n\n/**\n * Applies client authentication to the request based on the specified method.\n *\n * Implements OAuth 2.1 client authentication methods:\n * - `client_secret_basic`: HTTP Basic authentication (RFC 6749 Section 2.3.1)\n * - `client_secret_post`: Credentials in request body (RFC 6749 Section 2.3.1)\n * - `none`: Public client authentication (RFC 6749 Section 2.1)\n *\n * @param method - The authentication method to use\n * @param clientInformation - OAuth client information containing credentials\n * @param headers - HTTP headers object to modify\n * @param params - URL search parameters to modify\n * @throws {Error} When required credentials are missing\n */\nexport function applyClientAuthentication(\n    method: ClientAuthMethod,\n    clientInformation: OAuthClientInformation,\n    headers: Headers,\n    params: URLSearchParams\n): void {\n    const { client_id, client_secret } = clientInformation;\n\n    switch (method) {\n        case 'client_secret_basic': {\n            applyBasicAuth(client_id, client_secret, headers);\n            return;\n        }\n        case 'client_secret_post': {\n            applyPostAuth(client_id, client_secret, params);\n            return;\n        }\n        case 'none': {\n            applyPublicAuth(client_id, params);\n            return;\n        }\n        default: {\n            throw new Error(`Unsupported client authentication method: ${method}`);\n        }\n    }\n}\n\n/**\n * Applies HTTP Basic authentication (RFC 6749 Section 2.3.1)\n */\nexport function applyBasicAuth(clientId: string, clientSecret: string | undefined, headers: Headers): void {\n    if (!clientSecret) {\n        throw new Error('client_secret_basic authentication requires a client_secret');\n    }\n\n    const credentials = btoa(`${clientId}:${clientSecret}`);\n    headers.set('Authorization', `Basic ${credentials}`);\n}\n\n/**\n * Applies POST body authentication (RFC 6749 Section 2.3.1)\n */\nexport function applyPostAuth(clientId: string, clientSecret: string | undefined, params: URLSearchParams): void {\n    params.set('client_id', clientId);\n    if (clientSecret) {\n        params.set('client_secret', clientSecret);\n    }\n}\n\n/**\n * Applies public client authentication (RFC 6749 Section 2.1)\n */\nexport function applyPublicAuth(clientId: string, params: URLSearchParams): void {\n    params.set('client_id', clientId);\n}\n\n/**\n * Loopback hosts exempt from the in-transit `https:` requirement (RFC 8252 §7.3).\n * Includes bare `localhost` and any name ending in `.localhost` (RFC 6761 §6.3).\n */\nfunction isLoopbackHost(hostname: string): boolean {\n    return (\n        hostname === 'localhost' ||\n        hostname.endsWith('.localhost') ||\n        hostname === '127.0.0.1' ||\n        hostname === '[::1]' ||\n        hostname === '::1'\n    );\n}\n\n/**\n * Refuse to send credentials to a non-TLS token endpoint. The MCP authorization\n * specification requires authorization server endpoints to use HTTPS. Loopback\n * hosts are exempt here for local development.\n *\n * @throws {@linkcode InsecureTokenEndpointError} if the endpoint is insecure.\n */\nexport function assertSecureTokenEndpoint(tokenEndpoint: string | URL): URL {\n    const url = new URL(String(tokenEndpoint));\n    if (url.protocol !== 'https:' && !isLoopbackHost(url.hostname)) {\n        throw new InsecureTokenEndpointError(url.href);\n    }\n    return url;\n}\n\n/**\n * Derives an OIDC `application_type` from a client's registered redirect URIs\n * when the consumer has not set one explicitly (SEP-837). Loopback hosts and\n * non-`http(s)` custom URI schemes indicate a native application (RFC 8252);\n * everything else is treated as a web application. The result is a heuristic\n * default — callers that know better should set `clientMetadata.application_type`\n * themselves, which {@linkcode resolveClientMetadata} never overwrites.\n *\n * A mixed redirect set (for example a public `https:` URI alongside a loopback\n * URI) is inherently ambiguous under OIDC DCR §2 — neither value satisfies the\n * AS for both URIs — so consumers with mixed sets should set `application_type`\n * explicitly rather than relying on this heuristic.\n */\nfunction deriveApplicationType(redirectUris: readonly string[] | undefined): 'native' | 'web' {\n    for (const raw of redirectUris ?? []) {\n        let url: URL;\n        try {\n            url = new URL(raw);\n        } catch {\n            continue;\n        }\n        if (url.protocol !== 'http:' && url.protocol !== 'https:') return 'native';\n        if (isLoopbackHost(url.hostname)) return 'native';\n    }\n    return 'web';\n}\n\n/**\n * Reads {@linkcode OAuthClientProvider.clientMetadata | clientMetadata} from the\n * provider and fills the SEP-837 / SEP-2207 defaults the SDK relies on, so\n * {@linkcode registerClient} sees a consistent, fully-populated document.\n *\n * - `grant_types` defaults to `['authorization_code', 'refresh_token']` for\n *   interactive providers (those with a {@linkcode OAuthClientProvider.redirectUrl | redirectUrl})\n *   so authorization servers that gate refresh-token issuance on the registered\n *   grant types issue one (SEP-2207). Non-interactive providers (no\n *   `redirectUrl`) get no `grant_types` default. This default applies to the\n *   Dynamic Client Registration body only — it does **not** drive\n *   {@linkcode determineScope}'s `offline_access` augmentation.\n * - `application_type` defaults from `redirect_uris`: loopback redirect hosts\n *   and custom URI schemes → `'native'`, otherwise `'web'` (SEP-837 / RFC 8252).\n *\n * A field the consumer set explicitly is **never** overwritten. {@linkcode auth}\n * calls this once at the top of the flow; direct callers of\n * {@linkcode registerClient} that want the same defaults should pass the result\n * of this function as `clientMetadata`.\n */\nexport function resolveClientMetadata(provider: Pick<OAuthClientProvider, 'clientMetadata' | 'redirectUrl'>): OAuthClientMetadata {\n    const clientMetadata = provider.clientMetadata;\n    return {\n        ...clientMetadata,\n        grant_types:\n            clientMetadata.grant_types ?? (provider.redirectUrl === undefined ? undefined : ['authorization_code', 'refresh_token']),\n        application_type: clientMetadata.application_type ?? deriveApplicationType(clientMetadata.redirect_uris)\n    };\n}\n\n/**\n * Parses an OAuth error response from a string or Response object.\n *\n * If the input is a standard OAuth2.0 error response, it will be parsed according to the spec\n * and an {@linkcode OAuthError} will be returned with the appropriate error code.\n * If parsing fails, it falls back to a generic {@linkcode OAuthErrorCode.ServerError | ServerError} that includes\n * the response status (if available) and original content.\n *\n * @param input - A Response object or string containing the error response\n * @returns A Promise that resolves to an {@linkcode OAuthError} instance\n */\nexport async function parseErrorResponse(input: Response | string): Promise<OAuthError> {\n    const statusCode = input instanceof Response ? input.status : undefined;\n    const body = input instanceof Response ? await input.text() : input;\n\n    try {\n        const result = OAuthErrorResponseSchema.parse(JSON.parse(body));\n        return OAuthError.fromResponse(result);\n    } catch (error) {\n        // Not a valid OAuth error response, but try to inform the user of the raw data anyway\n        const errorMessage = `${statusCode ? `HTTP ${statusCode}: ` : ''}Invalid OAuth error response: ${error}. Raw body: ${body}`;\n        return new OAuthError(OAuthErrorCode.ServerError, errorMessage);\n    }\n}\n\n/**\n * Options for {@linkcode auth}. The full OAuth flow orchestrator's input.\n */\nexport interface AuthOptions {\n    /** The MCP server URL — the protected resource the flow authorizes against. */\n    serverUrl: string | URL;\n    /**\n     * The authorization code returned by the authorization server on the redirect\n     * callback. When set, {@linkcode auth} exchanges it for tokens; when unset,\n     * {@linkcode auth} runs discovery and either refreshes or initiates redirect.\n     */\n    authorizationCode?: string;\n    /**\n     * The form-urldecoded `iss` query parameter from the authorization callback,\n     * if present. Passed through to RFC 9207 §2.4 issuer validation alongside\n     * `authorizationCode`. Validated against the recorded issuer per RFC 9207\n     * §2.4 before the code is redeemed — see\n     * {@linkcode validateAuthorizationResponseIssuer} and the migration guide's\n     * *Authorization-server mix-up defense* section.\n     */\n    iss?: string;\n    /** Scope to request; computed by Scope Selection Strategy when omitted. */\n    scope?: string;\n    /** Explicit `resource_metadata` URL from a `WWW-Authenticate` challenge. */\n    resourceMetadataUrl?: URL;\n    /** Custom `fetch` implementation. */\n    fetchFn?: FetchLike;\n    /**\n     * Opt-out for the RFC 8414 §3.3 issuer-echo check during authorization\n     * server discovery. Disabling it is **security-weakening** and intended only\n     * for authorization servers known to publish a mismatched `issuer`. The unchecked\n     * `issuer` is also what `expectedIssuer` and stored `issuer` stamps are compared with.\n     *\n     * @default false\n     */\n    skipIssuerMetadataValidation?: boolean;\n    /**\n     * When `true`, {@linkcode auth} skips the refresh-token branch even when a\n     * `refresh_token` is available, and proceeds directly to a fresh\n     * authorization request ({@linkcode startAuthorization}).\n     *\n     * Set by the transport's `403 insufficient_scope` step-up path when the\n     * required scope is a strict superset of the current token's granted scope:\n     * the refresh grant cannot widen scope (RFC 6749 §6), so refreshing would\n     * silently drop the new scope and the next request would 403 again. Forcing\n     * a fresh authorization request ensures the widened scope reaches the\n     * authorization server.\n     *\n     * Hosts driving step-up themselves (with `onInsufficientScope: 'throw'`)\n     * should set this when {@linkcode isStrictScopeSuperset} of the union over\n     * the current token's `scope` is `true`.\n     *\n     * @default false\n     */\n    forceReauthorization?: boolean;\n}\n\n/**\n * Recovering from a recoverable OAuth error discards stored credentials and silently starts a\n * fresh authorization. On a headless client whose `redirectToAuthorization()` is a no-op that\n * recovery is indistinguishable from nothing happening at all, so name the cause. The most\n * common case is `invalid_grant` — an expired, revoked, or rotation-reuse-detected refresh\n * token. See issue #2034.\n */\nfunction warnCredentialInvalidation(provider: OAuthClientProvider, error: OAuthError, invalidated: string): void {\n    // `invalidateCredentials` is optional. When a provider omits it nothing is actually\n    // discarded, so do not claim otherwise — the stale credential is still in storage and\n    // will be replayed on the next call, which is the thing worth telling the operator.\n    const action =\n        provider.invalidateCredentials === undefined\n            ? `retrying authorization without discarding the stored ${invalidated} (provider implements no invalidateCredentials())`\n            : `invalidating the stored ${invalidated} and retrying authorization`;\n    // JSON-stringify the AS-supplied values so attacker-supplied control characters cannot\n    // forge log lines — the authorization server is resolved from the resource server's\n    // metadata, and both `code` and `message` are echoed from its response verbatim.\n    console.warn(`[mcp-sdk] OAuth ${JSON.stringify(error.code)} — ${action}. Cause: ${JSON.stringify(error.message)}`);\n}\n\n/**\n * Orchestrates the full auth flow with a server.\n *\n * This can be used as a single entry point for all authorization functionality,\n * instead of linking together the other lower-level functions in this module.\n */\nexport async function auth(provider: OAuthClientProvider, options: AuthOptions): Promise<AuthResult> {\n    try {\n        return await authInternal(provider, options);\n    } catch (error) {\n        // Handle recoverable error types by invalidating credentials and retrying\n        if (error instanceof OAuthError) {\n            if (error.code === OAuthErrorCode.InvalidClient || error.code === OAuthErrorCode.UnauthorizedClient) {\n                warnCredentialInvalidation(provider, error, 'client credentials and tokens');\n                // Not 'all' — preserve discoveryState so the callback-leg gate on retry doesn't\n                // fire a false 'discoveryState was not available on the callback leg' AuthorizationServerMismatchError that masks the\n                // real invalid_client.\n                await provider.invalidateCredentials?.('client');\n                await provider.invalidateCredentials?.('tokens');\n                return await authInternal(provider, options);\n            } else if (error.code === OAuthErrorCode.InvalidGrant || error.code === OAuthErrorCode.InvalidDpopProof) {\n                // invalid_dpop_proof on refresh typically means the stored refresh token is bound\n                // (RFC 9449 §5) to a DPoP key this process no longer holds — e.g. a non-extractable\n                // key regenerated across a restart. Like invalid_grant, the token set is unusable;\n                // drop it and fall through to a fresh authorization.\n                warnCredentialInvalidation(provider, error, 'tokens');\n                await provider.invalidateCredentials?.('tokens');\n                return await authInternal(provider, options);\n            }\n        }\n\n        // Throw otherwise\n        throw error;\n    }\n}\n\n/**\n * Selects scopes per the MCP spec and augment for refresh token support.\n */\nexport function determineScope(options: {\n    requestedScope?: string;\n    resourceMetadata?: OAuthProtectedResourceMetadata;\n    authServerMetadata?: AuthorizationServerMetadata;\n    clientMetadata: OAuthClientMetadata;\n}): string | undefined {\n    const { requestedScope, resourceMetadata, authServerMetadata, clientMetadata } = options;\n\n    // Scope selection priority (MCP spec):\n    //   1. WWW-Authenticate header scope\n    //   2. PRM scopes_supported\n    //   3. clientMetadata.scope (SDK fallback)\n    //   4. Omit scope parameter\n    let effectiveScope = requestedScope || resourceMetadata?.scopes_supported?.join(' ') || clientMetadata.scope;\n\n    // SEP-2207: Append offline_access when the AS advertises it and the client\n    // supports the refresh_token grant. Gated on consumer-supplied grant_types;\n    // SDK DCR default intentionally NOT applied here so statically-registered/CIMD\n    // clients are not pushed into offline_access + prompt=consent.\n    if (\n        effectiveScope &&\n        authServerMetadata?.scopes_supported?.includes('offline_access') &&\n        !effectiveScope.split(' ').includes('offline_access') &&\n        clientMetadata.grant_types?.includes('refresh_token')\n    ) {\n        effectiveScope = `${effectiveScope} offline_access`;\n    }\n\n    return effectiveScope;\n}\n\nasync function authInternal(\n    provider: OAuthClientProvider,\n    {\n        serverUrl,\n        authorizationCode,\n        iss,\n        scope,\n        resourceMetadataUrl,\n        fetchFn,\n        skipIssuerMetadataValidation,\n        forceReauthorization\n    }: AuthOptions\n): Promise<AuthResult> {\n    // SEP-837 / SEP-2207: resolve spec defaults for the DCR body. determineScope()\n    // intentionally reads the raw provider.clientMetadata instead.\n    const clientMetadata = resolveClientMetadata(provider);\n\n    // Check if the provider has cached discovery state to skip discovery\n    const cachedState = await provider.discoveryState?.();\n\n    let resourceMetadata: OAuthProtectedResourceMetadata | undefined;\n    let authorizationServerUrl: string | URL;\n    let metadata: AuthorizationServerMetadata | undefined;\n    let freshDiscoveryState: OAuthDiscoveryState | undefined;\n\n    // If resourceMetadataUrl is not provided, try to load it from cached state\n    // This handles browser redirects where the URL was saved before navigation\n    let effectiveResourceMetadataUrl = resourceMetadataUrl;\n    if (!effectiveResourceMetadataUrl && cachedState?.resourceMetadataUrl) {\n        effectiveResourceMetadataUrl = new URL(cachedState.resourceMetadataUrl);\n    }\n\n    if (cachedState?.authorizationServerUrl) {\n        // Restore discovery state from cache\n        authorizationServerUrl = cachedState.authorizationServerUrl;\n        resourceMetadata = cachedState.resourceMetadata;\n        metadata =\n            cachedState.authorizationServerMetadata ??\n            (await discoverAuthorizationServerMetadata(authorizationServerUrl, {\n                fetchFn,\n                skipIssuerValidation: skipIssuerMetadataValidation\n            }));\n\n        // If resource metadata wasn't cached, try to fetch it for selectResourceURL\n        if (!resourceMetadata) {\n            try {\n                resourceMetadata = await discoverOAuthProtectedResourceMetadata(\n                    serverUrl,\n                    { resourceMetadataUrl: effectiveResourceMetadataUrl },\n                    fetchFn\n                );\n            } catch (error) {\n                // Network failures (DNS, connection refused) surface as TypeError — propagate\n                // those rather than masking a transient reachability problem.\n                if (error instanceof TypeError) {\n                    throw error;\n                }\n                // RFC 9728 not available — selectResourceURL will handle undefined\n            }\n        }\n\n        // Re-save if we enriched the cached state with missing metadata\n        if (metadata !== cachedState.authorizationServerMetadata || resourceMetadata !== cachedState.resourceMetadata) {\n            await provider.saveDiscoveryState?.({\n                authorizationServerUrl: String(authorizationServerUrl),\n                resourceMetadataUrl: effectiveResourceMetadataUrl?.toString(),\n                resourceMetadata,\n                authorizationServerMetadata: metadata\n            });\n        }\n    } else {\n        // Full discovery via RFC 9728\n        const serverInfo = await discoverOAuthServerInfo(serverUrl, {\n            resourceMetadataUrl: effectiveResourceMetadataUrl,\n            fetchFn,\n            skipIssuerMetadataValidation\n        });\n        authorizationServerUrl = serverInfo.authorizationServerUrl;\n        metadata = serverInfo.authorizationServerMetadata;\n        resourceMetadata = serverInfo.resourceMetadata;\n\n        // Captured now, persisted only after the SEP-2352 callback-leg gate below — so a\n        // gate throw cannot leave a freshly resolved (potentially PRM-poisoned) AS recorded\n        // for the retry to read back as `recordedIssuer`.\n        // TODO: resourceMetadataUrl is only populated when explicitly provided via options\n        // or loaded from cached state. The URL derived internally by\n        // discoverOAuthProtectedResourceMetadata() is not captured back here.\n        freshDiscoveryState = {\n            authorizationServerUrl: String(authorizationServerUrl),\n            resourceMetadataUrl: effectiveResourceMetadataUrl?.toString(),\n            resourceMetadata,\n            authorizationServerMetadata: metadata\n        };\n    }\n\n    // SEP-2352: the canonical authorization-server identity for this flow. `metadata.issuer`\n    // is RFC 8414 §3.3-validated to equal the discovery URL; when no metadata document was\n    // found (legacy fallback) the discovery URL itself is the only identifier available.\n    const issuer = metadata?.issuer ?? String(authorizationServerUrl);\n    const infoCtx: OAuthClientInformationContext = { issuer };\n\n    // Deprecated write-only hook, kept for providers (e.g. Cross-App Access) that read it\n    // internally. The SDK never reads `authorizationServerUrl()`.\n    await provider.saveAuthorizationServerUrl?.(issuer);\n\n    // SEP-2352 callback-leg gate. Stored credentials are protected structurally by the\n    // issuer stamp, but the in-flight `authorization_code` + PKCE `code_verifier` are not\n    // stored — they are bound to the AS the redirect targeted, recorded in `discoveryState()`.\n    // Fail-closed: a provider that implements saveDiscoveryState but returned no discovery\n    // state on the callback leg (e.g. not persisted alongside codeVerifier across page navigation) MUST NOT\n    // proceed — fresh discovery may have resolved a different AS than the one the user\n    // approved at /authorize, and the clientInformation stamp alone does not protect a keyed\n    // multi-AS provider here. Providers that do not implement saveDiscoveryState at all keep\n    // the (legacy) warn-and-proceed behavior.\n    if (authorizationCode !== undefined) {\n        const recordedIssuer = cachedState?.authorizationServerMetadata?.issuer ?? cachedState?.authorizationServerUrl;\n        if (recordedIssuer === undefined) {\n            if (provider.saveDiscoveryState !== undefined) {\n                throw new AuthorizationServerMismatchError(\n                    'discoveryState was not available on the callback leg; ensure your provider persists discoveryState alongside codeVerifier',\n                    issuer\n                );\n            }\n            console.warn(\n                '[mcp-sdk] OAuthClientProvider does not implement saveDiscoveryState()/discoveryState(); ' +\n                    'the SEP-2352 callback-leg authorization-server binding cannot be checked. ' +\n                    'Implement discoveryState (persist alongside codeVerifier) — see docs/migration/upgrade-to-v2.md §SEP-2352.'\n            );\n        } else if (!issuersMatch(recordedIssuer, issuer)) {\n            throw new AuthorizationServerMismatchError(recordedIssuer, issuer);\n        }\n    }\n\n    if (freshDiscoveryState) {\n        await provider.saveDiscoveryState?.(freshDiscoveryState);\n    }\n\n    // Send the metadata's resource indicator verbatim: `selectResourceURL` returns a parsed\n    // `URL`, and `URL.href` appends \"/\" to a pathless indicator such as `https://example.com`,\n    // which exact-match authorization servers reject (#1968). A URL returned by the\n    // provider's own `validateResourceURL` is used as returned.\n    const selectedResource = await selectResourceURL(serverUrl, provider, resourceMetadata);\n    const resource: string | URL | undefined =\n        selectedResource && resourceMetadata && !provider.validateResourceURL ? resourceMetadata.resource : selectedResource;\n\n    // Save resource URL for providers that need it (e.g., CrossAppAccessProvider)\n    if (resource) {\n        await provider.saveResourceUrl?.(resourceIndicatorToString(resource));\n    }\n\n    // Scope selection used consistently for DCR and the authorization request.\n    const resolvedScope = determineScope({\n        requestedScope: scope,\n        resourceMetadata,\n        authServerMetadata: metadata,\n        clientMetadata: provider.clientMetadata\n    });\n\n    // Handle client registration if needed. SEP-2352: a stored credential whose `issuer`\n    // stamp names a different authorization server reads back as `undefined`, so the flow\n    // re-registers exactly as if nothing were stored.\n    const rawClientInfo = await Promise.resolve(provider.clientInformation(infoCtx));\n    let clientInformation = discardIfIssuerMismatch(rawClientInfo, issuer, {\n        canPersistStamp: provider.saveClientInformation !== undefined\n    });\n    if (clientInformation === undefined && rawClientInfo?.issuer && provider.saveClientInformation === undefined) {\n        // Static-credential provider (no DCR) whose `expectedIssuer` stamp names a different\n        // AS — surface the typed error with both issuers rather than the generic\n        // \"client information must be saveable for dynamic registration\" fallback.\n        throw new AuthorizationServerMismatchError(rawClientInfo.issuer, issuer);\n    }\n    if (clientInformation && clientInformation.issuer === undefined) {\n        // SEP-2352 back-stamp: legacy (pre-SEP-2352) storage returned an unstamped value.\n        // Bind it to the first AS resolved after upgrade so subsequent calls have a real\n        // stamp to compare against — closes the otherwise-permanent unstamped window.\n        clientInformation = { ...clientInformation, issuer };\n        await provider.saveClientInformation?.(clientInformation, infoCtx);\n    }\n    if (!clientInformation) {\n        if (authorizationCode !== undefined) {\n            throw new Error('Existing OAuth client information is required when exchanging an authorization code');\n        }\n\n        const supportsUrlBasedClientId = metadata?.client_id_metadata_document_supported === true;\n        const clientMetadataUrl = provider.clientMetadataUrl;\n\n        if (clientMetadataUrl && !isHttpsUrl(clientMetadataUrl)) {\n            throw new OAuthError(\n                OAuthErrorCode.InvalidClientMetadata,\n                `clientMetadataUrl must be a valid HTTPS URL with a non-root pathname, got: ${clientMetadataUrl}`\n            );\n        }\n\n        const shouldUseUrlBasedClientId = supportsUrlBasedClientId && clientMetadataUrl;\n\n        if (shouldUseUrlBasedClientId) {\n            // SEP-991: URL-based Client IDs\n            clientInformation = { client_id: clientMetadataUrl, issuer };\n            await provider.saveClientInformation?.(clientInformation, infoCtx);\n        } else {\n            // Fallback to dynamic registration\n            if (!provider.saveClientInformation) {\n                throw new Error('OAuth client information must be saveable for dynamic registration');\n            }\n\n            const fullInformation = await registerClient(authorizationServerUrl, {\n                metadata,\n                clientMetadata,\n                scope: resolvedScope,\n                fetchFn\n            });\n\n            clientInformation = { ...fullInformation, issuer };\n            await provider.saveClientInformation(clientInformation, infoCtx);\n        }\n    }\n\n    // Non-interactive flows (e.g., client_credentials, jwt-bearer) don't need a redirect URL\n    const nonInteractiveFlow = !provider.redirectUrl;\n\n    // Exchange authorization code for tokens, or fetch tokens directly for non-interactive flows\n    if (authorizationCode !== undefined || nonInteractiveFlow) {\n        // RFC 9207: validate the callback `iss` against the recorded issuer before the\n        // authorization code is sent to any token endpoint. Non-interactive flows have no\n        // authorization response, so the gate is keyed on `authorizationCode`.\n        if (authorizationCode !== undefined) {\n            validateAuthorizationResponseIssuer({\n                iss,\n                expectedIssuer: metadata?.issuer,\n                issParameterSupported: isIssParameterSupported(metadata)\n            });\n        }\n\n        const tokens = await fetchToken(provider, authorizationServerUrl, {\n            metadata,\n            resource,\n            authorizationCode,\n            iss,\n            scope: resolvedScope,\n            fetchFn\n        });\n\n        await provider.saveTokens({ ...tokens, issuer }, infoCtx);\n        return 'AUTHORIZED';\n    }\n\n    // SEP-2352: a refresh_token stamped for a different authorization server reads back\n    // as `undefined`, so it is never POSTed to this AS's token endpoint.\n    let tokens = discardIfIssuerMismatch(await provider.tokens(infoCtx), issuer);\n    if (tokens && tokens.issuer === undefined) {\n        // SEP-2352 back-stamp: bind a legacy unstamped token set to the first-resolved AS\n        // so the stamp check is effective from the next call onward.\n        tokens = { ...tokens, issuer };\n        await provider.saveTokens(tokens, infoCtx);\n    }\n\n    // Handle token refresh or new authorization. The step-up path sets\n    // `forceReauthorization` when the requested scope strictly exceeds the\n    // current token's granted scope — refreshing would not widen it (RFC 6749\n    // §6), so skip straight to a fresh authorization request.\n    if (tokens?.refresh_token && !forceReauthorization) {\n        const refreshScope = await provider.scopeForRefresh?.(tokens);\n        let newTokens: OAuthTokens | undefined;\n        try {\n            // Attempt to refresh the token\n            newTokens = await refreshAuthorization(authorizationServerUrl, {\n                metadata,\n                clientInformation,\n                refreshToken: tokens.refresh_token,\n                scope: refreshScope,\n                resource,\n                addClientAuthentication: provider.addClientAuthentication,\n                dpop: await provider.dpop?.(),\n                fetchFn\n            });\n        } catch (error) {\n            // A non-TLS token endpoint is a configuration error — re-authorizing cannot\n            // fix it. Surface it so the consumer sees the misconfiguration instead of an\n            // unexplained re-auth prompt.\n            if (error instanceof InsecureTokenEndpointError) {\n                throw error;\n            }\n            // If this is a ServerError, or an unknown type, log it out and try to continue. Otherwise, escalate so we can fix things and retry.\n            if (!(error instanceof OAuthError) || error.code === OAuthErrorCode.ServerError) {\n                // Could not refresh OAuth tokens. The fallthrough to a fresh authorization\n                // request is deliberate, but it is invisible on a headless client whose\n                // redirectToAuthorization() is a no-op — so say why it happened.\n                // JSON-stringify the cause: on the non-OAuth-shaped path it carries the raw\n                // response body, so it is arbitrary attacker-supplied bytes.\n                console.warn(\n                    `[mcp-sdk] Could not refresh OAuth tokens; falling back to a new authorization request. ` +\n                        `Cause: ${JSON.stringify(error instanceof Error ? error.message : String(error))}`\n                );\n            } else {\n                // Refresh failed for another reason, re-throw\n                throw error;\n            }\n        }\n\n        // Persist any newly minted tokens. Persistence failures must always\n        // propagate: the authorization server may have rotated the refresh\n        // token, so silently dropping the new tokens would leave the client\n        // with credentials that are already invalid server-side.\n        if (newTokens) {\n            await provider.saveTokens({ ...newTokens, issuer }, infoCtx);\n            return 'AUTHORIZED';\n        }\n    }\n\n    const state = provider.state ? await provider.state() : undefined;\n\n    // Start new authorization flow\n    const { authorizationUrl, codeVerifier } = await startAuthorization(authorizationServerUrl, {\n        metadata,\n        clientInformation,\n        state,\n        redirectUrl: provider.redirectUrl,\n        scope: resolvedScope,\n        resource\n    });\n\n    await provider.saveCodeVerifier(codeVerifier);\n    await provider.redirectToAuthorization(authorizationUrl);\n    return 'REDIRECT';\n}\n\n/**\n * Validates that the given `clientMetadataUrl` is a valid HTTPS URL with a non-root pathname.\n *\n * No-op when `url` is `undefined` or empty (providers that do not use URL-based client IDs\n * are unaffected). When the value is defined but invalid, throws an {@linkcode OAuthError}\n * with code {@linkcode OAuthErrorCode.InvalidClientMetadata}.\n *\n * {@linkcode OAuthClientProvider} implementations that accept a `clientMetadataUrl` should\n * call this in their constructors for early validation.\n *\n * @param url - The `clientMetadataUrl` value to validate (from `OAuthClientProvider.clientMetadataUrl`)\n * @throws {OAuthError} When `url` is defined but is not a valid HTTPS URL with a non-root pathname\n */\nexport function validateClientMetadataUrl(url: string | undefined): void {\n    if (url && !isHttpsUrl(url)) {\n        throw new OAuthError(\n            OAuthErrorCode.InvalidClientMetadata,\n            `clientMetadataUrl must be a valid HTTPS URL with a non-root pathname, got: ${url}`\n        );\n    }\n}\n\n/**\n * SEP-991: URL-based Client IDs\n * Validate that the `client_id` is a valid URL with `https` scheme\n */\nexport function isHttpsUrl(value?: string): boolean {\n    if (!value) return false;\n    try {\n        const url = new URL(value);\n        return url.protocol === 'https:' && url.pathname !== '/';\n    } catch {\n        return false;\n    }\n}\n\n/**\n * Selects the RFC 8707 resource indicator for an MCP server: the provider's\n * {@linkcode OAuthClientProvider.validateResourceURL | validateResourceURL} result when\n * implemented, otherwise the protected resource metadata's `resource` (checked against the\n * server URL with `checkResourceAllowed`), or `undefined` when there is no metadata.\n *\n * The result is a parsed `URL`, so a pathless indicator such as `https://example.com` has\n * the `href` `https://example.com/`. {@linkcode auth} therefore sends the metadata string\n * verbatim instead of this URL's `href` (#1968); callers that emit the `resource`\n * parameter themselves should do the same.\n */\nexport async function selectResourceURL(\n    serverUrl: string | URL,\n    provider: OAuthClientProvider,\n    resourceMetadata?: OAuthProtectedResourceMetadata\n): Promise<URL | undefined> {\n    const defaultResource = resourceUrlFromServerUrl(serverUrl);\n\n    // If provider has custom validation, delegate to it\n    if (provider.validateResourceURL) {\n        return await provider.validateResourceURL(defaultResource, resourceMetadata?.resource);\n    }\n\n    // Only include resource parameter when Protected Resource Metadata is present\n    if (!resourceMetadata) {\n        return undefined;\n    }\n\n    // Validate that the metadata's resource is compatible with our request\n    if (!checkResourceAllowed({ requestedResource: defaultResource, configuredResource: resourceMetadata.resource })) {\n        throw new Error(`Protected resource ${resourceMetadata.resource} does not match expected ${defaultResource} (or origin)`);\n    }\n    // Prefer the resource from metadata since it's what the server is telling us to request\n    return new URL(resourceMetadata.resource);\n}\n\n/** Auth-scheme challenge tokens {@linkcode extractWWWAuthenticateParams} recognizes. */\nconst RECOGNIZED_CHALLENGE_SCHEMES = new Set(['bearer', 'dpop']);\n\n/**\n * Extract `resource_metadata`, `scope`, `error`, and `error_description` from a\n * `WWW-Authenticate` header.\n *\n * Recognizes both the `Bearer` scheme (RFC 6750) and the `DPoP` scheme (RFC 9449 §7.1,\n * SEP-1932) — a DPoP-protected resource's challenge carries the same parameters under `DPoP`\n * instead of `Bearer`, and this must still surface `resource_metadata`/`scope` from it for\n * discovery and SEP-2350 step-up to work against such a resource.\n */\nexport function extractWWWAuthenticateParams(res: Response): {\n    resourceMetadataUrl?: URL;\n    scope?: string;\n    error?: string;\n    errorDescription?: string;\n} {\n    const authenticateHeader = res.headers.get('WWW-Authenticate');\n    if (!authenticateHeader) {\n        return {};\n    }\n\n    const [type, scheme] = authenticateHeader.split(' ');\n    if (!type || !RECOGNIZED_CHALLENGE_SCHEMES.has(type.toLowerCase()) || !scheme) {\n        return {};\n    }\n\n    const resourceMetadataMatch = extractFieldFromWwwAuth(res, 'resource_metadata') || undefined;\n\n    let resourceMetadataUrl: URL | undefined;\n    if (resourceMetadataMatch) {\n        try {\n            resourceMetadataUrl = new URL(resourceMetadataMatch);\n        } catch {\n            // Ignore invalid URL\n        }\n    }\n\n    const scope = extractFieldFromWwwAuth(res, 'scope') || undefined;\n    const error = extractFieldFromWwwAuth(res, 'error') || undefined;\n    const errorDescription = extractFieldFromWwwAuth(res, 'error_description') || undefined;\n\n    return {\n        resourceMetadataUrl,\n        scope,\n        error,\n        errorDescription\n    };\n}\n\n/**\n * Extracts a specific field's value from the `WWW-Authenticate` header string.\n *\n * @param response The HTTP response object containing the headers.\n * @param fieldName The name of the field to extract (e.g., `\"realm\"`, `\"nonce\"`).\n * @returns The field value\n */\nfunction extractFieldFromWwwAuth(response: Response, fieldName: string): string | null {\n    const wwwAuthHeader = response.headers.get('WWW-Authenticate');\n    if (!wwwAuthHeader) {\n        return null;\n    }\n\n    const pattern = new RegExp(String.raw`${fieldName}=(?:\"([^\"]+)\"|([^\\s,]+))`);\n    const match = wwwAuthHeader.match(pattern);\n\n    if (match) {\n        // Pattern matches: field_name=\"value\" or field_name=value (unquoted)\n        const result = match[1] || match[2];\n        if (result) {\n            return result;\n        }\n    }\n\n    return null;\n}\n\n/**\n * Extract `resource_metadata` from response header.\n * @deprecated Use {@linkcode extractWWWAuthenticateParams} instead.\n */\nexport function extractResourceMetadataUrl(res: Response): URL | undefined {\n    const authenticateHeader = res.headers.get('WWW-Authenticate');\n    if (!authenticateHeader) {\n        return undefined;\n    }\n\n    const [type, scheme] = authenticateHeader.split(' ');\n    if (type?.toLowerCase() !== 'bearer' || !scheme) {\n        return undefined;\n    }\n    const regex = /resource_metadata=\"([^\"]*)\"/;\n    const match = regex.exec(authenticateHeader);\n\n    if (!match || !match[1]) {\n        return undefined;\n    }\n\n    try {\n        return new URL(match[1]);\n    } catch {\n        return undefined;\n    }\n}\n\n/**\n * Looks up {@link https://datatracker.ietf.org/doc/html/rfc9728 | RFC 9728}\n * OAuth 2.0 Protected Resource Metadata.\n *\n * If the server returns a 404 for the well-known endpoint, this function will\n * return `undefined`. Any other errors will be thrown as exceptions.\n */\nexport async function discoverOAuthProtectedResourceMetadata(\n    serverUrl: string | URL,\n    opts?: { protocolVersion?: string; resourceMetadataUrl?: string | URL },\n    fetchFn: FetchLike = fetch\n): Promise<OAuthProtectedResourceMetadata> {\n    const response = await discoverMetadataWithFallback(serverUrl, 'oauth-protected-resource', fetchFn, {\n        protocolVersion: opts?.protocolVersion,\n        metadataUrl: opts?.resourceMetadataUrl\n    });\n\n    if (!response || response.status === 404) {\n        await response?.text?.().catch(() => {});\n        throw new Error(`Resource server does not implement OAuth 2.0 Protected Resource Metadata.`);\n    }\n\n    if (!response.ok) {\n        await response.text?.().catch(() => {});\n        throw new Error(`HTTP ${response.status} trying to load well-known OAuth protected resource metadata.`);\n    }\n    return OAuthProtectedResourceMetadataSchema.parse(await response.json());\n}\n\n/**\n * Fetch with a retry heuristic for CORS errors caused by custom headers.\n *\n * In browsers, adding a custom header (e.g. `MCP-Protocol-Version`) triggers a CORS preflight.\n * If the server doesn't allow that header, the browser throws a `TypeError` before any response\n * is received. Retrying without custom headers often succeeds because the request becomes\n * \"simple\" (no preflight). If the server sends no CORS headers at all, the retry also fails\n * with `TypeError` and we return `undefined` so callers can fall through to an alternate URL.\n *\n * However, `fetch()` also throws `TypeError` for non-CORS failures (DNS resolution, connection\n * refused, invalid URL). Swallowing those and returning `undefined` masks real errors and can\n * cause callers to silently fall through to a different discovery URL. CORS is a browser-only\n * concept, so in non-browser runtimes (Node.js, Workers) a `TypeError` from `fetch` is never a\n * CORS error — there we propagate the error instead of swallowing it.\n *\n * In browsers, we cannot reliably distinguish CORS `TypeError` from network `TypeError` from the\n * error object alone, so the swallow-and-fallthrough heuristic is preserved there.\n */\nasync function fetchWithCorsRetry(url: URL, headers?: Record<string, string>, fetchFn: FetchLike = fetch): Promise<Response | undefined> {\n    const withinOrigin = fetchWithinOrigin(fetchFn);\n    try {\n        return await withinOrigin(url, { headers });\n    } catch (error) {\n        if (!(error instanceof TypeError) || !CORS_IS_POSSIBLE) {\n            throw error;\n        }\n        if (headers) {\n            // Could be a CORS preflight rejection caused by our custom header. Retry as a simple\n            // request: if that succeeds, we've sidestepped the preflight.\n            try {\n                return await withinOrigin(url, {});\n            } catch (retryError) {\n                if (!(retryError instanceof TypeError)) {\n                    throw retryError;\n                }\n                // Retry also got CORS-blocked (server sends no CORS headers at all).\n                // Return undefined so the caller tries the next discovery URL.\n                return undefined;\n            }\n        }\n        return undefined;\n    }\n}\n\n/**\n * Constructs the well-known path for auth-related metadata discovery\n */\nfunction buildWellKnownPath(\n    wellKnownPrefix: 'oauth-authorization-server' | 'oauth-protected-resource' | 'openid-configuration',\n    pathname: string = '',\n    options: { prependPathname?: boolean } = {}\n): string {\n    // Strip trailing slash from pathname to avoid double slashes\n    if (pathname.endsWith('/')) {\n        pathname = pathname.slice(0, -1);\n    }\n\n    return options.prependPathname ? `${pathname}/.well-known/${wellKnownPrefix}` : `/.well-known/${wellKnownPrefix}${pathname}`;\n}\n\n/**\n * Tries to discover OAuth metadata at a specific URL\n */\nasync function tryMetadataDiscovery(url: URL, protocolVersion: string, fetchFn: FetchLike = fetch): Promise<Response | undefined> {\n    const headers = {\n        'MCP-Protocol-Version': protocolVersion\n    };\n    return await fetchWithCorsRetry(url, headers, fetchFn);\n}\n\n/**\n * Determines if fallback to root discovery should be attempted\n */\nfunction shouldAttemptFallback(response: Response | undefined, pathname: string): boolean {\n    if (!response) return true; // CORS error — always try fallback\n    if (pathname === '/') return false; // Already at root\n    return (!response.ok && response.status < 500) || response.status === 502;\n}\n\n/**\n * Generic function for discovering OAuth metadata with fallback support\n */\nasync function discoverMetadataWithFallback(\n    serverUrl: string | URL,\n    wellKnownType: 'oauth-authorization-server' | 'oauth-protected-resource',\n    fetchFn: FetchLike,\n    opts?: { protocolVersion?: string; metadataUrl?: string | URL; metadataServerUrl?: string | URL }\n): Promise<Response | undefined> {\n    const issuer = new URL(serverUrl);\n    const protocolVersion = opts?.protocolVersion ?? LATEST_PROTOCOL_VERSION;\n\n    let url: URL;\n    if (opts?.metadataUrl) {\n        url = new URL(opts.metadataUrl);\n    } else {\n        // Try path-aware discovery first\n        const wellKnownPath = buildWellKnownPath(wellKnownType, issuer.pathname);\n        url = new URL(wellKnownPath, opts?.metadataServerUrl ?? issuer);\n        url.search = issuer.search;\n    }\n\n    let response = await tryMetadataDiscovery(url, protocolVersion, fetchFn);\n\n    // If path-aware discovery fails (4xx, 502 or a redirect not followed) and we're not already at root, try fallback to root discovery\n    if (!opts?.metadataUrl && shouldAttemptFallback(response, issuer.pathname)) {\n        const rootUrl = new URL(`/.well-known/${wellKnownType}`, issuer);\n        response = await tryMetadataDiscovery(rootUrl, protocolVersion, fetchFn);\n    }\n\n    return response;\n}\n\n/**\n * Looks up RFC 8414 OAuth 2.0 Authorization Server Metadata.\n *\n * If the server returns a 404 for the well-known endpoint, this function will\n * return `undefined`. Any other errors will be thrown as exceptions.\n *\n * @deprecated This function is deprecated in favor of {@linkcode discoverAuthorizationServerMetadata}.\n */\nexport async function discoverOAuthMetadata(\n    issuer: string | URL,\n    {\n        authorizationServerUrl,\n        protocolVersion\n    }: {\n        authorizationServerUrl?: string | URL;\n        protocolVersion?: string;\n    } = {},\n    fetchFn: FetchLike = fetch\n): Promise<OAuthMetadata | undefined> {\n    if (typeof issuer === 'string') {\n        issuer = new URL(issuer);\n    }\n    if (!authorizationServerUrl) {\n        authorizationServerUrl = issuer;\n    }\n    if (typeof authorizationServerUrl === 'string') {\n        authorizationServerUrl = new URL(authorizationServerUrl);\n    }\n    protocolVersion ??= LATEST_PROTOCOL_VERSION;\n\n    const response = await discoverMetadataWithFallback(authorizationServerUrl, 'oauth-authorization-server', fetchFn, {\n        protocolVersion,\n        metadataServerUrl: authorizationServerUrl\n    });\n\n    if (!response || response.status === 404) {\n        await response?.text?.().catch(() => {});\n        return undefined;\n    }\n\n    if (!response.ok) {\n        await response.text?.().catch(() => {});\n        throw new Error(`HTTP ${response.status} trying to load well-known OAuth metadata`);\n    }\n\n    return OAuthMetadataSchema.parse(await response.json());\n}\n\n/**\n * Builds a list of discovery URLs to try for authorization server metadata.\n * URLs are returned in priority order:\n * 1. OAuth metadata at the given URL\n * 2. OIDC metadata endpoints at the given URL\n */\nexport function buildDiscoveryUrls(authorizationServerUrl: string | URL): { url: URL; type: 'oauth' | 'oidc' }[] {\n    const url = typeof authorizationServerUrl === 'string' ? new URL(authorizationServerUrl) : authorizationServerUrl;\n    const hasPath = url.pathname !== '/';\n    const urlsToTry: { url: URL; type: 'oauth' | 'oidc' }[] = [];\n\n    if (!hasPath) {\n        urlsToTry.push(\n            // Root path: https://example.com/.well-known/oauth-authorization-server\n\n            {\n                url: new URL('/.well-known/oauth-authorization-server', url.origin),\n                type: 'oauth'\n            },\n            // OIDC: https://example.com/.well-known/openid-configuration\n\n            {\n                url: new URL(`/.well-known/openid-configuration`, url.origin),\n                type: 'oidc'\n            }\n        );\n\n        return urlsToTry;\n    }\n\n    // Strip trailing slash from pathname to avoid double slashes\n    let pathname = url.pathname;\n    if (pathname.endsWith('/')) {\n        pathname = pathname.slice(0, -1);\n    }\n\n    urlsToTry.push(\n        // 1. OAuth metadata at the given URL\n        // Insert well-known before the path: https://example.com/.well-known/oauth-authorization-server/tenant1\n        {\n            url: new URL(`/.well-known/oauth-authorization-server${pathname}`, url.origin),\n            type: 'oauth'\n        },\n        // 2. OIDC metadata endpoints\n        // RFC 8414 style: Insert /.well-known/openid-configuration before the path\n        {\n            url: new URL(`/.well-known/openid-configuration${pathname}`, url.origin),\n            type: 'oidc'\n        },\n        // OIDC Discovery 1.0 style: Append /.well-known/openid-configuration after the path\n\n        {\n            url: new URL(`${pathname}/.well-known/openid-configuration`, url.origin),\n            type: 'oidc'\n        }\n    );\n\n    return urlsToTry;\n}\n\n/**\n * Discovers authorization server metadata with support for\n * {@link https://datatracker.ietf.org/doc/html/rfc8414 | RFC 8414} OAuth 2.0\n * Authorization Server Metadata and\n * {@link https://openid.net/specs/openid-connect-discovery-1_0.html | OpenID Connect Discovery 1.0}\n * specifications.\n *\n * This function implements a fallback strategy for authorization server discovery:\n * 1. Attempts RFC 8414 OAuth metadata discovery first\n * 2. If OAuth discovery fails, falls back to OpenID Connect Discovery\n *\n * @param authorizationServerUrl - The authorization server URL obtained from the MCP Server's\n *                                 protected resource metadata, or the MCP server's URL if the\n *                                 metadata was not found.\n * The returned metadata's `issuer` is validated against `authorizationServerUrl`\n * per RFC 8414 §3.3 (and OIDC Discovery §4.3): if they differ the metadata is\n * **rejected** with {@linkcode IssuerMismatchError} and not returned. Set\n * `skipIssuerValidation: true` to suppress this check — **security-weakening**,\n * intended only for known-misconfigured authorization servers.\n *\n * @param options - Configuration options\n * @param options.fetchFn - Optional fetch function for making HTTP requests, defaults to global fetch\n * @param options.protocolVersion - MCP protocol version to use, defaults to {@linkcode LATEST_PROTOCOL_VERSION}\n * @param options.skipIssuerValidation - Skip the RFC 8414 §3.3 `issuer` echo check. **Security-weakening.**\n * @returns Promise resolving to authorization server metadata, or undefined if discovery fails\n * @throws {IssuerMismatchError} when the metadata's `issuer` does not match `authorizationServerUrl`\n */\nexport async function discoverAuthorizationServerMetadata(\n    authorizationServerUrl: string | URL,\n    {\n        fetchFn = fetch,\n        protocolVersion = LATEST_PROTOCOL_VERSION,\n        skipIssuerValidation = false\n    }: {\n        fetchFn?: FetchLike;\n        protocolVersion?: string;\n        skipIssuerValidation?: boolean;\n    } = {}\n): Promise<AuthorizationServerMetadata | undefined> {\n    const headers = {\n        'MCP-Protocol-Version': protocolVersion,\n        Accept: 'application/json'\n    };\n\n    // Get the list of URLs to try\n    const urlsToTry = buildDiscoveryUrls(authorizationServerUrl);\n\n    // Try each URL in order\n    for (const { url: endpointUrl, type } of urlsToTry) {\n        const response = await fetchWithCorsRetry(endpointUrl, headers, fetchFn);\n\n        if (!response) {\n            /**\n             * CORS error occurred - don't throw as the endpoint may not allow CORS,\n             * continue trying other possible endpoints\n             */\n            continue;\n        }\n\n        if (!response.ok) {\n            await response.text?.().catch(() => {});\n            if (response.status < 500 || response.status === 502) {\n                continue; // Try next URL for 4xx, 502 (Bad Gateway) or a redirect that was not followed\n            }\n            throw new Error(\n                `HTTP ${response.status} trying to load ${type === 'oauth' ? 'OAuth' : 'OpenID provider'} metadata from ${endpointUrl}`\n            );\n        }\n\n        // Parse and validate based on type\n        const parsed =\n            type === 'oauth'\n                ? OAuthMetadataSchema.parse(await response.json())\n                : OpenIdProviderDiscoveryMetadataSchema.parse(await response.json());\n\n        if (!skipIssuerValidation) {\n            // RFC 8414 §3.3 / OIDC Discovery §4.3: the `issuer` value in the document MUST be\n            // identical to the issuer identifier used to construct the well-known URL. Compare\n            // against the raw input string — callers pass the exact issuer string the AS published.\n            const expectedIssuer = typeof authorizationServerUrl === 'string' ? authorizationServerUrl : authorizationServerUrl.href;\n            // One narrow tolerance: the SDK's own legacy-fallback path synthesizes the AS URL via\n            // `String(new URL('/', serverUrl))`, which always carries a trailing `/`. That value is\n            // SDK-generated (not attacker-controlled), so accept the slash-only difference here.\n            // The tolerance is one-directional and end-anchored — a different host or path is still\n            // a mismatch.\n            const matches =\n                parsed.issuer === expectedIssuer || (expectedIssuer.endsWith('/') && parsed.issuer === expectedIssuer.slice(0, -1));\n            if (!matches) {\n                throw new IssuerMismatchError('metadata', expectedIssuer, parsed.issuer);\n            }\n        }\n\n        return parsed;\n    }\n\n    return undefined;\n}\n\n/**\n * Result of {@linkcode discoverOAuthServerInfo}.\n */\nexport interface OAuthServerInfo {\n    /**\n     * The authorization server URL, either discovered via RFC 9728\n     * or derived from the MCP server URL as a fallback.\n     */\n    authorizationServerUrl: string;\n\n    /**\n     * The authorization server metadata (endpoints, capabilities),\n     * or `undefined` if metadata discovery failed.\n     */\n    authorizationServerMetadata?: AuthorizationServerMetadata;\n\n    /**\n     * The OAuth 2.0 Protected Resource Metadata from RFC 9728,\n     * or `undefined` if the server does not support it.\n     */\n    resourceMetadata?: OAuthProtectedResourceMetadata;\n}\n\n/**\n * Discovers the authorization server for an MCP server following\n * {@link https://datatracker.ietf.org/doc/html/rfc9728 | RFC 9728} (OAuth 2.0 Protected\n * Resource Metadata), with fallback to treating the server URL as the\n * authorization server.\n *\n * This function combines two discovery steps into one call:\n * 1. Probes `/.well-known/oauth-protected-resource` on the MCP server to find the\n *    authorization server URL (RFC 9728).\n * 2. Fetches authorization server metadata from that URL (RFC 8414 / OpenID Connect Discovery).\n *\n * Use this when you need the authorization server metadata for operations outside the\n * {@linkcode auth} orchestrator, such as token refresh or token revocation.\n *\n * @param serverUrl - The MCP resource server URL\n * @param opts - Optional configuration\n * @param opts.resourceMetadataUrl - Override URL for the protected resource metadata endpoint\n * @param opts.fetchFn - Custom fetch function for HTTP requests\n * @returns Authorization server URL, metadata, and resource metadata (if available)\n */\nexport async function discoverOAuthServerInfo(\n    serverUrl: string | URL,\n    opts?: {\n        resourceMetadataUrl?: URL;\n        fetchFn?: FetchLike;\n        /**\n         * Forwarded to {@linkcode discoverAuthorizationServerMetadata} as\n         * `skipIssuerValidation`. **Security-weakening** — see {@linkcode AuthOptions.skipIssuerMetadataValidation}.\n         */\n        skipIssuerMetadataValidation?: boolean;\n    }\n): Promise<OAuthServerInfo> {\n    let resourceMetadata: OAuthProtectedResourceMetadata | undefined;\n    let authorizationServerUrl: string | undefined;\n\n    try {\n        resourceMetadata = await discoverOAuthProtectedResourceMetadata(\n            serverUrl,\n            { resourceMetadataUrl: opts?.resourceMetadataUrl },\n            opts?.fetchFn\n        );\n        if (resourceMetadata.authorization_servers && resourceMetadata.authorization_servers.length > 0) {\n            authorizationServerUrl = resourceMetadata.authorization_servers[0];\n        }\n    } catch (error) {\n        // Network failures (DNS, connection refused) surface as TypeError from fetch. Those are\n        // transient reachability problems, not \"server doesn't support PRM\" — propagate so the\n        // caller sees the real error instead of silently falling back to a different auth server.\n        if (error instanceof TypeError) {\n            throw error;\n        }\n        // RFC 9728 not supported -- fall back to treating the server URL as the authorization server\n    }\n\n    // If we don't get a valid authorization server from protected resource metadata,\n    // fall back to the legacy MCP spec behavior: MCP server base URL acts as the authorization server\n    if (!authorizationServerUrl) {\n        authorizationServerUrl = String(new URL('/', serverUrl));\n    }\n\n    const authorizationServerMetadata = await discoverAuthorizationServerMetadata(authorizationServerUrl, {\n        fetchFn: opts?.fetchFn,\n        skipIssuerValidation: opts?.skipIssuerMetadataValidation\n    });\n\n    return {\n        authorizationServerUrl,\n        authorizationServerMetadata,\n        resourceMetadata\n    };\n}\n\nfunction resourceIndicatorToString(resource: string | URL): string {\n    return typeof resource === 'string' ? resource : resource.href;\n}\n\n/**\n * Begins the authorization flow with the given server, by generating a PKCE challenge and constructing the authorization URL.\n */\nexport async function startAuthorization(\n    authorizationServerUrl: string | URL,\n    {\n        metadata,\n        clientInformation,\n        redirectUrl,\n        scope,\n        state,\n        resource\n    }: {\n        metadata?: AuthorizationServerMetadata;\n        clientInformation: OAuthClientInformationMixed;\n        redirectUrl: string | URL;\n        scope?: string;\n        state?: string;\n        resource?: string | URL;\n    }\n): Promise<{ authorizationUrl: URL; codeVerifier: string }> {\n    let authorizationUrl: URL;\n    if (metadata) {\n        authorizationUrl = new URL(metadata.authorization_endpoint);\n\n        if (!metadata.response_types_supported.includes(AUTHORIZATION_CODE_RESPONSE_TYPE)) {\n            throw new Error(`Incompatible auth server: does not support response type ${AUTHORIZATION_CODE_RESPONSE_TYPE}`);\n        }\n\n        if (\n            metadata.code_challenge_methods_supported &&\n            !metadata.code_challenge_methods_supported.includes(AUTHORIZATION_CODE_CHALLENGE_METHOD)\n        ) {\n            throw new Error(`Incompatible auth server: does not support code challenge method ${AUTHORIZATION_CODE_CHALLENGE_METHOD}`);\n        }\n    } else {\n        authorizationUrl = new URL('/authorize', authorizationServerUrl);\n    }\n\n    // Generate PKCE challenge\n    const challenge = await pkceChallenge();\n    const codeVerifier = challenge.code_verifier;\n    const codeChallenge = challenge.code_challenge;\n\n    authorizationUrl.searchParams.set('response_type', AUTHORIZATION_CODE_RESPONSE_TYPE);\n    authorizationUrl.searchParams.set('client_id', clientInformation.client_id);\n    authorizationUrl.searchParams.set('code_challenge', codeChallenge);\n    authorizationUrl.searchParams.set('code_challenge_method', AUTHORIZATION_CODE_CHALLENGE_METHOD);\n    authorizationUrl.searchParams.set('redirect_uri', String(redirectUrl));\n\n    if (state) {\n        authorizationUrl.searchParams.set('state', state);\n    }\n\n    if (scope) {\n        authorizationUrl.searchParams.set('scope', scope);\n    }\n\n    if (scope?.split(' ').includes('offline_access')) {\n        // if the request includes the OIDC-only \"offline_access\" scope,\n        // we need to set the prompt to \"consent\" to ensure the user is prompted to grant offline access\n        // https://openid.net/specs/openid-connect-core-1_0.html#OfflineAccess\n        authorizationUrl.searchParams.append('prompt', 'consent');\n    }\n\n    if (resource) {\n        authorizationUrl.searchParams.set('resource', resourceIndicatorToString(resource));\n    }\n\n    return { authorizationUrl, codeVerifier };\n}\n\n/**\n * Prepares token request parameters for an authorization code exchange.\n *\n * This is the default implementation used by {@linkcode fetchToken} when the provider\n * doesn't implement {@linkcode OAuthClientProvider.prepareTokenRequest | prepareTokenRequest}.\n *\n * @param authorizationCode - The authorization code received from the authorization endpoint\n * @param codeVerifier - The PKCE code verifier\n * @param redirectUri - The redirect URI used in the authorization request\n * @returns URLSearchParams for the `authorization_code` grant\n */\nexport function prepareAuthorizationCodeRequest(\n    authorizationCode: string,\n    codeVerifier: string,\n    redirectUri: string | URL\n): URLSearchParams {\n    return new URLSearchParams({\n        grant_type: 'authorization_code',\n        code: authorizationCode,\n        code_verifier: codeVerifier,\n        redirect_uri: String(redirectUri)\n    });\n}\n\n/**\n * Internal helper to execute a token request with the given parameters.\n * Used by {@linkcode exchangeAuthorization}, {@linkcode refreshAuthorization}, and {@linkcode fetchToken}.\n */\nexport async function executeTokenRequest(\n    authorizationServerUrl: string | URL,\n    {\n        metadata,\n        tokenRequestParams,\n        clientInformation,\n        addClientAuthentication,\n        resource,\n        dpop,\n        fetchFn\n    }: {\n        metadata?: AuthorizationServerMetadata;\n        tokenRequestParams: URLSearchParams;\n        clientInformation?: OAuthClientInformationMixed;\n        addClientAuthentication?: OAuthClientProvider['addClientAuthentication'];\n        resource?: string | URL;\n        /**\n         * SEP-1932 / RFC 9449 §5: when set, signs a DPoP proof into the token request's `DPoP`\n         * header — the prerequisite for obtaining a DPoP-bound access token. On a `400\n         * use_dpop_nonce` challenge (RFC 9449 §8) the request is retried exactly once with a\n         * fresh proof carrying the server-supplied nonce.\n         */\n        dpop?: DpopSession;\n        fetchFn?: FetchLike;\n    }\n): Promise<OAuthTokens> {\n    const tokenUrl = assertSecureTokenEndpoint(metadata?.token_endpoint ?? new URL('/token', authorizationServerUrl));\n\n    const headers = new Headers({\n        'Content-Type': 'application/x-www-form-urlencoded',\n        Accept: 'application/json'\n    });\n\n    if (resource) {\n        tokenRequestParams.set('resource', resourceIndicatorToString(resource));\n    }\n\n    if (!addClientAuthentication && clientInformation) {\n        const supportedMethods = metadata?.token_endpoint_auth_methods_supported ?? [];\n        const authMethod = selectClientAuthMethod(clientInformation, supportedMethods);\n        applyClientAuthentication(authMethod, clientInformation as OAuthClientInformation, headers, tokenRequestParams);\n    }\n\n    const requestOnce = async (): Promise<Response> => {\n        const requestHeaders = new Headers(headers);\n        // Per attempt, not once up front: a `private_key_jwt` client_assertion carries a one-time\n        // `jti` (RFC 7521 §5.2), so the DPoP nonce retry below must mint a fresh one, not replay it.\n        if (addClientAuthentication) {\n            await addClientAuthentication(requestHeaders, tokenRequestParams, tokenUrl, metadata);\n        }\n        if (dpop) {\n            // No `ath`: RFC 9449 §4.3 step 12a only binds a proof to an access token when one is\n            // presented, and the token request is presenting credentials to *obtain* one.\n            requestHeaders.set('DPoP', await dpop.buildProof({ htm: 'POST', htu: tokenUrl }));\n        }\n        return fetchWithinOrigin(fetchFn ?? fetch)(tokenUrl, {\n            method: 'POST',\n            headers: requestHeaders,\n            body: tokenRequestParams\n        });\n    };\n\n    let response = await requestOnce();\n\n    // RFC 9449 §8: the AS may answer with `400 { error: \"use_dpop_nonce\" }` + `DPoP-Nonce`; a\n    // conformant client retries the token request once with a fresh proof carrying that nonce\n    // (buildProof picks it up automatically via the session's remembered nonce for this origin).\n    // Peek the body via a clone so a non-nonce 400 still flows into parseErrorResponse below with\n    // an unconsumed body.\n    if (dpop && response.status === 400) {\n        const challenge = (await response\n            .clone()\n            .json()\n            .catch(() => {})) as { error?: string } | undefined;\n        if (challenge?.error === OAuthErrorCode.UseDpopNonce) {\n            dpop.observeNonce(response, tokenUrl);\n            response = await requestOnce();\n        }\n    }\n    // RFC 9449 §8.2: newest-wins nonce capture applies to any response, success included.\n    dpop?.observeNonce(response, tokenUrl);\n\n    if (!response.ok) {\n        throw await parseErrorResponse(response);\n    }\n\n    const json: unknown = await response.json();\n\n    try {\n        return OAuthTokensSchema.parse(withoutIssuer(json));\n    } catch (parseError) {\n        // Some OAuth servers (e.g., GitHub) return error responses with HTTP 200 status.\n        // Check for error field only if token parsing failed.\n        if (typeof json === 'object' && json !== null && 'error' in json) {\n            throw await parseErrorResponse(JSON.stringify(json));\n        }\n        throw parseError;\n    }\n}\n\n/**\n * Exchanges an authorization code for an access token with the given server.\n *\n * Supports multiple client authentication methods as specified in OAuth 2.1:\n * - Automatically selects the best authentication method based on server support\n * - Falls back to appropriate defaults when server metadata is unavailable\n *\n * @param authorizationServerUrl - The authorization server's base URL\n * @param options - Configuration object containing client info, auth code, etc.\n * @returns Promise resolving to OAuth tokens\n * @throws {Error} When token exchange fails or authentication is invalid\n */\nexport async function exchangeAuthorization(\n    authorizationServerUrl: string | URL,\n    {\n        metadata,\n        clientInformation,\n        authorizationCode,\n        iss,\n        codeVerifier,\n        redirectUri,\n        resource,\n        addClientAuthentication,\n        dpop,\n        fetchFn\n    }: {\n        metadata?: AuthorizationServerMetadata;\n        clientInformation: OAuthClientInformationMixed;\n        authorizationCode: string;\n        /**\n         * The form-urldecoded `iss` query parameter from the authorization callback.\n         * Validated per RFC 9207 §2.4 against `metadata.issuer` before the code is\n         * redeemed; see {@linkcode validateAuthorizationResponseIssuer}.\n         */\n        iss?: string;\n        codeVerifier: string;\n        redirectUri: string | URL;\n        resource?: string | URL;\n        addClientAuthentication?: OAuthClientProvider['addClientAuthentication'];\n        /** SEP-1932 / RFC 9449: see {@linkcode executeTokenRequest}'s `dpop` option. */\n        dpop?: DpopSession;\n        fetchFn?: FetchLike;\n    }\n): Promise<OAuthTokens> {\n    validateAuthorizationResponseIssuer({\n        iss,\n        expectedIssuer: metadata?.issuer,\n        issParameterSupported: isIssParameterSupported(metadata)\n    });\n\n    const tokenRequestParams = prepareAuthorizationCodeRequest(authorizationCode, codeVerifier, redirectUri);\n\n    return executeTokenRequest(authorizationServerUrl, {\n        metadata,\n        tokenRequestParams,\n        clientInformation,\n        addClientAuthentication,\n        resource,\n        dpop,\n        fetchFn\n    });\n}\n\n/**\n * Exchange a refresh token for an updated access token.\n *\n * Supports multiple client authentication methods as specified in OAuth 2.1:\n * - Automatically selects the best authentication method based on server support\n * - Preserves the original refresh token if a new one is not returned\n *\n * @param authorizationServerUrl - The authorization server's base URL\n * @param options - Configuration object containing client info, refresh token, etc.\n * @returns Promise resolving to OAuth tokens (preserves original `refresh_token` if not replaced)\n * @throws {Error} When token refresh fails or authentication is invalid\n */\nexport async function refreshAuthorization(\n    authorizationServerUrl: string | URL,\n    {\n        metadata,\n        clientInformation,\n        refreshToken,\n        scope,\n        resource,\n        addClientAuthentication,\n        dpop,\n        fetchFn\n    }: {\n        metadata?: AuthorizationServerMetadata;\n        clientInformation: OAuthClientInformationMixed;\n        refreshToken: string;\n        /**\n         * `scope` to send on the request; omitted or `''` sends none, which asks for the scope\n         * already granted (RFC 6749 §6). When sent, it is also the result's `scope` if the response has none.\n         */\n        scope?: string;\n        resource?: string | URL;\n        addClientAuthentication?: OAuthClientProvider['addClientAuthentication'];\n        /** SEP-1932 / RFC 9449: see {@linkcode executeTokenRequest}'s `dpop` option. */\n        dpop?: DpopSession;\n        fetchFn?: FetchLike;\n    }\n): Promise<OAuthTokens> {\n    const tokenRequestParams = new URLSearchParams({\n        grant_type: 'refresh_token',\n        refresh_token: refreshToken\n    });\n    if (scope) {\n        tokenRequestParams.set('scope', scope);\n    }\n\n    const tokens = await executeTokenRequest(authorizationServerUrl, {\n        metadata,\n        tokenRequestParams,\n        clientInformation,\n        addClientAuthentication,\n        resource,\n        dpop,\n        fetchFn\n    });\n\n    // Preserve the original refresh token, and the scope sent (RFC 6749 §5.1), if the server didn't return new ones\n    return { refresh_token: refreshToken, ...tokens, ...(scope && !tokens.scope && { scope }) };\n}\n\n/**\n * Unified token fetching that works with any grant type via {@linkcode OAuthClientProvider.prepareTokenRequest | prepareTokenRequest()}.\n *\n * This function provides a single entry point for obtaining tokens regardless of the\n * OAuth grant type. The provider's `prepareTokenRequest()` method determines which grant\n * to use and supplies the grant-specific parameters.\n *\n * @param provider - OAuth client provider that implements `prepareTokenRequest()`\n * @param authorizationServerUrl - The authorization server's base URL\n * @param options - Configuration for the token request\n * @returns Promise resolving to OAuth tokens\n * @throws {Error} When provider doesn't implement `prepareTokenRequest` or token fetch fails\n *\n * @example\n * ```ts source=\"./auth.examples.ts#fetchToken_clientCredentials\"\n * // Provider for client_credentials:\n * class MyProvider extends MyProviderBase implements OAuthClientProvider {\n *     prepareTokenRequest(scope?: string) {\n *         const params = new URLSearchParams({ grant_type: 'client_credentials' });\n *         if (scope) params.set('scope', scope);\n *         return params;\n *     }\n * }\n *\n * const tokens = await fetchToken(new MyProvider(), authServerUrl, { metadata });\n * ```\n */\nexport async function fetchToken(\n    provider: OAuthClientProvider,\n    authorizationServerUrl: string | URL,\n    {\n        metadata,\n        resource,\n        authorizationCode,\n        iss,\n        scope,\n        fetchFn\n    }: {\n        metadata?: AuthorizationServerMetadata;\n        resource?: string | URL;\n        /** Authorization code for the default `authorization_code` grant flow */\n        authorizationCode?: string;\n        /**\n         * The form-urldecoded `iss` query parameter from the authorization callback.\n         * Validated per RFC 9207 §2.4 when `authorizationCode` is present;\n         * see {@linkcode validateAuthorizationResponseIssuer}.\n         */\n        iss?: string;\n        /** Optional scope parameter from auth() options */\n        scope?: string;\n        fetchFn?: FetchLike;\n    } = {}\n): Promise<OAuthTokens> {\n    if (authorizationCode !== undefined) {\n        validateAuthorizationResponseIssuer({\n            iss,\n            expectedIssuer: metadata?.issuer,\n            issParameterSupported: isIssParameterSupported(metadata)\n        });\n    }\n\n    // SEP-2352: nothing is sent to an authorization server other than the one the client information is stamped for.\n    const issuer = metadata?.issuer ?? String(authorizationServerUrl);\n    const readClientInformation = async () => {\n        const rawClientInfo = await provider.clientInformation({ issuer });\n        const checked = discardIfIssuerMismatch(rawClientInfo, issuer, { canPersistStamp: false });\n        if (rawClientInfo && checked === undefined) {\n            throw new AuthorizationServerMismatchError(String(rawClientInfo.issuer), issuer);\n        }\n        return checked;\n    };\n    let clientInformation = await readClientInformation();\n\n    // Prefer scope from options, fallback to provider.clientMetadata.scope\n    const effectiveScope = scope ?? provider.clientMetadata.scope;\n\n    // Use provider's prepareTokenRequest if available, otherwise fall back to authorization_code\n    let tokenRequestParams: URLSearchParams | undefined;\n    if (provider.prepareTokenRequest) {\n        tokenRequestParams = await provider.prepareTokenRequest(effectiveScope);\n    }\n\n    // Default to authorization_code grant if no custom prepareTokenRequest\n    if (!tokenRequestParams) {\n        if (!authorizationCode) {\n            throw new Error('Either provider.prepareTokenRequest() or authorizationCode is required');\n        }\n        if (!provider.redirectUrl) {\n            throw new Error('redirectUrl is required for authorization_code flow');\n        }\n        const codeVerifier = await provider.codeVerifier();\n        tokenRequestParams = prepareAuthorizationCodeRequest(authorizationCode, codeVerifier, provider.redirectUrl);\n    }\n\n    // A provider may fill in its client information while the request is prepared.\n    clientInformation ??= await readClientInformation();\n\n    return executeTokenRequest(authorizationServerUrl, {\n        metadata,\n        tokenRequestParams,\n        clientInformation,\n        addClientAuthentication: provider.addClientAuthentication,\n        resource,\n        dpop: await provider.dpop?.(),\n        fetchFn\n    });\n}\n\n/**\n * Performs OAuth 2.0 Dynamic Client Registration according to\n * {@link https://datatracker.ietf.org/doc/html/rfc7591 | RFC 7591}.\n *\n * If `scope` is provided, it overrides `clientMetadata.scope` in the registration\n * request body. This allows callers to apply the Scope Selection Strategy (SEP-835)\n * consistently across both DCR and the subsequent authorization request.\n *\n * @deprecated Dynamic Client Registration is deprecated as of protocol version\n * 2026-07-28 in favor of Client ID Metadata Documents (SEP-991); the deprecation\n * landed via spec PR\n * {@link https://github.com/modelcontextprotocol/modelcontextprotocol/pull/2858 | modelcontextprotocol#2858}\n * (SEP-2577 is the separate roots/sampling/logging deprecation). Remains\n * functional during the deprecation window — at least twelve months under the\n * feature lifecycle policy (SEP-2596), so 2027-07-28 is the earliest possible\n * removal date. Prefer a CIMD URL `client_id` when the authorization server\n * advertises `client_id_metadata_document_supported`: the built-in `auth()` flow\n * skips registration for you when that capability is advertised AND your\n * provider supplies `clientMetadataUrl`, but `registerClient` itself does not\n * gate — calling it directly always sends the registration request.\n */\nexport async function registerClient(\n    authorizationServerUrl: string | URL,\n    {\n        metadata,\n        clientMetadata,\n        scope,\n        fetchFn\n    }: {\n        metadata?: AuthorizationServerMetadata;\n        clientMetadata: OAuthClientMetadata;\n        scope?: string;\n        fetchFn?: FetchLike;\n    }\n): Promise<OAuthClientInformationFull> {\n    let registrationUrl: URL;\n\n    if (metadata) {\n        if (!metadata.registration_endpoint) {\n            throw new Error('Incompatible auth server: does not support dynamic client registration');\n        }\n\n        registrationUrl = new URL(metadata.registration_endpoint);\n    } else {\n        registrationUrl = new URL('/register', authorizationServerUrl);\n    }\n\n    // `clientMetadata` arrives via resolveClientMetadata() inside auth(), so the\n    // SEP-837/2207 defaults are already applied. Direct callers that want the\n    // same defaults should pass resolveClientMetadata(provider) here.\n    const submittedMetadata: OAuthClientMetadata = {\n        ...clientMetadata,\n        ...(scope === undefined ? {} : { scope })\n    };\n\n    const response = await fetchWithinOrigin(fetchFn ?? fetch)(registrationUrl, {\n        method: 'POST',\n        headers: {\n            'Content-Type': 'application/json'\n        },\n        body: JSON.stringify(submittedMetadata)\n    });\n\n    if (!response.ok) {\n        throw new RegistrationRejectedError({ status: response.status, body: await response.text(), submittedMetadata });\n    }\n\n    return OAuthClientInformationFullSchema.parse(withoutIssuer(await response.json()));\n}\n","import type { ListToolsResult, Tool } from '@modelcontextprotocol/core-internal';\n\n/**\n * Client-side response cache for SEP-2549 (`CacheableResult`) freshness hints.\n *\n * The store is a dumb keyed-value carrier: every freshness, scope and\n * invalidation decision lives in the {@linkcode ClientResponseCache} (the\n * `Client`'s single cache-coordination collaborator). The `stamp` field is\n * mcp.d's re-derivation key — a derived view (e.g. the `name → Tool` index)\n * re-computes only when the backing entry's stamp changes.\n *\n * Reference design: mcp.d `client/cache.d` / `client/client.d` (`CacheStore`,\n * `cachedTool`, `cachedFetch`, `invalidateLogical`).\n */\n\n/** A value or a promise of one. The store interface is async-ready; the in-memory default returns plain values. */\nexport type MaybePromise<T> = T | Promise<T>;\n\n/** The freshness scope of a cached entry (SEP-2549 `cacheHints.scope`). */\nexport type CacheScope = 'public' | 'private';\n\n/**\n * Per-call cache disposition for the cacheable verbs (`listTools()` /\n * `listPrompts()` / `listResources()` / `listResourceTemplates()` /\n * `readResource()`):\n *\n * - `'use'` (the default) — serve a still-fresh cached entry without a round\n *   trip; on miss/stale, fetch and write.\n * - `'refresh'` — always fetch (ignore any held entry) and write the fresh\n *   result.\n * - `'bypass'` — fetch without consulting OR writing the cache (the result is\n *   not stored). The `tools/list`-derived index (mirroring / output\n *   validation) is therefore unaffected by a `'bypass'` call.\n */\nexport type CacheMode = 'use' | 'refresh' | 'bypass';\n\n/**\n * A logical cache address. `params` is the canonical result-affecting params\n * key (`''` for the four list ops, the `uri` for `resources/read`); omitted is\n * equivalent to `''`. `partition` namespaces the entry by connected-server\n * identity AND per-principal scope: the `Client` writes a JSON-encoded\n * `[serverIdentity, principal]` pair (so a server-controlled `serverInfo`\n * string cannot bleed into the principal slot regardless of what characters\n * it contains). A `'public'`-scoped entry lives at `[serverIdentity, '']`; a\n * `'private'`-scoped entry at `[serverIdentity, cachePartition]`. Omitted is\n * equivalent to `''`.\n */\nexport interface CacheKey {\n    readonly method: string;\n    readonly params?: string;\n    readonly partition?: string;\n}\n\n/**\n * One cached response body. `value` is the JSON-serialized result document —\n * a store is a dumb string carrier and persists it verbatim; the cache owns\n * both codec halves. `stamp` is the store-generated monotonically increasing write counter —\n * opaque to callers. Derived views (e.g. a `name → Tool` index) memoize\n * against it and re-derive only when it changes. `expiresAt` (absolute ms\n * epoch, `now + ttlMs`) and `scope` are the client-computed freshness\n * metadata; the store MUST persist them and hand them back on `get` so the\n * read path can decide freshness and gate the shared-partition fallback on\n * `scope === 'public'`.\n */\nexport interface CacheEntry {\n    readonly value: string;\n    readonly stamp: number;\n    readonly expiresAt?: number;\n    readonly scope?: CacheScope;\n}\n\n/**\n * The pluggable response-cache store. The interface is intentionally narrow;\n * the in-memory default is the only implementation the SDK ships.\n *\n * Every method is async-ready ({@linkcode MaybePromise}) so a Redis-style\n * store can implement the same interface without a later breaking change; the\n * in-memory default stays synchronous (plain values are valid under\n * `MaybePromise`). The `Client` `await`s every call site.\n *\n * Entries are keyed by `{method, params, partition}` where `partition` is the\n * `Client`-derived `[serverIdentity, principal]` JSON pair, so one store\n * instance is safe to share across `Client` instances connected to different\n * servers and/or principals: writes from distinct connections never collide,\n * the shared-partition read fallback is gated on the stored\n * `scope === 'public'`, and `list_changed` / `HEADER_MISMATCH` evictions are\n * scoped to the connected server's two partitions — co-tenants on a shared\n * store are unaffected. The `Client` constructor still allocates a fresh\n * {@linkcode InMemoryResponseCacheStore} per instance by default; supply your\n * own to share or persist.\n */\nexport interface ResponseCacheStore {\n    get(key: CacheKey): MaybePromise<CacheEntry | undefined>;\n    /**\n     * Writes `entry` under `key` and returns the store-generated stamp the\n     * resulting {@linkcode CacheEntry} carries. The store owns the stamp\n     * counter; callers do not supply one. The caller owns `expiresAt` and\n     * `scope` (the client-computed freshness metadata); the store MUST persist\n     * them and hand them back on `get`.\n     */\n    set(key: CacheKey, entry: { value: string; expiresAt?: number; scope?: CacheScope }): MaybePromise<number>;\n    /**\n     * Drop the single entry under `key` (no-op if absent). Called for both\n     * `notifications/resources/updated` (per-URI) and the `list_changed`\n     * notifications (the list singletons live at `{method, params: '', partition}`).\n     */\n    delete(key: CacheKey): MaybePromise<void>;\n    /**\n     * Drop every entry for `method` across every partition. The `Client` does\n     * NOT call this (its `list_changed` path issues two partition-scoped\n     * `delete()` calls so co-tenants on a shared store keep their entries);\n     * kept on the interface for callers that want a method-wide bulk-clear.\n     */\n    evict(method: string): MaybePromise<void>;\n    /** Drop every entry (connection reset). */\n    clear(): MaybePromise<void>;\n}\n\n/** Options for {@linkcode InMemoryResponseCacheStore}. */\nexport interface InMemoryResponseCacheStoreOptions {\n    /**\n     * Maximum number of held `resources/read` entries (the only\n     * unbounded-keyspace method). When inserting a new `resources/read` key\n     * would exceed this, the oldest such entry (by insertion order) is\n     * evicted first. The list-singleton methods (`tools/list`,\n     * `prompts/list`, `resources/list`, `resources/templates/list`,\n     * `server/discover`) are **exempt** — they hold at most one entry per\n     * partition and back the `tools/list`-derived index, so an unbounded URI\n     * working set never displaces them. The default of `512` bounds growth on\n     * a long-lived client against template-expanded URIs. `0` disables the\n     * bound.\n     */\n    maxEntries?: number;\n}\n\n/**\n * Methods whose entries are exempt from the\n * {@linkcode InMemoryResponseCacheStoreOptions.maxEntries} cap. Each holds at\n * most one entry per partition (a small bounded set) and the\n * `tools/list`-derived index depends on its entry surviving regardless of the\n * `resources/read` working-set size. Only `resources/read` keys count toward\n * the cap and are eligible for FIFO eviction.\n */\nconst CAP_EXEMPT_METHODS: ReadonlySet<string> = new Set([\n    'tools/list',\n    'prompts/list',\n    'resources/list',\n    'resources/templates/list',\n    'server/discover'\n]);\n\n/**\n * In-memory default. Bounded by an insertion-ordered size cap (default `512`;\n * see {@linkcode InMemoryResponseCacheStoreOptions.maxEntries}) on the\n * `resources/read` keyspace so an unbounded stream of distinct URIs cannot\n * grow it without limit; the list-singleton methods are exempt and never\n * evicted by the cap. `Map` preserves insertion order, so the oldest live\n * capped key is the first matching iteration entry.\n */\nexport class InMemoryResponseCacheStore implements ResponseCacheStore {\n    private readonly _entries = new Map<string, CacheEntry>();\n    private readonly _maxEntries: number;\n    private _stamp = 0;\n    /** Count of held entries that are subject to the cap (i.e. not in {@linkcode CAP_EXEMPT_METHODS}). */\n    private _cappedSize = 0;\n\n    constructor(options?: InMemoryResponseCacheStoreOptions) {\n        this._maxEntries = options?.maxEntries ?? 512;\n    }\n\n    /** Number of held entries (for diagnostics / bounding tests). */\n    get size(): number {\n        return this._entries.size;\n    }\n\n    get(key: CacheKey): CacheEntry | undefined {\n        return this._entries.get(keyOf(key));\n    }\n\n    set(key: CacheKey, entry: { value: string; expiresAt?: number; scope?: CacheScope }): number {\n        const k = keyOf(key);\n        const exempt = CAP_EXEMPT_METHODS.has(key.method);\n        const isNew = !this._entries.has(k);\n        // Evict the oldest CAPPED entry first when adding a NEW capped key\n        // would exceed the cap (re-set of an existing key never evicts; an\n        // exempt-method write never evicts). `Map` iteration order is\n        // insertion order, so the first non-exempt key is the oldest one.\n        if (!exempt && isNew && this._maxEntries > 0 && this._cappedSize >= this._maxEntries) {\n            for (const oldKey of this._entries.keys()) {\n                if (!CAP_EXEMPT_METHODS.has(oldKey.slice(0, oldKey.indexOf('\\0')))) {\n                    this._entries.delete(oldKey);\n                    this._cappedSize--;\n                    break;\n                }\n            }\n        }\n        const stamp = ++this._stamp;\n        this._entries.set(k, { ...entry, stamp });\n        if (isNew && !exempt) this._cappedSize++;\n        return stamp;\n    }\n\n    delete(key: CacheKey): void {\n        if (this._entries.delete(keyOf(key)) && !CAP_EXEMPT_METHODS.has(key.method)) this._cappedSize--;\n    }\n\n    evict(method: string): void {\n        const prefix = `${method}\\0`;\n        const exempt = CAP_EXEMPT_METHODS.has(method);\n        for (const k of this._entries.keys()) {\n            if (k.startsWith(prefix)) {\n                this._entries.delete(k);\n                if (!exempt) this._cappedSize--;\n            }\n        }\n    }\n\n    clear(): void {\n        this._entries.clear();\n        this._cappedSize = 0;\n    }\n}\n\n/**\n * Serialize a {@linkcode CacheKey} for the in-memory map. `method` is always\n * an SDK-set MCP method string (never contains a NUL), so the `\\0` prefix\n * delimiter is safe and lets {@linkcode InMemoryResponseCacheStore.evict} do a\n * cheap prefix scan. `partition` (already a JSON-encoded\n * `[serverIdentity, principal]` pair) and `params` (a resource URI on the\n * `resources/read` path — caller-controlled) are JSON-array-encoded together,\n * which is collision-free regardless of any NUL or delimiter characters they\n * carry.\n */\nfunction keyOf(key: CacheKey): string {\n    return `${key.method}\\0${JSON.stringify([key.partition ?? '', key.params ?? ''])}`;\n}\n\n/**\n * Serialize a `{method, params}` pair for the eviction-generation map. The\n * list singletons key on `method` alone (their {@linkcode ClientResponseCache.evict}\n * is whole-method); `resources/read` keys on `` `${method}\\0${uri}` `` so\n * {@linkcode ClientResponseCache.evictKey} bumps a per-URI counter.\n */\nfunction genKey(method: string, params?: string): string {\n    return params === undefined ? method : `${method}\\0${params}`;\n}\n\n/**\n * Upper bound on the server-supplied `ttlMs` honoured by\n * {@linkcode ClientResponseCache} (24h). A server cannot pin an entry\n * indefinitely.\n */\nexport const MAX_CACHE_TTL_MS = 86_400_000;\n\n/**\n * The `Client`'s cache-coordination collaborator.\n *\n * Owns the per-connection cache state that used to live as five private\n * fields on `Client` — the backing {@linkcode ResponseCacheStore}, the\n * per-method eviction-generation counter, the user-supplied/default flag, and\n * the stamp-memoized derived indices over the `tools/list` entry. `Client`\n * holds exactly one instance and never reaches past it to the store.\n *\n * Not exported from the package index — internal to the client package.\n *\n * @internal\n */\nexport class ClientResponseCache {\n    /**\n     * Per-logical-key eviction-generation counter. {@linkcode evict} (whole\n     * method) and {@linkcode evictKey} (single `{method, params}`) bump it\n     * before touching the store; {@linkcode captureGeneration} reads it before\n     * the request; {@linkcode write} skips when it moved — so a `list_changed`\n     * arriving mid-walk, or a `resources/updated` arriving while a\n     * `readResource()` for the same URI is in flight, is not overwritten by\n     * the in-flight request's stale write. The map key is `method` for the\n     * list singletons and `` `${method}\\0${params}` `` for per-URI keys.\n     *\n     * Growth is bounded by keys the CLIENT has issued a `captureGeneration`\n     * for: {@linkcode captureGeneration} records the key (so an interleaved\n     * {@linkcode evictKey} sees there is an in-flight write to suppress);\n     * {@linkcode evictKey} only bumps a key that is already recorded — a\n     * server streaming `notifications/resources/updated` for URIs the client\n     * has never read therefore cannot grow this map.\n     */\n    private readonly _evictionGeneration = new Map<string, number>();\n    /**\n     * `name → Tool` index derived from the cached `tools/list` entry, memoized\n     * against the entry's `stamp` so it re-derives only when the backing entry\n     * changes (mcp.d's `cachedTool` pattern).\n     */\n    private _toolIndex?: { stamp: number; byName: Map<string, Tool> };\n    /**\n     * `name → compiled output-schema validator` derived from the cached\n     * `tools/list` entry; same stamp-keyed memoization as `_toolIndex`. Typed\n     * `unknown` so this class stays free of any validator-provider dependency\n     * — the compile callback supplied to {@linkcode outputValidator} owns the\n     * concrete type.\n     */\n    private _toolOutputValidatorIndex?: { stamp: number; byName: Map<string, unknown> };\n    /**\n     * The connected server's identity (`serverInfo.name@version`, the\n     * transport's `sessionId`, or a client-generated per-connection\n     * surrogate). Set by the `Client` immediately after a successful connect;\n     * `''` is the pre-connect sentinel. Every storage partition is derived\n     * from this (see `_partitionFor`), so two clients sharing one store but\n     * connected to different servers never collide on `tools/list` and a\n     * server cannot read another server's `'public'` entries.\n     */\n    private _serverIdentity = '';\n\n    constructor(\n        private readonly _store: ResponseCacheStore,\n        /**\n         * Whether `_store` was supplied by the caller. A user-supplied store is\n         * never `clear()`ed by {@linkcode resetForReconnect} (defeats the only\n         * reason to supply one).\n         */\n        private readonly _isUserSupplied: boolean,\n        /**\n         * Sink for a custom store's `set()`/`evict()` failure. {@linkcode write}\n         * never lets a store rejection cost the caller a result it already\n         * fetched — the failure is reported here and the write resolves. The\n         * `Client` wires this to `onerror`.\n         */\n        private readonly _reportError: (error: unknown) => void = () => {},\n        /**\n         * The opaque per-principal identifier for this client (the\n         * `private`-scope storage slot within the connected server's\n         * namespace). `''` (the default) makes the `private` slot identical to\n         * the server's shared `public` slot — the safe single-tenant posture.\n         * See `_partitionFor`.\n         */\n        private readonly _cachePartition: string = '',\n        /**\n         * Clock seam (testing). The freshness check (`entry.expiresAt > now()`)\n         * and the `expiresAt = now() + ttlMs` stamp both read it via\n         * {@linkcode now}. Default `Date.now`.\n         */\n        private readonly _now: () => number = Date.now\n    ) {}\n\n    /** The clock used for every freshness computation and check. */\n    now(): number {\n        return this._now();\n    }\n\n    /**\n     * Record the connected server's identity. Called by `Client` immediately\n     * after a successful connect: `serverInfo.name@version` when the server\n     * identified itself, else the transport's `sessionId`, else a\n     * client-generated per-connection surrogate (`serverInfo` is a spec\n     * SHOULD on 2026-07-28, so anonymous servers exist). Surrogate-keyed\n     * partitions are NOT stable across reconnects — no identity means no\n     * cross-connection cache reuse, and a shared long-lived store should\n     * bound its own size accordingly. Every partition derived after this\n     * call is scoped to this identity; entries written under the pre-connect\n     * `''` sentinel are no longer reachable.\n     */\n    setServerIdentity(identity: string): void {\n        this._serverIdentity = identity;\n    }\n\n    /**\n     * Derive the storage partition for `scope`. The encoding is\n     * `JSON.stringify([serverIdentity, principal])` — JSON escaping makes it\n     * collision-free by construction: a malicious server cannot craft a\n     * `serverInfo.name`/`version` whose concatenated form bleeds into another\n     * server's namespace or another principal's slot, regardless of `@` / `|`\n     * / `\"` / NUL in the server-controlled strings. `'public'` →\n     * `[serverIdentity, '']` (shared within this server); `'private'` →\n     * `[serverIdentity, cachePartition]`. When `cachePartition` is `''` the\n     * two coincide.\n     */\n    private _partitionFor(scope: CacheScope): string {\n        return JSON.stringify([this._serverIdentity, scope === 'public' ? '' : this._cachePartition]);\n    }\n\n    /**\n     * Two-probe lookup: this client's own (private) partition first, then the\n     * connected server's shared (public) partition. The shared probe is gated\n     * on `entry.scope === 'public'` — a co-tenant client that omits\n     * `cachePartition` writes its `'private'`-scoped entries at the public\n     * partition, and serving those to a correctly-partitioned client would\n     * leak private bodies (mcp.d's `cachedEntry` two-probe order; the scope\n     * gate is defence-in-depth on top of the partition split). When\n     * `cachePartition` is `''` the two partitions are identical and only one\n     * probe is issued.\n     */\n    private async _probe(method: string, params?: string): Promise<CacheEntry | undefined> {\n        const key = { method, params: params ?? '' };\n        const ownPartition = this._partitionFor('private');\n        const own = await this._store.get({ ...key, partition: ownPartition });\n        if (own !== undefined) return own;\n        const sharedPartition = this._partitionFor('public');\n        if (sharedPartition === ownPartition) return undefined;\n        const shared = await this._store.get({ ...key, partition: sharedPartition });\n        return shared?.scope === 'public' ? shared : undefined;\n    }\n\n    /**\n     * Bump the per-method generation (so an in-flight {@linkcode write} for the\n     * same method becomes a no-op) and drop the connected server's two list\n     * singletons (own + shared partition; `params: ''`). The generation bump\n     * is unconditional and FIRST — the {@linkcode write} race guard relies on\n     * the bump, not on the store's deletes completing.\n     *\n     * Eviction is scoped to this client's `[serverIdentity, principal]`\n     * partitions (mirroring {@linkcode evictKey}) — the method-wide\n     * `store.evict()` is NOT called, so on a shared store one server's\n     * `list_changed` cannot wipe a co-tenant's entry. A custom store's\n     * `delete()` may throw or reject; each partition is guarded\n     * independently so a failure on one does not skip the other, the failure\n     * is reported via the constructor's sink, and the call resolves so\n     * dispatch proceeds.\n     */\n    async evict(method: string): Promise<void> {\n        this._evictionGeneration.set(method, (this._evictionGeneration.get(method) ?? 0) + 1);\n        await this._deleteBoth(method, '');\n    }\n\n    /**\n     * Guarded two-partition delete of `{method, params}`: each partition's\n     * `delete` is independently wrapped so a custom store's failure on one is\n     * reported and does not skip the other, and the call always resolves.\n     */\n    private async _deleteBoth(method: string, params: string): Promise<void> {\n        const ownPartition = this._partitionFor('private');\n        const sharedPartition = this._partitionFor('public');\n        try {\n            await this._store.delete({ method, params, partition: ownPartition });\n        } catch (error) {\n            this._reportError(error);\n        }\n        if (sharedPartition !== ownPartition) {\n            try {\n                await this._store.delete({ method, params, partition: sharedPartition });\n            } catch (error) {\n                this._reportError(error);\n            }\n        }\n    }\n\n    /**\n     * Drop the single logical entry `{method, params}` from BOTH the private\n     * and public partitions for this client's connected server (mcp.d's\n     * `invalidateLogical`). Used for `notifications/resources/updated`'s\n     * per-URI eviction. The per-key generation is bumped FIRST (so an\n     * in-flight {@linkcode write} for the same `{method, params}` becomes a\n     * no-op and cannot re-cache the now-stale body) but only when the key was\n     * already recorded by {@linkcode captureGeneration} — bounding the map to\n     * keys the client has actually read. A custom store's `delete()` may\n     * throw or reject; each partition's delete is guarded independently so a\n     * failure on one does not skip the other, and the call resolves so\n     * dispatch proceeds.\n     */\n    async evictKey(method: string, params: string): Promise<void> {\n        const gk = genKey(method, params);\n        // Only bump a key the client has actually captured: if no entry is\n        // present there is no in-flight write to suppress, and an\n        // unconditional bump would let a server streaming distinct-URI\n        // `resources/updated` notifications grow this map without bound. The\n        // store deletes still run regardless (a previously-written entry may\n        // be held even when the generation entry has since been cleared by\n        // `resetForReconnect`).\n        const current = this._evictionGeneration.get(gk);\n        if (current !== undefined) this._evictionGeneration.set(gk, current + 1);\n        await this._deleteBoth(method, params);\n    }\n\n    /**\n     * Snapshot the eviction generation for `{method, params}` before issuing\n     * the request (a list walk's page 1, or a `resources/read` for `params`).\n     * Records the key so an interleaved {@linkcode evictKey} for the same\n     * `{method, params}` knows there is an in-flight write to suppress and\n     * bumps; without the record, `evictKey`'s recorded-only bump would skip\n     * and the stale body would be cached.\n     */\n    captureGeneration(method: string, params?: string): number {\n        const gk = genKey(method, params);\n        const current = this._evictionGeneration.get(gk) ?? 0;\n        this._evictionGeneration.set(gk, current);\n        return current;\n    }\n\n    /**\n     * Write `value` under `{method}` unless the per-method generation moved\n     * since `capturedGen` was taken — a `list_changed` that landed mid-walk has\n     * already invalidated the result the caller is about to write, and\n     * overwriting the eviction with the stale aggregate would lose the\n     * invalidation.\n     *\n     * The value is stored as its JSON-serialized document; serialization\n     * doubles as the mutation barrier, so a caller mutating the returned\n     * aggregate cannot reach the cache or its derived indices. A value that\n     * is not JSON-serializable (reachable only via in-process transports)\n     * fails the write loudly into the `reportError` sink. A custom store\n     * whose `set()` throws or rejects is routed to the same sink and the\n     * write resolves — cache bookkeeping never costs the caller a result it\n     * already fetched.\n     *\n     * `freshness` carries the client-computed `expiresAt` (absolute ms epoch,\n     * `now + ttlMs`) and the server-reported `cacheScope`. The storage\n     * `partition` is derived from the scope via `_partitionFor`:\n     * `'public'` → `[serverIdentity, '']` (shared within this server);\n     * `'private'` → `[serverIdentity, cachePartition]` (so a shared store\n     * never serves a private entry to another identity). Absent `freshness`\n     * preserves the substrate write (no `expiresAt`, private partition) — the\n     * `tools/list` retain-for-schema posture: never served by\n     * {@linkcode read}'s freshness gate, always readable by\n     * {@linkcode toolDefinition}.\n     *\n     * After storing under the derived partition, the same `{method, params}`\n     * is deleted from the OPPOSITE partition (mirroring {@linkcode evictKey}'s\n     * two-partition posture). A server that flips a result's `cacheScope` for\n     * the same key would otherwise leave the previous entry in the other slot\n     * — and since `_probe` checks own-partition first, a stale private entry\n     * would shadow the fresh public one (or a stale public entry would keep\n     * serving co-tenants). Both store calls are independently guarded so a\n     * custom store's failure on one does not skip the other.\n     */\n    async write(\n        method: string,\n        value: unknown,\n        capturedGen: number,\n        freshness?: { expiresAt: number; scope: CacheScope; params?: string }\n    ): Promise<void> {\n        if ((this._evictionGeneration.get(genKey(method, freshness?.params)) ?? 0) !== capturedGen) return;\n        const params = freshness?.params ?? '';\n        const ownPartition = this._partitionFor('private');\n        const sharedPartition = this._partitionFor('public');\n        const partition = (freshness?.scope ?? 'private') === 'public' ? sharedPartition : ownPartition;\n        try {\n            await this._store.set(\n                { method, params, partition },\n                { value: encodeCacheValue(value), expiresAt: freshness?.expiresAt, scope: freshness?.scope }\n            );\n        } catch (error) {\n            this._reportError(error);\n        }\n        if (sharedPartition !== ownPartition) {\n            try {\n                await this._store.delete({\n                    method,\n                    params,\n                    partition: partition === ownPartition ? sharedPartition : ownPartition\n                });\n            } catch (error) {\n                this._reportError(error);\n            }\n        }\n    }\n\n    /**\n     * Serve the fresh cached result for `{method, params}`, or `undefined`.\n     * Lookup is the two-probe order (own-partition then this server's shared\n     * partition, gated on `scope === 'public'`); freshness is\n     * `entry.expiresAt > now()` (a missing `expiresAt` is never fresh),\n     * checked BEFORE decoding so stale entries cost no parse. Every hit is\n     * freshly parsed, so the caller owns the value outright. An entry whose\n     * document does not parse or is not an object (corrupted external\n     * store) is reported,\n     * deleted, and treated as a miss — deleted because a fresh-but-corrupt\n     * entry would otherwise re-parse and re-report on every read until its\n     * `expiresAt` passes.\n     */\n    async read(method: string, params?: string): Promise<{ value: unknown } | undefined> {\n        const entry = await this._probe(method, params);\n        if (entry?.expiresAt === undefined || !(entry.expiresAt > this.now())) return undefined;\n        try {\n            const parsed: unknown = JSON.parse(entry.value);\n            if (typeof parsed !== 'object' || parsed === null || Array.isArray(parsed)) {\n                throw new TypeError('cached document is not an object');\n            }\n            return { value: parsed };\n        } catch (error) {\n            this._reportError(error);\n            await this._deleteBoth(method, params ?? '');\n            return undefined;\n        }\n    }\n\n    /**\n     * Connection reset. The per-instance default store IS cleared\n     * (connection-scoped); a user-supplied store is NOT — that would defeat\n     * the only reason to supply one. The generation map and every derived\n     * index are dropped regardless: they are connection-scoped even when the\n     * backing store survives, so the next read re-derives from whatever the\n     * store still holds. The server identity returns to the pre-connect\n     * sentinel. The default impl is synchronous, so the `MaybePromise<void>`\n     * return is a plain void here and the caller need not await.\n     */\n    resetForReconnect(): void {\n        if (!this._isUserSupplied) void this._store.clear();\n        this._evictionGeneration.clear();\n        this._toolIndex = undefined;\n        this._toolOutputValidatorIndex = undefined;\n        this._serverIdentity = '';\n    }\n\n    /**\n     * The descriptor for tool `name` taken from the cached `tools/list` entry.\n     * The `name → Tool` index is memoized against the entry's `stamp` and\n     * re-derived only when the backing entry changes (mcp.d's `cachedTool`).\n     * Returns `undefined` only when no `tools/list` response is held at all,\n     * or the held list does not contain `name`.\n     *\n     * Consumed by `callTool()`'s SEP-2243 `_resolveXMcpHeaderScan` (mirroring)\n     * and, via {@linkcode outputValidator}, its output-schema validation.\n     */\n    async toolDefinition(name: string): Promise<Tool | undefined> {\n        const entry = await this._probe('tools/list');\n        if (entry === undefined) {\n            this._toolIndex = undefined;\n            return undefined;\n        }\n        if (this._toolIndex?.stamp !== entry.stamp) {\n            const list = this._decodeListTools(entry);\n            const byName = new Map<string, Tool>();\n            if (list !== undefined) for (const tool of list.tools) byName.set(tool.name, tool);\n            // A failed decode memoizes an EMPTY index under the same stamp, so\n            // the corrupt document is parsed (and reported) once per stamp —\n            // not once per callTool — and a later rewrite re-derives.\n            this._toolIndex = { stamp: entry.stamp, byName };\n        }\n        return this._toolIndex.byName.get(name);\n    }\n\n    /**\n     * The compiled output-schema validator for tool `name`, derived from the\n     * cached `tools/list` entry — same source and same stamp-keyed\n     * memoization as {@linkcode toolDefinition}. The `name → validator` index\n     * re-derives only when the backing entry's stamp changes (a refetched\n     * `tools/list` recompiles; a `list_changed` eviction drops it). Returns\n     * `undefined` when no `tools/list` is held, the tool is absent, or it has\n     * no `outputSchema`.\n     *\n     * `compile` is the caller-supplied validator-compile callback (the\n     * `Client` passes its `_jsonSchemaValidator` wrapper) so this\n     * class carries no validator-provider dependency. One tool's uncompilable\n     * `outputSchema` (e.g. an invalid `pattern` regex or unresolvable `$ref`)\n     * must not poison every other tool's `callTool` — the callback isolates\n     * that compile error per tool by returning a per-tool error variant which\n     * the index stores alongside the good ones, and `callTool` surfaces it as\n     * a typed `InvalidParams` only for that name. Because the error is held on\n     * this stamp-keyed substrate (not a parallel map), it inherits the\n     * substrate's invalidation lifecycle: a `list_changed` eviction drops it,\n     * a refetched `tools/list` re-derives it, and `resetForReconnect` clears\n     * the lot.\n     */\n    async outputValidator<V>(name: string, compile: (tool: Tool) => V | undefined): Promise<V | undefined> {\n        const entry = await this._probe('tools/list');\n        if (entry === undefined) {\n            this._toolOutputValidatorIndex = undefined;\n            return undefined;\n        }\n        if (this._toolOutputValidatorIndex?.stamp !== entry.stamp) {\n            const list = this._decodeListTools(entry) ?? { tools: [] };\n            const byName = new Map<string, unknown>();\n            for (const tool of list.tools) {\n                const compiled = compile(tool);\n                if (compiled !== undefined) byName.set(tool.name, compiled);\n            }\n            this._toolOutputValidatorIndex = { stamp: entry.stamp, byName };\n        }\n        return this._toolOutputValidatorIndex.byName.get(name) as V | undefined;\n    }\n\n    /** Parse a held `tools/list` document for the index builders; a document\n     * that does not parse OR whose `tools` is not an array of objects\n     * (both mean a corrupted external store) is reported and treated as if\n     * nothing were held. Callers memoize the outcome against the entry's\n     * stamp, so a corrupt document costs one parse + report per stamp, not\n     * per lookup. */\n    private _decodeListTools(entry: CacheEntry): ListToolsResult | undefined {\n        try {\n            const parsed = JSON.parse(entry.value) as ListToolsResult | null;\n            if (!Array.isArray(parsed?.tools) || !parsed.tools.every(t => t !== null && typeof t === 'object')) {\n                throw new TypeError('cached tools/list document has a malformed tools array');\n            }\n            return parsed;\n        } catch (error) {\n            this._reportError(error);\n            return undefined;\n        }\n    }\n}\n\n/**\n * Serialize a result for storage; throws TypeError for anything without a\n * JSON representation (legal wire results always have one). Two failure\n * modes need folding into that one throw: `JSON.stringify` throws on cycles\n * and BigInt, but silently returns `undefined` (not a string) for a\n * top-level function, symbol, or `undefined`.\n */\nfunction encodeCacheValue(value: unknown): string {\n    let json: string | undefined;\n    try {\n        json = JSON.stringify(value);\n    } catch (error) {\n        throw new TypeError(`cache value is not JSON-serializable: ${error instanceof Error ? error.message : String(error)}`);\n    }\n    if (typeof json !== 'string') throw new TypeError('cache value is not JSON-serializable: it has no JSON representation');\n    return json;\n}\n","/**\n * Auth-seam provenance stamp (internal — not part of the public API).\n *\n * Errors escaping a transport auth seam — the `authProvider.token()` read,\n * an `onUnauthorized` invocation (SDK adapter or custom user callback), the\n * 403 step-up flow, the transport's own auth-failure constructions — are\n * stamped at the throw boundary. The version-negotiation probe routes stamped\n * errors as auth outcomes; provenance is recorded where it is known, never\n * reconstructed from error types downstream.\n *\n * `Symbol.for` uses the global symbol registry, so the stamp survives a\n * duplicated SDK copy in one process (bundler double-install, version skew)\n * by design: both copies resolve the same symbol.\n */\nconst AUTH_SEAM = Symbol.for('mcp.authSeamEscape');\n\n/**\n * Stamp `error` as an auth-seam escape and return it — identity-preserving\n * (the same object flows on, `instanceof` and `.cause` chains intact). A\n * frozen/sealed object is returned unstamped rather than replaced: identity\n * outranks provenance. Primitive throws cannot carry the stamp.\n */\nexport function markAuthSeamEscape<T>(error: T): T {\n    if ((typeof error === 'object' && error !== null) || typeof error === 'function') {\n        try {\n            Object.defineProperty(error, AUTH_SEAM, { value: true, configurable: true });\n        } catch {\n            // Frozen/sealed: leave unstamped.\n        }\n    }\n    return error;\n}\n\n/** Whether `error` escaped through a transport auth seam. */\nexport function isAuthSeamEscape(error: unknown): boolean {\n    return (\n        ((typeof error === 'object' && error !== null) || typeof error === 'function') &&\n        (error as Record<PropertyKey, unknown>)[AUTH_SEAM] === true\n    );\n}\n","/**\n * Probe outcome classifier (pure module): maps the outcome of the connect-time\n * `server/discover` probe onto one of four verdicts — modern era, the\n * spec-mandated `-32022` corrective continuation, legacy fallback (the plain\n * 2025 `initialize` handshake — on the probed connection for in-place probes,\n * on the session child's fresh pipe when the probe rode a disposable\n * sibling), or a typed connect error.\n *\n * The classifier is deliberately conservative: anything it does not positively\n * recognize as modern resolves to the legacy fallback, and a network outage or\n * an auth-status rejection (HTTP 401/403) is a typed connect error, never an\n * era verdict. The verdicts apply to the\n * negotiation phase only — an established modern connection is never silently\n * demoted to `initialize` by a later failure.\n */\nimport type { DiscoverResult } from '@modelcontextprotocol/core-internal';\nimport {\n    codecForVersion,\n    MODERN_WIRE_REVISION,\n    modernProtocolVersions,\n    SdkError,\n    SdkErrorCode,\n    SdkHttpError,\n    UnsupportedProtocolVersionError\n} from '@modelcontextprotocol/core-internal';\n\n/**\n * The runtime environment the probe executed in. Only consulted for the\n * network-failure row: a browser CORS-preflight rejection is treated as a\n * legacy signal, while in Node a network failure stays a typed connect error.\n */\nexport type ProbeEnvironment = 'node' | 'browser';\n\n/**\n * The transport class the probe ran on. Consulted for the timeout and closed\n * rows: a stdio probe that times out — or whose child exits, closing the\n * connection — signals a legacy server, while an HTTP timeout or close stays\n * a typed error. Anything that is not the stdio child-process transport is\n * treated like HTTP.\n */\nexport type ProbeTransportKind = 'stdio' | 'http';\n\n/**\n * A normalized probe outcome, produced by the connect-time wiring from the raw\n * transport exchange.\n */\nexport type ProbeOutcome =\n    | { kind: 'result'; result: unknown }\n    /** Answered with a JSON-RPC error (any HTTP status, including 200-bodied errors and stdio in-band errors). */\n    | { kind: 'rpc-error'; code: number; message: string; data?: unknown }\n    /** The HTTP layer rejected the probe POST (non-2xx); `body` is the raw response text and `statusText` the HTTP reason phrase, when available. */\n    | { kind: 'http-error'; status: number; body?: string; statusText?: string }\n    | { kind: 'network-error'; error: unknown }\n    /** The probe was answered 2xx without a usable reply (body is not JSON, or an unaccepted media type); `error` is the transport's failure. */\n    | { kind: 'unusable-reply'; error: unknown }\n    /** The transport's auth flow challenged or failed during the probe send — an error stamped at a transport auth seam, or an `UnauthorizedError` (the foreign-transport contract). `error` propagates unchanged. */\n    | { kind: 'auth-required'; error: Error }\n    /** The transport reported close while the probe awaited its reply. */\n    | { kind: 'closed' }\n    /** No response arrived within the probe timeout. */\n    | { kind: 'timeout'; timeoutMs: number };\n\nexport interface ProbeClassifierContext {\n    /** Modern-era versions this client can negotiate, in preference order (never empty). */\n    clientModernVersions: readonly string[];\n    /** The version the probe carried in its `_meta` envelope (used to synthesize `data.requested` on typed errors). */\n    requestedVersion: string;\n    /**\n     * Whether a legacy `initialize` fallback is possible — `false` for a\n     * modern-only client and for `pin` mode. Without a fallback, rows carrying\n     * modern evidence but no usable version overlap — a `DiscoverResult` with\n     * no overlapping version, or a `-32022` whose `data.supported` lists only\n     * legacy revisions — yield a typed `UnsupportedProtocolVersionError` built\n     * from that evidence; the remaining rows that would have fallen back still\n     * classify as `legacy`, and the caller reports them as a typed negotiation\n     * error instead of starting an `initialize` handshake.\n     */\n    fallbackAvailable: boolean;\n    /** See {@linkcode ProbeEnvironment}. */\n    environment: ProbeEnvironment;\n    /** See {@linkcode ProbeTransportKind}. */\n    transportKind: ProbeTransportKind;\n}\n\nexport type ProbeVerdict =\n    /** Definitive modern evidence: select `version` and continue without `initialize`. */\n    | { kind: 'modern'; version: string; discover: DiscoverResult }\n    /**\n     * `-32022` with a mutual modern version: re-send the probe at `version`.\n     * Spec-mandated select-and-continue — the caller runs it exactly once and\n     * arms a loop guard on the second rejection, throwing `error`.\n     */\n    | { kind: 'corrective'; version: string; error: UnsupportedProtocolVersionError }\n    /** Definitive legacy signal or unrecognized shape: perform the plain legacy `initialize` handshake (on the probed connection in the in-place modes; on the session child's fresh pipe on the sibling path). */\n    | { kind: 'legacy' }\n    /** Typed connect error — never converted to an era verdict. */\n    | { kind: 'error'; error: Error };\n\n/**\n * A cached era verdict for `connect({ prior })` — the persistable subset of\n * the {@linkcode ProbeVerdict} vocabulary (`'modern'` = speaks 2026-07-28+,\n * `'legacy'` = 2025-era `initialize` only). Freshness is the supplying host's\n * responsibility: a stale modern verdict fails loudly at the first request,\n * but a stale legacy verdict succeeds silently forever (an upgraded server\n * still answers `initialize`) — date cached legacy verdicts in your own\n * storage and stop supplying them past your policy horizon. Full recipe:\n * the gateway guide (`docs/advanced/gateway.md`).\n */\nexport type PriorDiscovery =\n    /** Adopt `discover` directly: zero round trips. */\n    | { kind: 'modern'; discover: DiscoverResult }\n    /** Known-legacy server: skip the `server/discover` probe and run the plain legacy `initialize` handshake. */\n    | { kind: 'legacy' };\n\n/** The `-32022` UnsupportedProtocolVersion protocol error code (negotiation-phase recognition). */\nconst UNSUPPORTED_PROTOCOL_VERSION = -32_022;\n/**\n * Deliberately not probe-recognized in either direction: deployed servers\n * overload `-32001` (the SDK-conventional `Session not found` body on a 2025\n * stateful server), and the spec-assigned `-32020` (`HeaderMismatch`) /\n * `-32021` (`MissingRequiredClientCapability`) are not era evidence — all\n * fall into the conservative legacy default.\n */\nconst NOT_PROBE_RECOGNIZED = new Set([-32_001, -32_020, -32_021]);\n\n/**\n * Classify a single probe outcome. Pure: no I/O, no state — loop-guard and\n * retry state live in the caller.\n */\nexport function classifyProbeOutcome(outcome: ProbeOutcome, context: ProbeClassifierContext): ProbeVerdict {\n    switch (outcome.kind) {\n        case 'result': {\n            return classifyResult(outcome.result, context);\n        }\n        case 'rpc-error': {\n            return classifyRpcError(outcome, context);\n        }\n        case 'http-error': {\n            return classifyHttpError(outcome, context);\n        }\n        case 'network-error': {\n            return classifyNetworkError(outcome.error, context);\n        }\n        case 'unusable-reply': {\n            // An unreadable 2xx is not era evidence: reject and say what was answered, never fall back.\n            return {\n                kind: 'error',\n                error: new SdkError(\n                    SdkErrorCode.EraNegotiationFailed,\n                    `Version negotiation probe failed: the server answered with an unusable reply (${describeError(outcome.error)})`,\n                    { cause: outcome.error },\n                    { cause: outcome.error }\n                )\n            };\n        }\n        case 'auth-required': {\n            // Not era evidence: propagate the auth challenge unchanged so the\n            // caller can run finishAuth() and reconnect — the reconnect probes\n            // again with the token and settles the era with real evidence.\n            // Converting to a legacy fallback here would re-run the auth flow\n            // inside the same connect (a second authorization prompt) and then\n            // handshake an auth-gated modern server as legacy.\n            return { kind: 'error', error: outcome.error };\n        }\n        case 'closed': {\n            if (context.transportKind === 'stdio') {\n                // A stdio child that exits on the unrecognized probe instead of\n                // answering is a legacy signal — the same backward-compatibility\n                // rule as the timeout row below (SDKs like the official Rust one\n                // terminate the server on ANY pre-initialize request).\n                return { kind: 'legacy' };\n            }\n            // On HTTP a mid-probe close is an ambiguous network condition — the\n            // same typed connect error as any probe transport failure.\n            return classifyNetworkError(new Error('Connection closed during the version negotiation probe'), context);\n        }\n        case 'timeout': {\n            if (context.transportKind === 'stdio') {\n                // Per the stdio transport's backward-compatibility rule, a probe\n                // nobody answers within the timeout indicates a legacy server —\n                // fall back to `initialize` (the sibling path runs it on the\n                // session child's fresh pipe; in-place probes reuse the stream).\n                return { kind: 'legacy' };\n            }\n            // On HTTP a deployed server answers, so silence is an outage, not a\n            // legacy signal: keep the typed timeout error (the compatibility\n            // matrix keys the HTTP legacy signal to a 4xx, never to silence).\n            return {\n                kind: 'error',\n                error: new SdkError(SdkErrorCode.RequestTimeout, `Version negotiation probe timed out after ${outcome.timeoutMs}ms`, {\n                    timeout: outcome.timeoutMs\n                })\n            };\n        }\n    }\n}\n\nfunction classifyResult(result: unknown, context: ProbeClassifierContext): ProbeVerdict {\n    // The 2026 wire schema carries the spec receiver-side leniency for\n    // `resultType` ('complete'), `ttlMs` (0) and `cacheScope` ('private'), so\n    // routing through the codec is behavior-neutral with the prior public-schema\n    // parse for absent and malformed cache hints (`.catch()` per spec receiver\n    // leniency): a server that omits or malforms them still classifies `modern`.\n    const parsed = codecForVersion(MODERN_WIRE_REVISION).validateResult('server/discover', result);\n    if (!parsed.ok) {\n        // Unrecognized result shape: not modern evidence — conservative legacy fallback.\n        return { kind: 'legacy' };\n    }\n    const supportedVersions = parsed.value.supportedVersions;\n    const overlap = context.clientModernVersions.find(version => supportedVersions.includes(version));\n    if (overlap !== undefined) {\n        return { kind: 'modern', version: overlap, discover: parsed.value };\n    }\n    // A DiscoverResult with no overlap still drives era selection: the legacy\n    // `initialize` fallback when available, otherwise a typed error.\n    if (context.fallbackAvailable) {\n        return { kind: 'legacy' };\n    }\n    return {\n        kind: 'error',\n        error: new UnsupportedProtocolVersionError({ supported: [...supportedVersions], requested: context.requestedVersion })\n    };\n}\n\nfunction classifyRpcError(outcome: { code: number; message: string; data?: unknown }, context: ProbeClassifierContext): ProbeVerdict {\n    const { code, message, data } = outcome;\n\n    if (code === UNSUPPORTED_PROTOCOL_VERSION) {\n        const supported = parseSupportedList(data);\n        if (supported === undefined) {\n            // -32022 without a valid data.supported list is not actionable modern evidence.\n            return { kind: 'legacy' };\n        }\n        const requested = parseRequested(data) ?? context.requestedVersion;\n        const error = new UnsupportedProtocolVersionError({ supported, requested }, message);\n        const supportedModern = modernProtocolVersions(supported);\n        const mutual = context.clientModernVersions.find(version => supportedModern.includes(version));\n        if (mutual !== undefined) {\n            // Mutual modern version: spec-mandated select-and-continue — never\n            // fall back to initialize here.\n            return { kind: 'corrective', version: mutual, error };\n        }\n        if (supportedModern.length > 0) {\n            // Disjoint-but-modern list: typed error, never initialize.\n            return { kind: 'error', error };\n        }\n        // Legacy-only list: definitive legacy signal (typed error for a modern-only client).\n        return context.fallbackAvailable ? { kind: 'legacy' } : { kind: 'error', error };\n    }\n\n    if (NOT_PROBE_RECOGNIZED.has(code)) {\n        return { kind: 'legacy' };\n    }\n\n    // Everything else — -32601, the deployed -32000 literals/free-text, code 0,\n    // any unrecognized code — is a legacy signal or the conservative default.\n    return { kind: 'legacy' };\n}\n\nfunction classifyHttpError(outcome: { status: number; body?: string; statusText?: string }, context: ProbeClassifierContext): ProbeVerdict {\n    // Auth statuses are never era evidence, and a 401/403 body is the auth\n    // layer's, not the server/discover handler's — this row ranks above the\n    // JSON-RPC body parse. Parallel to the auth-required row: a typed failure\n    // naming the status (response text on `data.text`), never a legacy\n    // fallback. The codes are the auth ones, NOT EraNegotiationFailed: hosts\n    // key era-recovery recipes (e.g. the gateway guide's cached-verdict flow)\n    // on EraNegotiationFailed, and an auth wall must never enter era recovery\n    // — persisting a legacy verdict for it would recreate the silent-legacy\n    // bug at the fleet level.\n    if (outcome.status === 401 || outcome.status === 403) {\n        const isDenial = outcome.status === 403;\n        return {\n            kind: 'error',\n            error: new SdkHttpError(\n                isDenial ? SdkErrorCode.ClientHttpForbidden : SdkErrorCode.ClientHttpAuthentication,\n                `Version negotiation failed: ${isDenial ? 'the server denied access (HTTP 403)' : 'the server requires authorization (HTTP 401)'}`,\n                {\n                    status: outcome.status,\n                    statusText: outcome.statusText,\n                    text: outcome.body\n                }\n            )\n        };\n    }\n    if (outcome.status >= 500) {\n        // A server failure is not era evidence, whatever the body says — this\n        // row too ranks above the JSON-RPC body parse (a 5xx body is the\n        // infrastructure's: a mid-deploy gateway's JSON error page, a crashed\n        // handler's -32603, neither a server/discover verdict). The spec keys\n        // the HTTP legacy signal to client-error rejections (a 2025 server\n        // answers the unknown probe 4xx), never to 5xx.\n        return {\n            kind: 'error',\n            error: new SdkHttpError(\n                SdkErrorCode.EraNegotiationFailed,\n                `Version negotiation failed: the server answered the probe with HTTP ${outcome.status}`,\n                {\n                    status: outcome.status,\n                    statusText: outcome.statusText,\n                    text: outcome.body\n                }\n            )\n        };\n    }\n    // HTTP-rejected probes carry their JSON-RPC error in the response body — classify it like an in-band error.\n    const rpcError = parseJsonRpcErrorBody(outcome.body);\n    if (rpcError !== undefined) {\n        return classifyRpcError(rpcError, context);\n    }\n    // Unparseable or unrecognized 4xx rejection: conservative legacy fallback.\n    // With the auth and 5xx rows above, this row's legacy set now equals the\n    // spec-licensed set exactly — the 4xx a deployed 2025 server answers a\n    // request it does not recognize.\n    return { kind: 'legacy' };\n}\n\nfunction classifyNetworkError(error: unknown, context: ProbeClassifierContext): ProbeVerdict {\n    if (context.environment === 'browser' && isOpaqueFetchTypeError(error)) {\n        // A browser CORS-preflight rejection against a deployed 2025 server is\n        // an opaque TypeError. The legacy fallback also preflights (its JSON\n        // Content-Type is non-simple), but carries only the pre-2026 headers a\n        // deployed server's CORS allowlist already covers — so it can proceed\n        // where the probe's 2026 headers could not.\n        return { kind: 'legacy' };\n    }\n    return {\n        kind: 'error',\n        error: new SdkError(\n            SdkErrorCode.EraNegotiationFailed,\n            `Version negotiation probe failed: ${describeError(error)}`,\n            // Keep data.cause for existing consumers while also exposing the\n            // standard Error.cause chain (#2657).\n            { cause: error },\n            { cause: error }\n        )\n    };\n}\n\nfunction isOpaqueFetchTypeError(error: unknown): boolean {\n    // Cross-realm safe: a bundled or sandboxed fetch may not share this realm's TypeError identity.\n    return error instanceof TypeError || (error instanceof Error && error.name === 'TypeError');\n}\n\nfunction describeError(error: unknown): string {\n    return error instanceof Error ? error.message : String(error);\n}\n\nfunction parseSupportedList(data: unknown): string[] | undefined {\n    if (typeof data !== 'object' || data === null) return undefined;\n    const supported = (data as { supported?: unknown }).supported;\n    if (!Array.isArray(supported) || supported.length === 0 || !supported.every(v => typeof v === 'string')) {\n        return undefined;\n    }\n    return supported as string[];\n}\n\nfunction parseRequested(data: unknown): string | undefined {\n    if (typeof data !== 'object' || data === null) return undefined;\n    const requested = (data as { requested?: unknown }).requested;\n    return typeof requested === 'string' ? requested : undefined;\n}\n\nfunction parseJsonRpcErrorBody(body: string | undefined): { code: number; message: string; data?: unknown } | undefined {\n    if (body === undefined || body === '') return undefined;\n    let parsed: unknown;\n    try {\n        parsed = JSON.parse(body);\n    } catch {\n        return undefined;\n    }\n    if (typeof parsed !== 'object' || parsed === null) return undefined;\n    const error = (parsed as { error?: unknown }).error;\n    if (typeof error !== 'object' || error === null) return undefined;\n    const { code, message, data } = error as { code?: unknown; message?: unknown; data?: unknown };\n    if (typeof code !== 'number') return undefined;\n    return { code, message: typeof message === 'string' ? message : '', data };\n}\n","/**\n * Connect-time protocol version negotiation (opt-in via\n * `ClientOptions.versionNegotiation`): the option surface, the probe window (a\n * raw transport exchange run before the Protocol machinery attaches), and the\n * negotiation engine driving the pure {@linkcode classifyProbeOutcome} classifier.\n *\n * Invariants: the probe uses string ids and consumes no Protocol message ids, so\n * a legacy fallback's `initialize` is byte-equivalent to a plain legacy connect;\n * the transport's protocol-version slot is never mutated during negotiation\n * (probe headers derive from the probe message body) and is set exactly once\n * after a modern resolution; while the probe window is open, inbound messages\n * that are not the probe response are dropped with zero bytes written back.\n */\nimport type { ClientCapabilities, DiscoverResult, Implementation, JSONRPCRequest, Transport } from '@modelcontextprotocol/core-internal';\nimport {\n    codecForVersion,\n    isJSONRPCErrorResponse,\n    isJSONRPCResultResponse,\n    isModernProtocolVersion,\n    legacyProtocolVersions,\n    modernProtocolVersions,\n    SdkError,\n    SdkErrorCode,\n    SdkHttpError,\n    SUPPORTED_MODERN_PROTOCOL_VERSIONS\n} from '@modelcontextprotocol/core-internal';\n\nimport { UnauthorizedError } from './auth';\nimport { isAuthSeamEscape } from './authSeam';\nimport type { ProbeEnvironment, ProbeOutcome, ProbeTransportKind, ProbeVerdict } from './probeClassifier';\nimport { classifyProbeOutcome } from './probeClassifier';\n\n/**\n * Probe policy for `'auto'` and pinned negotiation modes.\n *\n * There is no special probe timeout opinion: the probe inherits the client's\n * STANDARD request timeout unless `timeoutMs` overrides it.\n */\nexport interface VersionNegotiationProbeOptions {\n    /**\n     * Timeout for the probe exchange, in milliseconds.\n     *\n     * The timeout verdict is transport-aware: on stdio, a probe that gets no\n     * response within the timeout indicates a legacy server and falls back to\n     * the `initialize` handshake (measured on the disposable sibling for the\n     * SDK's own stdio transport, with the fallback running on the session\n     * child's fresh pipe; in place for custom stdio-shaped transports); on\n     * HTTP, where a deployed server answers and silence means an outage,\n     * `connect()` rejects with the standard typed timeout error instead.\n     *\n     * @default the standard request timeout (`DEFAULT_REQUEST_TIMEOUT_MSEC`, or the `timeout` passed to `connect()`)\n     */\n    timeoutMs?: number;\n\n    /**\n     * Number of times to re-send the probe after a timeout before reaching the\n     * timeout verdict. Governs timeout re-sends only — the spec-mandated\n     * `-32022` corrective continuation (select-and-continue with a mutual\n     * version) is a separate negotiation step and is never counted against\n     * `maxRetries`.\n     *\n     * @default 0 (no retries)\n     */\n    maxRetries?: number;\n}\n\n/**\n * Negotiation mode:\n *\n * - `'legacy'` — no negotiation: the plain 2025 connect sequence, byte-identical\n *   to a client without this option.\n * - `'auto'` — probe with `server/discover` at connect; conservative fallback to\n *   the plain legacy `initialize` handshake unless the outcome is definitive\n *   modern evidence. Network outage rejects with a typed connect error; a\n *   probe timeout falls back to `initialize` on stdio (a silent server on a\n *   local pipe is a legacy server) and rejects with a typed timeout error on\n *   HTTP (silence there is an outage). On the SDK's stdio transport (the base\n *   `StdioClientTransport` exactly; subclasses probe in place) the probe\n *   runs on a short-lived sibling process spawned from the same parameters\n *   (its stderr is discarded) and the caller's transport starts once, after\n *   the era is known — so a child that exits on the unrecognized probe, the\n *   shape of servers built on SDKs that terminate on any pre-`initialize`\n *   request, is simply a legacy server. A mid-probe connection close on HTTP\n *   (or on a custom stdio-shaped transport, which probes in place) rejects\n *   with the typed connect error.\n * - `{ pin: '<version>' }` — modern era at exactly the pinned revision: the\n *   connect-time `server/discover` must offer it. No fallback — anything else\n *   fails loudly with a typed error.\n */\nexport type VersionNegotiationMode = 'legacy' | 'auto' | { pin: string };\n\n/**\n * Opt-in protocol version negotiation, configured on\n * `ClientOptions.versionNegotiation`.\n */\nexport interface VersionNegotiationOptions {\n    /**\n     * @default 'legacy'\n     */\n    mode?: VersionNegotiationMode;\n\n    /**\n     * Probe timeout/retry policy (only consulted by the probing modes).\n     */\n    probe?: VersionNegotiationProbeOptions;\n}\n\n/**\n * The default mode when `versionNegotiation` (or its `mode`) is absent;\n * changing the default later is a flip of this single line.\n */\nconst DEFAULT_VERSION_NEGOTIATION_MODE: VersionNegotiationMode = 'legacy';\n\n/** A fully resolved negotiation plan for one `connect()` call. */\nexport type ResolvedVersionNegotiation =\n    | { kind: 'legacy' }\n    | {\n          kind: 'auto';\n          /** Modern versions this client offers, in preference order (never empty). */\n          modernVersions: string[];\n          /** Whether this client can fall back to the legacy `initialize` handshake. */\n          fallbackAvailable: boolean;\n          probe: VersionNegotiationProbeOptions;\n      }\n    | { kind: 'pin'; version: string; probe: VersionNegotiationProbeOptions };\n\n/**\n * Resolve the negotiation options into a per-connect plan. The raw (not\n * defaulted) `supportedProtocolVersions` option supplies the modern offer list;\n * a list without any legacy version makes this a modern-only client (no fallback).\n */\nexport function resolveVersionNegotiation(\n    options: VersionNegotiationOptions | undefined,\n    supportedProtocolVersionsOption: readonly string[] | undefined\n): ResolvedVersionNegotiation {\n    const mode = options?.mode ?? DEFAULT_VERSION_NEGOTIATION_MODE;\n    if (mode === 'legacy') {\n        return { kind: 'legacy' };\n    }\n    const probe = options?.probe ?? {};\n    if (typeof mode === 'object') {\n        if (!isModernProtocolVersion(mode.pin)) {\n            throw new TypeError(\n                `versionNegotiation: { pin: '${mode.pin}' } is not a modern protocol revision — ` +\n                    `pinning is for 2026-07-28 and later; omit versionNegotiation (or use mode: 'legacy') for 2025-era servers.`\n            );\n        }\n        return { kind: 'pin', version: mode.pin, probe };\n    }\n    const explicitModern = supportedProtocolVersionsOption ? modernProtocolVersions(supportedProtocolVersionsOption) : [];\n    const modernVersions = explicitModern.length > 0 ? explicitModern : [...SUPPORTED_MODERN_PROTOCOL_VERSIONS];\n    const fallbackAvailable = supportedProtocolVersionsOption ? legacyProtocolVersions(supportedProtocolVersionsOption).length > 0 : true;\n    return { kind: 'auto', modernVersions, fallbackAvailable, probe };\n}\n\n/** Detect the probe environment for the network-failure row — see {@linkcode ProbeEnvironment}. */\nexport function detectProbeEnvironment(): ProbeEnvironment {\n    const g = globalThis as { window?: unknown; document?: unknown };\n    return g.window !== undefined && g.document !== undefined ? 'browser' : 'node';\n}\n\n/**\n * Detect the transport class for the transport-aware timeout and closed verdicts (see\n * {@linkcode ProbeTransportKind}). The stdio child-process transport is\n * recognized structurally (`stderr`/`pid` accessors, no `instanceof` — safe\n * across bundles); everything else is treated like HTTP.\n */\nexport function detectProbeTransportKind(transport: Transport): ProbeTransportKind {\n    return 'stderr' in transport && 'pid' in transport ? 'stdio' : 'http';\n}\n\n/** Raw reply from one probe exchange, before normalization. */\ntype RawProbeReply =\n    | { kind: 'response'; result?: unknown; error?: { code: number; message: string; data?: unknown } }\n    | { kind: 'send-error'; error: unknown }\n    | { kind: 'closed' }\n    | { kind: 'timeout' };\n\n/**\n * Temporary ownership of a raw transport for the negotiation exchange, before\n * the Protocol machinery attaches. `open()` installs the window's handlers and\n * starts the transport; `release()` detaches them and arms a one-shot `start()`\n * pass-through so the subsequent Protocol connect (which always starts its\n * transport) takes over the already-started channel without a double-start error.\n *\n * Handlers a caller pre-set on the transport before `connect()` are saved on\n * open and restored on detach, so `Protocol.connect()` finds and chains them\n * exactly as it would on a plain (non-negotiating) connect. Error and close\n * events are forwarded to the saved handlers during the window, so negotiation\n * does not change what a pre-attached observer sees of the transport\n * lifecycle. (Inbound messages are deliberately NOT forwarded — the window's\n * drop-guard is a module invariant, and the probe reply has no plain-connect\n * counterpart; a pre-set `onmessage` is restored at detach and chained by\n * `Protocol.connect()` like the others.)\n */\nclass ProbeWindow {\n    private _pending: { id: string; resolve: (reply: RawProbeReply) => void } | undefined;\n    private _probeCounter = 0;\n    private readonly _savedOnMessage: Transport['onmessage'];\n    private readonly _savedOnError: Transport['onerror'];\n    private readonly _savedOnClose: Transport['onclose'];\n    private _closeDelivered = false;\n\n    private constructor(private readonly _transport: Transport) {\n        this._savedOnMessage = _transport.onmessage;\n        this._savedOnError = _transport.onerror;\n        this._savedOnClose = _transport.onclose;\n    }\n\n    static async open(transport: Transport): Promise<ProbeWindow> {\n        const window = new ProbeWindow(transport);\n        transport.onmessage = message => {\n            const pending = window._pending;\n            if (\n                pending !== undefined &&\n                (isJSONRPCResultResponse(message) || isJSONRPCErrorResponse(message)) &&\n                message.id === pending.id\n            ) {\n                window._pending = undefined;\n                if (isJSONRPCResultResponse(message)) {\n                    pending.resolve({ kind: 'response', result: message.result });\n                } else {\n                    pending.resolve({ kind: 'response', error: message.error });\n                }\n                return;\n            }\n            // Probe-window guard: drop everything else with zero bytes written back (see module doc).\n        };\n        transport.onerror = error => {\n            // Out-of-band transport errors are not necessarily fatal; the probe\n            // resolves via a send failure, the close signal, or the timeout.\n            window._savedOnError?.(error);\n        };\n        transport.onclose = () => {\n            const pending = window._pending;\n            if (pending !== undefined) {\n                window._pending = undefined;\n                pending.resolve({ kind: 'closed' });\n            }\n            // Forward exactly once: after a mid-window close is delivered, the\n            // restored handler must not re-deliver it when cleanup paths call\n            // `transport.close()` again.\n            window._closeDelivered = true;\n            window._savedOnClose?.();\n        };\n        try {\n            await transport.start();\n        } catch (error) {\n            window.detach();\n            throw error;\n        }\n        return window;\n    }\n\n    /**\n     * Send one probe request and await its reply. Probe ids are strings, so they\n     * never collide with Protocol's numeric ids (e.g. on a shared stdio pipe).\n     */\n    async exchange(buildRequest: (id: string) => JSONRPCRequest, timeoutMs: number): Promise<RawProbeReply> {\n        const id = `server-discover-probe-${++this._probeCounter}`;\n        return new Promise<RawProbeReply>(resolve => {\n            let settled = false;\n            const settle = (reply: RawProbeReply) => {\n                if (settled) return;\n                settled = true;\n                clearTimeout(timer);\n                if (this._pending?.id === id) {\n                    this._pending = undefined;\n                }\n                resolve(reply);\n            };\n            const timer = setTimeout(() => settle({ kind: 'timeout' }), timeoutMs);\n            this._pending = { id, resolve: settle };\n            this._transport.send(buildRequest(id)).catch((error: unknown) => settle({ kind: 'send-error', error }));\n        });\n    }\n\n    /** Detach the window's handlers, restoring any the caller pre-set, leaving the transport's own `start` untouched. */\n    detach(): void {\n        this._pending = undefined;\n        this._transport.onmessage = this._savedOnMessage;\n        this._transport.onerror = this._savedOnError;\n        if (this._closeDelivered && this._savedOnClose !== undefined) {\n            // The forwarded mid-window close is spent — the caller's cleanup\n            // close() must not re-deliver it — but the slot must not be emptied\n            // either: the caller still owns the transport, and its observer must\n            // keep seeing later closes. The skip is scoped to the cleanup close\n            // via disarmSpentCloseGuard(): transports whose close() re-fires\n            // onclose (HTTP) consume it there; transports that never re-fire\n            // (stdio: onclose comes only from the child's close event, which\n            // already happened) would otherwise leave it armed to swallow the\n            // NEXT genuine close after a restart.\n            const saved = this._savedOnClose;\n            const transport = this._transport;\n            let spent = false;\n            const wrapper = () => {\n                if (!spent) {\n                    spent = true;\n                    return;\n                }\n                saved();\n            };\n            transport.onclose = wrapper;\n            pendingSpentCloseGuards.set(transport, () => {\n                // Restore by identity — never clobber a handler the caller\n                // replaced in the meantime.\n                if (transport.onclose === wrapper) {\n                    transport.onclose = saved;\n                }\n            });\n        } else {\n            this._transport.onclose = this._savedOnClose;\n        }\n    }\n\n    /** Detach the handlers and arm the one-shot `start()` pass-through for the `Protocol.connect()` handover. */\n    release(): void {\n        this.detach();\n        const transport = this._transport;\n        // Save the raw property value (not a bound copy) so the restore below\n        // returns `transport.start` to its original identity — no wrapper or\n        // bind layer accretes across repeated connects on the same transport.\n        const originalStart = transport.start;\n        let armed = true;\n        transport.start = async function (this: unknown): Promise<void> {\n            if (armed) {\n                armed = false;\n                transport.start = originalStart;\n                return;\n            }\n            return originalStart.call(transport);\n        };\n    }\n}\n\n/**\n * Spent-close guards from failed negotiations, pending disarm by the cleanup\n * site (keyed weakly — an abandoned transport carries its guard to GC).\n */\nconst pendingSpentCloseGuards = new WeakMap<Transport, () => void>();\n\n/**\n * Disarm a failed negotiation's spent-close guard once the cleanup `close()`\n * has settled. Any re-delivery of the spent mid-window close happens DURING\n * that close (HTTP transports re-fire `onclose` there; stdio transports never\n * do — their close event already fired), so after it every close is genuine\n * and must reach the caller's pre-set observer.\n */\nexport function disarmSpentCloseGuard(transport: Transport): void {\n    const disarm = pendingSpentCloseGuards.get(transport);\n    pendingSpentCloseGuards.delete(transport);\n    disarm?.();\n}\n\n/** Build the probe request: `server/discover` carrying the full per-request `_meta` envelope. */\nexport function buildProbeRequest(\n    id: string,\n    protocolVersion: string,\n    clientInfo: Implementation,\n    capabilities: ClientCapabilities\n): JSONRPCRequest {\n    return {\n        jsonrpc: '2.0',\n        id,\n        method: 'server/discover',\n        params: {\n            // The era codec owns the keyed-envelope shape; the probe is sent\n            // for a modern version, so this is always the 2026 envelope.\n            _meta: codecForVersion(protocolVersion).outboundEnvelope({\n                protocolVersion,\n                clientInfo,\n                clientCapabilities: capabilities\n            })\n        }\n    };\n}\n\n/** True for what the transport throws when the probe was answered 2xx without a usable reply. */\nfunction isUnusableReplyError(error: unknown): boolean {\n    if (error instanceof SdkError && error.code === SdkErrorCode.ClientHttpUnexpectedContent) {\n        return true;\n    }\n    // Matched by name: this is what response.json() throws for a body that is not JSON.\n    return error instanceof Error && error.name === 'SyntaxError';\n}\n\nfunction normalizeReply(reply: RawProbeReply, timeoutMs: number): ProbeOutcome {\n    switch (reply.kind) {\n        case 'response': {\n            return reply.error === undefined ? { kind: 'result', result: reply.result } : { kind: 'rpc-error', ...reply.error };\n        }\n        case 'send-error': {\n            const error = reply.error;\n            const isAuthOutcome =\n                // Provenance recorded at the throw boundary: the transport\n                // stamps every error escaping one of its auth seams (the\n                // token() read, onUnauthorized invocations — SDK flow and\n                // custom callbacks alike — the 403 step-up method, and its\n                // own auth-failure constructions). Never reconstructed here\n                // from error types.\n                isAuthSeamEscape(error) ||\n                // The published contract for foreign transports: an\n                // UnauthorizedError by brand, or by name for one thrown by a\n                // differently bundled SDK copy at a skewed version or an auth\n                // middleware's own class.\n                error instanceof UnauthorizedError ||\n                (error instanceof Error && error.name === 'UnauthorizedError');\n            if (isAuthOutcome) {\n                // Auth-gated server: propagate unchanged.\n                return { kind: 'auth-required', error: error as Error };\n            }\n            if (error instanceof SdkHttpError) {\n                const text = (error.data as { text?: unknown } | undefined)?.text;\n                return {\n                    kind: 'http-error',\n                    status: error.data.status,\n                    body: typeof text === 'string' ? text : undefined,\n                    statusText: error.data.statusText\n                };\n            }\n            if (isUnusableReplyError(error)) {\n                return { kind: 'unusable-reply', error };\n            }\n            return { kind: 'network-error', error };\n        }\n        case 'closed': {\n            // Not folded into network-error: the classifier's closed row is\n            // transport-aware (stdio legacy signal vs typed error).\n            return { kind: 'closed' };\n        }\n        case 'timeout': {\n            return { kind: 'timeout', timeoutMs };\n        }\n    }\n}\n\nexport interface NegotiationDeps {\n    transport: Transport;\n    clientInfo: Implementation;\n    capabilities: ClientCapabilities;\n    environment: ProbeEnvironment;\n    /** The transport class, for the transport-aware timeout and closed verdicts (see {@linkcode ProbeTransportKind}). */\n    transportKind: ProbeTransportKind;\n    /** The standard request timeout for this connect (probe inherits it unless `probe.timeoutMs` overrides). */\n    defaultTimeoutMs: number;\n    /**\n     * The probe transport is a disposable sibling (see\n     * {@linkcode negotiateStdioViaSibling}): a mid-probe close is ordinary\n     * legacy evidence — the probe child spent itself — never a connect-fatal\n     * condition. Absent for in-place probes, where a closed connection has no\n     * fallback stream and stays a typed error.\n     */\n    disposableProbe?: boolean;\n}\n\nexport type NegotiationResult = { era: 'modern'; version: string; discover: DiscoverResult } | { era: 'legacy' };\n\n/**\n * Run the negotiation probe state machine on a raw (not yet Protocol-connected)\n * transport. Resolves with the negotiated era; throws typed connect errors. On\n * return the probe window has been released: the transport is started,\n * handler-free, and ready for `Protocol.connect()` handover. On throw the\n * window is detached and the transport's `start` is left untouched.\n */\nexport async function negotiateEra(\n    negotiation: Extract<ResolvedVersionNegotiation, { kind: 'auto' | 'pin' }>,\n    deps: NegotiationDeps\n): Promise<NegotiationResult> {\n    const timeoutMs = negotiation.probe.timeoutMs ?? deps.defaultTimeoutMs;\n    const maxRetries = Math.max(0, negotiation.probe.maxRetries ?? 0);\n    const clientModernVersions = negotiation.kind === 'pin' ? [negotiation.version] : negotiation.modernVersions;\n    const fallbackAvailable = negotiation.kind === 'auto' && negotiation.fallbackAvailable;\n\n    const window = await ProbeWindow.open(deps.transport);\n\n    const probe = async (): Promise<NegotiationResult> => {\n        let requestedVersion = clientModernVersions[0]!;\n        // The -32022 corrective continuation runs exactly once (even when the\n        // mutual version equals the just-rejected one); the loop guard arms on\n        // the second rejection.\n        let correctiveUsed = false;\n        // `maxRetries` governs timeout re-sends only — independent of (and\n        // never counted against) the corrective continuation.\n        let timeoutRetriesRemaining = maxRetries;\n        for (;;) {\n            const reply = await window.exchange(\n                id => buildProbeRequest(id, requestedVersion, deps.clientInfo, deps.capabilities),\n                timeoutMs\n            );\n\n            if (reply.kind === 'timeout' && timeoutRetriesRemaining > 0) {\n                timeoutRetriesRemaining--;\n                continue;\n            }\n\n            const outcome = normalizeReply(reply, timeoutMs);\n            const verdict: ProbeVerdict = classifyProbeOutcome(outcome, {\n                clientModernVersions,\n                requestedVersion,\n                fallbackAvailable,\n                environment: deps.environment,\n                transportKind: deps.transportKind\n            });\n\n            switch (verdict.kind) {\n                case 'modern': {\n                    return { era: 'modern', version: verdict.version, discover: verdict.discover };\n                }\n                case 'corrective': {\n                    if (correctiveUsed) {\n                        // Second rejection: loop guard.\n                        throw verdict.error;\n                    }\n                    correctiveUsed = true;\n                    requestedVersion = verdict.version;\n                    continue;\n                }\n                case 'legacy': {\n                    // A closed outcome carries its own cause — diagnostics must\n                    // name the close instead of implying a server/discover\n                    // verdict that never happened.\n                    const closedCause = outcome.kind === 'closed' ? 'the connection closed during the server/discover probe' : undefined;\n                    if (negotiation.kind === 'pin') {\n                        throw new SdkError(\n                            SdkErrorCode.EraNegotiationFailed,\n                            closedCause === undefined\n                                ? `Version negotiation failed: the server did not offer pinned protocol version ${negotiation.version} ` +\n                                  `via server/discover (no fallback in pin mode)`\n                                : `Version negotiation failed: ${closedCause} before the server offered ` +\n                                  `pinned protocol version ${negotiation.version} (no fallback in pin mode)`\n                        );\n                    }\n                    if (!negotiation.fallbackAvailable) {\n                        // Modern-only client: the legacy initialize fallback is\n                        // unavailable and must never carry a 2026-era version string.\n                        throw new SdkError(\n                            SdkErrorCode.EraNegotiationFailed,\n                            closedCause === undefined\n                                ? 'Version negotiation failed: the server gave no modern evidence and this client supports no ' +\n                                  'pre-2026-07-28 protocol version to fall back to'\n                                : `Version negotiation failed: ${closedCause} and this client supports no ` +\n                                  'pre-2026-07-28 protocol version to fall back to'\n                        );\n                    }\n                    if (closedCause !== undefined && deps.disposableProbe !== true) {\n                        // In-place probe: the connection died with the child and\n                        // there is no disposable sibling to spend — the\n                        // same-stream initialize fallback is impossible, so this\n                        // stays a typed connect error.\n                        throw new SdkError(\n                            SdkErrorCode.EraNegotiationFailed,\n                            `Version negotiation failed: ${closedCause} ` +\n                                \"(this transport probed in place — the disposable sibling probe requires the SDK's base StdioClientTransport)\"\n                        );\n                    }\n                    return { era: 'legacy' };\n                }\n                case 'error': {\n                    throw verdict.error;\n                }\n            }\n        }\n    };\n\n    let result: NegotiationResult;\n    try {\n        result = await probe();\n    } catch (error) {\n        // A failed negotiation leaves the transport exactly as it found it:\n        // handlers detached, original start untouched (no pass-through armed).\n        window.detach();\n        throw error;\n    }\n    window.release();\n    return result;\n}\n\n/**\n * Structural read of the SDK stdio transport's retained spawn parameters —\n * `undefined` for stdio-shaped transports that do not expose them, and for\n * SUBCLASSES of the SDK transport (those probe in place, where a mid-probe\n * close stays a typed connect error). The sibling path requires the transport\n * to be exactly the base class: a subclass cannot be faithfully cloned by\n * re-invoking its constructor with the retained params alone (extra ctor\n * arguments, transformed state, side effects). Exactness is checked without\n * importing the class (the negotiation graph must stay runtime-neutral): only\n * the base class's own prototype carries the internal `_dispose` reaper the\n * sibling flow depends on — a subclass's prototype does not own it.\n */\nexport function readStdioServerParams(transport: Transport): Record<string, unknown> | undefined {\n    const proto = Object.getPrototypeOf(transport) as object | null;\n    if (proto === null || !Object.prototype.hasOwnProperty.call(proto, '_dispose')) {\n        return undefined;\n    }\n    const params = (transport as { _serverParams?: unknown })._serverParams;\n    return typeof params === 'object' && params !== null && typeof (params as { command?: unknown }).command === 'string'\n        ? (params as Record<string, unknown>)\n        : undefined;\n}\n\n/**\n * stdio era negotiation on a DISPOSABLE SIBLING: stdio servers built on SDKs\n * that terminate on any pre-`initialize` request exit when the probe arrives,\n * so the probe must not spend the caller's one process life. `server/discover`\n * runs on a short-lived sibling spawned from the same parameters; the caller's\n * transport starts exactly once, after the era is known. The sibling is\n * invisible infrastructure: its stderr is discarded, and it is reaped before\n * this resolves (signal escalation awaiting process exit — a helper holding\n * its pipes never blocks disposal). A caller `close()` on the session\n * transport during the probe aborts the connect with the typed negotiation\n * error, and the session transport is never started.\n */\nexport async function negotiateStdioViaSibling(\n    negotiation: Extract<ResolvedVersionNegotiation, { kind: 'auto' | 'pin' }>,\n    sessionTransport: Transport,\n    params: Record<string, unknown>,\n    deps: Omit<NegotiationDeps, 'transport' | 'transportKind' | 'disposableProbe'>\n): Promise<NegotiationResult> {\n    const SiblingTransport = sessionTransport.constructor as new (params: Record<string, unknown>) => Transport;\n    const sibling = new SiblingTransport({ ...params, stderr: 'ignore' });\n\n    // The session transport is unstarted while the sibling probes, and closing\n    // an unstarted transport records nothing — so watch its close() for the\n    // window's duration (raw property saved; identity restored in the finally).\n    // The abort races the probe: a caller close rejects promptly instead of\n    // waiting out the probe timeout.\n    const originalClose = sessionTransport.close;\n    let callerClosed = false;\n    let signalClosed: (() => void) | undefined;\n    const closedSignal = new Promise<never>((_, reject) => {\n        signalClosed = () => reject(callerCloseAbortError());\n    });\n    sessionTransport.close = async function (): Promise<void> {\n        callerClosed = true;\n        signalClosed?.();\n        return originalClose.call(sessionTransport);\n    };\n\n    let result: NegotiationResult;\n    try {\n        const negotiated = negotiateEra(negotiation, {\n            ...deps,\n            transport: sibling,\n            transportKind: 'stdio',\n            disposableProbe: true\n        });\n        // The abort may orphan the probe promise; its late settlement (the\n        // disposed sibling's close, a timeout) must not surface anywhere.\n        negotiated.catch(() => {});\n        result = await Promise.race([negotiated, closedSignal]);\n    } finally {\n        // Dispose FIRST, with the close watch still armed: a caller close()\n        // landing during the disposal window must still trip the abort below —\n        // only once the sibling is reaped does the caller get its close back.\n        await disposeSibling(sibling);\n        sessionTransport.close = originalClose;\n    }\n    if (callerClosed) {\n        // Checked AFTER the finally so a close during either the probe or the\n        // disposal window aborts: the session transport is never started.\n        throw callerCloseAbortError();\n    }\n    return result;\n}\n\n/** The typed abort for a caller `close()` landing while the sibling probes. */\nfunction callerCloseAbortError(): SdkError {\n    return new SdkError(\n        SdkErrorCode.EraNegotiationFailed,\n        'Version negotiation failed: the transport was closed during the server/discover probe'\n    );\n}\n\n/** Reap a probe sibling — best-effort; a sibling that cannot be reaped must not turn a settled verdict into an error. */\nasync function disposeSibling(sibling: Transport): Promise<void> {\n    try {\n        const dispose = (sibling as { _dispose?: () => Promise<void> })._dispose;\n        await (typeof dispose === 'function' ? dispose.call(sibling) : sibling.close());\n    } catch {\n        // ignore\n    }\n}\n","import { DefaultJsonSchemaValidator } from '@modelcontextprotocol/client/_shims';\nimport type {\n    BaseContext,\n    CallToolRequest,\n    CallToolResult,\n    ClientCapabilities,\n    ClientContext,\n    ClientNotification,\n    ClientRequest,\n    CompleteRequest,\n    CompleteResult,\n    DiscoverResult,\n    EmptyResult,\n    GetPromptRequest,\n    GetPromptResult,\n    Implementation,\n    InputRequiredOptions,\n    JSONRPCNotification,\n    JSONRPCRequest,\n    JSONRPCResponse,\n    JsonSchemaType,\n    JsonSchemaValidator,\n    jsonSchemaValidator,\n    ListChangedHandlers,\n    ListChangedOptions,\n    ListPromptsRequest,\n    ListPromptsResult,\n    ListResourcesRequest,\n    ListResourcesResult,\n    ListResourceTemplatesRequest,\n    ListResourceTemplatesResult,\n    ListToolsRequest,\n    ListToolsResult,\n    LoggingLevel,\n    MessageExtraInfo,\n    NonCompleteResultFlow,\n    NotificationMethod,\n    ProtocolEra,\n    ProtocolOptions,\n    ReadResourceRequest,\n    ReadResourceResult,\n    RequestMethod,\n    RequestOptions,\n    ResolvedInputRequiredDriverConfig,\n    Result,\n    ServerCapabilities,\n    StandardSchemaV1,\n    SubscribeRequest,\n    SubscriptionFilter,\n    Tool,\n    Transport,\n    UnsubscribeRequest,\n    XMcpHeaderScanResult\n} from '@modelcontextprotocol/core-internal';\nimport {\n    buildMcpParamHeaders,\n    codecForVersion,\n    DEFAULT_REQUEST_TIMEOUT_MSEC,\n    DiscoverResultSchema,\n    HEADER_MISMATCH_ERROR_CODE,\n    isJSONRPCErrorResponse,\n    isJSONRPCRequest,\n    isModernProtocolVersion,\n    isSpecType,\n    legacyProtocolVersions,\n    ListChangedOptionsBaseSchema,\n    mergeCapabilities,\n    modernProtocolVersions,\n    parseSchema,\n    Protocol,\n    ProtocolError,\n    ProtocolErrorCode,\n    resolveInputRequiredDriverConfig,\n    runInputRequiredFlow,\n    scanXMcpHeaderDeclarations,\n    SdkError,\n    SdkErrorCode,\n    SERVER_INFO_META_KEY,\n    SUBSCRIPTION_ID_META_KEY,\n    SUPPORTED_MODERN_PROTOCOL_VERSIONS\n} from '@modelcontextprotocol/core-internal';\n\nimport type { PriorDiscovery } from './probeClassifier';\nimport type { CacheMode, CacheScope, ResponseCacheStore } from './responseCache';\nimport { ClientResponseCache, InMemoryResponseCacheStore, MAX_CACHE_TTL_MS } from './responseCache';\nimport type { ResolvedVersionNegotiation, VersionNegotiationOptions } from './versionNegotiation';\nimport {\n    detectProbeEnvironment,\n    detectProbeTransportKind,\n    disarmSpentCloseGuard,\n    negotiateEra,\n    negotiateStdioViaSibling,\n    readStdioServerParams,\n    resolveVersionNegotiation\n} from './versionNegotiation';\n\n/**\n * The server identity a `DiscoverResult` carries in\n * `_meta['io.modelcontextprotocol/serverInfo']` (a spec SHOULD — absent means\n * the server offered no identity). Runtime-validated with the spec-type\n * guard because `connect({ prior })` accepts caller-supplied values that\n * never saw a wire parse.\n */\nfunction serverInfoFromDiscover(discover: DiscoverResult): Implementation | undefined {\n    const fromMeta = discover._meta?.[SERVER_INFO_META_KEY];\n    return isSpecType.Implementation(fromMeta) ? fromMeta : undefined;\n}\n\n/**\n * Elicitation default application helper. Applies defaults to the `data` based on the `schema`.\n *\n * @param schema - The schema to apply defaults to.\n * @param data - The data to apply defaults to.\n */\nfunction applyElicitationDefaults(schema: JsonSchemaType | undefined, data: unknown): void {\n    if (!schema || data === null || typeof data !== 'object') return;\n\n    // Handle object properties\n    if (schema.type === 'object' && schema.properties && typeof schema.properties === 'object') {\n        const obj = data as Record<string, unknown>;\n        const props = schema.properties as Record<string, JsonSchemaType & { default?: unknown }>;\n        for (const key of Object.keys(props)) {\n            const propSchema = props[key]!;\n            // If missing or explicitly undefined, apply default if present\n            if (obj[key] === undefined && Object.prototype.hasOwnProperty.call(propSchema, 'default')) {\n                obj[key] = propSchema.default;\n            }\n            // Recurse into existing nested objects/arrays\n            if (obj[key] !== undefined) {\n                applyElicitationDefaults(propSchema, obj[key]);\n            }\n        }\n    }\n\n    if (Array.isArray(schema.anyOf)) {\n        for (const sub of schema.anyOf) {\n            // Skip boolean schemas (true/false are valid JSON Schemas but have no defaults)\n            if (typeof sub !== 'boolean') {\n                applyElicitationDefaults(sub, data);\n            }\n        }\n    }\n\n    // Combine schemas\n    if (Array.isArray(schema.oneOf)) {\n        for (const sub of schema.oneOf) {\n            // Skip boolean schemas (true/false are valid JSON Schemas but have no defaults)\n            if (typeof sub !== 'boolean') {\n                applyElicitationDefaults(sub, data);\n            }\n        }\n    }\n}\n\n/**\n * Determines which elicitation modes are supported based on declared client capabilities.\n *\n * According to the spec:\n * - An empty elicitation capability object defaults to form mode support (backwards compatibility)\n * - URL mode is only supported if explicitly declared\n *\n * @param capabilities - The client's elicitation capabilities\n * @returns An object indicating which modes are supported\n */\nexport function getSupportedElicitationModes(capabilities: ClientCapabilities['elicitation']): {\n    supportsFormMode: boolean;\n    supportsUrlMode: boolean;\n} {\n    if (!capabilities) {\n        return { supportsFormMode: false, supportsUrlMode: false };\n    }\n\n    const hasFormCapability = capabilities.form !== undefined;\n    const hasUrlCapability = capabilities.url !== undefined;\n\n    // If neither form nor url are explicitly declared, form mode is supported (backwards compatibility)\n    const supportsFormMode = hasFormCapability || (!hasFormCapability && !hasUrlCapability);\n    const supportsUrlMode = hasUrlCapability;\n\n    return { supportsFormMode, supportsUrlMode };\n}\n\nexport type ClientOptions = ProtocolOptions & {\n    /**\n     * Capabilities to advertise as being supported by this client.\n     */\n    capabilities?: ClientCapabilities;\n\n    /**\n     * JSON Schema validator for tool output validation.\n     *\n     * The validator is used to validate structured content returned by tools\n     * against their declared output schemas.\n     *\n     * @default Runtime-selected validator (AJV-backed on Node.js, `@cfworker/json-schema`-backed on browser/workerd runtimes)\n     */\n    jsonSchemaValidator?: jsonSchemaValidator;\n\n    /**\n     * Opt-in protocol version negotiation (protocol revision 2026-07-28 and later).\n     *\n     * **The default is `'legacy'`**: absent (or `mode: 'legacy'`), `connect()`\n     * runs the plain 2025 sequence, byte-identical to today's behavior (no\n     * probe, no new headers). Opt into `'auto'` or pin to talk to a 2026-07-28\n     * server.\n     *\n     * - `mode: 'auto'` — `connect()` probes the server with `server/discover` first:\n     *   definitive modern evidence selects the modern era; definitive legacy signals\n     *   (and anything unrecognized) fall back to the plain legacy `initialize`\n     *   handshake, byte-equivalent to a 2025 client. On the SDK's own stdio\n     *   transport (the base `StdioClientTransport` exactly; subclasses probe in\n     *   place) the probe runs on a short-lived sibling process spawned from the\n     *   same parameters (one extra spawn per connect; its stderr is discarded) and\n     *   the caller's transport starts once, after the era is known; HTTP — and\n     *   custom or subclassed stdio-shaped transports — probe on the connection itself. A\n     *   network outage rejects with a typed connect error. A probe timeout is\n     *   transport-aware: on stdio it indicates a legacy server (some legacy servers\n     *   never answer unknown pre-`initialize` requests) and falls back to\n     *   `initialize`; on HTTP it rejects with a typed timeout\n     *   error (silence on a deployed server is an outage, not a legacy signal).\n     * - `mode: { pin: '2026-07-28' }` — modern era at exactly the pinned revision;\n     *   no probe-and-fallback: anything else fails loudly.\n     *\n     * Probe policy lives under `probe: { timeoutMs?, maxRetries? }`; the probe\n     * inherits the client's standard request timeout unless overridden, and\n     * `maxRetries` (default `0`) governs timeout re-sends only — the\n     * spec-mandated `-32022` corrective continuation is never counted against it.\n     *\n     * Once a modern era is negotiated, the client automatically attaches the\n     * per-request `_meta` envelope (the reserved protocol-version / client-info /\n     * client-capabilities keys) to every outgoing request and notification;\n     * user-supplied `_meta` keys take precedence over the auto-attached ones.\n     */\n    versionNegotiation?: VersionNegotiationOptions;\n\n    /**\n     * Multi-round-trip auto-fulfilment (protocol revision 2026-07-28).\n     *\n     * On the 2026-07-28 era, servers obtain client input (elicitation,\n     * sampling, roots) by answering `tools/call`, `prompts/get`, or\n     * `resources/read` with an `input_required` result instead of sending a\n     * server→client request. By default the client fulfils those embedded\n     * requests automatically through the SAME handlers registered via\n     * {@linkcode Client.setRequestHandler | setRequestHandler} (e.g.\n     * `elicitation/create`), then retries the original call with the\n     * collected `inputResponses` and a byte-exact echo of the opaque\n     * `requestState`, on a fresh request id, up to `maxRounds` rounds.\n     * `client.callTool()` (and its siblings) keep returning their plain\n     * result type — the interactive rounds happen inside the call.\n     *\n     * Set `autoFulfill: false` for manual mode: an `input_required` response\n     * then surfaces as a typed error unless the individual call passes\n     * `allowInputRequired: true` (pair it with `withInputRequired()` on the\n     * explicit-schema path to type both outcomes).\n     *\n     * Has no effect on 2025-era connections, which have no `input_required`\n     * vocabulary.\n     */\n    inputRequired?: InputRequiredOptions;\n\n    /**\n     * Configure handlers for list changed notifications (tools, prompts, resources).\n     *\n     * @example\n     * ```ts source=\"./client.examples.ts#ClientOptions_listChanged\"\n     * const client = new Client(\n     *     { name: 'my-client', version: '1.0.0' },\n     *     {\n     *         listChanged: {\n     *             tools: {\n     *                 onChanged: (error, tools) => {\n     *                     if (error) {\n     *                         console.error('Failed to refresh tools:', error);\n     *                         return;\n     *                     }\n     *                     console.log('Tools updated:', tools);\n     *                 }\n     *             },\n     *             prompts: {\n     *                 onChanged: (error, prompts) => console.log('Prompts updated:', prompts)\n     *             }\n     *         }\n     *     }\n     * );\n     * ```\n     */\n    listChanged?: ListChangedHandlers;\n\n    /**\n     * Cap on the number of pages the auto-aggregating\n     * {@linkcode Client.listTools | listTools()} /\n     * {@linkcode Client.listPrompts | listPrompts()} /\n     * {@linkcode Client.listResources | listResources()} /\n     * {@linkcode Client.listResourceTemplates | listResourceTemplates()} walk\n     * fetches before throwing (a defence against a server whose `nextCursor`\n     * never converges). `0` disables the cap. Default: `64`. Applies only to\n     * the no-argument auto-aggregate path; an explicit-`cursor` per-page call\n     * is never capped.\n     */\n    listMaxPages?: number;\n\n    /**\n     * The response-cache store backing the client's derived views (the cached\n     * `tools/list` result that {@linkcode Client.callTool | callTool}'s output\n     * validation and SEP-2243 header mirroring read) and the SEP-2549\n     * cache-hint serving on the cacheable verbs. Defaults to a fresh\n     * {@linkcode InMemoryResponseCacheStore} per client.\n     *\n     * Entries are automatically scoped by connected-server identity (derived\n     * from `serverInfo` after connect) AND, for `'private'`-scoped results,\n     * by `cachePartition` — encoded collision-free via `JSON.stringify`, so a\n     * server cannot craft a `serverInfo` that bleeds into another server's\n     * namespace or another principal's slot. One store may therefore back\n     * several clients (e.g. a host pool against the same server, or one\n     * persistent KV across servers); `list_changed` evictions are scoped to\n     * the connected server's partitions, so co-tenants are unaffected. Set\n     * `cachePartition` to your principal identifier (e.g. the auth subject)\n     * when sharing across principals. Note `serverInfo` is self-reported — a\n     * server that deliberately impersonates\n     * another's `name`/`version` shares its `'public'` slot; the\n     * per-principal isolation via `cachePartition` holds regardless.\n     */\n    responseCacheStore?: ResponseCacheStore;\n\n    /**\n     * Opaque per-principal identifier for response-cache writes whose\n     * server-reported `cacheScope` is `'private'` (the spec's \"MUST NOT share\n     * across authorization contexts\"). Within the connected server's\n     * namespace, `'public'`-scoped entries live at the shared\n     * `[serverIdentity, '']` partition and `'private'`-scoped entries at\n     * `[serverIdentity, cachePartition]`. Set this to a stable identity of\n     * the authorization context (e.g. the auth subject) when one\n     * `responseCacheStore` backs several principals; with the\n     * default `''` every entry — public or private — lives at the server's\n     * shared partition, which is the safe single-tenant posture.\n     */\n    cachePartition?: string;\n\n    /**\n     * TTL (ms) applied when a cacheable result arrives without a `ttlMs`\n     * field. Default `0` — a result without an explicit hint is never served\n     * from cache (every call refetches), but it is still **stored** so the\n     * `tools/list`-derived index that {@linkcode Client.callTool | callTool}'s\n     * SEP-2243 mirroring and output-schema validation read keeps working\n     * regardless. The spec defines absent-or-≤0 as \"immediately stale\".\n     */\n    defaultCacheTtlMs?: number;\n};\n\n/**\n * Options for {@linkcode Client.connect}. Extends {@linkcode RequestOptions}\n * (the timeout/signal apply to the connect-time handshake or probe) with the\n * cached-era-verdict knob.\n */\nexport type ConnectOptions = RequestOptions & {\n    /**\n     * A cached era verdict, taking precedence over `versionNegotiation`:\n     * `{ kind: 'modern', discover }` adopts a prior {@linkcode DiscoverResult}\n     * with zero round trips (throws `SdkError(EraNegotiationFailed)` on no\n     * 2026-07-28+ overlap); `{ kind: 'legacy' }` skips the probe and runs the\n     * plain legacy `initialize` handshake. Freshness is the supplying host's\n     * responsibility — see {@linkcode PriorDiscovery}. Reuse only within one\n     * authorization context.\n     */\n    prior?: PriorDiscovery;\n};\n\n/**\n * Rejects malformed persisted blobs with a typed `SdkError` before any state\n * change: unrecognized `kind`, a legacy verdict also carrying\n * DiscoverResult-shaped members (a corrupt blob must never era-choose), or a\n * modern `discover` payload failing the wire path's schema.\n */\nfunction validatePrior(prior: PriorDiscovery): PriorDiscovery {\n    if (typeof prior === 'object' && prior !== null) {\n        if (prior.kind === 'legacy' && !('supportedVersions' in prior) && !('discover' in prior)) {\n            return prior;\n        }\n        // Validation only: the blob is adopted verbatim, so unknown nested\n        // members survive re-persistence via getDiscoverResult().\n        if (prior.kind === 'modern' && DiscoverResultSchema.safeParse(prior.discover).success) {\n            return prior;\n        }\n    }\n    throw new SdkError(\n        SdkErrorCode.EraNegotiationFailed,\n        \"connect({ prior }): unrecognized prior — expected { kind: 'modern', discover } or { kind: 'legacy' }\"\n    );\n}\n\n/**\n * {@linkcode RequestOptions} extended with the per-call cache disposition for\n * the cacheable verbs (`listTools()` / `listPrompts()` / `listResources()` /\n * `listResourceTemplates()` / `readResource()`). See {@linkcode CacheMode}.\n */\nexport type CacheableRequestOptions = RequestOptions & {\n    /**\n     * `'use'` (default) serves a still-fresh cached entry without a round\n     * trip; `'refresh'` always fetches and re-stores; `'bypass'` fetches\n     * without consulting or writing the cache. Applies to the no-`cursor`\n     * auto-aggregate path on the list verbs and to `readResource`; ignored\n     * elsewhere.\n     */\n    cacheMode?: CacheMode;\n};\n\n/**\n * Options for {@linkcode Client.callTool}. Extends {@linkcode RequestOptions}\n * with an escape hatch for callers that already hold the tool definition\n * (e.g. from a previous session or configuration) — pass it via\n * `toolDefinition` so SEP-2243 `Mcp-Param-*` header mirroring can run without a\n * prior `tools/list`.\n */\nexport type CallToolRequestOptions = RequestOptions & {\n    /**\n     * The tool definition to use for SEP-2243 `Mcp-Param-*` header mirroring on\n     * a 2026-07-28 connection over Streamable HTTP, AND for output-schema\n     * validation of the result. When set, the client uses this definition's\n     * `inputSchema` and `outputSchema` instead of (and without consulting) the\n     * cached `tools/list` result, so the two derived views agree.\n     */\n    toolDefinition?: Tool;\n};\n\n/**\n * `list_changed` notification → response-cache method(s) to evict. `resources`\n * covers both list verbs (the spec's \"relevant notification ⇒ immediately\n * stale\").\n */\nconst LIST_CHANGED_EVICTIONS: Readonly<Record<string, readonly string[]>> = {\n    'notifications/tools/list_changed': ['tools/list'],\n    'notifications/prompts/list_changed': ['prompts/list'],\n    'notifications/resources/list_changed': ['resources/list', 'resources/templates/list']\n};\n\nconst DEFAULT_LIST_MAX_PAGES = 64;\n\n// Package-internal (not exported from the package): what the `ext/` clients share with Client. Set in Client's static block.\nexport const clientInternals = {} as {\n    enforceStrictCapabilities(client: Client): boolean;\n    walkPages<R extends { nextCursor?: string }>(\n        client: Client,\n        method: string,\n        fetchPage: (cursor: string | undefined) => Promise<R>,\n        items: (page: R) => unknown[]\n    ): Promise<R>;\n    readResource(\n        client: Client,\n        params: ReadResourceRequest['params'],\n        options?: CacheableRequestOptions\n    ): Promise<{ result: ReadResourceResult; cached: boolean }>;\n};\n\n/**\n * A handle to an open `subscriptions/listen` stream (protocol revision\n * 2026-07-28). Change notifications delivered on the stream dispatch to the\n * existing {@linkcode Client.setNotificationHandler} registrations.\n */\nexport interface McpSubscription {\n    /**\n     * The subset of the requested filter the server agreed to honor (from\n     * `notifications/subscriptions/acknowledged`).\n     */\n    readonly honoredFilter: SubscriptionFilter;\n    /**\n     * Tears the subscription down. Idempotent. Aborts the listen request's\n     * stream (where the transport supports it) AND sends\n     * `notifications/cancelled` referencing the listen request id — both,\n     * always, so close works on any transport.\n     */\n    close(): Promise<void>;\n    /**\n     * Resolves exactly once when the subscription has terminated. Never\n     * rejects — this is an observation, not an operation.\n     *\n     * - `'local'` — you called {@linkcode close} (or aborted the\n     *   `RequestOptions.signal` you passed to `listen()`).\n     * - `'graceful'` — the server ended the subscription deliberately by\n     *   sending the empty `subscriptions/listen` response (e.g. on shutdown).\n     * - `'remote'` — the stream ended without a response, or the transport\n     *   dropped — an unexpected disconnect. Re-listen if you still want\n     *   events.\n     */\n    readonly closed: Promise<'local' | 'graceful' | 'remote'>;\n}\n\n/** @internal */\ninterface ListenStateEntry {\n    /**\n     * The single funnel for the per-listen `opening → open → closed` state\n     * machine. Every transport-level feed source — the `_onnotification` /\n     * `_onresponse` / `_onclose` overrides, `onRequestStreamEnd`, send\n     * failure, ack timeout, caller-signal abort, `_resetConnectionState` —\n     * routes through it.\n     */\n    settle: (outcome: { ack: SubscriptionFilter } | { cause: 'local' | 'graceful' | 'remote'; error?: Error }) => void;\n}\n\n/**\n * Per-tool result of compiling an `outputSchema` (SEP-2106). Stored on the\n * response-cache substrate's stamp-keyed `name → validator` index so it\n * inherits that substrate's invalidation lifecycle (`list_changed` evicts,\n * a refetched `tools/list` re-derives, `resetForReconnect` clears) — no\n * parallel map to keep in sync.\n *\n * @internal\n */\ntype OutputSchemaCompileResult =\n    | { ok: true; validator: JsonSchemaValidator<unknown> }\n    | { ok: false; validator?: undefined; compileError: unknown };\n\n/**\n * An MCP client on top of a pluggable transport.\n *\n * The client will automatically begin the initialization flow with the server when {@linkcode connect} is called.\n *\n * To handle server-initiated requests (sampling, elicitation, roots), call {@linkcode setRequestHandler}.\n * The client must declare the corresponding capability for the handler to be accepted. For\n * `sampling/createMessage` and `elicitation/create`, the handler is automatically wrapped with\n * schema validation for both the incoming request and the returned result.\n *\n * Note: the `roots/list` and `sampling/createMessage` handler surfaces (and the corresponding\n * `roots` and `sampling` capabilities) are deprecated as of protocol version 2026-07-28\n * (SEP-2577). They remain functional during the deprecation window (at least twelve months).\n * Migrate sampling to calling LLM provider APIs directly, and roots to passing paths via tool\n * parameters, resource URIs, or configuration.\n *\n * @example Handling a sampling request\n * ```ts source=\"./client.examples.ts#Client_setRequestHandler_sampling\"\n * client.setRequestHandler('sampling/createMessage', async request => {\n *     const lastMessage = request.params.messages.at(-1);\n *     console.log('Sampling request:', lastMessage);\n *\n *     // In production, send messages to your LLM here\n *     return {\n *         model: 'my-model',\n *         role: 'assistant' as const,\n *         content: {\n *             type: 'text' as const,\n *             text: 'Response from the model'\n *         }\n *     };\n * });\n * ```\n */\nexport class Client extends Protocol<ClientContext> {\n    private _serverCapabilities?: ServerCapabilities;\n    private _serverVersion?: Implementation;\n    private _capabilities: ClientCapabilities;\n    private _instructions?: string;\n    private _jsonSchemaValidator: jsonSchemaValidator;\n    /**\n     * The response-cache substrate. Owns the backing store, the per-method\n     * eviction-generation counter, the user-supplied/default flag, and the\n     * stamp-memoized derived `name → Tool` / `name → output-validator`\n     * indices — the cache-coordination state that used to live as separate\n     * private fields here. The internal aggregating walk writes one entry per\n     * list verb; `list_changed` evicts the matching method;\n     * `_resetConnectionState` resets the lot. {@linkcode callTool}'s\n     * output-schema validation reads the derived `outputValidator` index (the\n     * substrate's first production caller); the stacked SEP-2243 PR wires\n     * `Mcp-Param-*` mirroring through `toolDefinition` on top.\n     */\n    private readonly _cache: ClientResponseCache;\n    private readonly _defaultCacheTtlMs: number;\n    private readonly _listMaxPages: number;\n    private _listChangedDebounceTimers: Map<string, ReturnType<typeof setTimeout>> = new Map();\n    /**\n     * The constructor `listChanged` configuration. Durable across reconnects:\n     * read fresh on every connect (legacy or modern), never consumed.\n     */\n    private readonly _listChangedConfig?: ListChangedHandlers;\n    private _enforceStrictCapabilities: boolean;\n    private _versionNegotiation?: VersionNegotiationOptions;\n    private _supportedProtocolVersionsOption?: string[];\n    private _inputRequiredDriverConfig: ResolvedInputRequiredDriverConfig;\n    /**\n     * Active subscriptions/listen state, keyed by subscription id (= the\n     * listen request's JSON-RPC id verbatim). The id is a STRING from a\n     * Client-owned counter (`'listen:' + N`) — JSON-RPC permits string ids,\n     * and Protocol's numeric `_requestMessageId` counter only ever issues\n     * numbers, so listen ids cannot collide with ordinary request ids.\n     */\n    private _listenState = new Map<string, ListenStateEntry>();\n    private _nextListenId = 0;\n    /** The auto-opened subscription backing ClientOptions.listChanged on a modern connection. */\n    private _autoOpenedSubscription?: McpSubscription;\n    /** Backing store for {@linkcode getDiscoverResult}. Per-connection. */\n    private _discoverResult?: DiscoverResult;\n\n    static {\n        clientInternals.enforceStrictCapabilities = client => client._enforceStrictCapabilities;\n        clientInternals.walkPages = (client, method, fetchPage, items) => client._walkPages(method, fetchPage, items);\n        clientInternals.readResource = (client, params, options) => client._readResource(params, options);\n    }\n\n    /**\n     * Clears every per-connection field in one place. Called at the start of\n     * each fresh (non-resuming) connect and from `close()`, so a stale\n     * negotiated era / server identity / auto-opened subscription cannot\n     * survive a reconnect.\n     */\n    private _resetConnectionState(): void {\n        this._negotiatedProtocolVersion = undefined;\n        this._serverCapabilities = undefined;\n        this._serverVersion = undefined;\n        this._instructions = undefined;\n        this._discoverResult = undefined;\n        this._autoOpenedSubscription = undefined;\n        // Settle every live per-listen state machine before clearing the map:\n        // a fresh connect (or close) on a connection whose prior transport\n        // never fired onclose would otherwise leave an in-flight listen()\n        // promise hanging forever. Each entry's settle() deletes only itself\n        // (Map self-delete during iteration is well-defined).\n        if (this._listenState.size > 0) {\n            const reason = new SdkError(\n                SdkErrorCode.ConnectionClosed,\n                'subscriptions/listen: client reconnected or closed; subscription state from the previous connection was reset'\n            );\n            for (const entry of this._listenState.values()) {\n                entry.settle({ cause: 'remote', error: reason });\n            }\n        }\n        this._listenState.clear();\n        // Debounce timers are connection-scoped: a callback armed on a\n        // connection that is now gone must not fire onto whatever connection\n        // (if any) replaces it.\n        for (const timer of this._listChangedDebounceTimers.values()) {\n            clearTimeout(timer);\n        }\n        this._listChangedDebounceTimers.clear();\n        // A user-supplied store is NOT cleared on reconnect/close — that would\n        // defeat the only reason to supply one. The per-instance default IS\n        // cleared (it is connection-scoped); derived indices and the\n        // generation map are dropped regardless. The default impl is\n        // synchronous, so the call returns plain void here.\n        this._cache.resetForReconnect();\n    }\n\n    override async close(): Promise<void> {\n        try {\n            await super.close();\n        } finally {\n            // Per-connection state is cleared even when the transport's close\n            // rejects, so a stale negotiated era / live listen state cannot\n            // survive a failed close.\n            this._resetConnectionState();\n        }\n    }\n\n    /**\n     * Initializes this client with the given name and version information.\n     */\n    constructor(\n        private _clientInfo: Implementation,\n        options?: ClientOptions\n    ) {\n        super(options);\n        this._capabilities = options?.capabilities ? { ...options.capabilities } : {};\n        this._jsonSchemaValidator = options?.jsonSchemaValidator ?? new DefaultJsonSchemaValidator();\n        this._enforceStrictCapabilities = options?.enforceStrictCapabilities ?? false;\n        this._versionNegotiation = options?.versionNegotiation;\n        this._supportedProtocolVersionsOption = options?.supportedProtocolVersions;\n        // Multi-round-trip auto-fulfilment driver (2026-07-28): on by default,\n        // configurable via ClientOptions.inputRequired.\n        this._inputRequiredDriverConfig = resolveInputRequiredDriverConfig(options?.inputRequired);\n        // Response-cache substrate. A fresh in-memory store is allocated when\n        // the caller does not supply one — never share a default across\n        // instances (see ClientOptions.responseCacheStore).\n        this._cache = new ClientResponseCache(\n            options?.responseCacheStore ?? new InMemoryResponseCacheStore(),\n            options?.responseCacheStore !== undefined,\n            error => this._reportStoreError(error),\n            options?.cachePartition ?? ''\n        );\n        this._defaultCacheTtlMs = options?.defaultCacheTtlMs ?? 0;\n        this._listMaxPages = options?.listMaxPages ?? DEFAULT_LIST_MAX_PAGES;\n\n        // Store list changed config for setup after connection (when we know server capabilities)\n        if (options?.listChanged) {\n            this._listChangedConfig = options.listChanged;\n        }\n    }\n\n    protected override buildContext(ctx: BaseContext, _transportInfo?: MessageExtraInfo): ClientContext {\n        return ctx;\n    }\n\n    /**\n     * Era-keyed direction enforcement for inbound traffic on channels whose\n     * transport does not classify (e.g. stdio): the 2026-07-28 era has no\n     * server→client JSON-RPC request channel — server-to-client interactions\n     * are carried in-band in `input_required` results — and on stdio the\n     * client must never write JSON-RPC responses. An inbound request arriving\n     * on a connection that negotiated a modern era is therefore dropped\n     * (surfaced via `onerror`) rather than answered. Connections on a legacy\n     * era — and all responses and notifications — keep today's dispatch path.\n     */\n    protected override _shouldDropInbound(message: JSONRPCRequest | JSONRPCNotification): 'drop' | undefined {\n        if (\n            this._negotiatedProtocolVersion !== undefined &&\n            isModernProtocolVersion(this._negotiatedProtocolVersion) &&\n            isJSONRPCRequest(message)\n        ) {\n            return 'drop';\n        }\n        return undefined;\n    }\n\n    /**\n     * Per-request `_meta` envelope auto-emission (protocol revision 2026-07-28):\n     * on a connection that negotiated a modern era — auto-negotiated or pinned —\n     * every outgoing request and notification automatically carries the reserved\n     * protocol-version / client-info / client-capabilities `_meta` keys (the\n     * same envelope the connect-time `server/discover` probe sends).\n     * User-supplied `_meta` keys take precedence over the auto-attached ones.\n     *\n     * Legacy-era connections return `undefined`: the envelope seam is a no-op\n     * and outbound traffic is byte-identical to a 2025 client (the legacy\n     * `'auto'` fallback included).\n     */\n    protected override _outboundMetaEnvelope(): Readonly<Record<string, unknown>> | undefined {\n        const version = this._negotiatedProtocolVersion;\n        if (version === undefined) return undefined;\n        // The era branch lives in the codec: the 2025 era's `outboundEnvelope`\n        // is `undefined` (legacy bytes stay identical); the 2026 era builds\n        // the keyed object.\n        return this._wireCodec().outboundEnvelope({\n            protocolVersion: version,\n            clientInfo: this._clientInfo,\n            clientCapabilities: this._capabilities\n        });\n    }\n\n    /**\n     * Wires the multi-round-trip auto-fulfilment engine (protocol revision\n     * 2026-07-28) into the response funnel: an `input_required` answer is\n     * fulfilled through the registered elicitation/sampling/roots handlers\n     * and the original request retried via `flow.retry`, up to\n     * `inputRequired.maxRounds` rounds. With auto-fulfilment disabled the\n     * response surfaces as a typed error steering to manual mode.\n     */\n    protected override _resolveNonCompleteResult<T extends StandardSchemaV1>(\n        decoded: { kind: 'input_required'; inputRequests: Record<string, unknown>; requestState?: string },\n        flow: NonCompleteResultFlow<T>\n    ): Promise<unknown> {\n        if (!this._inputRequiredDriverConfig.autoFulfill) {\n            return Promise.reject(\n                new SdkError(\n                    SdkErrorCode.UnsupportedResultType,\n                    `Unsupported result type 'input_required' for ${flow.request.method}: ` +\n                        `multi-round-trip auto-fulfilment is not enabled on this instance — ` +\n                        `pass allowInputRequired: true to handle it manually, or enable inputRequired.autoFulfill`,\n                    { resultType: 'input_required', method: flow.request.method }\n                )\n            );\n        }\n        return runInputRequiredFlow(\n            {\n                getRequestHandler: method =>\n                    this._getRequestHandler(method) as ((request: JSONRPCRequest, ctx: unknown) => Promise<Result>) | undefined,\n                buildContext: baseCtx => this.buildContext(baseCtx, undefined),\n                sessionId: this.transport?.sessionId\n            },\n            this._inputRequiredDriverConfig,\n            decoded,\n            flow\n        );\n    }\n\n    /**\n     * Set up handlers for list changed notifications based on config and server capabilities.\n     * This should only be called after initialization when server capabilities are known.\n     * Handlers are silently skipped if the server doesn't advertise the corresponding listChanged capability.\n     * @internal\n     */\n    private _setupListChangedHandlers(config: ListChangedHandlers): void {\n        // Every autoRefresh fetcher forces `cacheMode: 'refresh'`: the\n        // notification handler's `_cache.evict()` runs first, but a custom\n        // store whose `delete()` no-ops (or rejects) leaves the stale entry\n        // in place — a default-mode `list*()` would then cache-serve the very\n        // entry the notification declared stale. `'refresh'` bypasses the\n        // cache read so the fetcher always reaches the wire and overwrites.\n        if (config.tools && this._serverCapabilities?.tools?.listChanged) {\n            this._setupListChangedHandler('tools', 'notifications/tools/list_changed', config.tools, async () => {\n                const result = await this.listTools(undefined, { cacheMode: 'refresh' });\n                return result.tools;\n            });\n        }\n\n        if (config.prompts && this._serverCapabilities?.prompts?.listChanged) {\n            this._setupListChangedHandler('prompts', 'notifications/prompts/list_changed', config.prompts, async () => {\n                const result = await this.listPrompts(undefined, { cacheMode: 'refresh' });\n                return result.prompts;\n            });\n        }\n\n        if (config.resources && this._serverCapabilities?.resources?.listChanged) {\n            this._setupListChangedHandler('resources', 'notifications/resources/list_changed', config.resources, async () => {\n                const result = await this.listResources(undefined, { cacheMode: 'refresh' });\n                return result.resources;\n            });\n        }\n    }\n\n    /**\n     * Registers new capabilities. This can only be called before connecting to a transport.\n     *\n     * The new capabilities will be merged with any existing capabilities previously given (e.g., at initialization).\n     */\n    public registerCapabilities(capabilities: ClientCapabilities): void {\n        if (this.transport) {\n            throw new Error('Cannot register capabilities after connecting to transport');\n        }\n\n        this._capabilities = mergeCapabilities(this._capabilities, capabilities);\n    }\n\n    /**\n     * Configure protocol version negotiation before connecting (equivalent to\n     * passing `versionNegotiation` at construction time). Can only be called\n     * before connecting to a transport. Passing `undefined` clears a previously\n     * configured negotiation, restoring the default `'legacy'` posture.\n     *\n     * See {@linkcode ClientOptions | ClientOptions.versionNegotiation} for the mode semantics.\n     */\n    public setVersionNegotiation(options: VersionNegotiationOptions | undefined): void {\n        if (this.transport) {\n            throw new Error('Cannot configure version negotiation after connecting to transport');\n        }\n        this._versionNegotiation = options;\n    }\n\n    /**\n     * Enforces client-side validation for `elicitation/create` and `sampling/createMessage`\n     * regardless of how the handler was registered.\n     */\n    protected override _wrapHandler(\n        method: string,\n        handler: (request: JSONRPCRequest, ctx: ClientContext) => Promise<Result>\n    ): (request: JSONRPCRequest, ctx: ClientContext) => Promise<Result> {\n        if (method === 'elicitation/create') {\n            return async (request, ctx) => {\n                // Era-exact validation via the function-only WireCodec\n                // contract: resolved from the instance era at dispatch time.\n                // On the 2025 era the method is a wire request (registry\n                // validator); on the 2026 era it is in-band vocabulary\n                // reached only via the multi-round-trip driver, so the wire\n                // validator returns `not-in-era` and we fall through to the\n                // in-band one. The era registry entry IS the plain\n                // ElicitResult schema (the result map is aligned to the\n                // typed map — no widened unions), so no narrower surface is\n                // needed.\n                const codec = codecForVersion(this._negotiatedProtocolVersion);\n                let validatedRequest = codec.validateRequest('elicitation/create', request);\n                if (!validatedRequest.ok && validatedRequest.reason === 'not-in-era') {\n                    validatedRequest = codec.validateInputRequest('elicitation/create', request);\n                }\n                if (!validatedRequest.ok) {\n                    throw new ProtocolError(\n                        validatedRequest.reason === 'not-in-era' ? ProtocolErrorCode.InternalError : ProtocolErrorCode.InvalidParams,\n                        validatedRequest.reason === 'not-in-era'\n                            ? 'No wire schema for elicitation/create in the resolved era'\n                            : `Invalid elicitation request: ${validatedRequest.message}`\n                    );\n                }\n\n                const { params } = validatedRequest.value;\n                params.mode = params.mode ?? 'form';\n                const { supportsFormMode, supportsUrlMode } = getSupportedElicitationModes(this._capabilities.elicitation);\n\n                if (params.mode === 'form' && !supportsFormMode) {\n                    throw new ProtocolError(ProtocolErrorCode.InvalidParams, 'Client does not support form-mode elicitation requests');\n                }\n\n                if (params.mode === 'url' && !supportsUrlMode) {\n                    throw new ProtocolError(ProtocolErrorCode.InvalidParams, 'Client does not support URL-mode elicitation requests');\n                }\n\n                const result = await handler(request, ctx);\n\n                let validationResult = codec.validateResult('elicitation/create', result);\n                if (!validationResult.ok && validationResult.reason === 'not-in-era') {\n                    validationResult = codec.validateInputResponse('elicitation/create', result);\n                }\n                if (!validationResult.ok) {\n                    throw new ProtocolError(\n                        validationResult.reason === 'not-in-era' ? ProtocolErrorCode.InternalError : ProtocolErrorCode.InvalidParams,\n                        validationResult.reason === 'not-in-era'\n                            ? 'No wire schema for elicitation/create in the resolved era'\n                            : `Invalid elicitation result: ${validationResult.message}`\n                    );\n                }\n\n                const validatedResult = validationResult.value;\n                const requestedSchema = params.mode === 'form' ? (params.requestedSchema as JsonSchemaType) : undefined;\n\n                if (\n                    params.mode === 'form' &&\n                    validatedResult.action === 'accept' &&\n                    validatedResult.content &&\n                    requestedSchema &&\n                    this._capabilities.elicitation?.form?.applyDefaults\n                ) {\n                    try {\n                        applyElicitationDefaults(requestedSchema, validatedResult.content);\n                    } catch {\n                        // gracefully ignore errors in default application\n                    }\n                }\n\n                return validatedResult;\n            };\n        }\n\n        if (method === 'sampling/createMessage') {\n            return async (request, ctx) => {\n                // Era-exact validation via the instance era (see above): wire\n                // request validator on the 2025 era; on the 2026 era sampling\n                // is in-band vocabulary (it reaches the handler only as an\n                // embedded input request) so the wire validator returns\n                // `not-in-era` and we fall through to the in-band one.\n                const codec = codecForVersion(this._negotiatedProtocolVersion);\n                let validatedRequest = codec.validateRequest('sampling/createMessage', request);\n                if (!validatedRequest.ok && validatedRequest.reason === 'not-in-era') {\n                    validatedRequest = codec.validateInputRequest('sampling/createMessage', request);\n                }\n                if (!validatedRequest.ok) {\n                    throw new ProtocolError(\n                        validatedRequest.reason === 'not-in-era' ? ProtocolErrorCode.InternalError : ProtocolErrorCode.InvalidParams,\n                        validatedRequest.reason === 'not-in-era'\n                            ? 'No wire schema for sampling/createMessage in the resolved era'\n                            : `Invalid sampling request: ${validatedRequest.message}`\n                    );\n                }\n\n                const { params } = validatedRequest.value;\n\n                const result = await handler(request, ctx);\n\n                // The result-side validator mirrors the request-side selection\n                // so both stay on the same era's vocabulary. On the 2025 era\n                // the schema depends on the REQUEST params (tools vs no tools)\n                // — `samplingResultVariant` owns that pair. On the 2026 era\n                // it returns `not-in-era` and we fall through to the embedded\n                // response validator (it covers plain and tool-bearing\n                // responses alike).\n                const hasTools = Boolean(params.tools || params.toolChoice);\n                let validatedResult = codec.samplingResultVariant(hasTools, result);\n                if (!validatedResult.ok && validatedResult.reason === 'not-in-era') {\n                    validatedResult = codec.validateInputResponse('sampling/createMessage', result);\n                }\n                if (!validatedResult.ok) {\n                    throw new ProtocolError(\n                        validatedResult.reason === 'not-in-era' ? ProtocolErrorCode.InternalError : ProtocolErrorCode.InvalidParams,\n                        validatedResult.reason === 'not-in-era'\n                            ? 'No result schema for sampling/createMessage in the resolved era'\n                            : `Invalid sampling result: ${validatedResult.message}`\n                    );\n                }\n\n                return validatedResult.value;\n            };\n        }\n\n        return handler;\n    }\n\n    protected assertCapability(capability: keyof ServerCapabilities, method: string): void {\n        if (!this._serverCapabilities?.[capability]) {\n            throw new SdkError(SdkErrorCode.CapabilityNotSupported, `Server does not support ${capability} (required for ${method})`);\n        }\n    }\n\n    /**\n     * Connects to a server via the given transport and performs the MCP initialization handshake.\n     *\n     * @example Basic usage (stdio)\n     * ```ts source=\"./client.examples.ts#Client_connect_stdio\"\n     * const client = new Client({ name: 'my-client', version: '1.0.0' });\n     * const transport = new StdioClientTransport({ command: 'my-mcp-server' });\n     * await client.connect(transport);\n     * ```\n     *\n     * @example Streamable HTTP with SSE fallback\n     * ```ts source=\"./client.examples.ts#Client_connect_sseFallback\"\n     * const baseUrl = new URL(url);\n     *\n     * try {\n     *     // Try modern Streamable HTTP transport first\n     *     const client = new Client({ name: 'my-client', version: '1.0.0' });\n     *     const transport = new StreamableHTTPClientTransport(baseUrl);\n     *     await client.connect(transport);\n     *     return { client, transport };\n     * } catch {\n     *     // Fall back to legacy SSE transport\n     *     const client = new Client({ name: 'my-client', version: '1.0.0' });\n     *     const transport = new SSEClientTransport(baseUrl);\n     *     await client.connect(transport);\n     *     return { client, transport };\n     * }\n     * ```\n     */\n    override async connect(transport: Transport, options?: ConnectOptions): Promise<void> {\n        // `!= null`: a persisted prior slot naturally revives as JSON `null`\n        // — treat it like an absent option, not a shape error.\n        if (options?.prior != null) {\n            // Cached era verdict: bypasses versionNegotiation resolution entirely.\n            return this._connectFromPrior(transport, validatePrior(options.prior), options);\n        }\n        // The configured versionNegotiation mode decides the era.\n        const negotiation = resolveVersionNegotiation(this._versionNegotiation, this._supportedProtocolVersionsOption);\n        if (negotiation.kind !== 'legacy') {\n            return this._connectNegotiated(transport, negotiation, options);\n        }\n        return this._connectPlainLegacy(transport, options);\n    }\n\n    /**\n     * Plain legacy connect — the pinned 2025 sequence, byte-untouched. The\n     * `mode: 'legacy'` connect body, shared with the `prior` legacy verdict.\n     */\n    private async _connectPlainLegacy(transport: Transport, options?: RequestOptions): Promise<void> {\n        await super.connect(transport);\n        // When transport sessionId is already set this means we are trying to reconnect.\n        // Restore the protocol version negotiated during the original initialize handshake\n        // so HTTP transports include the required mcp-protocol-version header, but skip re-init.\n        if (transport.sessionId !== undefined) {\n            const negotiatedProtocolVersion = this._negotiatedProtocolVersion;\n            if (negotiatedProtocolVersion !== undefined) {\n                // Resuming keeps the original negotiation: the instance still\n                // holds the negotiated version (and with it the wire era) —\n                // only the new transport needs the header pushed again.\n                transport.setProtocolVersion?.(negotiatedProtocolVersion);\n            }\n            return;\n        }\n        // Fresh connect: per-connection state left over from a previous\n        // connection must not survive into a new handshake. Clearing it puts\n        // the instance back in the pre-negotiation phase, so the initialize\n        // exchange below rides the bootstrap method pins (legacy era) instead\n        // of a dead session's era. Without this, an instance that once\n        // negotiated a modern era could never re-run a fresh handshake:\n        // `initialize` is physically absent from the modern registry. (The\n        // resume branch above keeps it instead.)\n        this._resetConnectionState();\n        await this._legacyHandshake(transport, options);\n    }\n\n    /**\n     * The 2025 `initialize` handshake — the body of the plain legacy connect and\n     * the `'auto'`-mode fallback path (same `initialize` body, zero 2026 headers;\n     * on the stdio sibling path it opens the session child's fresh pipe, in the\n     * in-place modes it rides the probed connection). Callers clear the negotiated protocol version before\n     * the handshake; its completion sets the negotiated (legacy) version.\n     */\n    private async _legacyHandshake(transport: Transport, options?: RequestOptions): Promise<void> {\n        // initialize is a legacy-era handshake: only the legacy subset of the\n        // supported versions is ever offered or accepted here — a 2026-era\n        // revision is negotiated exclusively via server/discover.\n        const legacyVersions = legacyProtocolVersions(this._supportedProtocolVersions);\n        try {\n            const offeredVersion = legacyVersions[0];\n            if (offeredVersion === undefined) {\n                throw new SdkError(\n                    SdkErrorCode.EraNegotiationFailed,\n                    'Cannot run the initialize handshake: supportedProtocolVersions contains no pre-2026-07-28 protocol version'\n                );\n            }\n            const result = await this.request(\n                {\n                    method: 'initialize',\n                    params: {\n                        protocolVersion: offeredVersion,\n                        capabilities: this._capabilities,\n                        clientInfo: this._clientInfo\n                    }\n                },\n                options\n            );\n\n            if (result === undefined) {\n                throw new Error(`Server sent invalid initialize result: ${result}`);\n            }\n\n            if (!legacyVersions.includes(result.protocolVersion)) {\n                throw new Error(`Server's protocol version is not supported: ${result.protocolVersion}`);\n            }\n\n            this._serverCapabilities = result.capabilities;\n            this._serverVersion = result.serverInfo;\n            this._cache.setServerIdentity(this._deriveServerIdentity(transport));\n            // HTTP transports must set the protocol version in each header after initialization.\n            if (transport.setProtocolVersion) {\n                transport.setProtocolVersion(result.protocolVersion);\n            }\n\n            this._instructions = result.instructions;\n\n            await this.notification({\n                method: 'notifications/initialized'\n            });\n\n            // Handshake completion: the negotiated version becomes the\n            // instance's connection state, and with it the wire era for\n            // everything this connection sends/receives from here on (the\n            // negotiated version cashes out as the negotiated wire ERA —\n            // Q1-SD1). Set AFTER the initialized notification: the initialize\n            // EXCHANGE is the legacy handshake by definition and completes on\n            // that era.\n            this._negotiatedProtocolVersion = result.protocolVersion;\n\n            // Set up list changed handlers now that we know server capabilities\n            if (this._listChangedConfig) {\n                this._setupListChangedHandlers(this._listChangedConfig);\n            }\n        } catch (error) {\n            // Disconnect if initialization fails.\n            void this.close();\n            throw error;\n        }\n    }\n\n    /**\n     * Negotiated connect (mode `'auto'` or `{ pin }`): probe with `server/discover`\n     * before the Protocol machinery attaches — on a disposable sibling process for\n     * the SDK's stdio transport, in place otherwise — then either establish the\n     * modern era or perform the plain legacy handshake.\n     */\n    private async _connectNegotiated(\n        transport: Transport,\n        negotiation: Extract<ResolvedVersionNegotiation, { kind: 'auto' | 'pin' }>,\n        options?: RequestOptions\n    ): Promise<void> {\n        // Session-resuming reconnect: restore the previously negotiated version,\n        // never re-probe mid-session.\n        if (transport.sessionId !== undefined) {\n            await super.connect(transport);\n            const negotiatedProtocolVersion = this._negotiatedProtocolVersion;\n            if (negotiatedProtocolVersion !== undefined && transport.setProtocolVersion) {\n                transport.setProtocolVersion(negotiatedProtocolVersion);\n            }\n            return;\n        }\n\n        // Fresh connect: stale connection state must not survive into a new\n        // negotiation — every fresh negotiated connect re-runs the probe.\n        this._resetConnectionState();\n\n        let result: Awaited<ReturnType<typeof negotiateEra>>;\n        try {\n            const transportKind = detectProbeTransportKind(transport);\n            const baseDeps = {\n                clientInfo: this._clientInfo,\n                capabilities: this._capabilities,\n                environment: detectProbeEnvironment(),\n                defaultTimeoutMs: options?.timeout ?? DEFAULT_REQUEST_TIMEOUT_MSEC\n            };\n            // The SDK's stdio transport probes on a disposable sibling process,\n            // so the caller's transport spends its one child life on the\n            // session, never on the probe. Stdio-shaped transports without\n            // readable spawn parameters (and HTTP) probe in place, as before.\n            const stdioParams = transportKind === 'stdio' ? readStdioServerParams(transport) : undefined;\n            result =\n                stdioParams === undefined\n                    ? await negotiateEra(negotiation, { ...baseDeps, transport, transportKind })\n                    : await negotiateStdioViaSibling(negotiation, transport, stdioParams, baseDeps);\n        } catch (error) {\n            // Typed connect error — close the channel like a failed initialize does.\n            await transport.close().catch(() => {});\n            // The cleanup close has settled: any re-delivery of a spent\n            // mid-probe close has happened by now, so the spent-close guard\n            // must not outlive it — on transports whose close() never re-fires\n            // onclose (stdio), an armed guard would swallow the next GENUINE\n            // close after a restart.\n            disarmSpentCloseGuard(transport);\n            throw error;\n        }\n\n        // Success path: no cleanup close ever runs here, so no re-delivery of a\n        // spent mid-window close is coming — disarm any guard NOW, before\n        // Protocol chains the handler slot, or an in-place negotiation that\n        // succeeded after a same-tick reply-then-close would carry the armed\n        // skip into the live session and swallow its first genuine close.\n        disarmSpentCloseGuard(transport);\n\n        await super.connect(transport);\n\n        if (result.era === 'legacy') {\n            // Conservative fallback: the in-place probing modes run the plain\n            // legacy handshake on the probed connection; the sibling path runs\n            // it as the session child's first exchange (the probe never touched\n            // the transport version slot either way).\n            await this._legacyHandshake(transport, options);\n            return;\n        }\n\n        this._serverCapabilities = result.discover.capabilities;\n        this._serverVersion = serverInfoFromDiscover(result.discover);\n        this._cache.setServerIdentity(this._deriveServerIdentity(transport));\n        this._instructions = result.discover.instructions;\n        this._discoverResult = result.discover;\n        // Modern selection: the same connection state the legacy handshake completion sets.\n        this._negotiatedProtocolVersion = result.version;\n        // The single setProtocolVersion call site on this path, mirroring the legacy path after initialize.\n        if (transport.setProtocolVersion) {\n            transport.setProtocolVersion(result.version);\n        }\n        // The modern era has no notifications/initialized; list-changed handlers\n        // are configured straight from the advertised capabilities. On a modern\n        // connection the configured handlers are fed by an auto-opened\n        // subscriptions/listen stream (the modern era never delivers change\n        // notifications unsolicited); on a legacy connection they fire on the\n        // 2025-era unsolicited notifications, no listen needed.\n        if (this._listChangedConfig) {\n            const config = this._listChangedConfig;\n            // Compute configured ∩ server-advertised ONCE and use that single\n            // value for BOTH handler registration and the auto-open filter, so\n            // a configured-but-not-advertised type is neither subscribed to\n            // nor handled (the two stay in lockstep).\n            const advertised = this._serverCapabilities;\n            const effective: ListChangedHandlers = {\n                ...(config.tools && advertised?.tools?.listChanged && { tools: config.tools }),\n                ...(config.prompts && advertised?.prompts?.listChanged && { prompts: config.prompts }),\n                ...(config.resources && advertised?.resources?.listChanged && { resources: config.resources })\n            };\n            // Handler registration validates the per-type options and can\n            // throw on misconfiguration; the modern connection IS established\n            // at this point and is fully usable without listChanged handlers,\n            // so a misconfiguration surfaces via onerror and connect resolves\n            // (matching the auto-open soft-fail posture). When registration\n            // fails the auto-open is SKIPPED — opening a listen stream for\n            // types whose handler never registered would consume a server\n            // slot to deliver notifications nothing handles.\n            let handlersRegistered = true;\n            try {\n                this._setupListChangedHandlers(effective);\n            } catch (error) {\n                handlersRegistered = false;\n                this.onerror?.(error instanceof Error ? error : new Error(String(error)));\n            }\n            const filter: SubscriptionFilter = handlersRegistered\n                ? {\n                      ...(effective.tools && { toolsListChanged: true as const }),\n                      ...(effective.prompts && { promptsListChanged: true as const }),\n                      ...(effective.resources && { resourcesListChanged: true as const })\n                  }\n                : {};\n            if (Object.keys(filter).length > 0) {\n                // A failed auto-open MUST NOT fail connect: the modern\n                // connection is fully usable without a listen stream (the\n                // server may not support it, or refuse on capacity). Surface\n                // via onerror; the consumer can call listen() later.\n                //\n                // listen() binds RequestOptions.signal to the SUBSCRIPTION\n                // lifetime, so connect()'s signal must NOT be forwarded\n                // verbatim — a connect-scoped `AbortSignal.timeout(30_000)`\n                // would silently tear the auto-opened stream down the moment\n                // it fires after connect has resolved. But connect()'s signal\n                // MUST still cancel the in-connect ack WAIT (otherwise an\n                // aborted connect blocks here for the full ack timeout).\n                // Derived one-shot: bound to connect()'s signal only for the\n                // duration of the listen() await; the listener is removed in\n                // `finally` so the auto-opened subscription outlives connect's\n                // signal.\n                const ackAbort = new AbortController();\n                const onConnectAbort = (): void => ackAbort.abort(options?.signal?.reason);\n                // Handle the already-aborted case (aborted between the\n                // discover leg resolving and now): the listener never fires\n                // for a past event.\n                if (options?.signal?.aborted) onConnectAbort();\n                options?.signal?.addEventListener('abort', onConnectAbort);\n                try {\n                    this._autoOpenedSubscription = await this.listen(filter, {\n                        timeout: options?.timeout,\n                        signal: ackAbort.signal\n                    });\n                } catch (error) {\n                    // Connect-signal abort during the ack wait propagates as a\n                    // connect() rejection (caller asked to abort connect). The\n                    // transport is already started, so close it before\n                    // rethrowing — a connect() rejection MUST NOT leave a\n                    // half-open connection. A server-side refusal stays a\n                    // soft onerror (connect succeeds, no listen stream).\n                    if (options?.signal?.aborted) {\n                        await this.close().catch(() => {});\n                        throw error;\n                    }\n                    this.onerror?.(error instanceof Error ? error : new Error(String(error)));\n                } finally {\n                    options?.signal?.removeEventListener('abort', onConnectAbort);\n                }\n            }\n        }\n    }\n\n    /**\n     * Connect from a validated {@linkcode PriorDiscovery}: the modern arm\n     * adopts the `DiscoverResult` (zero round trips; `EraNegotiationFailed`\n     * on no 2026-07-28+ overlap), the legacy arm runs the plain legacy connect.\n     */\n    private async _connectFromPrior(transport: Transport, prior: PriorDiscovery, options?: RequestOptions): Promise<void> {\n        if (prior.kind === 'legacy') {\n            // Known-legacy verdict: byte-identical to a mode: 'legacy' connect.\n            return this._connectPlainLegacy(transport, options);\n        }\n        const discover = prior.discover;\n        this._resetConnectionState();\n\n        const explicit = this._supportedProtocolVersionsOption;\n        const clientModern =\n            explicit && modernProtocolVersions(explicit).length > 0 ? modernProtocolVersions(explicit) : SUPPORTED_MODERN_PROTOCOL_VERSIONS;\n        const version = clientModern.find(v => discover.supportedVersions.includes(v));\n        if (version === undefined) {\n            throw new SdkError(\n                SdkErrorCode.EraNegotiationFailed,\n                'connect({ prior }) with a modern verdict requires a 2026-07-28+ mutual protocol version; the supplied DiscoverResult and ' +\n                    \"this client's supportedProtocolVersions have no modern overlap. For a server known to be legacy, pass \" +\n                    \"prior: { kind: 'legacy' } to skip the probe and initialize directly, or use \" +\n                    \"versionNegotiation: { mode: 'auto' } to re-probe with legacy fallback.\"\n            );\n        }\n\n        await super.connect(transport);\n\n        this._discoverResult = discover;\n        this._serverCapabilities = discover.capabilities;\n        this._serverVersion = serverInfoFromDiscover(discover);\n        this._cache.setServerIdentity(this._deriveServerIdentity(transport));\n        this._instructions = discover.instructions;\n        this._negotiatedProtocolVersion = version;\n        transport.setProtocolVersion?.(version);\n\n        // No auto-opened listen stream on this path (request-only workers).\n        if (this._listChangedConfig) {\n            try {\n                this._setupListChangedHandlers(this._listChangedConfig);\n            } catch (error) {\n                this.onerror?.(error instanceof Error ? error : new Error(String(error)));\n            }\n        }\n    }\n\n    /**\n     * After initialization has completed, this will be populated with the server's reported capabilities.\n     */\n    getServerCapabilities(): ServerCapabilities | undefined {\n        return this._serverCapabilities;\n    }\n\n    /**\n     * The connected server's self-reported name and version, when it\n     * identified itself: required on the legacy `initialize` result; a spec\n     * SHOULD in the discover result's `_meta` on 2026-07-28, so a successful\n     * modern connect against an anonymous server leaves this `undefined`.\n     */\n    getServerVersion(): Implementation | undefined {\n        return this._serverVersion;\n    }\n\n    /**\n     * The connected server's identity for response-cache partitioning. The\n     * `serverInfo` `name@version` pair when available (required on\n     * `initialize`; a SHOULD in the discover result's `_meta` since spec PR\n     * #3002); falls back to the transport's `sessionId`, then to a\n     * per-connection surrogate. The surrogate matters since #3002 made\n     * identity optional: without it, two identity-less servers reached over\n     * sessionId-less transports would share the cache's pre-connect `''`\n     * partition and read each other's entries — no stable identity means no\n     * cross-connection cache reuse. The value itself is server-controlled —\n     * the collision-safety of the storage partition comes from\n     * {@linkcode ClientResponseCache}'s JSON-array encoding around it, not\n     * from any character it does or does not contain.\n     */\n    private _deriveServerIdentity(transport: Transport): string {\n        const v = this._serverVersion;\n        if (v !== undefined) return `${v.name}@${v.version}`;\n        return transport.sessionId ?? `anonymous:${Date.now()}-${Math.random().toString(36).slice(2)}`;\n    }\n\n    /**\n     * After initialization has completed, this will be populated with the protocol version negotiated\n     * during the initialize handshake. When manually reconstructing a transport for reconnection, pass this\n     * value to the new transport so it continues sending the required `mcp-protocol-version` header.\n     */\n    getNegotiatedProtocolVersion(): string | undefined {\n        return this._negotiatedProtocolVersion;\n    }\n\n    /**\n     * After initialization has completed, this returns the protocol era of the\n     * connection: `'modern'` when the connection negotiated a 2026-07-28+\n     * revision (via `server/discover`), `'legacy'` for the 2025-era\n     * `initialize` handshake, or `undefined` before the connection is\n     * established.\n     */\n    getProtocolEra(): ProtocolEra | undefined {\n        const version = this._negotiatedProtocolVersion;\n        if (version === undefined) return undefined;\n        return isModernProtocolVersion(version) ? 'modern' : 'legacy';\n    }\n\n    /**\n     * After initialization has completed, this may be populated with information about the server's instructions.\n     */\n    getInstructions(): string | undefined {\n        return this._instructions;\n    }\n\n    /**\n     * The {@linkcode DiscoverResult} from the last `'auto'`/pinned probe,\n     * {@linkcode discover} call, or `connect({ prior })` that adopted a\n     * modern verdict (a legacy verdict leaves this `undefined` — there is no\n     * `DiscoverResult` on that path). Persistable via `JSON.stringify`; wrap\n     * as `{ kind: 'modern', discover }` and feed to {@linkcode ConnectOptions}\n     * `prior`.\n     */\n    getDiscoverResult(): DiscoverResult | undefined {\n        return this._discoverResult;\n    }\n\n    protected assertCapabilityForMethod(method: RequestMethod | string): void {\n        switch (method as ClientRequest['method']) {\n            // Deprecated as of protocol version 2026-07-28 (SEP-2577); remains\n            // functional during the deprecation window (at least twelve months).\n            case 'logging/setLevel': {\n                if (!this._serverCapabilities?.logging) {\n                    throw new SdkError(SdkErrorCode.CapabilityNotSupported, `Server does not support logging (required for ${method})`);\n                }\n                break;\n            }\n\n            case 'prompts/get':\n            case 'prompts/list': {\n                if (!this._serverCapabilities?.prompts) {\n                    throw new SdkError(SdkErrorCode.CapabilityNotSupported, `Server does not support prompts (required for ${method})`);\n                }\n                break;\n            }\n\n            case 'resources/list':\n            case 'resources/templates/list':\n            case 'resources/read':\n            case 'resources/subscribe':\n            case 'resources/unsubscribe': {\n                if (!this._serverCapabilities?.resources) {\n                    throw new SdkError(SdkErrorCode.CapabilityNotSupported, `Server does not support resources (required for ${method})`);\n                }\n\n                if (method === 'resources/subscribe' && !this._serverCapabilities.resources.subscribe) {\n                    throw new SdkError(\n                        SdkErrorCode.CapabilityNotSupported,\n                        `Server does not support resource subscriptions (required for ${method})`\n                    );\n                }\n\n                break;\n            }\n\n            case 'tools/call':\n            case 'tools/list': {\n                if (!this._serverCapabilities?.tools) {\n                    throw new SdkError(SdkErrorCode.CapabilityNotSupported, `Server does not support tools (required for ${method})`);\n                }\n                break;\n            }\n\n            case 'completion/complete': {\n                if (!this._serverCapabilities?.completions) {\n                    throw new SdkError(SdkErrorCode.CapabilityNotSupported, `Server does not support completions (required for ${method})`);\n                }\n                break;\n            }\n\n            case 'initialize': {\n                // No specific capability required for initialize\n                break;\n            }\n\n            case 'server/discover': {\n                // No specific capability required for discover (protocol revision\n                // 2026-07-28; servers on that revision MUST implement it)\n                break;\n            }\n\n            case 'ping': {\n                // No specific capability required for ping\n                break;\n            }\n        }\n    }\n\n    protected assertNotificationCapability(method: NotificationMethod | string): void {\n        switch (method as ClientNotification['method']) {\n            // Deprecated as of protocol version 2026-07-28 (SEP-2577); remains\n            // functional during the deprecation window (at least twelve months).\n            case 'notifications/roots/list_changed': {\n                if (!this._capabilities.roots?.listChanged) {\n                    throw new SdkError(\n                        SdkErrorCode.CapabilityNotSupported,\n                        `Client does not support roots list changed notifications (required for ${method})`\n                    );\n                }\n                break;\n            }\n\n            case 'notifications/initialized': {\n                // No specific capability required for initialized\n                break;\n            }\n\n            case 'notifications/cancelled': {\n                // Cancellation notifications are always allowed\n                break;\n            }\n\n            case 'notifications/progress': {\n                // Progress notifications are always allowed\n                break;\n            }\n        }\n    }\n\n    protected assertRequestHandlerCapability(method: string): void {\n        switch (method) {\n            // Deprecated as of protocol version 2026-07-28 (SEP-2577); remains\n            // functional during the deprecation window (at least twelve months).\n            case 'sampling/createMessage': {\n                if (!this._capabilities.sampling) {\n                    throw new SdkError(\n                        SdkErrorCode.CapabilityNotSupported,\n                        `Client does not support sampling capability (required for ${method})`\n                    );\n                }\n                break;\n            }\n\n            case 'elicitation/create': {\n                if (!this._capabilities.elicitation) {\n                    throw new SdkError(\n                        SdkErrorCode.CapabilityNotSupported,\n                        `Client does not support elicitation capability (required for ${method})`\n                    );\n                }\n                break;\n            }\n\n            // Deprecated as of protocol version 2026-07-28 (SEP-2577); remains\n            // functional during the deprecation window (at least twelve months).\n            case 'roots/list': {\n                if (!this._capabilities.roots) {\n                    throw new SdkError(\n                        SdkErrorCode.CapabilityNotSupported,\n                        `Client does not support roots capability (required for ${method})`\n                    );\n                }\n                break;\n            }\n\n            case 'ping': {\n                // No specific capability required for ping\n                break;\n            }\n        }\n    }\n\n    async ping(options?: RequestOptions): Promise<EmptyResult> {\n        return this.request({ method: 'ping' }, options);\n    }\n\n    /**\n     * Send `server/discover` (2026-07-28+) and record the result for\n     * {@linkcode getDiscoverResult}.\n     */\n    async discover(options?: RequestOptions): Promise<DiscoverResult> {\n        const result = await this._requestWithSchema({ method: 'server/discover' }, DiscoverResultSchema, options);\n        this._discoverResult = result;\n        return result;\n    }\n\n    /** Requests argument autocompletion suggestions from the server for a prompt or resource. */\n    async complete(params: CompleteRequest['params'], options?: RequestOptions): Promise<CompleteResult> {\n        return this.request({ method: 'completion/complete', params }, options);\n    }\n\n    /**\n     * Sets the minimum severity level for log messages sent by the server.\n     *\n     * @deprecated Deprecated as of protocol version 2026-07-28 (SEP-2577).\n     * Remains functional during the deprecation window (at least twelve months).\n     * Migrate to stderr logging (STDIO servers) or OpenTelemetry.\n     */\n    async setLoggingLevel(level: LoggingLevel, options?: RequestOptions): Promise<EmptyResult> {\n        return this.request({ method: 'logging/setLevel', params: { level } }, options);\n    }\n\n    /** Retrieves a prompt by name from the server, passing the given arguments for template substitution. */\n    async getPrompt(params: GetPromptRequest['params'], options?: RequestOptions): Promise<GetPromptResult> {\n        return this.request({ method: 'prompts/get', params }, options);\n    }\n\n    /**\n     * Lists available prompts.\n     *\n     * Called without a `cursor` (the common case), this walks every page and\n     * returns the complete aggregated list with no `nextCursor`; the\n     * aggregate is also written to the {@linkcode ResponseCacheStore}. Pass an\n     * explicit `{ cursor }` to fetch a single page and walk pagination\n     * yourself — the per-page path returns the server's raw page (with\n     * `nextCursor` for the next call) and does not write the response cache.\n     * The auto-aggregate path is capped by\n     * {@linkcode ClientOptions | ClientOptions.listMaxPages} (default 64); the per-page path\n     * is not.\n     *\n     * Returns an empty list if the server does not advertise prompts capability\n     * (or throws if {@linkcode ClientOptions.enforceStrictCapabilities} is enabled).\n     *\n     * @example\n     * ```ts source=\"./client.examples.ts#Client_listPrompts_pagination\"\n     * // No cursor → all pages aggregated for you.\n     * const { prompts } = await client.listPrompts();\n     * console.log(\n     *     'Available prompts:',\n     *     prompts.map(p => p.name)\n     * );\n     * ```\n     */\n    async listPrompts(params?: ListPromptsRequest['params'], options?: CacheableRequestOptions): Promise<ListPromptsResult> {\n        if (!this._serverCapabilities?.prompts && !this._enforceStrictCapabilities) {\n            // Respect capability negotiation: server does not support prompts\n            console.debug('Client.listPrompts() called but server does not advertise prompts capability - returning empty list');\n            return { prompts: [] };\n        }\n        if (params?.cursor !== undefined) {\n            return this.request({ method: 'prompts/list', params }, options);\n        }\n        const hit = await this._serveFromCache<ListPromptsResult>('prompts/list', undefined, options);\n        if (hit !== undefined) return hit;\n        return this._listAllPages<ListPromptsResult>('prompts/list', params, options, r => r.prompts);\n    }\n\n    /**\n     * Lists available resources.\n     *\n     * Called without a `cursor` (the common case), this walks every page and\n     * returns the complete aggregated list with no `nextCursor`; the\n     * aggregate is also written to the {@linkcode ResponseCacheStore}. Pass an\n     * explicit `{ cursor }` to fetch a single page and walk pagination\n     * yourself — the per-page path returns the server's raw page (with\n     * `nextCursor` for the next call) and does not write the response cache.\n     * The auto-aggregate path is capped by\n     * {@linkcode ClientOptions | ClientOptions.listMaxPages} (default 64); the per-page path\n     * is not.\n     *\n     * Returns an empty list if the server does not advertise resources capability\n     * (or throws if {@linkcode ClientOptions.enforceStrictCapabilities} is enabled).\n     *\n     * @example\n     * ```ts source=\"./client.examples.ts#Client_listResources_pagination\"\n     * // No cursor → all pages aggregated for you.\n     * const { resources } = await client.listResources();\n     * console.log(\n     *     'Available resources:',\n     *     resources.map(r => r.name)\n     * );\n     * ```\n     */\n    async listResources(params?: ListResourcesRequest['params'], options?: CacheableRequestOptions): Promise<ListResourcesResult> {\n        if (!this._serverCapabilities?.resources && !this._enforceStrictCapabilities) {\n            // Respect capability negotiation: server does not support resources\n            console.debug('Client.listResources() called but server does not advertise resources capability - returning empty list');\n            return { resources: [] };\n        }\n        if (params?.cursor !== undefined) {\n            return this.request({ method: 'resources/list', params }, options);\n        }\n        const hit = await this._serveFromCache<ListResourcesResult>('resources/list', undefined, options);\n        if (hit !== undefined) return hit;\n        return this._listAllPages<ListResourcesResult>('resources/list', params, options, r => r.resources);\n    }\n\n    /**\n     * Lists available resource URI templates for dynamic resources.\n     *\n     * Called without a `cursor`, this walks every page and returns the\n     * complete aggregated list with no `nextCursor`; the aggregate is\n     * also written to the {@linkcode ResponseCacheStore}. Pass an explicit\n     * `{ cursor }` to fetch a single page — see\n     * {@linkcode listResources | listResources()} for the per-page contract.\n     *\n     * Returns an empty list if the server does not advertise resources capability\n     * (or throws if {@linkcode ClientOptions.enforceStrictCapabilities} is enabled).\n     */\n    async listResourceTemplates(\n        params?: ListResourceTemplatesRequest['params'],\n        options?: CacheableRequestOptions\n    ): Promise<ListResourceTemplatesResult> {\n        if (!this._serverCapabilities?.resources && !this._enforceStrictCapabilities) {\n            // Respect capability negotiation: server does not support resources\n            console.debug(\n                'Client.listResourceTemplates() called but server does not advertise resources capability - returning empty list'\n            );\n            return { resourceTemplates: [] };\n        }\n        if (params?.cursor !== undefined) {\n            return this.request({ method: 'resources/templates/list', params }, options);\n        }\n        const hit = await this._serveFromCache<ListResourceTemplatesResult>('resources/templates/list', undefined, options);\n        if (hit !== undefined) return hit;\n        return this._listAllPages<ListResourceTemplatesResult>('resources/templates/list', params, options, r => r.resourceTemplates);\n    }\n\n    /**\n     * Walk every page of a paginated list verb, aggregate, and write ONE\n     * entry to the response cache. Internal — backs the public `list*`\n     * methods' no-`cursor` auto-aggregate path. Page 1's result object is\n     * mutated in place (its items array is extended; `nextCursor` is\n     * cleared); page-1 metadata (`ttlMs`, `cacheScope`, `_meta`) is preserved.\n     * A page with the same items and `nextCursor` as the previous page ends the walk;\n     * {@linkcode ClientOptions.listMaxPages} is a hard cap — hitting it\n     * throws, so a partial aggregate is never cached. The\n     * captured-generation guard skips the write when a `list_changed` landed\n     * mid-walk, so the eviction is never overwritten by a stale aggregate.\n     * `finalize` runs on the complete aggregate before the cache write — the\n     * SEP-2243 invalid-`x-mcp-header` exclusion hooks here so the cached\n     * `tools/list` entry is already filtered.\n     *\n     * The caller's `baseParams` (everything except `cursor`) is threaded into\n     * every page request — page 1 sends `{...baseParams}`, later pages\n     * `{...baseParams, cursor}` — so a typed, documented `_meta` (e.g. W3C\n     * trace context) supplied to the public `list*()` reaches every wire\n     * request the walk issues.\n     */\n    private async _listAllPages<R extends { nextCursor?: string }>(\n        method: RequestMethod,\n        baseParams: { readonly [key: string]: unknown } | undefined,\n        options: CacheableRequestOptions | undefined,\n        items: (result: R) => unknown[],\n        finalize?: (acc: R) => void\n    ): Promise<R> {\n        // `'bypass'` is the no-touch path: the cache is neither read nor\n        // written, so the substrate is byte-untouched (the `tools/list`\n        // derived index keeps whatever it held).\n        const bypass = options?.cacheMode === 'bypass';\n        // Capture the eviction generation BEFORE page 1: a `list_changed` that\n        // lands mid-walk bumps the counter, and the terminal `write` skips\n        // when it observes the bump (the result still returns to the caller —\n        // it just is not cached).\n        const generation = this._cache.captureGeneration(method);\n        const fetchPage = (cursor: string | undefined): Promise<R> => {\n            const params = cursor === undefined ? baseParams && { ...baseParams } : { ...baseParams, cursor };\n            return this.request({ method, ...(params && { params }) }, options) as Promise<R>;\n        };\n        const acc = await this._walkPages(method, fetchPage, items);\n        // delete, not `= undefined`: the cache's JSON codec drops\n        // explicit-undefined properties, so only absence keeps\n        // `'nextCursor' in result` identical between wire and cache hit.\n        delete acc.nextCursor;\n        finalize?.(acc);\n        if (bypass) return acc;\n        // The aggregate is ALWAYS written: even when the resolved TTL is ≤0\n        // the entry is stored already-stale (mcp.d's `retainForSchema`\n        // posture) so the `tools/list`-derived index keeps working regardless,\n        // while the freshness gate in `_serveFromCache` never serves it.\n        // Page-1 carries the result-level `ttlMs`/`cacheScope` (`acc` IS the\n        // mutated page-1 object).\n        await this._cache.write(method, acc, generation, this._freshness(acc));\n        return acc;\n    }\n\n    // Every page's items appended to page 1's: `listMaxPages` caps the walk, a page repeating the one before ends it.\n    private async _walkPages<R extends { nextCursor?: string }>(\n        method: string,\n        fetchPage: (cursor: string | undefined) => Promise<R>,\n        items: (result: R) => unknown[]\n    ): Promise<R> {\n        const acc = await fetchPage(undefined);\n        let cursor = acc.nextCursor;\n        let previous = acc;\n        let pages = 1;\n        while (cursor !== undefined) {\n            if (this._listMaxPages !== 0 && pages >= this._listMaxPages) {\n                throw new SdkError(\n                    SdkErrorCode.ListPaginationExceeded,\n                    `${method}: exceeded listMaxPages (${this._listMaxPages}); server pagination did not terminate`,\n                    { method, listMaxPages: this._listMaxPages }\n                );\n            }\n            const page = await fetchPage(cursor);\n            // Same items and same cursor as the page before: the server made no progress.\n            if (page.nextCursor === cursor && JSON.stringify(items(page)) === JSON.stringify(items(previous))) break;\n            items(acc).push(...items(page));\n            previous = page;\n            cursor = page.nextCursor;\n            pages++;\n        }\n        return acc;\n    }\n\n    /**\n     * Compute the {@linkcode ClientResponseCache.write} freshness payload from\n     * a cacheable result body. The single seam through which the client reads\n     * `ttlMs`/`cacheScope` (mcp.d's `cachedFetch` engine). The fields pass\n     * through the loose result schema, so they are read off the runtime body;\n     * a missing `ttlMs` falls back to\n     * {@linkcode ClientOptions | ClientOptions.defaultCacheTtlMs}; an explicit server-sent\n     * `ttlMs` (including `0` — the spec's \"immediately stale\") is honoured\n     * as-is. The default of `0` means `expiresAt === now()` ⇒ never served,\n     * only stored. A missing `cacheScope` is treated as `'private'` — the\n     * spec's `'public'` grant (\"any client … MAY serve to any user\") is too\n     * strong to infer by default, and matches this SDK's server-side stamp\n     * default.\n     */\n    private _freshness(result: unknown, params?: string): { expiresAt: number; scope: CacheScope; params?: string } {\n        const body = result as { ttlMs?: unknown; cacheScope?: unknown };\n        const ttlMs = typeof body.ttlMs === 'number' ? body.ttlMs : this._defaultCacheTtlMs;\n        const scope: CacheScope = body.cacheScope === 'public' ? 'public' : 'private';\n        // Clamp at 24h (`MAX_CACHE_TTL_MS`) so a server cannot pin an entry\n        // indefinitely; floor at 0 so a negative `ttlMs` is treated as\n        // immediately stale (the spec's absent-or-≤0 rule).\n        return { expiresAt: this._cache.now() + Math.min(Math.max(0, ttlMs), MAX_CACHE_TTL_MS), scope, params };\n    }\n\n    /**\n     * The cache-serving front of every cacheable verb (mcp.d's `cachedFetch`\n     * read half): under `cacheMode: 'use'` (the default), a fresh held entry\n     * is served and the round trip is skipped. `'refresh'` and `'bypass'`\n     * always fetch (the caller decides whether to write). Freshness and\n     * decoding live in {@linkcode ClientResponseCache.read}; every hit is\n     * freshly parsed, so the caller owns it outright. A custom store\n     * whose `get()` rejects is routed to `onerror` and treated as a miss —\n     * cache bookkeeping never blocks a request from reaching the wire.\n     */\n    private async _serveFromCache<R>(\n        method: string,\n        params: string | undefined,\n        options: CacheableRequestOptions | undefined\n    ): Promise<R | undefined> {\n        if (options?.cacheMode === 'bypass' || options?.cacheMode === 'refresh') return undefined;\n        const hit = await this._cache.read(method, params).catch(error => void this._reportStoreError(error));\n        if (hit !== undefined) {\n            // A pre-aborted caller signal must reject the same way it would on\n            // the wire path (`Protocol.request()` wraps an already-aborted\n            // signal as `SdkError(RequestTimeout, reason)`); without this guard\n            // a cache hit would resolve successfully and silently swallow the\n            // abort.\n            if (options?.signal?.aborted) {\n                const reason = options.signal.reason;\n                throw reason instanceof SdkError ? reason : new SdkError(SdkErrorCode.RequestTimeout, String(reason));\n            }\n            return hit.value as R;\n        }\n        return undefined;\n    }\n\n    /** Route a custom-store failure to `onerror` without aborting the surrounding dispatch. */\n    private _reportStoreError(e: unknown): void {\n        this.onerror?.(e instanceof Error ? e : new Error(String(e)));\n    }\n\n    /**\n     * Compile a single tool's `outputSchema`. Passed as the compile callback to\n     * {@linkcode ClientResponseCache.outputValidator} so the cache class stays\n     * free of any validator-provider dependency, and called directly for the\n     * `options.toolDefinition` path of {@linkcode callTool} (a one-off\n     * caller-supplied definition is compiled in isolation and never enters the\n     * cache, so it cannot poison the listed tool of the same name).\n     *\n     * Returns `undefined` when the tool has no `outputSchema`, or a\n     * discriminated `{ok}` result otherwise. SEP-2106: ANY throw from the\n     * validator engine — unsupported `$schema` dialect, invalid `pattern`\n     * regex, unresolvable `$ref`, or any other engine error — is captured as\n     * `{ok: false, compileError}` so one bad schema does not poison the rest\n     * of the listing; `callTool()` surfaces it as an `InvalidParams` error\n     * before the request. The `{ok}` discriminator (not\n     * `compileError !== undefined`) means a custom provider that does\n     * `throw undefined` is still treated as a captured failure.\n     */\n    private _compileOutputValidator(tool: Tool): OutputSchemaCompileResult | undefined {\n        if (!tool.outputSchema) return undefined;\n        try {\n            return { ok: true, validator: this._jsonSchemaValidator.getValidator(tool.outputSchema as JsonSchemaType) };\n        } catch (error) {\n            return { ok: false, compileError: error };\n        }\n    }\n\n    /**\n     * Resolve the SEP-2243 `x-mcp-header` declaration scan for a tool name.\n     *\n     * The caller-supplied `toolDefinition` escape hatch wins; otherwise the\n     * cached `tools/list` entry (via the cache's `toolDefinition`) is the\n     * source. Freshness is the response cache's lifecycle: `list_changed`\n     * evicts, otherwise the held schema is the best information available\n     * regardless of age, and a stale schema is recovered through the\n     * `HEADER_MISMATCH` → evict-refetch-retry path in {@linkcode callTool}.\n     * On a miss the call proceeds without `Mcp-Param-*` headers (the spec's\n     * \"client SHOULD send without custom headers\" guidance) and relies on the\n     * same recovery.\n     */\n    private async _resolveXMcpHeaderScan(name: string, override: Tool | undefined): Promise<XMcpHeaderScanResult | undefined> {\n        const tool = override ?? (await this._cache.toolDefinition(name));\n        return tool === undefined ? undefined : scanXMcpHeaderDeclarations(tool.inputSchema);\n    }\n\n    /**\n     * Reads the contents of a resource by URI.\n     *\n     * Honours the result's `ttlMs`/`cacheScope` (SEP-2549): a still-fresh\n     * cached body for the same `uri` is returned without a round trip\n     * (`cacheMode: 'use'`, the default). The cache key is `{method, uri}`\n     * partitioned by the resolved scope — `'private'` (the default when the\n     * server omits the field) is stored under this client's\n     * {@linkcode ClientOptions | ClientOptions.cachePartition}, so a shared\n     * store cannot serve one principal's resource body to another. Unlike the\n     * list verbs, a result whose resolved TTL is ≤0 is **not** stored\n     * (`resources/read` has no derived index and the URI keyspace is\n     * unbounded).\n     */\n    async readResource(params: ReadResourceRequest['params'], options?: CacheableRequestOptions): Promise<ReadResourceResult> {\n        const { result } = await this._readResource(params, options);\n        return result;\n    }\n\n    // `readResource`, and whether the result came from the response cache.\n    private async _readResource(\n        params: ReadResourceRequest['params'],\n        options: CacheableRequestOptions | undefined\n    ): Promise<{ result: ReadResourceResult; cached: boolean }> {\n        const hit = await this._serveFromCache<ReadResourceResult>('resources/read', params.uri, options);\n        if (hit !== undefined) return { result: hit, cached: true };\n        // Capture the per-URI eviction generation BEFORE the request: a\n        // `notifications/resources/updated` for this URI arriving while the\n        // read is in flight bumps it (via `evictKey`), and the terminal\n        // `write` skips so the now-stale body is not re-cached. Same guard as\n        // the list verbs' `_listAllPages`, keyed by `{method, uri}`.\n        const generation = this._cache.captureGeneration('resources/read', params.uri);\n        const result = await this.request({ method: 'resources/read', params }, options);\n        if (options?.cacheMode !== 'bypass') {\n            const freshness = this._freshness(result, params.uri);\n            if (freshness.expiresAt > this._cache.now()) {\n                await this._cache.write('resources/read', result, generation, freshness);\n            } else if (options?.cacheMode === 'refresh') {\n                // ttl≤0 → drop any held positive-TTL entry so the next\n                // default-mode read fetches fresh — a `'refresh'` that\n                // returns ttl≤0 must not leave the previously-warm entry\n                // serving stale until its old expiry (mcp.d's `cachedFetch`\n                // write half evicts on the no-store branch). Only on the\n                // `'refresh'` path: a default-mode miss already proved\n                // nothing fresh is held (`_serveFromCache` returned\n                // `undefined`), so `evictKey`'s store deletes would be wasted\n                // round trips against an async store on a ttl≤0 working set.\n                await this._cache.evictKey('resources/read', params.uri);\n            }\n        }\n        return { result, cached: false };\n    }\n\n    /** Subscribes to change notifications for a resource. The server must support resource subscriptions. */\n    async subscribeResource(params: SubscribeRequest['params'], options?: RequestOptions): Promise<EmptyResult> {\n        return this.request({ method: 'resources/subscribe', params }, options);\n    }\n\n    /** Unsubscribes from change notifications for a resource. */\n    async unsubscribeResource(params: UnsubscribeRequest['params'], options?: RequestOptions): Promise<EmptyResult> {\n        return this.request({ method: 'resources/unsubscribe', params }, options);\n    }\n\n    /**\n     * Opens a `subscriptions/listen` stream (protocol revision 2026-07-28).\n     *\n     * Resolves once the server's `notifications/subscriptions/acknowledged`\n     * arrives (the standard request timeout applies to this ack phase). Change\n     * notifications delivered on the stream are dispatched to the existing\n     * {@linkcode setNotificationHandler} registrations — the same handlers the\n     * 2025-era unsolicited notifications fire on a legacy connection — so\n     * `listen()` is era-transparent for consumers that already register those.\n     *\n     * `close()` tears the subscription down by aborting the listen request's\n     * `requestSignal` (closes the SSE stream where the transport honors it)\n     * AND sending `notifications/cancelled` referencing the listen request id\n     * — both, unconditionally, so any spec-compliant server on any transport\n     * sees the cancel. No automatic re-listen — call `listen()` again to\n     * re-establish.\n     *\n     * On a 2025-era connection this throws a typed\n     * {@linkcode SdkErrorCode.MethodNotSupportedByProtocolVersion} steering to\n     * `resources/subscribe` and `ClientOptions.listChanged` (the legacy\n     * unsolicited delivery model still applies there); no transparent shim.\n     */\n    async listen(filter: SubscriptionFilter, options?: RequestOptions): Promise<McpSubscription> {\n        // Connectivity is checked first so a closed instance rejects with\n        // NotConnected (no setup or ack timer is started); after close(),\n        // `_resetConnectionState` has also cleared the negotiated era, so the\n        // era guard alone would surface a misleading\n        // MethodNotSupportedByProtocolVersion.\n        if (this.transport === undefined) {\n            throw new SdkError(SdkErrorCode.NotConnected, 'Not connected');\n        }\n        const negotiated = this._negotiatedProtocolVersion;\n        if (negotiated === undefined || !isModernProtocolVersion(negotiated)) {\n            throw new SdkError(\n                SdkErrorCode.MethodNotSupportedByProtocolVersion,\n                `subscriptions/listen requires a 2026-07-28-era connection (negotiated: ${negotiated ?? 'none'}). ` +\n                    'On a 2025-era connection, change notifications are delivered unsolicited: use ClientOptions.listChanged ' +\n                    'and resources/subscribe instead.',\n                { method: 'subscriptions/listen', protocolVersion: negotiated }\n            );\n        }\n\n        // Honor RequestOptions.signal exactly as request() does: an\n        // already-aborted signal rejects synchronously before any setup, and\n        // the rejection is the same `SdkError(RequestTimeout, reason)` wrap\n        // request() / `_serveFromCache` apply (unless `reason` is already an\n        // SdkError — preserved verbatim).\n        if (options?.signal?.aborted) {\n            const reason = options.signal.reason;\n            throw reason instanceof SdkError ? reason : new SdkError(SdkErrorCode.RequestTimeout, String(reason));\n        }\n\n        const requestAbort = new AbortController();\n        // The listen request's JSON-RPC id (= the spec's subscription id\n        // verbatim). A STRING from a Client-owned counter so it cannot\n        // collide with Protocol's numeric `_requestMessageId` counter — the\n        // `_onresponse`/`_onnotification` overrides demux by string-id alone.\n        const listenId = `listen:${this._nextListenId++}`;\n\n        // Explicit `opening → open → closed` state machine. Every termination\n        // path — ack-arrives, ack-timeout, server-cancelled, user-close,\n        // stream-end, transport-close, send-failure — funnels through the\n        // single `settle` below, which clears the ack timer, transitions\n        // state, and resolves/rejects the opening promise exactly once. The\n        // cancelled-before-ack / close-before-ack hangs are impossible by\n        // construction.\n        let state: 'opening' | 'open' | 'closed' = 'opening';\n        let ackTimer: ReturnType<typeof setTimeout> | undefined;\n        let onCallerAbort: (() => void) | undefined;\n        let resolveOpening!: (honored: SubscriptionFilter) => void;\n        let rejectOpening!: (error: Error) => void;\n        const opening = new Promise<SubscriptionFilter>((resolve, reject) => {\n            resolveOpening = resolve;\n            rejectOpening = reject;\n        });\n        // The McpSubscription.closed observation. Resolved exactly once by\n        // settle()'s `→ closed` transition; never rejects. When listen()\n        // itself rejects (pre-ack) there is no McpSubscription to observe it\n        // on — settle() resolves it anyway so nothing dangles.\n        let resolveClosed!: (cause: 'local' | 'graceful' | 'remote') => void;\n        const closed = new Promise<'local' | 'graceful' | 'remote'>(resolve => {\n            resolveClosed = resolve;\n        });\n\n        const settle = (outcome: { ack: SubscriptionFilter } | { cause: 'local' | 'graceful' | 'remote'; error?: Error }): void => {\n            if (state === 'closed') return;\n            const wasOpening = state === 'opening';\n            if (ackTimer !== undefined) {\n                clearTimeout(ackTimer);\n                ackTimer = undefined;\n            }\n            if ('ack' in outcome) {\n                // The single `opening → open` transition; an ack after close\n                // hits the `closed` guard above and is a no-op.\n                state = 'open';\n                resolveOpening(outcome.ack);\n                return;\n            }\n            state = 'closed';\n            if (onCallerAbort !== undefined) {\n                options?.signal?.removeEventListener('abort', onCallerAbort);\n            }\n            this._listenState.delete(listenId);\n            // Abort the per-request signal so an HTTP SSE reader stops on a\n            // remote-initiated close too (server-cancel / stream-end /\n            // transport-drop). Idempotent; a no-op on transports that ignore\n            // requestSignal. wireTeardown() also aborts on the local paths —\n            // harmless redundancy.\n            requestAbort.abort();\n            resolveClosed(outcome.cause);\n            if (wasOpening) {\n                rejectOpening(\n                    outcome.error ??\n                        new SdkError(SdkErrorCode.ConnectionClosed, 'subscriptions/listen closed before the server acknowledged')\n                );\n            }\n        };\n\n        // Wire-level teardown for a locally-initiated close (user close, ack\n        // timeout, caller-signal abort). Transport-agnostic: ALWAYS abort the\n        // request signal (closes the SSE stream where the transport honors\n        // `requestSignal` — HTTP does, stdio does not) AND send\n        // `notifications/cancelled` referencing the listen id (which the\n        // stdio listen router and any spec-compliant server honor). Sent via\n        // `notification()` so the modern auto-envelope is attached exactly as\n        // for every other outbound. Idempotent over HTTP — the cancelled\n        // notification is a no-op once the stream is gone; correct on every\n        // other transport. Not called when the server already terminated.\n        const wireTeardown = async (): Promise<void> => {\n            requestAbort.abort();\n            await this.notification({ method: 'notifications/cancelled', params: { requestId: listenId } }).catch(() => {});\n        };\n\n        const close = async (): Promise<void> => {\n            if (state === 'closed') return;\n            settle({ cause: 'local' });\n            await wireTeardown();\n        };\n\n        // The per-subscription state is registered BEFORE the request is sent\n        // so a synchronously-delivered ack (an in-process transport) cannot\n        // race the registration.\n        this._listenState.set(listenId, { settle });\n\n        const ackTimeout = options?.timeout ?? DEFAULT_REQUEST_TIMEOUT_MSEC;\n        ackTimer = setTimeout(() => {\n            settle({\n                cause: 'remote',\n                error: new SdkError(SdkErrorCode.RequestTimeout, 'subscriptions/listen ack timed out', { timeout: ackTimeout })\n            });\n            void wireTeardown().catch(() => {});\n        }, ackTimeout);\n\n        // RequestOptions.signal aborts the subscription at any point in its\n        // lifecycle (mirrors request()'s cancel path). While `opening`, settle\n        // rejects the pending listen() promise with the signal's reason; while\n        // `open`, it transitions to `closed` (`closed` resolves `'local'`) and\n        // tears the wire down. The listener is removed by `settle()` once the\n        // subscription has closed.\n        if (options?.signal) {\n            const callerSignal = options.signal;\n            onCallerAbort = () => {\n                if (state === 'closed') return;\n                const reason = callerSignal.reason;\n                settle({ cause: 'local', error: reason instanceof Error ? reason : new Error(String(reason ?? 'Aborted')) });\n                void wireTeardown().catch(() => {});\n            };\n            callerSignal.addEventListener('abort', onCallerAbort, { once: true });\n        }\n\n        // Send the listen request directly on the transport. The `_meta`\n        // envelope is built via the same `_outboundMetaEnvelope()` seam every\n        // other outbound uses (so a future envelope key cannot silently\n        // diverge here). `onRequestStreamEnd` feeds the per-request stream's\n        // non-deliberate end into the state machine on transports that open\n        // one (Streamable HTTP); stdio/InMemory ignore it.\n        const jsonrpcRequest: JSONRPCRequest = {\n            jsonrpc: '2.0',\n            id: listenId,\n            method: 'subscriptions/listen',\n            params: { _meta: { ...this._outboundMetaEnvelope() }, notifications: filter }\n        };\n        // The send is NOT serially awaited: `opening` must be the promise\n        // listen() suspends on so that a settle() firing while the send is\n        // still in flight (ack timeout, transport close, server cancel, a\n        // stdio send parked on 'drain') rejects a promise whose handler is\n        // already attached — otherwise the rejection escapes as a\n        // process-level unhandledRejection the caller cannot prevent, and a\n        // send that never settles leaves listen() suspended forever even\n        // though the ack timer already fired.\n        const routeSendFailure = (error: unknown): void => {\n            // Send failure (including a per-request abort fired before\n            // response headers — `streamableHttp._send` rethrows with onerror\n            // suppressed). `settle()` is idempotent so a locally-aborted send\n            // hitting this path after `close()` is a no-op.\n            settle({ cause: 'remote', error: error instanceof Error ? error : new Error(String(error)) });\n        };\n        try {\n            this.transport\n                .send(jsonrpcRequest, {\n                    requestSignal: requestAbort.signal,\n                    onRequestStreamEnd: () => settle({ cause: 'remote', error: new Error('subscriptions/listen: stream ended') })\n                })\n                .catch(routeSendFailure);\n        } catch (error) {\n            // A synchronous throw from send() (before it returns a promise).\n            routeSendFailure(error);\n        }\n\n        const honored = await opening;\n        return { honoredFilter: honored, close, closed };\n    }\n\n    /**\n     * The subscription auto-opened by `ClientOptions.listChanged` on a modern\n     * connection — the listen filter is the intersection of the configured\n     * sub-options and the server-advertised `listChanged` capabilities.\n     * `undefined` on a legacy connection, before connect, or when that\n     * intersection is empty (auto-open skipped). Exposed so the consumer can\n     * `close()` it.\n     */\n    get autoOpenedSubscription(): McpSubscription | undefined {\n        return this._autoOpenedSubscription;\n    }\n\n    /**\n     * Transport-level demux for `subscriptions/listen` notifications, before\n     * any decoding/era-gating/handler dispatch. Consumes the leading\n     * `notifications/subscriptions/acknowledged` referencing a live\n     * subscription id (resolves the ack waiter) and an inbound\n     * `notifications/cancelled` referencing a live string-typed subscription\n     * id (server-side teardown on stdio). Change notifications carrying a\n     * subscription id pass through to the existing registered handlers via\n     * `super`. An unmatched ack/cancelled is NOT consumed: it reaches\n     * `setNotificationHandler` / `fallbackNotificationHandler` instead of\n     * being silently swallowed.\n     */\n    protected override _onnotification(raw: JSONRPCNotification, extra?: MessageExtraInfo): void {\n        // Response-cache invalidation: a `list_changed` notification means the\n        // matching cached list result is stale. Evict (do NOT refetch) before\n        // dispatch so a handler that reaches the cache observes the cleared\n        // entry. Runs regardless of whether the user\n        // configured `listChanged` — derived views (the tool index, output\n        // validators) must drop the stale entry either way. `raw.method` is\n        // server-controlled; guard with `Object.hasOwn` so an inherited\n        // `Object.prototype` member name (`constructor`, `toString`, …) does\n        // not reach the iteration as a non-iterable function.\n        const evicted = Object.hasOwn(LIST_CHANGED_EVICTIONS, raw.method) ? LIST_CHANGED_EVICTIONS[raw.method] : undefined;\n        if (raw.method === 'notifications/resources/updated') {\n            // Per-URI eviction (mcp.d's `invalidateLogical`): the now-cached\n            // `resources/read` body for this URI is stale on receipt; drop it\n            // from BOTH partitions so the next `readResource` for the same URI\n            // refetches even within TTL (the documented subscribe → updated →\n            // re-read flow). Fire-and-forget like the `list_changed` path —\n            // dispatch must not block on an async store.\n            const uri = (raw.params as { uri?: unknown } | undefined)?.uri;\n            if (typeof uri === 'string') void this._cache.evictKey('resources/read', uri);\n        } else if (evicted !== undefined) {\n            for (const method of evicted) {\n                // `evict()` bumps the generation FIRST and unconditionally\n                // (the `ClientResponseCache.write` race guard relies on the\n                // bump, not on the store's deletes completing), then drops only THIS\n                // server's two partition singletons — co-tenants on a shared\n                // store keep their entries. Store failures are reported via\n                // `onerror` inside `evict()` and the call resolves, so\n                // dispatch (and the user's `listChanged` handler) runs\n                // regardless. Fire-and-forget — dispatch must not block on\n                // an async store.\n                void this._cache.evict(method);\n            }\n        }\n        if (raw.method === 'notifications/subscriptions/acknowledged') {\n            const params = raw.params as { _meta?: Record<string, unknown>; notifications?: unknown } | undefined;\n            const subscriptionId = params?._meta?.[SUBSCRIPTION_ID_META_KEY];\n            const entry = typeof subscriptionId === 'string' ? this._listenState.get(subscriptionId) : undefined;\n            if (entry !== undefined) {\n                // Route through the era codec (the ack is 2026-only\n                // vocabulary): a malformed honored filter still settles the\n                // listen — `{}` means \"nothing honored\".\n                const honored = this._wireCodec().validateNotification('notifications/subscriptions/acknowledged', raw);\n                entry.settle({ ack: honored.ok ? honored.value.params.notifications : {} });\n                return;\n            }\n        }\n        if (raw.method === 'notifications/cancelled') {\n            const cancelledId = (raw.params as { requestId?: unknown } | undefined)?.requestId;\n            const entry = typeof cancelledId === 'string' ? this._listenState.get(cancelledId) : undefined;\n            if (entry !== undefined) {\n                // Handles BOTH the pre-ack and post-ack server-side cancel:\n                // while opening, settle rejects the pending listen() promise;\n                // once open, settle transitions to closed and `closed` resolves\n                // 'remote' so the consumer can observe the server-initiated\n                // close.\n                entry.settle({ cause: 'remote', error: new Error('subscriptions/listen: server cancelled the subscription') });\n                return;\n            }\n        }\n        super._onnotification(raw, extra);\n    }\n\n    /**\n     * Transport-level demux for `subscriptions/listen` responses. A JSON-RPC\n     * ERROR for the listen id is the server's pre-ack capacity/params\n     * rejection; a JSON-RPC RESULT for the listen id is the spec's\n     * `SubscriptionsListenResult` — the server's GRACEFUL-close signal (sent\n     * on shutdown). A string-id response that matches a live `_listenState`\n     * entry is consumed here (Protocol's `_responseHandlers` map is keyed by\n     * NUMBER and never holds a listen id, so passing a string-id response\n     * through would surface as \"unknown message ID\" via `onerror`).\n     */\n    protected override _onresponse(response: JSONRPCResponse): void {\n        const id = response.id;\n        const entry = typeof id === 'string' ? this._listenState.get(id) : undefined;\n        if (entry !== undefined) {\n            if (isJSONRPCErrorResponse(response)) {\n                entry.settle({\n                    cause: 'remote',\n                    error: ProtocolError.fromError(response.error.code, response.error.message, response.error.data)\n                });\n            } else {\n                // The empty `SubscriptionsListenResult` — the server ended\n                // the subscription deliberately. Handles both pre-ack and\n                // post-ack: while opening, settle rejects the pending listen()\n                // promise with a ConnectionClosed (a server that answers\n                // before the ack is shutting down before serving); once open,\n                // settle transitions to closed and `closed` resolves\n                // 'graceful'. Per Q8, the result body itself is not validated\n                // — receipt for the listen id IS the signal (foreign servers\n                // may omit `_meta`).\n                entry.settle({\n                    cause: 'graceful',\n                    error: new SdkError(\n                        SdkErrorCode.ConnectionClosed,\n                        'subscriptions/listen: server closed the subscription gracefully before acknowledging'\n                    )\n                });\n            }\n            return;\n        }\n        super._onresponse(response);\n    }\n\n    /**\n     * Settle every live per-listen state machine on a transport-initiated\n     * close (the server dropping the connection on stdio/InMemory) before\n     * Protocol's `_onclose` tears the transport down. The base\n     * `_responseHandlers` settlement does not reach `_listenState` (listen\n     * ids are never registered there), so without this override a remote\n     * close would leave an in-flight `listen()` / open `McpSubscription`\n     * hanging.\n     */\n    protected override _onclose(): void {\n        if (this._listenState.size > 0) {\n            const reason = new SdkError(SdkErrorCode.ConnectionClosed, 'Connection closed');\n            for (const entry of this._listenState.values()) {\n                entry.settle({ cause: 'remote', error: reason });\n            }\n            this._listenState.clear();\n        }\n        super._onclose();\n    }\n\n    /**\n     * Calls a tool on the connected server and returns the result. Automatically validates structured output\n     * if the tool has an `outputSchema`.\n     *\n     * Tool results have two error surfaces: `result.isError` for tool-level failures (the tool ran but reported\n     * a problem), and thrown {@linkcode ProtocolError} for protocol-level failures or {@linkcode SdkError} for\n     * SDK-level issues (timeouts, missing capabilities).\n     *\n     * @example Basic usage\n     * ```ts source=\"./client.examples.ts#Client_callTool_basic\"\n     * const result = await client.callTool({\n     *     name: 'calculate-bmi',\n     *     arguments: { weightKg: 70, heightM: 1.75 }\n     * });\n     *\n     * // Tool-level errors are returned in the result, not thrown\n     * if (result.isError) {\n     *     console.error('Tool error:', result.content);\n     *     return;\n     * }\n     *\n     * console.log(result.content);\n     * ```\n     *\n     * @example Structured output\n     * ```ts source=\"./client.examples.ts#Client_callTool_structuredOutput\"\n     * const result = await client.callTool({\n     *     name: 'calculate-bmi',\n     *     arguments: { weightKg: 70, heightM: 1.75 }\n     * });\n     *\n     * // Machine-readable output for the client application. SEP-2106: structuredContent is\n     * // `unknown` (any JSON value). Check for presence with `!== undefined` and narrow before use.\n     * if (result.structuredContent !== undefined) {\n     *     const sc: unknown = result.structuredContent; // e.g. { bmi: 22.86 }\n     *     if (typeof sc === 'object' && sc !== null && 'bmi' in sc) {\n     *         console.log(sc.bmi);\n     *     }\n     * }\n     * ```\n     */\n    async callTool(params: CallToolRequest['params'], options?: CallToolRequestOptions): Promise<CallToolResult> {\n        // SEP-2243 `Mcp-Param-*` mirroring (protocol revision 2026-07-28; the\n        // 5-step client algorithm, steps 3–5). Modern-era only — the legacy\n        // `callTool` path is byte-untouched. Transports that share a single\n        // channel (stdio, in-memory) ignore the per-request `headers` option,\n        // so the spec's stdio MAY-ignore exemption holds without an explicit\n        // branch. In a browser environment, dynamically named `Mcp-Param-*`\n        // headers cannot be statically allow-listed for credentialed CORS\n        // (`Access-Control-Allow-Headers` admits no wildcard with\n        // credentials), so mirroring is skipped. NOTE: a conforming SEP-2243\n        // server (including this SDK's own `createMcpHandler`) rejects a\n        // `tools/call` whose body carries a non-null value for an\n        // `x-mcp-header`-declared parameter when the matching `Mcp-Param-*`\n        // header is absent — so a browser client of this SDK cannot\n        // successfully call such a tool with that argument present unless the\n        // server relaxes the missing-header check. This is a known limitation\n        // of running SEP-2243 from a browser; pass `null` for the designated\n        // argument or supply `options.toolDefinition` against a relaxed server.\n        const mirroringActive = this.getProtocolEra() === 'modern' && detectProbeEnvironment() !== 'browser';\n        // Mirroring (and output-schema validation below) read the cached\n        // `tools/list` entry directly via `_cache.toolDefinition` /\n        // `_cache.outputValidator`. `callTool` never issues a `tools/list`\n        // itself — the cache is populated by the caller's own\n        // {@linkcode listTools | listTools()} (which now auto-aggregates) and\n        // by the `HEADER_MISMATCH` recovery path below. A cold cache means\n        // the call proceeds without `Mcp-Param-*` headers (the spec's\n        // \"client SHOULD send without custom headers\" guidance) and without\n        // output-schema validation (the v1.x opportunistic behaviour, kept so\n        // a legacy/stdio `callTool` still issues zero extra requests).\n        const buildSendOptions = async (): Promise<CallToolRequestOptions | undefined> => {\n            if (!mirroringActive) return options;\n            // A custom store's `get()` may reject (the documented store\n            // contract); route that to `onerror` and degrade to sending\n            // without `Mcp-Param-*` headers — same posture as a cold cache —\n            // rather than aborting the call before it reaches the wire.\n            let scan: XMcpHeaderScanResult | undefined;\n            try {\n                scan = await this._resolveXMcpHeaderScan(params.name, options?.toolDefinition);\n            } catch (error) {\n                this._reportStoreError(error);\n            }\n            if (!scan?.valid || scan.declarations.length === 0) return options;\n            const paramHeaders = buildMcpParamHeaders(scan.declarations, params.arguments);\n            return Object.keys(paramHeaders).length === 0 ? options : { ...options, headers: { ...options?.headers, ...paramHeaders } };\n        };\n\n        // SEP-2106: resolve the output validator BEFORE the request so a tool whose outputSchema\n        // fails to compile (unsupported `$schema` dialect / invalid pattern / unresolvable `$ref` /\n        // any engine error) is surfaced here, per-tool, without a wasted network round-trip and\n        // server-side handler execution. When the caller supplied `toolDefinition`, that definition\n        // is the source for BOTH the `Mcp-Param-*` mirroring above AND output validation — the two\n        // derived views must agree — and is compiled in isolation (never written to the cache). The\n        // cache read is guarded: a custom store whose `get()` rejects routes to `onerror` and\n        // degrades to skipping validation (same outcome as a cold cache).\n        let compiled =\n            options?.toolDefinition === undefined\n                ? await this._cache\n                      .outputValidator(params.name, tool => this._compileOutputValidator(tool))\n                      .catch(error => void this._reportStoreError(error))\n                : this._compileOutputValidator(options.toolDefinition);\n        const assertCompiled = (): void => {\n            if (compiled === undefined || compiled.ok) return;\n            const err = compiled.compileError;\n            const message = (err instanceof Error ? err.message : String(err)).slice(0, 200);\n            throw new ProtocolError(ProtocolErrorCode.InvalidParams, `Tool '${params.name}' has an invalid outputSchema: ${message}`);\n        };\n        assertCompiled();\n\n        // The method-keyed request() path validates the era registry's plain\n        // CallToolResult schema — with the result map aligned to the typed\n        // map there is no wider union to narrow away.\n        let result: CallToolResult;\n        try {\n            result = await this.request({ method: 'tools/call', params }, await buildSendOptions());\n        } catch (error) {\n            // SEP-2243 one-refresh-on-miss: a `HEADER_MISMATCH` rejection on a\n            // modern connection means the server enforced an `Mcp-Param-*`\n            // header we did not (or could not) send — the cached `tools/list`\n            // entry is stale (or cold). Evict it, repopulate via\n            // {@linkcode listTools | listTools()} (which auto-aggregates and\n            // writes the cache), and retry once with the now-known schema.\n            // Never on the legacy era; never when the caller supplied\n            // `toolDefinition` (their schema is authoritative).\n            const isHeaderMismatch = error instanceof ProtocolError && error.code === HEADER_MISMATCH_ERROR_CODE;\n            if (!mirroringActive || !isHeaderMismatch || options?.toolDefinition !== undefined) {\n                throw error;\n            }\n            // `cacheMode: 'refresh'` so the recovery refetch always reaches\n            // the wire — `evict()` reports a custom store's `delete()`\n            // failure via `onerror` and resolves, but a no-op/failing\n            // `delete()` leaves the stale entry in place; without `'refresh'`\n            // the `listTools()` below would cache-serve the very entry whose\n            // staleness triggered this recovery. The generation bump still\n            // happens regardless, so the refetch's write overwrites.\n            const refreshOptions = { signal: options?.signal, timeout: options?.timeout, cacheMode: 'refresh' as const };\n            await this._cache.evict('tools/list');\n            // The recovery refetch may itself fail (e.g. `listMaxPages`, a\n            // transient error that hits only the `tools/list` walk). Surface\n            // it via `onerror` so the real cause is observable, then proceed\n            // to the retry. NOTE: when the refetch fails the cache stays\n            // empty and the retry goes out without `Mcp-Param-*` headers, so\n            // a conforming server will likely answer a second\n            // `HEADER_MISMATCH` — the refetch failure is observable only\n            // through `onerror`.\n            await this.listTools(undefined, refreshOptions).catch(error_ => this._reportStoreError(error_));\n            // Re-resolve the output validator against the freshly-fetched entry — the pre-flight\n            // `compiled` was resolved from the now-evicted cache and may be stale (different\n            // outputSchema) or absent (cold cache on the first attempt). The recovery path is only\n            // entered when `options.toolDefinition` is undefined, so the cache is the sole source.\n            // Re-run the same fail-fast compile-error check before issuing the retry.\n            compiled = await this._cache\n                .outputValidator(params.name, tool => this._compileOutputValidator(tool))\n                .catch(error_ => void this._reportStoreError(error_));\n            assertCompiled();\n            result = await this.request({ method: 'tools/call', params }, await buildSendOptions());\n        }\n\n        const validator = compiled !== undefined && compiled.ok ? compiled.validator : undefined;\n        if (validator) {\n            // If tool has outputSchema, it MUST return structuredContent (unless it's an error).\n            // SEP-2106: presence is `=== undefined`, not falsy — `null`/`0`/`false`/`\"\"` are legal\n            // values and are validated below (so a falsy value against an object-typed schema still\n            // fails; this is not a guard weakening).\n            if (result.structuredContent === undefined && !result.isError) {\n                throw new ProtocolError(\n                    ProtocolErrorCode.InvalidRequest,\n                    `Tool ${params.name} has an output schema but did not return structured content`\n                );\n            }\n\n            // Only validate structured content if present (not when there's an error)\n            if (result.structuredContent !== undefined && !result.isError) {\n                try {\n                    // Validate the structured content against the schema\n                    const validationResult = validator(result.structuredContent);\n\n                    if (!validationResult.valid) {\n                        throw new ProtocolError(\n                            ProtocolErrorCode.InvalidParams,\n                            `Structured content does not match the tool's output schema: ${validationResult.errorMessage}`\n                        );\n                    }\n                } catch (error) {\n                    if (error instanceof ProtocolError) {\n                        throw error;\n                    }\n                    throw new ProtocolError(\n                        ProtocolErrorCode.InvalidParams,\n                        `Failed to validate structured content: ${error instanceof Error ? error.message : String(error)}`\n                    );\n                }\n            }\n        }\n\n        return result;\n    }\n\n    /**\n     * Lists available tools.\n     *\n     * Called without a `cursor` (the common case), this walks every page and\n     * returns the complete aggregated list with no `nextCursor`; the\n     * aggregate is also written to the {@linkcode ResponseCacheStore} (the\n     * source for {@linkcode callTool | callTool()}'s output-schema validation\n     * and SEP-2243 `Mcp-Param-*` header mirroring). Pass an explicit\n     * `{ cursor }` to fetch a single page and walk pagination yourself — the\n     * per-page path returns the server's raw page (with `nextCursor` for the\n     * next call) and does not write the response cache. The auto-aggregate\n     * path is capped by {@linkcode ClientOptions | ClientOptions.listMaxPages} (default 64);\n     * the per-page path is not.\n     *\n     * Returns an empty list if the server does not advertise tools capability\n     * (or throws if {@linkcode ClientOptions.enforceStrictCapabilities} is enabled).\n     *\n     * @example\n     * ```ts source=\"./client.examples.ts#Client_listTools_pagination\"\n     * // No cursor → all pages aggregated for you.\n     * const { tools } = await client.listTools();\n     * console.log(\n     *     'Available tools:',\n     *     tools.map(t => t.name)\n     * );\n     * ```\n     */\n    async listTools(params?: ListToolsRequest['params'], options?: CacheableRequestOptions): Promise<ListToolsResult> {\n        if (!this._serverCapabilities?.tools && !this._enforceStrictCapabilities) {\n            // Respect capability negotiation: server does not support tools\n            console.debug('Client.listTools() called but server does not advertise tools capability - returning empty list');\n            return { tools: [] };\n        }\n        if (params?.cursor !== undefined) {\n            // Per-page: single request, never written to the response cache.\n            // SEP-2243: the spec's MUST has no carve-out for paginated reads,\n            // so the per-page result is filtered (on a non-stdio modern\n            // connection) before returning — the suppressed tool is never\n            // observable.\n            const page = await this.request({ method: 'tools/list', params }, options);\n            this._excludeInvalidXMcpHeaderTools(page);\n            return page;\n        }\n        const hit = await this._serveFromCache<ListToolsResult>('tools/list', undefined, options);\n        if (hit !== undefined) return hit;\n        // Auto-aggregate: SEP-2243 invalid-`x-mcp-header` exclusion runs on\n        // the complete aggregate via the `finalize` hook before the cache\n        // write, so the cached entry never holds an unmirrorable tool.\n        return this._listAllPages<ListToolsResult>(\n            'tools/list',\n            params,\n            options,\n            r => r.tools,\n            acc => this._excludeInvalidXMcpHeaderTools(acc)\n        );\n    }\n\n    /**\n     * SEP-2243 (protocol revision 2026-07-28): a Streamable HTTP client MUST\n     * exclude tool definitions whose `x-mcp-header` declarations violate the\n     * constraints, and SHOULD log a warning naming the tool and the reason.\n     * Applied to the CACHED aggregated `tools/list` result (so the entry\n     * mirroring reads never holds an unmirrorable tool) AND to every public\n     * per-page {@linkcode listTools | listTools()} return (the spec's MUST\n     * has no carve-out for paginated reads). The gate is era-only on\n     * non-stdio transports — `detectProbeTransportKind` cannot distinguish a\n     * real HTTP transport from in-memory/custom transports (it only\n     * positively recognizes stdio), and over-excluding on a non-HTTP modern\n     * connection is harmless: those transports never carry per-request\n     * headers, so an excluded tool would have been uncallable on a Streamable\n     * HTTP arm of the same server. Mutates `result.tools` in place.\n     */\n    private _excludeInvalidXMcpHeaderTools(result: ListToolsResult): void {\n        if (this.getProtocolEra() !== 'modern' || !this.transport || detectProbeTransportKind(this.transport) === 'stdio') return;\n        const filtered = result.tools.filter(tool => {\n            const scan = scanXMcpHeaderDeclarations(tool.inputSchema);\n            if (!scan.valid) {\n                console.warn(`[mcp-sdk] excluding tool '${tool.name}' from tools/list: invalid x-mcp-header declaration — ${scan.reason}`);\n                return false;\n            }\n            return true;\n        });\n        if (filtered.length !== result.tools.length) result.tools = filtered;\n    }\n\n    /**\n     * Set up a single list changed handler.\n     * @internal\n     */\n    private _setupListChangedHandler<T>(\n        listType: string,\n        notificationMethod: NotificationMethod,\n        options: ListChangedOptions<T>,\n        fetcher: () => Promise<T[]>\n    ): void {\n        // Validate options using Zod schema (validates autoRefresh and debounceMs)\n        const parseResult = parseSchema(ListChangedOptionsBaseSchema, options);\n        if (!parseResult.success) {\n            throw new Error(`Invalid ${listType} listChanged options: ${parseResult.error.message}`);\n        }\n\n        // Validate callback\n        if (typeof options.onChanged !== 'function') {\n            throw new TypeError(`Invalid ${listType} listChanged options: onChanged must be a function`);\n        }\n\n        const { autoRefresh, debounceMs } = parseResult.data;\n        const { onChanged } = options;\n\n        const refresh = async () => {\n            if (!autoRefresh) {\n                onChanged(null, null);\n                return;\n            }\n\n            try {\n                const items = await fetcher();\n                onChanged(null, items);\n            } catch (error) {\n                const newError = error instanceof Error ? error : new Error(String(error));\n                onChanged(newError, null);\n            }\n        };\n\n        const handler = () => {\n            if (debounceMs) {\n                // Clear any pending debounce timer for this list type\n                const existingTimer = this._listChangedDebounceTimers.get(listType);\n                if (existingTimer) {\n                    clearTimeout(existingTimer);\n                }\n\n                // Set up debounced refresh\n                const timer = setTimeout(refresh, debounceMs);\n                this._listChangedDebounceTimers.set(listType, timer);\n            } else {\n                // No debounce, refresh immediately\n                refresh();\n            }\n        };\n\n        // Register notification handler\n        this.setNotificationHandler(notificationMethod, handler);\n    }\n\n    /**\n     * Notifies the server that the client's root list has changed. Requires the `roots.listChanged` capability.\n     *\n     * @deprecated Deprecated as of protocol version 2026-07-28 (SEP-2577).\n     * Remains functional during the deprecation window (at least twelve months).\n     * Migrate to passing paths via tool parameters, resource URIs, or configuration.\n     */\n    async sendRootsListChanged() {\n        return this.notification({ method: 'notifications/roots/list_changed' });\n    }\n}\n","/**\n * The type of error that occurred.\n * @public\n */\nexport type ErrorType = 'invalid-retry' | 'unknown-field'\n\n/**\n * Error thrown when encountering an issue during parsing.\n *\n * @public\n */\nexport class ParseError extends Error {\n  /**\n   * The type of error that occurred.\n   */\n  type: ErrorType\n\n  /**\n   * In the case of an unknown field encountered in the stream, this will be the field name.\n   */\n  field?: string | undefined\n\n  /**\n   * In the case of an unknown field encountered in the stream, this will be the value of the field.\n   */\n  value?: string | undefined\n\n  /**\n   * The line that caused the error, if available.\n   */\n  line?: string | undefined\n\n  constructor(\n    message: string,\n    options: {type: ErrorType; field?: string; value?: string; line?: string},\n  ) {\n    super(message)\n    this.name = 'ParseError'\n    this.type = options.type\n    this.field = options.field\n    this.value = options.value\n    this.line = options.line\n  }\n}\n","/**\n * EventSource/Server-Sent Events parser\n * @see https://html.spec.whatwg.org/multipage/server-sent-events.html\n */\nimport {ParseError} from './errors.ts'\nimport type {EventSourceParser, ParserCallbacks} from './types.ts'\n\n// ASCII codes used in the hot parsing paths.\nconst LF = 10\nconst CR = 13\nconst SPACE = 32\n\n// oxlint-disable-next-line no-unused-vars\nfunction noop(_arg: unknown) {\n  // intentional noop\n}\n\n/**\n * Creates a new EventSource parser.\n *\n * @param callbacks - Callbacks to invoke on different parsing events:\n *   - `onEvent` when a new event is parsed\n *   - `onError` when an error occurs\n *   - `onRetry` when a new reconnection interval has been sent from the server\n *   - `onComment` when a comment is encountered in the stream\n *\n * @returns A new EventSource parser, with `parse` and `reset` methods.\n * @public\n */\nexport function createParser(callbacks: ParserCallbacks): EventSourceParser {\n  if (typeof callbacks === 'function') {\n    throw new TypeError(\n      '`callbacks` must be an object, got a function instead. Did you mean `{onEvent: fn}`?',\n    )\n  }\n\n  const {onEvent = noop, onError = noop, onRetry = noop, onComment} = callbacks\n\n  // Trailing bytes from prior `feed()` calls that did not yet form a complete line.\n  // Stored as an array of fragments and only joined when a line terminator arrives.\n  // Concatenating per-feed (`prefix + chunk`) is O(N²) when a single SSE line spans\n  // many chunks (e.g. a large `data:` payload streamed in tiny slices, or an MCP-style\n  // server that emits one giant content block). Buffering as fragments + joining once\n  // makes the same workload linear.\n  const pendingFragments: string[] = []\n\n  let isFirstChunk = true\n  let id: string | undefined\n  let data = ''\n  let dataLines = 0\n  let eventType: string | undefined\n\n  /**\n   * Feeds a chunk of the SSE stream to the parser. Any trailing bytes that do\n   * not yet form a complete line are held back and prepended to the next chunk,\n   * so callers can pass arbitrary slices of the stream without worrying about\n   * line boundaries.\n   *\n   * Per the SSE spec, a UTF-8 BOM (0xEF 0xBB 0xBF) at the start of the very\n   * first chunk is stripped before parsing.\n   *\n   * @see https://html.spec.whatwg.org/multipage/server-sent-events.html#parsing-an-event-stream\n   */\n  function feed(chunk: string) {\n    if (isFirstChunk) {\n      isFirstChunk = false\n      // Match and strip UTF-8 BOM from the start of the stream, if present.\n      // (Per the spec, this is only valid at the very start of the stream)\n      if (\n        chunk.charCodeAt(0) === 0xef &&\n        chunk.charCodeAt(1) === 0xbb &&\n        chunk.charCodeAt(2) === 0xbf\n      ) {\n        chunk = chunk.slice(3)\n      }\n    }\n\n    // Hot path: no buffered prefix from a prior partial line. Hand the chunk\n    // straight to `processLines`, exactly like the original implementation.\n    // Zero new work in the common case (every chunk ends with `\\n\\n`).\n    if (pendingFragments.length === 0) {\n      const trailing = processLines(chunk)\n      if (trailing !== '') pendingFragments.push(trailing)\n      return\n    }\n\n    // We have a buffered prefix. If this chunk also has no terminator, append\n    // to the buffer without concatenating — that's the O(N²) trap we're\n    // avoiding (large single `data:` payload split across many tiny chunks).\n    if (chunk.indexOf('\\n') === -1 && chunk.indexOf('\\r') === -1) {\n      pendingFragments.push(chunk)\n      return\n    }\n\n    // Terminator arrived. Join the accumulated fragments + this chunk once,\n    // process, and buffer any new trailing partial line.\n    pendingFragments.push(chunk)\n    const input = pendingFragments.join('')\n    pendingFragments.length = 0\n    const trailing = processLines(input)\n    if (trailing !== '') pendingFragments.push(trailing)\n  }\n\n  /**\n   * Splits `chunk` into SSE lines and dispatches each to the appropriate handler.\n   * Returns any trailing bytes that did not terminate with a line break, so the\n   * caller can prepend them to the next chunk.\n   *\n   * The SSE spec permits three line terminators: `\\n`, `\\r`, and `\\r\\n`. Real-world\n   * streams almost always use plain `\\n`, so we take a fast path when no `\\r` is\n   * present in the chunk. The slow path is spec-correct but does more work per line.\n   */\n  function processLines(chunk: string): string {\n    let searchIndex = 0\n\n    // Fast path: LF-only chunk (the common case for typical SSE servers).\n    // We can scan forward with a single `indexOf('\\n')` per line and inline\n    // the hot-path branches for `data:` and `event:` without the CR bookkeeping\n    // the slow path needs.\n    if (chunk.indexOf('\\r') === -1) {\n      let lfIndex = chunk.indexOf('\\n', searchIndex)\n      while (lfIndex !== -1) {\n        // Blank line: end-of-event marker. Dispatch the accumulated event (if any)\n        // and reset the buffered fields. This is hoisted out of `parseLine` because\n        // it's the single most common line shape after `data:` lines.\n        if (searchIndex === lfIndex) {\n          if (dataLines > 0) {\n            onEvent({id, event: eventType, data})\n          }\n          id = undefined\n          data = ''\n          dataLines = 0\n          eventType = undefined\n          searchIndex = lfIndex + 1\n          lfIndex = chunk.indexOf('\\n', searchIndex)\n          continue\n        }\n        const firstCharCode = chunk.charCodeAt(searchIndex)\n        if (isDataPrefix(chunk, searchIndex, firstCharCode)) {\n          // `data:` line — append the value to the event's data buffer.\n          // 'data:'.length === 5, 'data: '.length === 6\n          const valueStart =\n            chunk.charCodeAt(searchIndex + 5) === SPACE ? searchIndex + 6 : searchIndex + 5\n          const value = chunk.slice(valueStart, lfIndex)\n          // Fast path within a fast path: if this is the first data line AND the\n          // next char is another LF (i.e. `data:foo\\n\\n`), dispatch immediately\n          // without ever writing to the `data` buffer. This is the shape of a\n          // typical single-line SSE event (ChatGPT-style streams, etc.) and is\n          // hot enough to be worth the duplication.\n          if (dataLines === 0 && chunk.charCodeAt(lfIndex + 1) === LF) {\n            onEvent({id, event: eventType, data: value})\n            id = undefined\n            data = ''\n            eventType = undefined\n            searchIndex = lfIndex + 2\n            lfIndex = chunk.indexOf('\\n', searchIndex)\n            continue\n          }\n          // Multi-line data: concatenate with newline separator per spec.\n          data = dataLines === 0 ? value : `${data}\\n${value}`\n          dataLines++\n        } else if (isEventPrefix(chunk, searchIndex, firstCharCode)) {\n          // `event:` line — set the event type for the next dispatch. Per spec,\n          // an empty value resets `event type` to its default (undefined here).\n          // 'event:'.length === 6, 'event: '.length === 7\n          eventType =\n            chunk.slice(\n              chunk.charCodeAt(searchIndex + 6) === SPACE ? searchIndex + 7 : searchIndex + 6,\n              lfIndex,\n            ) || undefined\n        } else {\n          // Everything else: `id:`, `retry:`, comment lines (`:` prefix), unknown\n          // fields, or malformed lines. These are rarer and go through the full\n          // per-line parser, which handles the SSE field grammar in detail.\n          parseLine(chunk, searchIndex, lfIndex)\n        }\n        searchIndex = lfIndex + 1\n        lfIndex = chunk.indexOf('\\n', searchIndex)\n      }\n      return chunk.slice(searchIndex)\n    }\n\n    // Slow path: the chunk contains at least one `\\r`, so lines may be terminated\n    // by `\\r`, `\\n`, or `\\r\\n`. We locate the next terminator by looking at both\n    // the nearest `\\r` and `\\n` and picking whichever comes first.\n    while (searchIndex < chunk.length) {\n      const crIndex = chunk.indexOf('\\r', searchIndex)\n      const lfIndex = chunk.indexOf('\\n', searchIndex)\n\n      let lineEnd = -1\n      if (crIndex !== -1 && lfIndex !== -1) {\n        lineEnd = crIndex < lfIndex ? crIndex : lfIndex\n      } else if (crIndex !== -1) {\n        // A trailing `\\r` at the very end of the chunk is ambiguous: it could be\n        // a bare-CR terminator, or the first half of a `\\r\\n` whose `\\n` arrives\n        // in the next chunk. Defer until we see more input.\n        if (crIndex === chunk.length - 1) {\n          lineEnd = -1\n        } else {\n          lineEnd = crIndex\n        }\n      } else if (lfIndex !== -1) {\n        lineEnd = lfIndex\n      }\n\n      if (lineEnd === -1) {\n        break\n      }\n\n      parseLine(chunk, searchIndex, lineEnd)\n      searchIndex = lineEnd + 1\n      // If we just consumed a `\\r` and the next char is `\\n`, skip it so the\n      // pair is treated as a single terminator rather than an empty line.\n      if (chunk.charCodeAt(searchIndex - 1) === CR && chunk.charCodeAt(searchIndex) === LF) {\n        searchIndex++\n      }\n    }\n\n    return chunk.slice(searchIndex)\n  }\n\n  function parseLine(chunk: string, start: number, end: number) {\n    if (start === end) {\n      dispatchEvent()\n      return\n    }\n\n    const firstCharCode = chunk.charCodeAt(start)\n\n    if (isDataPrefix(chunk, start, firstCharCode)) {\n      // 'data:'.length === 5, 'data: '.length === 6\n      const valueStart = chunk.charCodeAt(start + 5) === SPACE ? start + 6 : start + 5\n      const value = chunk.slice(valueStart, end)\n      data = dataLines === 0 ? value : `${data}\\n${value}`\n      dataLines++\n      return\n    }\n\n    if (isEventPrefix(chunk, start, firstCharCode)) {\n      // 'event:'.length === 6, 'event: '.length === 7\n      eventType =\n        chunk.slice(chunk.charCodeAt(start + 6) === SPACE ? start + 7 : start + 6, end) || undefined\n      return\n    }\n\n    // Fast path for \"id:\" — 'i' = 105, 'd' = 100, ':' = 58\n    if (\n      firstCharCode === 105 &&\n      chunk.charCodeAt(start + 1) === 100 &&\n      chunk.charCodeAt(start + 2) === 58\n    ) {\n      // 'id:'.length === 3, 'id: '.length === 4\n      const value = chunk.slice(chunk.charCodeAt(start + 3) === SPACE ? start + 4 : start + 3, end)\n      id = value.includes('\\0') ? undefined : value\n      return\n    }\n\n    // Comment line — ':' = 58\n    if (firstCharCode === 58) {\n      if (onComment) {\n        const line = chunk.slice(start, end)\n        // skip ':' (+1), or ': ' (+2) when a space follows\n        onComment(line.slice(chunk.charCodeAt(start + 1) === SPACE ? 2 : 1))\n      }\n      return\n    }\n\n    const line = chunk.slice(start, end)\n    const fieldSeparatorIndex = line.indexOf(':')\n    if (fieldSeparatorIndex === -1) {\n      processField(line, '', line)\n      return\n    }\n\n    const field = line.slice(0, fieldSeparatorIndex)\n    // skip ':' (+1), or ': ' (+2) when a space follows\n    const offset = line.charCodeAt(fieldSeparatorIndex + 1) === SPACE ? 2 : 1\n    const value = line.slice(fieldSeparatorIndex + offset)\n    processField(field, value, line)\n  }\n\n  function processField(field: string, value: string, line: string) {\n    // Field names must be compared literally, with no case folding performed.\n    switch (field) {\n      case 'event':\n        // Set the `event type` buffer to field value\n        eventType = value || undefined\n        break\n      case 'data':\n        data = dataLines === 0 ? value : `${data}\\n${value}`\n        dataLines++\n        break\n      case 'id':\n        // If the field value does not contain U+0000 NULL, then set the `ID` buffer to\n        // the field value. Otherwise, ignore the field.\n        id = value.includes('\\0') ? undefined : value\n        break\n      case 'retry':\n        // If the field value consists of only ASCII digits, then interpret the field value as an\n        // integer in base ten, and set the event stream's reconnection time to that integer.\n        // Otherwise, ignore the field.\n        if (/^\\d+$/.test(value)) {\n          onRetry(parseInt(value, 10))\n        } else {\n          onError(\n            new ParseError(`Invalid \\`retry\\` value: \"${value}\"`, {\n              type: 'invalid-retry',\n              value,\n              line,\n            }),\n          )\n        }\n        break\n      default:\n        // Otherwise, the field is ignored.\n        onError(\n          new ParseError(\n            `Unknown field \"${field.length > 20 ? `${field.slice(0, 20)}…` : field}\"`,\n            {type: 'unknown-field', field, value, line},\n          ),\n        )\n        break\n    }\n  }\n\n  function dispatchEvent() {\n    if (dataLines > 0) {\n      onEvent({\n        id,\n        event: eventType,\n        data,\n      })\n    }\n\n    id = undefined\n    data = ''\n    dataLines = 0\n    eventType = undefined\n  }\n\n  function reset(options: {consume?: boolean} = {}) {\n    if (options.consume && pendingFragments.length > 0) {\n      const incompleteLine = pendingFragments.join('')\n      parseLine(incompleteLine, 0, incompleteLine.length)\n    }\n\n    isFirstChunk = true\n    id = undefined\n    data = ''\n    dataLines = 0\n    eventType = undefined\n    pendingFragments.length = 0\n  }\n\n  return {feed, reset}\n}\n\n/**\n * Checks if `chunk` starts with the literal `data:` at index `i`.\n *\n * Equivalent to `chunk.startsWith('data:', i)`, but benchmarks show this\n * hand-unrolled char-code comparison is ~20% faster on common event types.\n * The caller passes `firstCharCode` (the code at `i`) so it can be reused\n * across prefix checks.\n *\n * ASCII: 'd' = 100, 'a' = 97, 't' = 116, 'a' = 97, ':' = 58\n */\nfunction isDataPrefix(chunk: string, i: number, firstCharCode: number): boolean {\n  return (\n    firstCharCode === 100 &&\n    chunk.charCodeAt(i + 1) === 97 &&\n    chunk.charCodeAt(i + 2) === 116 &&\n    chunk.charCodeAt(i + 3) === 97 &&\n    chunk.charCodeAt(i + 4) === 58\n  )\n}\n\n/**\n * Checks if `chunk` starts with the literal `event:` at index `i`.\n *\n * See {@link isDataPrefix} for why this is hand-unrolled rather than using\n * `String.prototype.startsWith`.\n *\n * ASCII: 'e' = 101, 'v' = 118, 'e' = 101, 'n' = 110, 't' = 116, ':' = 58\n */\nfunction isEventPrefix(chunk: string, i: number, firstCharCode: number): boolean {\n  return (\n    firstCharCode === 101 &&\n    chunk.charCodeAt(i + 1) === 118 &&\n    chunk.charCodeAt(i + 2) === 101 &&\n    chunk.charCodeAt(i + 3) === 110 &&\n    chunk.charCodeAt(i + 4) === 116 &&\n    chunk.charCodeAt(i + 5) === 58\n  )\n}\n","/**\n * An extended version of the `Event` emitted by the `EventSource` object when an error occurs.\n * While the spec does not include any additional properties, we intentionally go beyond the spec\n * and provide some (minimal) additional information to aid in debugging.\n *\n * @public\n */\nexport class ErrorEvent extends Event {\n  /**\n   * HTTP status code, if this was triggered by an HTTP error\n   * Note: this is not part of the spec, but is included for better error handling.\n   *\n   * @public\n   */\n  public code?: number | undefined\n\n  /**\n   * Optional message attached to the error.\n   * Note: this is not part of the spec, but is included for better error handling.\n   *\n   * @public\n   */\n  public message?: string | undefined\n\n  /**\n   * Constructs a new `ErrorEvent` instance. This is typically not called directly,\n   * but rather emitted by the `EventSource` object when an error occurs.\n   *\n   * @param type - The type of the event (should be \"error\")\n   * @param errorEventInitDict - Optional properties to include in the error event\n   */\n  constructor(\n    type: string,\n    errorEventInitDict?: {message?: string | undefined; code?: number | undefined},\n  ) {\n    super(type)\n    this.code = errorEventInitDict?.code ?? undefined\n    this.message = errorEventInitDict?.message ?? undefined\n  }\n\n  /**\n   * Node.js \"hides\" the `message` and `code` properties of the `ErrorEvent` instance,\n   * when it is `console.log`'ed. This makes it harder to debug errors. To ease debugging,\n   * we explicitly include the properties in the `inspect` method.\n   *\n   * This is automatically called by Node.js when you `console.log` an instance of this class.\n   *\n   * @param _depth - The current depth\n   * @param options - The options passed to `util.inspect`\n   * @param inspect - The inspect function to use (prevents having to import it from `util`)\n   * @returns A string representation of the error\n   */\n  [Symbol.for('nodejs.util.inspect.custom')](\n    _depth: number,\n    options: {colors: boolean},\n    inspect: (obj: unknown, inspectOptions: {colors: boolean}) => string,\n  ): string {\n    return inspect(inspectableError(this), options)\n  }\n\n  /**\n   * Deno \"hides\" the `message` and `code` properties of the `ErrorEvent` instance,\n   * when it is `console.log`'ed. This makes it harder to debug errors. To ease debugging,\n   * we explicitly include the properties in the `inspect` method.\n   *\n   * This is automatically called by Deno when you `console.log` an instance of this class.\n   *\n   * @param inspect - The inspect function to use (prevents having to import it from `util`)\n   * @param options - The options passed to `Deno.inspect`\n   * @returns A string representation of the error\n   */\n  [Symbol.for('Deno.customInspect')](\n    inspect: (obj: unknown, inspectOptions: {colors: boolean}) => string,\n    options: {colors: boolean},\n  ): string {\n    return inspect(inspectableError(this), options)\n  }\n}\n\n/**\n * For environments where DOMException may not exist, we will use a SyntaxError instead.\n * While this isn't strictly according to spec, it is very close.\n *\n * @param message - The message to include in the error\n * @returns A `DOMException` or `SyntaxError` instance\n * @internal\n */\nexport function syntaxError(message: string): SyntaxError {\n  // If someone can figure out a way to make this work without depending on DOM/Node.js typings,\n  // and without casting to `any`, please send a PR 🙏\n\n  // eslint-disable-next-line @typescript-eslint/no-explicit-any\n  const DomException = (globalThis as any).DOMException\n  if (typeof DomException === 'function') {\n    return new DomException(message, 'SyntaxError')\n  }\n\n  return new SyntaxError(message)\n}\n\n/**\n * Flatten an error into a single error message string.\n * Unwraps nested errors and joins them with a comma.\n *\n * @param err - The error to flatten\n * @returns A string representation of the error\n * @internal\n */\nexport function flattenError(err: unknown): string {\n  if (!(err instanceof Error)) {\n    return `${err}`\n  }\n\n  if ('errors' in err && Array.isArray(err.errors)) {\n    return err.errors.map(flattenError).join(', ')\n  }\n\n  if ('cause' in err && err.cause instanceof Error) {\n    return `${err}: ${flattenError(err.cause)}`\n  }\n\n  return err.message\n}\n\n/**\n * Convert an `ErrorEvent` instance into a plain object for inspection.\n *\n * @param err - The `ErrorEvent` instance to inspect\n * @returns A plain object representation of the error\n * @internal\n */\nfunction inspectableError(err: ErrorEvent) {\n  return {\n    type: err.type,\n    message: err.message,\n    code: err.code,\n    defaultPrevented: err.defaultPrevented,\n    cancelable: err.cancelable,\n    timeStamp: err.timeStamp,\n  }\n}\n","import {createParser, type EventSourceMessage, type EventSourceParser} from 'eventsource-parser'\n\nimport {ErrorEvent, flattenError, syntaxError} from './errors.js'\nimport type {\n  AddEventListenerOptions,\n  EventListenerOptions,\n  EventListenerOrEventListenerObject,\n  EventSourceEventMap,\n  EventSourceFetchInit,\n  EventSourceInit,\n  FetchLike,\n  FetchLikeResponse,\n} from './types.js'\n\n/**\n * An `EventSource` instance opens a persistent connection to an HTTP server, which sends events\n * in `text/event-stream` format. The connection remains open until closed by calling `.close()`.\n *\n * @public\n * @example\n * ```js\n * const eventSource = new EventSource('https://example.com/stream')\n * eventSource.addEventListener('error', (error) => {\n *   console.error(error)\n * })\n * eventSource.addEventListener('message', (event) => {\n *  console.log('Received message:', event.data)\n * })\n * ```\n */\nexport class EventSource extends EventTarget {\n  /**\n   * ReadyState representing an EventSource currently trying to connect\n   *\n   * @public\n   */\n  static CONNECTING = 0 as const\n\n  /**\n   * ReadyState representing an EventSource connection that is open (eg connected)\n   *\n   * @public\n   */\n  static OPEN = 1 as const\n\n  /**\n   * ReadyState representing an EventSource connection that is closed (eg disconnected)\n   *\n   * @public\n   */\n  static CLOSED = 2 as const\n\n  /**\n   * ReadyState representing an EventSource currently trying to connect\n   *\n   * @public\n   */\n  readonly CONNECTING = 0 as const\n\n  /**\n   * ReadyState representing an EventSource connection that is open (eg connected)\n   *\n   * @public\n   */\n  readonly OPEN = 1 as const\n\n  /**\n   * ReadyState representing an EventSource connection that is closed (eg disconnected)\n   *\n   * @public\n   */\n  readonly CLOSED = 2 as const\n\n  /**\n   * Returns the state of this EventSource object's connection. It can have the values described below.\n   *\n   * [MDN Reference](https://developer.mozilla.org/docs/Web/API/EventSource/readyState)\n   *\n   * Note: typed as `number` instead of `0 | 1 | 2` for compatibility with the `EventSource` interface,\n   * defined in the TypeScript `dom` library.\n   *\n   * @public\n   */\n  public get readyState(): number {\n    return this.#readyState\n  }\n\n  /**\n   * Returns the URL providing the event stream.\n   *\n   * [MDN Reference](https://developer.mozilla.org/docs/Web/API/EventSource/url)\n   *\n   * @public\n   */\n  public get url(): string {\n    return this.#url.href\n  }\n\n  /**\n   * Returns true if the credentials mode for connection requests to the URL providing the event stream is set to \"include\", and false otherwise.\n   *\n   * [MDN Reference](https://developer.mozilla.org/docs/Web/API/EventSource/withCredentials)\n   */\n  public get withCredentials(): boolean {\n    return this.#withCredentials\n  }\n\n  /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/EventSource/error_event) */\n  public get onerror(): ((ev: ErrorEvent) => unknown) | null {\n    return this.#onError\n  }\n  public set onerror(value: ((ev: ErrorEvent) => unknown) | null) {\n    this.#onError = value\n  }\n\n  /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/EventSource/message_event) */\n  public get onmessage(): ((ev: MessageEvent) => unknown) | null {\n    return this.#onMessage\n  }\n  public set onmessage(value: ((ev: MessageEvent) => unknown) | null) {\n    this.#onMessage = value\n  }\n\n  /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/EventSource/open_event) */\n  public get onopen(): ((ev: Event) => unknown) | null {\n    return this.#onOpen\n  }\n  public set onopen(value: ((ev: Event) => unknown) | null) {\n    this.#onOpen = value\n  }\n\n  override addEventListener<K extends keyof EventSourceEventMap>(\n    type: K,\n    listener: (this: EventSource, ev: EventSourceEventMap[K]) => unknown,\n    options?: boolean | AddEventListenerOptions,\n  ): void\n  override addEventListener(\n    type: string,\n    listener: (this: EventSource, event: MessageEvent) => unknown,\n    options?: boolean | AddEventListenerOptions,\n  ): void\n  override addEventListener(\n    type: string,\n    listener: EventListenerOrEventListenerObject,\n    options?: boolean | AddEventListenerOptions,\n  ): void\n  override addEventListener(\n    type: string,\n    listener:\n      | ((this: EventSource, event: MessageEvent) => unknown)\n      | EventListenerOrEventListenerObject,\n    options?: boolean | AddEventListenerOptions,\n  ): void {\n    const listen = listener as (this: EventSource, event: Event) => unknown\n    super.addEventListener(type, listen, options)\n  }\n\n  override removeEventListener<K extends keyof EventSourceEventMap>(\n    type: K,\n    listener: (this: EventSource, ev: EventSourceEventMap[K]) => unknown,\n    options?: boolean | EventListenerOptions,\n  ): void\n  override removeEventListener(\n    type: string,\n    listener: (this: EventSource, event: MessageEvent) => unknown,\n    options?: boolean | EventListenerOptions,\n  ): void\n  override removeEventListener(\n    type: string,\n    listener: EventListenerOrEventListenerObject,\n    options?: boolean | EventListenerOptions,\n  ): void\n  override removeEventListener(\n    type: string,\n    listener:\n      | ((this: EventSource, event: MessageEvent) => unknown)\n      | EventListenerOrEventListenerObject,\n    options?: boolean | EventListenerOptions,\n  ): void {\n    const listen = listener as (this: EventSource, event: Event) => unknown\n    super.removeEventListener(type, listen, options)\n  }\n\n  constructor(url: string | URL, eventSourceInitDict?: EventSourceInit) {\n    super()\n\n    try {\n      if (url instanceof URL) {\n        this.#url = url\n      } else if (typeof url === 'string') {\n        this.#url = new URL(url, getBaseURL())\n      } else {\n        throw new Error('Invalid URL')\n      }\n    } catch (err) {\n      throw syntaxError('An invalid or illegal string was specified')\n    }\n\n    this.#parser = createParser({\n      onEvent: this.#onEvent,\n      onRetry: this.#onRetryChange,\n    })\n\n    this.#readyState = this.CONNECTING\n    this.#reconnectInterval = 3000\n    this.#fetch = eventSourceInitDict?.fetch ?? globalThis.fetch\n    this.#withCredentials = eventSourceInitDict?.withCredentials ?? false\n\n    this.#connect()\n  }\n\n  /**\n   * Aborts any instances of the fetch algorithm started for this EventSource object, and sets the readyState attribute to CLOSED.\n   *\n   * [MDN Reference](https://developer.mozilla.org/docs/Web/API/EventSource/close)\n   *\n   * @public\n   */\n  close(): void {\n    if (this.#reconnectTimer) clearTimeout(this.#reconnectTimer)\n    if (this.#readyState === this.CLOSED) return\n    if (this.#controller) this.#controller.abort()\n    this.#readyState = this.CLOSED\n    this.#controller = undefined\n  }\n\n  // PRIVATES FOLLOW\n\n  /**\n   * Current connection state\n   *\n   * @internal\n   */\n  #readyState: number\n\n  /**\n   * Original URL used to connect.\n   *\n   * Note that this will stay the same even after a redirect.\n   *\n   * @internal\n   */\n  #url: URL\n\n  /**\n   * The destination URL after a redirect. Is reset on reconnection.\n   *\n   * @internal\n   */\n  #redirectUrl: URL | undefined\n\n  /**\n   * Whether to include credentials in the request\n   *\n   * @internal\n   */\n  #withCredentials: boolean\n\n  /**\n   * The fetch implementation to use\n   *\n   * @internal\n   */\n  #fetch: FetchLike\n\n  /**\n   * The reconnection time in milliseconds\n   *\n   * @internal\n   */\n  #reconnectInterval: number\n\n  /**\n   * Reference to an ongoing reconnect attempt, if any\n   *\n   * @internal\n   */\n  #reconnectTimer: ReturnType<typeof setTimeout> | undefined\n\n  /**\n   * The last event ID seen by the EventSource, which will be sent as `Last-Event-ID` in the\n   * request headers on a reconnection attempt.\n   *\n   * @internal\n   */\n  #lastEventId: string | null = null\n\n  /**\n   * The AbortController instance used to abort the fetch request\n   *\n   * @internal\n   */\n  #controller: AbortController | undefined\n\n  /**\n   * Instance of an EventSource parser (`eventsource-parser` npm module)\n   *\n   * @internal\n   */\n  #parser: EventSourceParser\n\n  /**\n   * Holds the current error handler, attached through `onerror` property directly.\n   * Note that `addEventListener('error', …)` will not be stored here.\n   *\n   * @internal\n   */\n  #onError: ((ev: ErrorEvent) => unknown) | null = null\n\n  /**\n   * Holds the current message handler, attached through `onmessage` property directly.\n   * Note that `addEventListener('message', …)` will not be stored here.\n   *\n   * @internal\n   */\n  #onMessage: ((ev: MessageEvent) => unknown) | null = null\n\n  /**\n   * Holds the current open handler, attached through `onopen` property directly.\n   * Note that `addEventListener('open', …)` will not be stored here.\n   *\n   * @internal\n   */\n  #onOpen: ((ev: Event) => unknown) | null = null\n\n  /**\n   * Connect to the given URL and start receiving events\n   *\n   * @internal\n   */\n  #connect() {\n    this.#readyState = this.CONNECTING\n    this.#controller = new AbortController()\n\n    // Browser tests are failing if we directly call `this.#fetch()`, thus the indirection.\n    const fetch = this.#fetch\n    fetch(this.#url, this.#getRequestOptions())\n      .then(this.#onFetchResponse)\n      .catch(this.#onFetchError)\n  }\n\n  /**\n   * Handles the fetch response\n   *\n   * @param response - The Fetch(ish) response\n   * @internal\n   */\n  #onFetchResponse = async (response: FetchLikeResponse) => {\n    this.#parser.reset()\n\n    const {body, redirected, status, headers} = response\n\n    // [spec] a client can be told to stop reconnecting using the HTTP 204 No Content response code.\n    if (status === 204) {\n      // We still need to emit an error event - this mirrors the browser behavior,\n      // and without it there is no way to tell the user that the connection was closed.\n      this.#failConnection('Server sent HTTP 204, not reconnecting', 204)\n      this.close()\n      return\n    }\n\n    // [spec] …Event stream requests can be redirected using HTTP 301 and 307 redirects as with\n    // [spec] normal HTTP requests.\n    // Spec does not say anything about other redirect codes (302, 308), but this seems an\n    // unintended omission, rather than a feature. Browsers will happily redirect on other 3xxs's.\n    if (redirected) {\n      this.#redirectUrl = new URL(response.url)\n    } else {\n      this.#redirectUrl = undefined\n    }\n\n    // [spec] if res's status is not 200, …, then fail the connection.\n    if (status !== 200) {\n      this.#failConnection(`Non-200 status code (${status})`, status)\n      return\n    }\n\n    // [spec] …or if res's `Content-Type` is not `text/event-stream`, then fail the connection.\n    const contentType = headers.get('content-type') || ''\n    if (!contentType.startsWith('text/event-stream')) {\n      this.#failConnection('Invalid content type, expected \"text/event-stream\"', status)\n      return\n    }\n\n    // [spec] …if the readyState attribute is set to a value other than CLOSED…\n    if (this.#readyState === this.CLOSED) {\n      return\n    }\n\n    // [spec] …sets the readyState attribute to OPEN and fires an event\n    // [spec] …named open at the EventSource object.\n    this.#readyState = this.OPEN\n\n    const openEvent = new Event('open')\n    this.#onOpen?.(openEvent)\n    this.dispatchEvent(openEvent)\n\n    // Ensure that the response stream is a web stream\n    if (typeof body !== 'object' || !body || !('getReader' in body)) {\n      this.#failConnection('Invalid response body, expected a web ReadableStream', status)\n      this.close() // This should only happen if `fetch` provided is \"faulty\" - don't reconnect\n      return\n    }\n\n    const decoder = new TextDecoder()\n\n    const reader = body.getReader()\n    let open = true\n\n    do {\n      const {done, value} = await reader.read()\n      if (value) {\n        this.#parser.feed(decoder.decode(value, {stream: !done}))\n      }\n\n      if (!done) {\n        continue\n      }\n\n      open = false\n      this.#parser.reset()\n\n      this.#scheduleReconnect()\n    } while (open)\n  }\n\n  /**\n   * Handles rejected requests for the EventSource endpoint\n   *\n   * @param err - The error from `fetch()`\n   * @internal\n   */\n  #onFetchError = (err: Error & {type?: string}) => {\n    this.#controller = undefined\n\n    // We expect abort errors when the user manually calls `close()` - ignore those\n    if (err.name === 'AbortError' || err.type === 'aborted') {\n      return\n    }\n\n    this.#scheduleReconnect(flattenError(err))\n  }\n\n  /**\n   * Get request options for the `fetch()` request\n   *\n   * @returns The request options\n   * @internal\n   */\n  #getRequestOptions(): EventSourceFetchInit {\n    const lastEvent = this.#lastEventId ? {'Last-Event-ID': this.#lastEventId} : undefined\n\n    const init: EventSourceFetchInit = {\n      // [spec] Let `corsAttributeState` be `Anonymous`…\n      // [spec] …will have their mode set to \"cors\"…\n      mode: 'cors',\n      redirect: 'follow',\n      headers: {Accept: 'text/event-stream', ...lastEvent},\n      cache: 'no-store',\n      signal: this.#controller?.signal,\n    }\n\n    // Some environments crash if attempting to set `credentials` where it is not supported,\n    // eg on Cloudflare Workers. To avoid this, we only set it in browser-like environments.\n    if ('window' in globalThis) {\n      // [spec] …and their credentials mode set to \"same-origin\"\n      // [spec] …if the `withCredentials` attribute is `true`, set the credentials mode to \"include\"…\n      init.credentials = this.withCredentials ? 'include' : 'same-origin'\n    }\n\n    return init\n  }\n\n  /**\n   * Called by EventSourceParser instance when an event has successfully been parsed\n   * and is ready to be processed.\n   *\n   * @param event - The parsed event\n   * @internal\n   */\n  #onEvent = (event: EventSourceMessage) => {\n    if (typeof event.id === 'string') {\n      this.#lastEventId = event.id\n    }\n\n    const messageEvent = new MessageEvent(event.event || 'message', {\n      data: event.data,\n      origin: this.#redirectUrl ? this.#redirectUrl.origin : this.#url.origin,\n      lastEventId: event.id || '',\n    })\n\n    // The `onmessage` property of the EventSource instance only triggers on messages without an\n    // `event` field, or ones that explicitly set `message`.\n    if (this.#onMessage && (!event.event || event.event === 'message')) {\n      this.#onMessage(messageEvent)\n    }\n\n    this.dispatchEvent(messageEvent)\n  }\n\n  /**\n   * Called by EventSourceParser instance when a new reconnection interval is received\n   * from the EventSource endpoint.\n   *\n   * @param value - The new reconnection interval in milliseconds\n   * @internal\n   */\n  #onRetryChange = (value: number) => {\n    this.#reconnectInterval = value\n  }\n\n  /**\n   * Handles the process referred to in the EventSource specification as \"failing a connection\".\n   *\n   * @param error - The error causing the connection to fail\n   * @param code - The HTTP status code, if available\n   * @internal\n   */\n  #failConnection(message?: string, code?: number) {\n    // [spec] …if the readyState attribute is set to a value other than CLOSED,\n    // [spec] sets the readyState attribute to CLOSED…\n    if (this.#readyState !== this.CLOSED) {\n      this.#readyState = this.CLOSED\n    }\n\n    // [spec] …and fires an event named `error` at the `EventSource` object.\n    // [spec] Once the user agent has failed the connection, it does not attempt to reconnect.\n    // [spec] > Implementations are especially encouraged to report detailed information\n    // [spec] > to their development consoles whenever an error event is fired, since little\n    // [spec] > to no information can be made available in the events themselves.\n    // Printing to console is not very programatically helpful, though, so we emit a custom event.\n    const errorEvent = new ErrorEvent('error', {code, message})\n\n    this.#onError?.(errorEvent)\n    this.dispatchEvent(errorEvent)\n  }\n\n  /**\n   * Schedules a reconnection attempt against the EventSource endpoint.\n   *\n   * @param message - The error causing the connection to fail\n   * @param code - The HTTP status code, if available\n   * @internal\n   */\n  #scheduleReconnect(message?: string, code?: number) {\n    // [spec] If the readyState attribute is set to CLOSED, abort the task.\n    if (this.#readyState === this.CLOSED) {\n      return\n    }\n\n    // [spec] Set the readyState attribute to CONNECTING.\n    this.#readyState = this.CONNECTING\n\n    // [spec] Fire an event named `error` at the EventSource object.\n    const errorEvent = new ErrorEvent('error', {code, message})\n    this.#onError?.(errorEvent)\n    this.dispatchEvent(errorEvent)\n\n    // [spec] Wait a delay equal to the reconnection time of the event source.\n    this.#reconnectTimer = setTimeout(this.#reconnect, this.#reconnectInterval)\n  }\n\n  /**\n   * Reconnects to the EventSource endpoint after a disconnect/failure\n   *\n   * @internal\n   */\n  #reconnect = () => {\n    this.#reconnectTimer = undefined\n\n    // [spec] If the EventSource's readyState attribute is not set to CONNECTING, then return.\n    if (this.#readyState !== this.CONNECTING) {\n      return\n    }\n\n    this.#connect()\n  }\n}\n\n/**\n * According to spec, when constructing a URL:\n * > 1. Let baseURL be environment's base URL, if environment is a Document object\n * > 2. Return the result of applying the URL parser to url, with baseURL.\n *\n * Thus we should use `document.baseURI` if available, since it can be set through a base tag.\n *\n * @returns The base URL, if available - otherwise `undefined`\n * @internal\n */\nfunction getBaseURL(): string | undefined {\n  // eslint-disable-next-line @typescript-eslint/no-explicit-any\n  const doc = 'document' in globalThis ? (globalThis as any).document : undefined\n  return doc && typeof doc === 'object' && 'baseURI' in doc && typeof doc.baseURI === 'string'\n    ? doc.baseURI\n    : undefined\n}\n","import {createParser} from './parse.ts'\nimport type {EventSourceMessage, EventSourceParser} from './types.ts'\n\n/**\n * Options for the EventSourceParserStream.\n *\n * @public\n */\nexport interface StreamOptions {\n  /**\n   * Behavior when a parsing error occurs.\n   *\n   * - A custom function can be provided to handle the error.\n   * - `'terminate'` will error the stream and stop parsing.\n   * - Any other value will ignore the error and continue parsing.\n   *\n   * @defaultValue `undefined`\n   */\n  onError?: ('terminate' | ((error: Error) => void)) | undefined\n\n  /**\n   * Callback for when a reconnection interval is sent from the server.\n   *\n   * @param retry - The number of milliseconds to wait before reconnecting.\n   */\n  onRetry?: ((retry: number) => void) | undefined\n\n  /**\n   * Callback for when a comment is encountered in the stream.\n   *\n   * @param comment - The comment encountered in the stream.\n   */\n  onComment?: ((comment: string) => void) | undefined\n}\n\n/**\n * A TransformStream that ingests a stream of strings and produces a stream of `EventSourceMessage`.\n *\n * @example Basic usage\n * ```\n * const eventStream =\n *   response.body\n *     .pipeThrough(new TextDecoderStream())\n *     .pipeThrough(new EventSourceParserStream())\n * ```\n *\n * @example Terminate stream on parsing errors\n * ```\n * const eventStream =\n *  response.body\n *   .pipeThrough(new TextDecoderStream())\n *   .pipeThrough(new EventSourceParserStream({terminateOnError: true}))\n * ```\n *\n * @public\n */\nexport class EventSourceParserStream extends TransformStream<string, EventSourceMessage> {\n  constructor({onError, onRetry, onComment}: StreamOptions = {}) {\n    let parser!: EventSourceParser\n\n    super({\n      start(controller) {\n        parser = createParser({\n          onEvent: (event) => {\n            controller.enqueue(event)\n          },\n          onError(error) {\n            if (onError === 'terminate') {\n              controller.error(error)\n            } else if (typeof onError === 'function') {\n              onError(error)\n            }\n\n            // Ignore by default\n          },\n          onRetry,\n          onComment,\n        })\n      },\n      transform(chunk) {\n        parser.feed(chunk)\n      },\n    })\n  }\n}\n\nexport {type ErrorType, ParseError} from './errors.ts'\nexport type {EventSourceMessage} from './types.ts'\n","/**\n * OAuth provider extensions for specialized authentication flows.\n *\n * This module provides ready-to-use {@linkcode OAuthClientProvider} implementations\n * for common machine-to-machine authentication scenarios.\n */\n\nimport type { FetchLike, OAuthClientMetadata, StoredOAuthClientInformation, StoredOAuthTokens } from '@modelcontextprotocol/core-internal';\nimport type { CryptoKey, JWK } from 'jose';\n\nimport type { AddClientAuthentication, OAuthClientProvider } from './auth';\n\n/**\n * Helper to produce a `private_key_jwt` client authentication function.\n *\n * @example\n * ```ts source=\"./authExtensions.examples.ts#createPrivateKeyJwtAuth_basicUsage\"\n * const addClientAuth = createPrivateKeyJwtAuth({\n *     issuer: 'my-client',\n *     subject: 'my-client',\n *     privateKey: pemEncodedPrivateKey,\n *     alg: 'RS256'\n * });\n * // pass addClientAuth as provider.addClientAuthentication implementation\n * ```\n */\nexport function createPrivateKeyJwtAuth(options: {\n    issuer: string;\n    subject: string;\n    privateKey: string | Uint8Array | Record<string, unknown>;\n    alg: string;\n    audience?: string | URL;\n    lifetimeSeconds?: number;\n    claims?: Record<string, unknown>;\n}): AddClientAuthentication {\n    return async (_headers, params, url, metadata) => {\n        // Lazy import to avoid heavy dependency unless used\n        if (globalThis.crypto === undefined) {\n            throw new TypeError(\n                'crypto is not available, please ensure you have Web Crypto API support for older Node.js versions (see https://github.com/modelcontextprotocol/typescript-sdk#nodejs-web-crypto-globalthiscrypto-compatibility)'\n            );\n        }\n\n        const jose = await import('jose');\n\n        const audience = String(options.audience ?? metadata?.issuer ?? url);\n        const lifetimeSeconds = options.lifetimeSeconds ?? 300;\n\n        const now = Math.floor(Date.now() / 1000);\n        const jti = `${Date.now()}-${Math.random().toString(36).slice(2)}`;\n\n        const baseClaims = {\n            iss: options.issuer,\n            sub: options.subject,\n            aud: audience,\n            exp: now + lifetimeSeconds,\n            iat: now,\n            jti\n        };\n        const claims = options.claims ? { ...baseClaims, ...options.claims } : baseClaims;\n\n        // Import key for the requested algorithm\n        const alg = options.alg;\n        let key: unknown;\n        if (typeof options.privateKey === 'string') {\n            if (alg.startsWith('RS') || alg.startsWith('ES') || alg.startsWith('PS')) {\n                key = await jose.importPKCS8(options.privateKey, alg);\n            } else if (alg.startsWith('HS')) {\n                key = new TextEncoder().encode(options.privateKey);\n            } else {\n                throw new Error(`Unsupported algorithm ${alg}`);\n            }\n        } else if (options.privateKey instanceof Uint8Array) {\n            // Assume PKCS#8 DER in Uint8Array for asymmetric algorithms\n            key = alg.startsWith('HS') ? options.privateKey : await jose.importPKCS8(new TextDecoder().decode(options.privateKey), alg);\n        } else {\n            // Treat as JWK\n            key = await jose.importJWK(options.privateKey as JWK, alg);\n        }\n\n        // Sign JWT\n        const assertion = await new jose.SignJWT(claims)\n            .setProtectedHeader({ alg, typ: 'JWT' })\n            .setIssuer(options.issuer)\n            .setSubject(options.subject)\n            .setAudience(audience)\n            .setIssuedAt(now)\n            .setExpirationTime(now + lifetimeSeconds)\n            .setJti(jti)\n            .sign(key as unknown as Uint8Array | CryptoKey);\n\n        params.set('client_assertion', assertion);\n        params.set('client_assertion_type', 'urn:ietf:params:oauth:client-assertion-type:jwt-bearer');\n    };\n}\n\n/**\n * The `issuer` stamp for constructor-supplied client information. Omitting `expectedIssuer` is\n * deprecated: nothing else says which authorization server such credentials belong to.\n */\nfunction checkedExpectedIssuer(expectedIssuer: string | undefined): string | undefined {\n    if (expectedIssuer === undefined) {\n        console.warn(\n            '[mcp-sdk] Omitting `expectedIssuer` is deprecated. Without it, the MCP server decides which authorization ' +\n                \"server receives this client's credentials; pass your authorization server's issuer URL as \" +\n                '`expectedIssuer` so they are only sent there.'\n        );\n    } else if (typeof expectedIssuer !== 'string' || !expectedIssuer) {\n        throw new Error(\"expectedIssuer must be the authorization server's issuer URL\");\n    }\n    return expectedIssuer;\n}\n\n/**\n * Options for creating a {@linkcode ClientCredentialsProvider}.\n */\nexport interface ClientCredentialsProviderOptions {\n    /**\n     * The `client_id` for this OAuth client.\n     */\n    clientId: string;\n\n    /**\n     * The `client_secret` for `client_secret_basic` authentication.\n     */\n    clientSecret: string;\n\n    /**\n     * Optional client name for metadata.\n     */\n    clientName?: string;\n\n    /**\n     * Space-separated scopes values requested by the client.\n     */\n    scope?: string;\n\n    /**\n     * The authorization server's `issuer` identifier these credentials were registered with.\n     * Stamped onto the stored client information so `auth()`'s SEP-2352 issuer check\n     * refuses to send the credential to any other authorization server.\n     *\n     * Omitting it is deprecated: the credential then goes to whichever authorization server\n     * the MCP server advertises.\n     */\n    expectedIssuer?: string;\n}\n\n/**\n * OAuth provider for `client_credentials` grant with `client_secret_basic` authentication.\n *\n * This provider is designed for machine-to-machine authentication where\n * the client authenticates using a `client_id` and `client_secret`.\n *\n * @example\n * ```ts source=\"./authExtensions.examples.ts#ClientCredentialsProvider_basicUsage\"\n * const provider = new ClientCredentialsProvider({\n *     clientId: 'my-client',\n *     clientSecret: 'my-secret',\n *     expectedIssuer: 'https://auth.example.com'\n * });\n *\n * const transport = new StreamableHTTPClientTransport(serverUrl, {\n *     authProvider: provider\n * });\n * ```\n */\nexport class ClientCredentialsProvider implements OAuthClientProvider {\n    private _tokens?: StoredOAuthTokens;\n    private _clientInfo: StoredOAuthClientInformation;\n    private _clientMetadata: OAuthClientMetadata;\n\n    constructor(options: ClientCredentialsProviderOptions & { expectedIssuer: string });\n    /** @deprecated Pass `expectedIssuer` so the credentials are only sent to that authorization server. */\n    constructor(options: ClientCredentialsProviderOptions);\n    constructor(options: ClientCredentialsProviderOptions) {\n        this._clientInfo = {\n            client_id: options.clientId,\n            client_secret: options.clientSecret,\n            issuer: checkedExpectedIssuer(options.expectedIssuer)\n        };\n        this._clientMetadata = {\n            client_name: options.clientName ?? 'client-credentials-client',\n            redirect_uris: [],\n            grant_types: ['client_credentials'],\n            token_endpoint_auth_method: 'client_secret_basic',\n            scope: options.scope\n        };\n    }\n\n    get redirectUrl(): undefined {\n        return undefined;\n    }\n\n    get clientMetadata(): OAuthClientMetadata {\n        return this._clientMetadata;\n    }\n\n    clientInformation(): StoredOAuthClientInformation {\n        return this._clientInfo;\n    }\n\n    // No saveClientInformation: credentials are constructor-supplied and bound to a single\n    // authorization server. When `expectedIssuer` is set and the resolved AS differs, the\n    // SEP-2352 stamp check discards `clientInformation()` and auth() throws\n    // AuthorizationServerMismatchError(expectedIssuer, resolved) rather than sending the credential.\n\n    tokens(): StoredOAuthTokens | undefined {\n        return this._tokens;\n    }\n\n    saveTokens(tokens: StoredOAuthTokens): void {\n        this._tokens = tokens;\n    }\n\n    redirectToAuthorization(): void {\n        throw new Error('redirectToAuthorization is not used for client_credentials flow');\n    }\n\n    saveCodeVerifier(): void {\n        // Not used for client_credentials\n    }\n\n    codeVerifier(): string {\n        throw new Error('codeVerifier is not used for client_credentials flow');\n    }\n\n    prepareTokenRequest(scope?: string): URLSearchParams {\n        const params = new URLSearchParams({ grant_type: 'client_credentials' });\n        if (scope) params.set('scope', scope);\n        return params;\n    }\n}\n\n/**\n * Options for creating a {@linkcode PrivateKeyJwtProvider}.\n */\nexport interface PrivateKeyJwtProviderOptions {\n    /**\n     * The `client_id` for this OAuth client.\n     */\n    clientId: string;\n\n    /**\n     * The private key for signing JWT assertions.\n     * Can be a PEM string, Uint8Array, or JWK object.\n     */\n    privateKey: string | Uint8Array | Record<string, unknown>;\n\n    /**\n     * The algorithm to use for signing (e.g., 'RS256', 'ES256').\n     */\n    algorithm: string;\n\n    /**\n     * Optional client name for metadata.\n     */\n    clientName?: string;\n\n    /**\n     * Optional JWT lifetime in seconds (default: 300).\n     */\n    jwtLifetimeSeconds?: number;\n\n    /**\n     * Space-separated scopes values requested by the client.\n     */\n    scope?: string;\n\n    /**\n     * Optional custom claims to include in the JWT assertion.\n     * These are merged with the standard claims (`iss`, `sub`, `aud`, `exp`, `iat`, `jti`),\n     * with custom claims taking precedence for any overlapping keys.\n     *\n     * Useful for including additional claims that help scope the access token\n     * with finer granularity than what scopes alone allow.\n     */\n    claims?: Record<string, unknown>;\n\n    /**\n     * The authorization server's `issuer` identifier these credentials were registered with.\n     * Seeds the SEP-2352 issuer stamp — see {@linkcode ClientCredentialsProviderOptions.expectedIssuer}.\n     */\n    expectedIssuer?: string;\n}\n\n/**\n * OAuth provider for `client_credentials` grant with `private_key_jwt` authentication.\n *\n * This provider is designed for machine-to-machine authentication where\n * the client authenticates using a signed JWT assertion\n * ({@link https://datatracker.ietf.org/doc/html/rfc7523#section-2.2 | RFC 7523 Section 2.2}).\n *\n * @example\n * ```ts source=\"./authExtensions.examples.ts#PrivateKeyJwtProvider_basicUsage\"\n * const provider = new PrivateKeyJwtProvider({\n *     clientId: 'my-client',\n *     privateKey: pemEncodedPrivateKey,\n *     algorithm: 'RS256',\n *     expectedIssuer: 'https://auth.example.com'\n * });\n *\n * const transport = new StreamableHTTPClientTransport(serverUrl, {\n *     authProvider: provider\n * });\n * ```\n */\nexport class PrivateKeyJwtProvider implements OAuthClientProvider {\n    private _tokens?: StoredOAuthTokens;\n    private _clientInfo: StoredOAuthClientInformation;\n    private _clientMetadata: OAuthClientMetadata;\n    addClientAuthentication: AddClientAuthentication;\n\n    constructor(options: PrivateKeyJwtProviderOptions & { expectedIssuer: string });\n    /** @deprecated Pass `expectedIssuer` so the credentials are only sent to that authorization server. */\n    constructor(options: PrivateKeyJwtProviderOptions);\n    constructor(options: PrivateKeyJwtProviderOptions) {\n        this._clientInfo = {\n            client_id: options.clientId,\n            issuer: checkedExpectedIssuer(options.expectedIssuer)\n        };\n        this._clientMetadata = {\n            client_name: options.clientName ?? 'private-key-jwt-client',\n            redirect_uris: [],\n            grant_types: ['client_credentials'],\n            token_endpoint_auth_method: 'private_key_jwt',\n            scope: options.scope\n        };\n        this.addClientAuthentication = createPrivateKeyJwtAuth({\n            issuer: options.clientId,\n            subject: options.clientId,\n            privateKey: options.privateKey,\n            alg: options.algorithm,\n            lifetimeSeconds: options.jwtLifetimeSeconds,\n            claims: options.claims\n        });\n    }\n\n    get redirectUrl(): undefined {\n        return undefined;\n    }\n\n    get clientMetadata(): OAuthClientMetadata {\n        return this._clientMetadata;\n    }\n\n    clientInformation(): StoredOAuthClientInformation {\n        return this._clientInfo;\n    }\n\n    // No saveClientInformation: credentials are constructor-supplied; the SEP-2352 stamp\n    // check enforces `expectedIssuer` and auth() throws\n    // AuthorizationServerMismatchError(expectedIssuer, resolved) on mismatch.\n\n    tokens(): StoredOAuthTokens | undefined {\n        return this._tokens;\n    }\n\n    saveTokens(tokens: StoredOAuthTokens): void {\n        this._tokens = tokens;\n    }\n\n    redirectToAuthorization(): void {\n        throw new Error('redirectToAuthorization is not used for client_credentials flow');\n    }\n\n    saveCodeVerifier(): void {\n        // Not used for client_credentials\n    }\n\n    codeVerifier(): string {\n        throw new Error('codeVerifier is not used for client_credentials flow');\n    }\n\n    prepareTokenRequest(scope?: string): URLSearchParams {\n        const params = new URLSearchParams({ grant_type: 'client_credentials' });\n        if (scope) params.set('scope', scope);\n        return params;\n    }\n}\n\n/**\n * Options for creating a {@linkcode StaticPrivateKeyJwtProvider}.\n */\nexport interface StaticPrivateKeyJwtProviderOptions {\n    /**\n     * The `client_id` for this OAuth client.\n     */\n    clientId: string;\n\n    /**\n     * A pre-built JWT client assertion to use for authentication.\n     *\n     * This token should already contain the appropriate claims\n     * (`iss`, `sub`, `aud`, `exp`, etc.) and be signed by the client's key.\n     */\n    jwtBearerAssertion: string;\n\n    /**\n     * Optional client name for metadata.\n     */\n    clientName?: string;\n\n    /**\n     * Space-separated scopes values requested by the client.\n     */\n    scope?: string;\n\n    /**\n     * The authorization server's `issuer` identifier this assertion was minted for.\n     * Seeds the SEP-2352 issuer stamp — see {@linkcode ClientCredentialsProviderOptions.expectedIssuer}.\n     */\n    expectedIssuer?: string;\n}\n\n/**\n * OAuth provider for `client_credentials` grant with a static `private_key_jwt` assertion.\n *\n * This provider mirrors {@linkcode PrivateKeyJwtProvider} but instead of constructing and\n * signing a JWT on each request, it accepts a pre-built JWT assertion string and\n * uses it directly for authentication.\n */\nexport class StaticPrivateKeyJwtProvider implements OAuthClientProvider {\n    private _tokens?: StoredOAuthTokens;\n    private _clientInfo: StoredOAuthClientInformation;\n    private _clientMetadata: OAuthClientMetadata;\n    addClientAuthentication: AddClientAuthentication;\n\n    constructor(options: StaticPrivateKeyJwtProviderOptions & { expectedIssuer: string });\n    /** @deprecated Pass `expectedIssuer` so the credentials are only sent to that authorization server. */\n    constructor(options: StaticPrivateKeyJwtProviderOptions);\n    constructor(options: StaticPrivateKeyJwtProviderOptions) {\n        this._clientInfo = {\n            client_id: options.clientId,\n            issuer: checkedExpectedIssuer(options.expectedIssuer)\n        };\n        this._clientMetadata = {\n            client_name: options.clientName ?? 'static-private-key-jwt-client',\n            redirect_uris: [],\n            grant_types: ['client_credentials'],\n            token_endpoint_auth_method: 'private_key_jwt',\n            scope: options.scope\n        };\n\n        const assertion = options.jwtBearerAssertion;\n        this.addClientAuthentication = async (_headers, params) => {\n            params.set('client_assertion', assertion);\n            params.set('client_assertion_type', 'urn:ietf:params:oauth:client-assertion-type:jwt-bearer');\n        };\n    }\n\n    get redirectUrl(): undefined {\n        return undefined;\n    }\n\n    get clientMetadata(): OAuthClientMetadata {\n        return this._clientMetadata;\n    }\n\n    clientInformation(): StoredOAuthClientInformation {\n        return this._clientInfo;\n    }\n\n    // No saveClientInformation: credentials are constructor-supplied; the SEP-2352 stamp\n    // check enforces `expectedIssuer` and auth() throws\n    // AuthorizationServerMismatchError(expectedIssuer, resolved) on mismatch.\n\n    tokens(): StoredOAuthTokens | undefined {\n        return this._tokens;\n    }\n\n    saveTokens(tokens: StoredOAuthTokens): void {\n        this._tokens = tokens;\n    }\n\n    redirectToAuthorization(): void {\n        throw new Error('redirectToAuthorization is not used for client_credentials flow');\n    }\n\n    saveCodeVerifier(): void {\n        // Not used for client_credentials\n    }\n\n    codeVerifier(): string {\n        throw new Error('codeVerifier is not used for client_credentials flow');\n    }\n\n    prepareTokenRequest(scope?: string): URLSearchParams {\n        const params = new URLSearchParams({ grant_type: 'client_credentials' });\n        if (scope) params.set('scope', scope);\n        return params;\n    }\n}\n\n/**\n * Context provided to the assertion callback in {@linkcode CrossAppAccessProvider}.\n * Contains orchestrator-discovered information needed for JWT Authorization Grant requests.\n */\nexport interface CrossAppAccessContext {\n    /**\n     * The authorization server URL of the target MCP server.\n     * Discovered via RFC 9728 protected resource metadata.\n     */\n    authorizationServerUrl: string;\n\n    /**\n     * The resource URL of the target MCP server.\n     * Discovered via RFC 9728 protected resource metadata.\n     */\n    resourceUrl: string;\n\n    /**\n     * Optional scope being requested for the MCP server.\n     */\n    scope?: string;\n\n    /**\n     * Fetch function to use for HTTP requests (e.g., for IdP token exchange).\n     */\n    fetchFn: FetchLike;\n}\n\n/**\n * Callback function type that provides a JWT Authorization Grant (ID-JAG).\n *\n * The callback receives context about the target MCP server (authorization server URL,\n * resource URL, scope) and should return a JWT Authorization Grant that will be used\n * to obtain an access token from the MCP server.\n */\nexport type AssertionCallback = (context: CrossAppAccessContext) => string | Promise<string>;\n\n/**\n * Options for creating a {@linkcode CrossAppAccessProvider}.\n */\nexport interface CrossAppAccessProviderOptions {\n    /**\n     * Callback function that provides a JWT Authorization Grant (ID-JAG).\n     *\n     * The callback receives the MCP server's authorization server URL, resource URL,\n     * and requested scope, and should return a JWT Authorization Grant obtained from\n     * the enterprise IdP via RFC 8693 token exchange.\n     *\n     * You can use the utility functions from the `crossAppAccess` module\n     * for standard flows, or implement custom logic.\n     *\n     * @example\n     * ```ts\n     * assertion: async (ctx) => {\n     *     const result = await discoverAndRequestJwtAuthGrant({\n     *         idpUrl: 'https://idp.example.com',\n     *         audience: ctx.authorizationServerUrl,\n     *         resource: ctx.resourceUrl,\n     *         idToken: await getIdToken(),\n     *         clientId: 'my-idp-client',\n     *         clientSecret: 'my-idp-secret',\n     *         scope: ctx.scope,\n     *         fetchFn: ctx.fetchFn\n     *     });\n     *     return result.jwtAuthGrant;\n     * }\n     * ```\n     */\n    assertion: AssertionCallback;\n\n    /**\n     * The `client_id` registered with the MCP server's authorization server.\n     */\n    clientId: string;\n\n    /**\n     * The `client_secret` for authenticating with the MCP server's authorization server.\n     */\n    clientSecret: string;\n\n    /**\n     * Optional client name for metadata.\n     */\n    clientName?: string;\n\n    /**\n     * Custom fetch implementation. Defaults to global fetch.\n     */\n    fetchFn?: FetchLike;\n\n    /**\n     * The MCP authorization server's `issuer` identifier these credentials were registered with.\n     * Seeds the SEP-2352 issuer stamp — see {@linkcode ClientCredentialsProviderOptions.expectedIssuer}.\n     */\n    expectedIssuer?: string;\n}\n\n/**\n * OAuth provider for Cross-App Access (Enterprise Managed Authorization) using JWT Authorization Grant.\n *\n * This provider implements the Enterprise Managed Authorization flow (SEP-990) where:\n * 1. User authenticates with an enterprise IdP and the client obtains an ID Token\n * 2. Client exchanges the ID Token for a JWT Authorization Grant (ID-JAG) via RFC 8693 token exchange\n * 3. Client uses the JAG to obtain an access token from the MCP server via RFC 7523 JWT bearer grant\n *\n * The provider handles steps 2-3 automatically, with the JAG acquisition delegated to\n * a callback function that you provide. This allows flexibility in how you obtain and\n * cache ID Tokens from the IdP.\n *\n * @see https://github.com/modelcontextprotocol/ext-auth/blob/main/specification/stable/enterprise-managed-authorization.mdx\n *\n * @example\n * ```ts\n * const provider = new CrossAppAccessProvider({\n *     assertion: async (ctx) => {\n *         const result = await discoverAndRequestJwtAuthGrant({\n *             idpUrl: 'https://idp.example.com',\n *             audience: ctx.authorizationServerUrl,\n *             resource: ctx.resourceUrl,\n *             idToken: await getIdToken(), // Your function to get ID token\n *             clientId: 'my-idp-client',\n *             clientSecret: 'my-idp-secret',\n *             scope: ctx.scope,\n *             fetchFn: ctx.fetchFn\n *         });\n *         return result.jwtAuthGrant;\n *     },\n *     clientId: 'my-mcp-client',\n *     clientSecret: 'my-mcp-secret',\n *     expectedIssuer: 'https://auth.example.com'\n * });\n *\n * const transport = new StreamableHTTPClientTransport(serverUrl, {\n *     authProvider: provider\n * });\n * ```\n */\nexport class CrossAppAccessProvider implements OAuthClientProvider {\n    private _tokens?: StoredOAuthTokens;\n    private _clientInfo: StoredOAuthClientInformation;\n    private _clientMetadata: OAuthClientMetadata;\n    private _assertionCallback: AssertionCallback;\n    private _fetchFn: FetchLike;\n    private _authorizationServerUrl?: string;\n    private _resourceUrl?: string;\n    private _scope?: string;\n\n    constructor(options: CrossAppAccessProviderOptions & { expectedIssuer: string });\n    /** @deprecated Pass `expectedIssuer` so the credentials are only sent to that authorization server. */\n    constructor(options: CrossAppAccessProviderOptions);\n    constructor(options: CrossAppAccessProviderOptions) {\n        this._clientInfo = {\n            client_id: options.clientId,\n            client_secret: options.clientSecret,\n            issuer: checkedExpectedIssuer(options.expectedIssuer)\n        };\n        this._clientMetadata = {\n            client_name: options.clientName ?? 'cross-app-access-client',\n            redirect_uris: [],\n            grant_types: ['urn:ietf:params:oauth:grant-type:jwt-bearer'],\n            token_endpoint_auth_method: 'client_secret_basic'\n        };\n        this._assertionCallback = options.assertion;\n        this._fetchFn = options.fetchFn ?? fetch;\n    }\n\n    get redirectUrl(): undefined {\n        return undefined;\n    }\n\n    get clientMetadata(): OAuthClientMetadata {\n        return this._clientMetadata;\n    }\n\n    clientInformation(): StoredOAuthClientInformation {\n        return this._clientInfo;\n    }\n\n    // No saveClientInformation: credentials are constructor-supplied; the SEP-2352 stamp\n    // check enforces `expectedIssuer` and auth() throws\n    // AuthorizationServerMismatchError(expectedIssuer, resolved) on mismatch.\n\n    tokens(): StoredOAuthTokens | undefined {\n        return this._tokens;\n    }\n\n    saveTokens(tokens: StoredOAuthTokens): void {\n        this._tokens = tokens;\n    }\n\n    redirectToAuthorization(): void {\n        throw new Error('redirectToAuthorization is not used for jwt-bearer flow');\n    }\n\n    saveCodeVerifier(): void {\n        // Not used for jwt-bearer\n    }\n\n    codeVerifier(): string {\n        throw new Error('codeVerifier is not used for jwt-bearer flow');\n    }\n\n    /**\n     * Saves the authorization server URL discovered during OAuth flow.\n     * This is called by the auth() function after RFC 9728 discovery.\n     */\n    saveAuthorizationServerUrl(authorizationServerUrl: string): void {\n        this._authorizationServerUrl = authorizationServerUrl;\n    }\n\n    /**\n     * Returns the cached authorization server URL if available.\n     */\n    authorizationServerUrl(): string | undefined {\n        return this._authorizationServerUrl;\n    }\n\n    /**\n     * Saves the resource URL discovered during OAuth flow.\n     * This is called by the auth() function after RFC 9728 discovery.\n     */\n    saveResourceUrl?(resourceUrl: string): void {\n        this._resourceUrl = resourceUrl;\n    }\n\n    /**\n     * Returns the cached resource URL if available.\n     */\n    resourceUrl?(): string | undefined {\n        return this._resourceUrl;\n    }\n\n    async prepareTokenRequest(scope?: string): Promise<URLSearchParams> {\n        // Get the authorization server URL and resource URL from cached state\n        const authServerUrl = this._authorizationServerUrl;\n        const resourceUrl = this._resourceUrl;\n\n        if (!authServerUrl) {\n            throw new Error('Authorization server URL not available. Ensure auth() has been called first.');\n        }\n\n        if (!resourceUrl) {\n            throw new Error(\n                'Resource URL not available — server may not implement RFC 9728 ' +\n                    'Protected Resource Metadata (required for Cross-App Access), or ' +\n                    'auth() has not been called'\n            );\n        }\n\n        // Store scope for assertion callback\n        this._scope = scope;\n\n        // Call the assertion callback to get the JWT Authorization Grant\n        const jwtAuthGrant = await this._assertionCallback({\n            authorizationServerUrl: authServerUrl,\n            resourceUrl: resourceUrl,\n            scope: this._scope,\n            fetchFn: this._fetchFn\n        });\n\n        // Return params for JWT bearer grant per RFC 7523\n        const params = new URLSearchParams({\n            grant_type: 'urn:ietf:params:oauth:grant-type:jwt-bearer',\n            assertion: jwtAuthGrant\n        });\n\n        if (scope) {\n            params.set('scope', scope);\n        }\n\n        return params;\n    }\n}\n","/**\n * Cross-App Access (Enterprise Managed Authorization) Layer 2 utilities.\n *\n * Provides standalone functions for RFC 8693 Token Exchange and RFC 7523 JWT Authorization Grant\n * flows as specified in the Enterprise Managed Authorization specification (SEP-990).\n *\n * @see https://github.com/modelcontextprotocol/ext-auth/blob/main/specification/stable/enterprise-managed-authorization.mdx\n * @module\n */\n\nimport type { FetchLike } from '@modelcontextprotocol/core-internal';\nimport {\n    fetchWithinOrigin,\n    IdJagTokenExchangeResponseSchema,\n    OAuthErrorResponseSchema,\n    OAuthTokensSchema,\n    withoutIssuer\n} from '@modelcontextprotocol/core-internal';\n\nimport type { ClientAuthMethod } from './auth';\nimport { applyClientAuthentication, assertSecureTokenEndpoint, discoverAuthorizationServerMetadata } from './auth';\n\n/**\n * Options for requesting a JWT Authorization Grant via RFC 8693 Token Exchange.\n */\nexport interface RequestJwtAuthGrantOptions {\n    /**\n     * The IdP's token endpoint URL where the token exchange request will be sent.\n     */\n    tokenEndpoint: string | URL;\n\n    /**\n     * The authorization server URL of the target MCP server (used as `audience` in the token exchange request).\n     */\n    audience: string | URL;\n\n    /**\n     * The resource identifier of the target MCP server (RFC 9728).\n     */\n    resource: string | URL;\n\n    /**\n     * The identity assertion (ID Token) from the enterprise IdP.\n     * This should be the OpenID Connect ID Token obtained during user authentication.\n     */\n    idToken: string;\n\n    /**\n     * The client ID registered with the IdP for token exchange.\n     */\n    clientId: string;\n\n    /**\n     * The client secret for authenticating with the IdP.\n     *\n     * Optional: the IdP may register the MCP client as a public client. RFC 8693 does\n     * not mandate confidential clients for token exchange. Omitting this parameter\n     * omits `client_secret` from the request body.\n     */\n    clientSecret?: string;\n\n    /**\n     * Optional space-separated list of scopes to request for the target MCP server.\n     */\n    scope?: string;\n\n    /**\n     * Custom fetch implementation. Defaults to global fetch.\n     */\n    fetchFn?: FetchLike;\n}\n\n/**\n * Options for discovering the IdP's token endpoint and requesting a JWT Authorization Grant.\n * Extends {@linkcode RequestJwtAuthGrantOptions} with IdP discovery.\n */\nexport interface DiscoverAndRequestJwtAuthGrantOptions extends Omit<RequestJwtAuthGrantOptions, 'tokenEndpoint'> {\n    /**\n     * The IdP's issuer URL for OAuth metadata discovery.\n     * Will be used to discover the token endpoint via `.well-known/oauth-authorization-server`.\n     */\n    idpUrl: string | URL;\n}\n\n/**\n * Result from a successful JWT Authorization Grant token exchange.\n */\nexport interface JwtAuthGrantResult {\n    /**\n     * The JWT Authorization Grant (ID-JAG) that can be used to request an access token from the MCP server.\n     */\n    jwtAuthGrant: string;\n\n    /**\n     * Optional expiration time in seconds for the JWT Authorization Grant.\n     */\n    expiresIn?: number;\n\n    /**\n     * Optional scope granted by the IdP (may differ from requested scope).\n     */\n    scope?: string;\n}\n\n/**\n * Requests a JWT Authorization Grant (ID-JAG) from an enterprise IdP using RFC 8693 Token Exchange.\n *\n * This function performs step 2 of the Enterprise Managed Authorization flow:\n * exchanges an ID Token for a JWT Authorization Grant that can be used with the target MCP server.\n *\n * @param options - Configuration for the token exchange request\n * @returns The JWT Authorization Grant and related metadata\n * @throws {Error} If the token exchange fails or returns an error response\n *\n * @example\n * ```ts\n * const result = await requestJwtAuthorizationGrant({\n *     tokenEndpoint: 'https://idp.example.com/token',\n *     audience: 'https://auth.chat.example/',\n *     resource: 'https://mcp.chat.example/',\n *     idToken: 'eyJhbGciOiJS...',\n *     clientId: 'my-idp-client',\n *     clientSecret: 'my-idp-secret',\n *     scope: 'chat.read chat.history'\n * });\n *\n * // Use result.jwtAuthGrant with the MCP server's authorization server\n * ```\n */\nexport async function requestJwtAuthorizationGrant(options: RequestJwtAuthGrantOptions): Promise<JwtAuthGrantResult> {\n    const { tokenEndpoint, audience, resource, idToken, clientId, clientSecret, scope, fetchFn = fetch } = options;\n\n    const tokenUrl = assertSecureTokenEndpoint(tokenEndpoint);\n\n    // Prepare token exchange request per RFC 8693\n    const params = new URLSearchParams({\n        grant_type: 'urn:ietf:params:oauth:grant-type:token-exchange',\n        requested_token_type: 'urn:ietf:params:oauth:token-type:id-jag',\n        audience: String(audience),\n        resource: String(resource),\n        subject_token: idToken,\n        subject_token_type: 'urn:ietf:params:oauth:token-type:id_token',\n        client_id: clientId\n    });\n\n    // Only include client_secret when provided — sending an empty/undefined secret\n    // triggers `invalid_client` on strict IdPs that registered this as a public client.\n    if (clientSecret) {\n        params.set('client_secret', clientSecret);\n    }\n\n    if (scope) {\n        params.set('scope', scope);\n    }\n\n    const response = await fetchWithinOrigin(fetchFn)(tokenUrl, {\n        method: 'POST',\n        headers: {\n            'Content-Type': 'application/x-www-form-urlencoded'\n        },\n        body: params.toString()\n    });\n\n    if (!response.ok) {\n        const errorBody = await response.json().catch(() => ({}));\n\n        // Try to parse as OAuth error response\n        const parseResult = OAuthErrorResponseSchema.safeParse(errorBody);\n        if (parseResult.success) {\n            const { error, error_description } = parseResult.data;\n            throw new Error(`Token exchange failed: ${error}${error_description ? ` - ${error_description}` : ''}`);\n        }\n\n        throw new Error(`Token exchange failed with status ${response.status}: ${JSON.stringify(errorBody)}`);\n    }\n\n    const parseResult = IdJagTokenExchangeResponseSchema.safeParse(await response.json());\n    if (!parseResult.success) {\n        throw new Error(`Invalid token exchange response: ${parseResult.error.message}`);\n    }\n\n    return {\n        jwtAuthGrant: parseResult.data.access_token,\n        expiresIn: parseResult.data.expires_in,\n        scope: parseResult.data.scope\n    };\n}\n\n/**\n * Discovers the IdP's token endpoint and requests a JWT Authorization Grant.\n *\n * This is a convenience wrapper around {@linkcode requestJwtAuthorizationGrant} that\n * first performs OAuth metadata discovery to find the token endpoint.\n *\n * @param options - Configuration including IdP URL for discovery\n * @returns The JWT Authorization Grant and related metadata\n * @throws {Error} If discovery fails or the token exchange fails\n *\n * @example\n * ```ts\n * const result = await discoverAndRequestJwtAuthGrant({\n *     idpUrl: 'https://idp.example.com',\n *     audience: 'https://auth.chat.example/',\n *     resource: 'https://mcp.chat.example/',\n *     idToken: await getIdToken(),\n *     clientId: 'my-idp-client',\n *     clientSecret: 'my-idp-secret'\n * });\n * ```\n */\nexport async function discoverAndRequestJwtAuthGrant(options: DiscoverAndRequestJwtAuthGrantOptions): Promise<JwtAuthGrantResult> {\n    const { idpUrl, fetchFn = fetch, ...restOptions } = options;\n\n    // Discover IdP's authorization server metadata\n    const metadata = await discoverAuthorizationServerMetadata(String(idpUrl), { fetchFn });\n\n    if (!metadata?.token_endpoint) {\n        throw new Error(`Failed to discover token endpoint for IdP: ${idpUrl}`);\n    }\n\n    // Perform token exchange\n    return requestJwtAuthorizationGrant({\n        ...restOptions,\n        tokenEndpoint: metadata.token_endpoint,\n        fetchFn\n    });\n}\n\n/**\n * Exchanges a JWT Authorization Grant for an access token at the MCP server's authorization server.\n *\n * This function performs step 3 of the Enterprise Managed Authorization flow:\n * uses the JWT Authorization Grant to obtain an access token from the MCP server.\n *\n * @param options - Configuration for the JWT grant exchange\n * @returns OAuth tokens (access token, token type, etc.)\n * @throws {Error} If the exchange fails or returns an error response\n *\n * Defaults to `client_secret_basic` (HTTP Basic Authorization header), matching\n * `CrossAppAccessProvider`'s declared `token_endpoint_auth_method` and the\n * SEP-990 conformance test requirements. Use `authMethod: 'client_secret_post'` only\n * when the authorization server explicitly requires it.\n *\n * @example\n * ```ts\n * const tokens = await exchangeJwtAuthGrant({\n *     tokenEndpoint: 'https://auth.chat.example/token',\n *     jwtAuthGrant: 'eyJhbGci...',\n *     clientId: 'my-mcp-client',\n *     clientSecret: 'my-mcp-secret'\n * });\n *\n * // Use tokens.access_token to access the MCP server\n * ```\n */\nexport async function exchangeJwtAuthGrant(options: {\n    tokenEndpoint: string | URL;\n    jwtAuthGrant: string;\n    clientId: string;\n    clientSecret?: string;\n    /**\n     * Client authentication method. Defaults to `'client_secret_basic'` to align with\n     * `CrossAppAccessProvider` and SEP-990 conformance requirements.\n     * Callers with no `clientSecret` should pass `'none'` for public-client auth.\n     */\n    authMethod?: ClientAuthMethod;\n    fetchFn?: FetchLike;\n}): Promise<{ access_token: string; token_type: string; expires_in?: number; scope?: string }> {\n    const { tokenEndpoint, jwtAuthGrant, clientId, clientSecret, authMethod = 'client_secret_basic', fetchFn = fetch } = options;\n\n    const tokenUrl = assertSecureTokenEndpoint(tokenEndpoint);\n\n    // Prepare JWT bearer grant request per RFC 7523\n    const params = new URLSearchParams({\n        grant_type: 'urn:ietf:params:oauth:grant-type:jwt-bearer',\n        assertion: jwtAuthGrant\n    });\n\n    const headers = new Headers({\n        'Content-Type': 'application/x-www-form-urlencoded'\n    });\n\n    applyClientAuthentication(authMethod, { client_id: clientId, client_secret: clientSecret }, headers, params);\n\n    const response = await fetchWithinOrigin(fetchFn)(tokenUrl, {\n        method: 'POST',\n        headers,\n        body: params.toString()\n    });\n\n    if (!response.ok) {\n        const errorBody = await response.json().catch(() => ({}));\n\n        // Try to parse as OAuth error response\n        const parseResult = OAuthErrorResponseSchema.safeParse(errorBody);\n        if (parseResult.success) {\n            const { error, error_description } = parseResult.data;\n            throw new Error(`JWT grant exchange failed: ${error}${error_description ? ` - ${error_description}` : ''}`);\n        }\n\n        throw new Error(`JWT grant exchange failed with status ${response.status}: ${JSON.stringify(errorBody)}`);\n    }\n\n    const responseBody = await response.json();\n\n    // Validate response using core schema\n    const parseResult = OAuthTokensSchema.safeParse(withoutIssuer(responseBody));\n    if (!parseResult.success) {\n        throw new Error(`Invalid token response: ${parseResult.error.message}`);\n    }\n\n    return parseResult.data;\n}\n","/**\n * DPoP (Demonstrating Proof of Possession) client support.\n *\n * Implements the client half of {@link https://datatracker.ietf.org/doc/html/rfc9449 | RFC 9449},\n * adopted by MCP as the draft extension\n * {@link https://github.com/modelcontextprotocol/ext-auth/blob/main/specification/draft/dpop-extension.mdx | SEP-1932}.\n * DPoP binds an OAuth access token to a client-held asymmetric key: every request carries a\n * signed proof JWT over the key, so a stolen bearer token alone cannot be replayed elsewhere.\n *\n * This module is opt-in — nothing here runs unless a caller creates a {@linkcode DpopSession}\n * and wires it into {@linkcode OAuthClientProvider.dpop} (see `auth.ts`) or a {@linkcode withDpop}\n * middleware (see `middleware.ts`). Existing Bearer-token flows are unaffected.\n *\n * `jose` is loaded lazily so the (larger) WebCrypto-key-management code path is only pulled in\n * when a caller actually constructs a {@linkcode DpopSession} — mirroring the lazy `jose` import\n * in {@linkcode createPrivateKeyJwtAuth} (`authExtensions.ts`).\n */\n\nimport type { CryptoKey, JWK } from 'jose';\n\n/** Asymmetric JWS algorithms usable for a DPoP proof (RFC 9449 §11.6 forbids symmetric algs and `none`). */\nexport const DPOP_SUPPORTED_ALGS = ['ES256', 'ES384', 'ES512', 'RS256', 'RS384', 'RS512', 'PS256', 'PS384', 'PS512', 'EdDSA'] as const;\n\n/** A DPoP JWS algorithm this SDK can sign proofs with. */\nexport type DpopAlg = (typeof DPOP_SUPPORTED_ALGS)[number];\n\nconst DEFAULT_DPOP_ALG: DpopAlg = 'ES256';\nconst DPOP_TYP = 'dpop+jwt';\n\nasync function importJose(): Promise<typeof import('jose')> {\n    if (globalThis.crypto === undefined) {\n        throw new TypeError(\n            'crypto is not available, please ensure you have Web Crypto API support for older Node.js versions (see https://github.com/modelcontextprotocol/typescript-sdk#nodejs-web-crypto-globalthiscrypto-compatibility)'\n        );\n    }\n    return import('jose');\n}\n\n/** A DPoP signing key pair: the private key signs proofs, the public JWK is embedded in them. */\nexport interface DpopKeyPair {\n    /** Signs proofs. Non-extractable unless {@linkcode GenerateDpopKeyPairOptions.extractable} was set. */\n    privateKey: CryptoKey;\n    /** Matches {@linkcode publicJwk}; rarely needed directly. */\n    publicKey: CryptoKey;\n    /** Embedded in each proof's `jwk` header parameter (RFC 9449 §4.2). */\n    publicJwk: JWK;\n    /** RFC 7638 JWK SHA-256 thumbprint — the value an authorization server binds as the token's `cnf.jkt`. */\n    thumbprint: string;\n    /** The JWS algorithm this key pair signs with. */\n    alg: DpopAlg;\n}\n\nexport interface GenerateDpopKeyPairOptions {\n    /** Signing algorithm. @default 'ES256' */\n    alg?: DpopAlg;\n    /**\n     * Allow the private key to be exported (e.g. for persistence across process restarts).\n     *\n     * @default false — RFC 9449 §11.1 and §11.7 recommend non-extractable keys (hardware-backed\n     * where available) so the private key cannot be exfiltrated by XSS or a compromised dependency.\n     * Only set this when the host has its own plan for protecting the exported key material.\n     */\n    extractable?: boolean;\n}\n\n/** Generate an asymmetric DPoP signing key pair. Non-extractable by default (RFC 9449 §11). */\nexport async function generateDpopKeyPair(options: GenerateDpopKeyPairOptions = {}): Promise<DpopKeyPair> {\n    const alg = options.alg ?? DEFAULT_DPOP_ALG;\n    const jose = await importJose();\n    const { publicKey, privateKey } = await jose.generateKeyPair(alg, { extractable: options.extractable ?? false });\n    const publicJwk = await jose.exportJWK(publicKey);\n    const thumbprint = await jose.calculateJwkThumbprint(publicJwk, 'sha256');\n    return { privateKey, publicKey, publicJwk, thumbprint, alg };\n}\n\n/**\n * Compute the `ath` claim for a DPoP proof presented alongside an access token: the\n * base64url-encoded SHA-256 digest of the ASCII access-token value (RFC 9449 §4.1).\n *\n * Uses Web Crypto (`crypto.subtle`) rather than a Node-only hashing API so this stays usable\n * in browser and edge runtimes.\n */\nexport async function accessTokenHash(accessToken: string): Promise<string> {\n    if (globalThis.crypto?.subtle === undefined) {\n        throw new TypeError(\n            'crypto.subtle is not available, please ensure you have Web Crypto API support for older Node.js versions (see https://github.com/modelcontextprotocol/typescript-sdk#nodejs-web-crypto-globalthiscrypto-compatibility)'\n        );\n    }\n    const digest = await globalThis.crypto.subtle.digest('SHA-256', new TextEncoder().encode(accessToken));\n    return base64UrlEncode(new Uint8Array(digest));\n}\n\nfunction base64UrlEncode(bytes: Uint8Array): string {\n    let binary = '';\n    for (const byte of bytes) binary += String.fromCodePoint(byte);\n    return btoa(binary).replaceAll('+', '-').replaceAll('/', '_').replaceAll('=', '');\n}\n\n/** Strip the query and fragment from a URL, per RFC 9449 §4.2 (`htu` MUST NOT contain either). */\nfunction stripQueryAndFragment(url: string | URL): string {\n    const u = new URL(url.toString());\n    return `${u.origin}${u.pathname}`;\n}\n\n/** A fresh, cryptographically random `jti` (RFC 9449 §4.2 — MUST be unique per proof). */\nfunction randomJti(): string {\n    const bytes = new Uint8Array(16);\n    globalThis.crypto.getRandomValues(bytes);\n    return base64UrlEncode(bytes);\n}\n\n/** Inputs for a single DPoP proof (RFC 9449 §4.2). */\nexport interface DpopProofRequest {\n    /** HTTP method of the target request (`htm` claim). Case-normalized to upper-case. */\n    htm: string;\n    /** HTTP target URI of the request (`htu` claim) — query/fragment are stripped automatically. */\n    htu: string | URL;\n    /** When set, binds the proof to this access token via the `ath` claim (RFC 9449 §4.1). */\n    accessToken?: string;\n    /**\n     * Explicit server-provided nonce to embed. When omitted, the session's remembered nonce for\n     * `htu`'s origin (if any) is used automatically — see {@linkcode DpopSession.rememberNonce}.\n     */\n    nonce?: string;\n}\n\n/**\n * A DPoP signing identity plus the small amount of state RFC 9449 requires across requests:\n * the key pair and, per origin, the most recently server-supplied nonce (RFC 9449 §8/§9).\n *\n * One `DpopSession` is meant to live for the lifetime of a single OAuth client registration —\n * the token endpoint and the resource server are different origins and get independent nonce\n * slots, so a nonce challenge from one never leaks into proofs sent to the other.\n */\nexport class DpopSession {\n    private readonly nonces = new Map<string, string>();\n\n    private constructor(private readonly keyPair: DpopKeyPair) {}\n\n    /** Create a session with a fresh key pair, or reuse a caller-supplied one. */\n    static async create(options: { alg?: DpopAlg; keyPair?: DpopKeyPair } = {}): Promise<DpopSession> {\n        const keyPair = options.keyPair ?? (await generateDpopKeyPair({ alg: options.alg }));\n        return new DpopSession(keyPair);\n    }\n\n    /** RFC 7638 JWK SHA-256 thumbprint of the signing key — matches the token's `cnf.jkt` once bound. */\n    get thumbprint(): string {\n        return this.keyPair.thumbprint;\n    }\n\n    /** The JWS algorithm this session signs proofs with. */\n    get alg(): DpopAlg {\n        return this.keyPair.alg;\n    }\n\n    /** The public JWK embedded in every proof's `jwk` header parameter. */\n    get publicJwk(): JWK {\n        return this.keyPair.publicJwk;\n    }\n\n    /** The remembered nonce for `url`'s origin, if the server has issued one (RFC 9449 §8/§9). */\n    nonceFor(url: string | URL): string | undefined {\n        return this.nonces.get(new URL(url.toString()).origin);\n    }\n\n    /** Record a server-supplied nonce for `url`'s origin (newest-wins, RFC 9449 §8.2). */\n    rememberNonce(url: string | URL, nonce: string): void {\n        this.nonces.set(new URL(url.toString()).origin, nonce);\n    }\n\n    /**\n     * Capture a `DPoP-Nonce` response header, if present, for `url`'s origin. RFC 9449 §8.2 says a\n     * fresh nonce may ride on *any* response (success or failure), so call this unconditionally\n     * after every request, not only on a `use_dpop_nonce` challenge.\n     */\n    observeNonce(response: Response, url: string | URL): void {\n        const nonce = response.headers.get('dpop-nonce');\n        if (nonce) this.rememberNonce(url, nonce);\n    }\n\n    /**\n     * Build a fresh DPoP proof JWT. Always mints a new `jti` — proofs are never cached or reused,\n     * since RFC 9449 §4.3 step 9 requires each to be presented at most once.\n     */\n    async buildProof(request: DpopProofRequest): Promise<string> {\n        const jose = await importJose();\n        const htu = stripQueryAndFragment(request.htu);\n        const nonce = request.nonce ?? this.nonceFor(request.htu);\n\n        const payload: Record<string, unknown> = {\n            jti: randomJti(),\n            htm: request.htm.toUpperCase(),\n            htu,\n            iat: Math.floor(Date.now() / 1000)\n        };\n        if (request.accessToken !== undefined) {\n            payload.ath = await accessTokenHash(request.accessToken);\n        }\n        if (nonce !== undefined) {\n            payload.nonce = nonce;\n        }\n\n        return new jose.SignJWT(payload)\n            .setProtectedHeader({ alg: this.keyPair.alg, typ: DPOP_TYP, jwk: this.keyPair.publicJwk })\n            .sign(this.keyPair.privateKey);\n    }\n}\n\n/**\n * Whether `wwwAuthenticate` advertises a `DPoP` auth-scheme challenge (matched at the start of the\n * header or after a comma, per RFC 9110 §11.6.1 — a server may list several schemes together, e.g.\n * `Bearer …, DPoP …`).\n */\nfunction hasDpopChallenge(wwwAuthenticate: string): boolean {\n    return /(?:^|,)\\s*dpop(?:\\s|$|,)/i.test(wwwAuthenticate);\n}\n\n/**\n * Whether `response` is a resource-server `use_dpop_nonce` challenge (RFC 9449 §9): a `401` whose\n * `WWW-Authenticate` header carries a `DPoP` challenge with `error=\"use_dpop_nonce\"`.\n *\n * A conformant retry re-signs the proof with the nonce {@linkcode DpopSession.observeNonce} just\n * captured — never resend the original proof: RFC 9449 §4.2 requires a unique `jti` per proof, and\n * replaying one across the challenge/retry boundary is itself a violation.\n */\nexport function isDpopNonceChallenge(response: Response): boolean {\n    if (response.status !== 401) return false;\n    const wwwAuthenticate = response.headers.get('www-authenticate') ?? '';\n    return hasDpopChallenge(wwwAuthenticate) && /use_dpop_nonce/i.test(wwwAuthenticate);\n}\n","import type { FetchLike } from '@modelcontextprotocol/core-internal';\n\n// eslint-disable-next-line @typescript-eslint/no-unused-vars -- AuthProvider referenced in JSDoc {@linkcode}\nimport type { AuthProvider, OAuthClientProvider } from './auth';\nimport { auth, extractWWWAuthenticateParams, UnauthorizedError } from './auth';\nimport { markAuthSeamEscape } from './authSeam';\nimport type { DpopSession } from './dpop';\nimport { isDpopNonceChallenge } from './dpop';\n\n/**\n * Middleware function that wraps and enhances fetch functionality.\n * Takes a fetch handler and returns an enhanced fetch handler.\n */\nexport type Middleware = (next: FetchLike) => FetchLike;\n\n/**\n * Creates a fetch wrapper that handles OAuth authentication automatically.\n *\n * This wrapper will:\n * - Add `Authorization` headers with access tokens\n * - Handle 401 responses by attempting re-authentication\n * - Retry the original request after successful auth\n * - Handle OAuth errors appropriately ({@linkcode index.OAuthErrorCode.InvalidClient | OAuthErrorCode.InvalidClient}, etc.)\n * - When {@linkcode OAuthClientProvider.dpop | provider.dpop()} is implemented, present DPoP-bound\n *   tokens with the `DPoP` scheme plus a per-request proof (RFC 9449 / SEP-1932) by composing\n *   {@linkcode withDpopFromProvider} underneath — so a `use_dpop_nonce` challenge is retried\n *   inline on every attempt, independently of the single re-authentication retry here\n *\n * The `baseUrl` parameter is optional and defaults to using the domain from the request URL.\n * However, you should explicitly provide `baseUrl` when:\n * - Making requests to multiple subdomains (e.g., api.example.com, cdn.example.com)\n * - Using API paths that differ from OAuth discovery paths (e.g., requesting /api/v1/data but OAuth is at /)\n * - The OAuth server is on a different domain than your API requests\n * - You want to ensure consistent OAuth behavior regardless of request URLs\n *\n * For MCP transports, set `baseUrl` to the same URL you pass to the transport constructor.\n *\n * Note: This wrapper is designed for general-purpose fetch operations.\n * MCP transports (SSE and StreamableHTTP) already have built-in OAuth handling\n * and should not need this wrapper.\n *\n * @param provider - OAuth client provider for authentication\n * @param baseUrl - Base URL for OAuth server discovery (defaults to request URL domain)\n * @returns A fetch middleware function\n */\nexport const withOAuth =\n    (provider: OAuthClientProvider, baseUrl?: string | URL): Middleware =>\n    baseNext => {\n        // DPoP request-signing (and its nonce retry) sits *below* the Bearer/re-auth layer so it\n        // sees the final method/URL of every attempt and every response. `auth()` keeps the\n        // unwrapped fetch: token-endpoint DPoP is handled inside executeTokenRequest.\n        const next = provider.dpop ? withDpopFromProvider(provider)(baseNext) : baseNext;\n\n        return async (input, init) => {\n            const makeRequest = async (): Promise<Response> => {\n                const headers = new Headers(init?.headers);\n\n                // Add authorization header if tokens are available\n                const tokens = await provider.tokens();\n                if (tokens) {\n                    headers.set('Authorization', `Bearer ${tokens.access_token}`);\n                }\n\n                return await next(input, { ...init, headers });\n            };\n\n            let response = await makeRequest();\n\n            // Handle 401 responses by attempting re-authentication\n            if (response.status === 401) {\n                try {\n                    const { resourceMetadataUrl, scope } = extractWWWAuthenticateParams(response);\n\n                    // Use provided baseUrl or extract from request URL\n                    const serverUrl = baseUrl || (typeof input === 'string' ? new URL(input).origin : input.origin);\n\n                    const result = await auth(provider, {\n                        serverUrl,\n                        resourceMetadataUrl,\n                        scope,\n                        fetchFn: baseNext\n                    });\n\n                    if (result === 'REDIRECT') {\n                        throw new UnauthorizedError('Authentication requires user authorization - redirect initiated');\n                    }\n\n                    if (result !== 'AUTHORIZED') {\n                        throw new UnauthorizedError(`Authentication failed with result: ${result}`);\n                    }\n\n                    // Retry the request with fresh tokens\n                    response = await makeRequest();\n                } catch (error) {\n                    if (error instanceof UnauthorizedError) {\n                        throw error;\n                    }\n                    throw new UnauthorizedError(`Failed to re-authenticate: ${error instanceof Error ? error.message : String(error)}`);\n                }\n            }\n\n            // If we still have a 401 after re-auth attempt, throw an error\n            if (response.status === 401) {\n                const url = typeof input === 'string' ? input : input.toString();\n                throw new UnauthorizedError(`Authentication failed for ${url}`);\n            }\n\n            return response;\n        };\n    };\n\n/**\n * A function returning the current access token, or `undefined` if none is available yet. See\n * {@linkcode withDpop}.\n */\nexport type DpopTokenSource = () => string | undefined | Promise<string | undefined>;\n\n/**\n * A {@linkcode DpopSession}, or a function resolving to one (or to `undefined` to leave the request\n * untouched). The function form lets the session be created lazily or come from\n * {@linkcode OAuthClientProvider.dpop}. See {@linkcode withDpop}.\n */\nexport type DpopSessionSource = DpopSession | (() => DpopSession | undefined | Promise<DpopSession | undefined>);\n\n/**\n * Creates a fetch wrapper that presents an access token using the `DPoP` Authorization scheme\n * (RFC 9449 / SEP-1932) instead of `Bearer`: every request carries `Authorization: DPoP <token>`\n * plus a fresh `DPoP` proof bound to that request's method and URL, a resource-server\n * `use_dpop_nonce` challenge (RFC 9449 §9) is retried once, inline, with the server-supplied nonce,\n * and a `DPoP-Nonce` delivered on any response is remembered for the next proof (RFC 9449 §8.2).\n *\n * Because it wraps `fetch` itself, the proof is always bound to the request actually sent and every\n * response is observed — which is why the MCP transports apply this wrapper internally (via\n * {@linkcode withDpopFromProvider}) when their `authProvider` implements\n * {@linkcode OAuthClientProvider.dpop | dpop()}, rather than threading request context through\n * {@linkcode AuthProvider}.\n *\n * Use this directly when you already manage the access token yourself (a non-OAuth token source,\n * or credentials obtained out-of-band) and only need DPoP's request-signing behavior — e.g.\n * `fetch: withDpop(session, getToken)(fetch)` alongside a minimal `authProvider: { token }`.\n *\n * @param session - The DPoP signing session (key pair + nonce state), or a function resolving to\n *   it. Reuse the same session across requests to the same server so its nonce state persists.\n *   When the function resolves to `undefined` the request passes through unchanged.\n * @param getToken - Returns the current access token, or `undefined` if none is available (the\n *   request passes through unchanged — any `Authorization` header already on it is left as is).\n * @returns A fetch middleware function\n */\nexport const withDpop =\n    (session: DpopSessionSource, getToken: DpopTokenSource): Middleware =>\n    next => {\n        const resolveSession = typeof session === 'function' ? session : () => session;\n\n        return async (input, init) => {\n            const method = (init?.method ?? 'GET').toUpperCase();\n            const url = new URL(input.toString());\n            const activeSession = await resolveSession();\n            if (!activeSession) return next(input, init);\n\n            const makeRequest = async (): Promise<Response> => {\n                const accessToken = await getToken();\n                if (!accessToken) return next(input, init);\n                const headers = new Headers(init?.headers);\n                const proof = await activeSession.buildProof({ htm: method, htu: url, accessToken });\n                headers.set('Authorization', `DPoP ${accessToken}`);\n                headers.set('DPoP', proof);\n                return next(input, { ...init, headers });\n            };\n\n            let response = await makeRequest();\n\n            // Only retry when the challenge carries a fresh DPoP-Nonce — otherwise the retry\n            // would re-send the nonce the server just rejected. RFC 9449 §4.2: the retry gets a\n            // freshly signed proof (new jti); the original is never replayed.\n            if (isDpopNonceChallenge(response) && response.headers.has('dpop-nonce')) {\n                activeSession.observeNonce(response, url);\n                await response.text?.().catch(() => {});\n                response = await makeRequest();\n            }\n            // RFC 9449 §8.2: a fresh nonce may ride on any response, success included.\n            activeSession.observeNonce(response, url);\n\n            return response;\n        };\n    };\n\n/**\n * {@linkcode withDpop} driven by an {@linkcode OAuthClientProvider}: the session comes from\n * {@linkcode OAuthClientProvider.dpop | provider.dpop()} and the token from\n * {@linkcode OAuthClientProvider.tokens | provider.tokens()} — presented with the DPoP scheme only\n * when the AS actually issued `token_type: \"DPoP\"` (RFC 9449 §7.1); a Bearer token passes through\n * untouched.\n *\n * This is what the MCP transports and {@linkcode withOAuth} compose internally when the provider\n * implements `dpop()`. Use it directly only when building your own fetch pipeline around an\n * `OAuthClientProvider` (e.g. a custom re-authorization middleware) — place it *innermost*, below\n * whatever sets `Authorization: Bearer` and handles 401 re-authentication.\n */\nexport const withDpopFromProvider = (provider: OAuthClientProvider): Middleware =>\n    withDpop(\n        async () => {\n            try {\n                return await provider.dpop?.();\n            } catch (error) {\n                throw markAuthSeamEscape(error);\n            }\n        },\n        async () => {\n            let tokens;\n            try {\n                tokens = await provider.tokens();\n            } catch (error) {\n                throw markAuthSeamEscape(error);\n            }\n            return tokens?.token_type?.toLowerCase() === 'dpop' ? tokens.access_token : undefined;\n        }\n    );\n\n/**\n * Logger function type for HTTP requests\n */\nexport type RequestLogger = (input: {\n    method: string;\n    url: string | URL;\n    status: number;\n    statusText: string;\n    duration: number;\n    requestHeaders?: Headers;\n    responseHeaders?: Headers;\n    error?: Error;\n}) => void;\n\n/**\n * Configuration options for the logging middleware\n */\nexport type LoggingOptions = {\n    /**\n     * Custom logger function, defaults to console logging\n     */\n    logger?: RequestLogger;\n\n    /**\n     * Whether to include request headers in logs\n     * @default false\n     */\n    includeRequestHeaders?: boolean;\n\n    /**\n     * Whether to include response headers in logs\n     * @default false\n     */\n    includeResponseHeaders?: boolean;\n\n    /**\n     * Status level filter - only log requests with status >= this value\n     * Set to `0` to log all requests, `400` to log only errors\n     * @default 0\n     */\n    statusLevel?: number;\n};\n\n/**\n * Creates a fetch middleware that logs HTTP requests and responses.\n *\n * When called without arguments `withLogging()`, it uses the default logger that:\n * - Logs successful requests (2xx) to `console.log`\n * - Logs error responses (4xx/5xx) and network errors to `console.error`\n * - Logs all requests regardless of status (`statusLevel: 0`)\n * - Does not include request or response headers in logs\n * - Measures and displays request duration in milliseconds\n *\n * Important: the default logger uses both `console.log` and `console.error` so it should not be used with\n * `stdio` transports and applications.\n *\n * @param options - Logging configuration options\n * @returns A fetch middleware function\n */\nexport const withLogging = (options: LoggingOptions = {}): Middleware => {\n    const { logger, includeRequestHeaders = false, includeResponseHeaders = false, statusLevel = 0 } = options;\n\n    const defaultLogger: RequestLogger = input => {\n        const { method, url, status, statusText, duration, requestHeaders, responseHeaders, error } = input;\n\n        let message = error\n            ? `HTTP ${method} ${url} failed: ${error.message} (${duration}ms)`\n            : `HTTP ${method} ${url} ${status} ${statusText} (${duration}ms)`;\n\n        // Add headers to message if requested\n        if (includeRequestHeaders && requestHeaders) {\n            const reqHeaders = [...requestHeaders.entries()].map(([key, value]) => `${key}: ${value}`).join(', ');\n            message += `\\n  Request Headers: {${reqHeaders}}`;\n        }\n\n        if (includeResponseHeaders && responseHeaders) {\n            const resHeaders = [...responseHeaders.entries()].map(([key, value]) => `${key}: ${value}`).join(', ');\n            message += `\\n  Response Headers: {${resHeaders}}`;\n        }\n\n        if (error || status >= 400) {\n            // eslint-disable-next-line no-console\n            console.error(message);\n        } else {\n            // eslint-disable-next-line no-console\n            console.log(message);\n        }\n    };\n\n    const logFn = logger || defaultLogger;\n\n    return next => async (input, init) => {\n        const startTime = performance.now();\n        const method = init?.method || 'GET';\n        const url = typeof input === 'string' ? input : input.toString();\n        const requestHeaders = includeRequestHeaders ? new Headers(init?.headers) : undefined;\n\n        try {\n            const response = await next(input, init);\n            const duration = performance.now() - startTime;\n\n            // Only log if status meets the log level threshold\n            if (response.status >= statusLevel) {\n                logFn({\n                    method,\n                    url,\n                    status: response.status,\n                    statusText: response.statusText,\n                    duration,\n                    requestHeaders,\n                    responseHeaders: includeResponseHeaders ? response.headers : undefined\n                });\n            }\n\n            return response;\n        } catch (error) {\n            const duration = performance.now() - startTime;\n\n            // Always log errors regardless of log level\n            logFn({\n                method,\n                url,\n                status: 0,\n                statusText: 'Network Error',\n                duration,\n                requestHeaders,\n                error: error as Error\n            });\n\n            throw error;\n        }\n    };\n};\n\n/**\n * Composes multiple fetch middleware functions into a single middleware pipeline.\n * Middleware are applied in the order they appear, creating a chain of handlers.\n *\n * @example\n * ```ts source=\"./middleware.examples.ts#applyMiddlewares_basicUsage\"\n * // Create a middleware pipeline that handles both OAuth and logging\n * const enhancedFetch = applyMiddlewares(withOAuth(oauthProvider, 'https://api.example.com'), withLogging({ statusLevel: 400 }))(fetch);\n *\n * // Use the enhanced fetch - it will handle auth and log errors\n * const response = await enhancedFetch('https://api.example.com/data');\n * ```\n *\n * @param middleware - Array of fetch middleware to compose into a pipeline\n * @returns A single composed middleware function\n */\nexport const applyMiddlewares = (...middleware: Middleware[]): Middleware => {\n    return next => {\n        let handler = next;\n        for (const mw of middleware) {\n            handler = mw(handler);\n        }\n        return handler;\n    };\n};\n\n/**\n * Helper function to create custom fetch middleware with cleaner syntax.\n * Provides the next handler and request details as separate parameters for easier access.\n *\n * @example\n * ```ts source=\"./middleware.examples.ts#createMiddleware_examples\"\n * // Create custom authentication middleware\n * const customAuthMiddleware = createMiddleware(async (next, input, init) => {\n *     const headers = new Headers(init?.headers);\n *     headers.set('X-Custom-Auth', 'my-token');\n *\n *     const response = await next(input, { ...init, headers });\n *\n *     if (response.status === 401) {\n *         console.log('Authentication failed');\n *     }\n *\n *     return response;\n * });\n *\n * // Create conditional middleware\n * const conditionalMiddleware = createMiddleware(async (next, input, init) => {\n *     const url = typeof input === 'string' ? input : input.toString();\n *\n *     // Only add headers for API routes\n *     if (url.includes('/api/')) {\n *         const headers = new Headers(init?.headers);\n *         headers.set('X-API-Version', 'v2');\n *         return next(input, { ...init, headers });\n *     }\n *\n *     // Pass through for non-API routes\n *     return next(input, init);\n * });\n *\n * // Create caching middleware\n * const cacheMiddleware = createMiddleware(async (next, input, init) => {\n *     const cacheKey = typeof input === 'string' ? input : input.toString();\n *\n *     // Check cache first\n *     const cached = await getFromCache(cacheKey);\n *     if (cached) {\n *         return new Response(cached, { status: 200 });\n *     }\n *\n *     // Make request and cache result\n *     const response = await next(input, init);\n *     if (response.ok) {\n *         await saveToCache(cacheKey, await response.clone().text());\n *     }\n *\n *     return response;\n * });\n * ```\n *\n * @param handler - Function that receives the next handler and request parameters\n * @returns A fetch middleware function\n */\nexport const createMiddleware = (handler: (next: FetchLike, input: string | URL, init?: RequestInit) => Promise<Response>): Middleware => {\n    return next => (input, init) => handler(next, input as string | URL, init);\n};\n","import type { FetchLike, JSONRPCMessage, Transport } from '@modelcontextprotocol/core-internal';\nimport {\n    brandedHasInstance,\n    createFetchWithInit,\n    fetchLeavingRedirects,\n    fetchWithinOrigin,\n    JSONRPCMessageSchema,\n    SdkError,\n    SdkErrorCode,\n    SdkHttpError,\n    stampErrorBrands,\n    unfollowedRedirect\n} from '@modelcontextprotocol/core-internal';\nimport type { ErrorEvent, EventSourceInit } from 'eventsource';\nimport { EventSource } from 'eventsource';\n\nimport type { AuthProvider, OAuthClientProvider } from './auth';\nimport {\n    adaptOAuthProvider,\n    auth,\n    extractWWWAuthenticateParams,\n    isOAuthClientProvider,\n    resolveAuthorizationCallbackParams,\n    UnauthorizedError\n} from './auth';\n// eslint-disable-next-line @typescript-eslint/no-unused-vars -- referenced in JSDoc {@linkcode}\nimport type { IssuerMismatchError } from './authErrors';\nimport { markAuthSeamEscape } from './authSeam';\nimport type { Middleware } from './middleware';\nimport { withDpopFromProvider } from './middleware';\n\nexport class SseError extends Error {\n    static {\n        Object.defineProperty(this, 'mcpBrand', { value: 'mcp.SseError' });\n    }\n\n    static override [Symbol.hasInstance](value: unknown): boolean {\n        return brandedHasInstance(this, value);\n    }\n\n    /**\n     * Brand-based type guard: equivalent to `value instanceof this`, as an\n     * explicit static predicate (the axios/AWS-SDK `isInstance` style). Reads\n     * the caller's own brand via `this`, so every branded subclass gets a\n     * correctly-scoped guard by inheritance. Must be invoked on the class —\n     * in callback position write `v => SdkError.isInstance(v)`, not\n     * `.filter(SdkError.isInstance)` (detached calls throw rather than\n     * silently matching nothing).\n     */\n    static isInstance<T extends abstract new (...args: never[]) => unknown>(this: T, value: unknown): value is InstanceType<T> {\n        if (typeof this !== 'function') {\n            throw new TypeError(\n                'isInstance must be called on the class (e.g. `SdkError.isInstance(value)`); for callbacks use `v => SdkError.isInstance(v)`'\n            );\n        }\n        return brandedHasInstance(this, value);\n    }\n\n    constructor(\n        public readonly code: number | undefined,\n        message: string | undefined,\n        public readonly event: ErrorEvent\n    ) {\n        super(`SSE error: ${message}`);\n        stampErrorBrands(this, new.target);\n    }\n}\n\n/**\n * Configuration options for the {@linkcode SSEClientTransport}.\n */\nexport type SSEClientTransportOptions = {\n    /**\n     * An OAuth client provider to use for authentication.\n     *\n     * {@linkcode AuthProvider.token | token()} is called before every request to obtain the\n     * bearer token. When the server responds with 401, {@linkcode AuthProvider.onUnauthorized | onUnauthorized()}\n     * is called (if provided) to refresh credentials, then the request is retried once. If\n     * the retry also gets 401, `SdkHttpError` (`SdkErrorCode.ClientHttpAuthentication`) is thrown.\n     * If `onUnauthorized` is not provided, {@linkcode UnauthorizedError} is thrown.\n     *\n     * For simple bearer tokens: `{ token: async () => myApiKey }`.\n     *\n     * For OAuth flows, pass an {@linkcode index.OAuthClientProvider | OAuthClientProvider} implementation.\n     * Interactive flows: after {@linkcode UnauthorizedError}, redirect the user, then call\n     * {@linkcode SSEClientTransport.finishAuth | finishAuth} with the authorization code before reconnecting.\n     */\n    authProvider?: AuthProvider | OAuthClientProvider;\n\n    /**\n     * Opt-out for the RFC 8414 §3.3 issuer-echo check during authorization-server\n     * metadata discovery. **Security-weakening** — see\n     * {@linkcode index.AuthOptions.skipIssuerMetadataValidation | AuthOptions.skipIssuerMetadataValidation}.\n     * Only honoured when {@linkcode SSEClientTransportOptions.authProvider | authProvider}\n     * is an `OAuthClientProvider`.\n     */\n    skipIssuerMetadataValidation?: boolean;\n\n    /**\n     * Customizes the initial SSE request to the server (the request that begins the stream).\n     *\n     * A custom `fetch` supplied here is still wrapped by the transport: the\n     * transport-managed headers, including the `Authorization` header derived from\n     * {@linkcode SSEClientTransportOptions.authProvider | authProvider}, are attached to the\n     * SSE request and take precedence over a same-named entry in `requestInit.headers`\n     * (see {@linkcode SSEClientTransportOptions.requestInit | requestInit}).\n     */\n    eventSourceInit?: EventSourceInit;\n\n    /**\n     * Customizes recurring `POST` requests to the server.\n     *\n     * The transport-managed headers take precedence over a same-named entry in\n     * `headers`: `Authorization` when\n     * {@linkcode SSEClientTransportOptions.authProvider | authProvider} yields a token, and\n     * `mcp-protocol-version`. A caller-supplied `Authorization` value is therefore only sent\n     * while the provider has no token, which lets a static API key fall back to OAuth once\n     * the provider obtains one.\n     *\n     * A `redirect` of `'error'` or `'manual'` is passed to fetch as it is for the `POST`\n     * requests that carry messages. For the OAuth requests, and for any other value,\n     * `redirect` is consulted only when\n     * {@linkcode SSEClientTransportOptions.redirectPolicy | redirectPolicy} is `'follow'`. The\n     * request that begins the stream does not read it.\n     */\n    requestInit?: RequestInit;\n\n    /**\n     * Custom fetch implementation used for all network requests.\n     */\n    fetch?: FetchLike;\n\n    /**\n     * How a redirect of one of the transport's requests is handled, including the OAuth\n     * requests it makes for {@linkcode SSEClientTransportOptions.authProvider | authProvider}.\n     * The option does not reach requests that a provider makes with a fetch of its own, such as\n     * those of the `assertion` callback of a `CrossAppAccessProvider`.\n     *\n     * - `'same-origin'` (default): a redirect is followed only when it stays within the origin\n     *   of the request and keeps the method, and any other redirect fails the request.\n     * - `'follow'`: redirects are left to the fetch implementation, as in earlier versions. It\n     *   follows them to any origin unless `requestInit.redirect` says otherwise, which the\n     *   request that begins the stream does not read.\n     *\n     * @default 'same-origin'\n     */\n    redirectPolicy?: 'same-origin' | 'follow';\n};\n\n/**\n * Client transport for SSE: this will connect to a server using Server-Sent Events for receiving\n * messages and make separate `POST` requests for sending messages.\n * @deprecated SSEClientTransport is deprecated. Prefer to use {@linkcode index.StreamableHTTPClientTransport | StreamableHTTPClientTransport} where possible instead. Note that because some servers are still using SSE, clients may need to support both transports during the migration period.\n */\nexport class SSEClientTransport implements Transport {\n    private _eventSource?: EventSource;\n    private _endpoint?: URL;\n    private _abortController?: AbortController;\n    private _url: URL;\n    private _resourceMetadataUrl?: URL;\n    private _scope?: string;\n    private _eventSourceInit?: EventSourceInit;\n    private _requestInit?: RequestInit;\n    private _authProvider?: AuthProvider;\n    private _oauthProvider?: OAuthClientProvider;\n    private _skipIssuerMetadataValidation?: boolean;\n    private _fetch?: FetchLike;\n    private _fetchWithInit: FetchLike;\n    private _redirectPolicy?: 'same-origin' | 'follow';\n    private _dpop?: Middleware;\n    private _protocolVersion?: string;\n\n    onclose?: () => void;\n    onerror?: (error: Error) => void;\n    onmessage?: (message: JSONRPCMessage) => void;\n\n    constructor(url: URL, opts?: SSEClientTransportOptions) {\n        this._url = url;\n        this._resourceMetadataUrl = undefined;\n        this._scope = undefined;\n        this._eventSourceInit = opts?.eventSourceInit;\n        this._requestInit = opts?.requestInit;\n        this._skipIssuerMetadataValidation = opts?.skipIssuerMetadataValidation;\n        this._fetch = opts?.fetch;\n        if (isOAuthClientProvider(opts?.authProvider)) {\n            this._oauthProvider = opts.authProvider;\n            this._authProvider = adaptOAuthProvider(opts.authProvider, {\n                skipIssuerMetadataValidation: opts.skipIssuerMetadataValidation\n            });\n            // SEP-1932 / RFC 9449: see the matching comment in StreamableHTTPClientTransport. The\n            // EventSource stream's fetch is wrapped at use, since `eventSourceInit.fetch` may\n            // override `_fetch` there.\n            if (opts.authProvider.dpop) {\n                this._dpop = withDpopFromProvider(opts.authProvider);\n                this._fetch = this._dpop(opts.fetch ?? fetch);\n            }\n        } else {\n            this._authProvider = opts?.authProvider;\n        }\n        this._redirectPolicy = opts?.redirectPolicy;\n        this._fetchWithInit = createFetchWithInit(opts?.fetch, opts?.requestInit);\n        if (this._redirectPolicy === 'follow') this._fetchWithInit = fetchLeavingRedirects(this._fetchWithInit);\n    }\n\n    private _last401Response?: Response;\n    // True from a 401-triggered refresh until the retry opens or fails.\n    private _connectAuthRetried = false;\n\n    /** `baseFetch` with redirects handled as `redirectPolicy` says. */\n    private _redirects(baseFetch: FetchLike): FetchLike {\n        return this._redirectPolicy === 'follow' ? baseFetch : fetchWithinOrigin(baseFetch);\n    }\n\n    /** Error text for a redirect `response` that was not followed, or `undefined` for any other response. */\n    private _unfollowedRedirect(url: string | URL, response: Response): string | undefined {\n        const text = this._redirectPolicy === 'follow' ? undefined : unfollowedRedirect(url, response);\n        return text && `${text} (redirectPolicy: 'same-origin')`;\n    }\n\n    private async _commonHeaders(): Promise<Headers> {\n        // Start from the caller-supplied `requestInit.headers` and `set()` the\n        // transport-managed headers on top. `Headers.set` compares names\n        // case-insensitively, so Authorization / mcp-protocol-version replace a\n        // same-named caller entry whatever its spelling. (A plain-object spread would\n        // keep `authorization` and `Authorization` side by side, and the Fetch `Headers`\n        // constructor would then combine them into one two-token value.) This lets\n        // a stale static `Authorization` placeholder (e.g. an env-var API key) fall back\n        // to the OAuth token once the provider has one, and keeps this transport in step\n        // with StreamableHTTPClientTransport. See #2208.\n        // `|| undefined` keeps the old tolerance for a falsy `headers` value (e.g. `null`\n        // from a JS caller or a JSON config forwarded verbatim): the Fetch `Headers`\n        // constructor accepts `undefined` but throws on `null`.\n        const headers = new Headers(this._requestInit?.headers || undefined);\n        let token: string | undefined;\n        try {\n            token = await this._authProvider?.token();\n        } catch (error) {\n            // Auth-seam stamp: a throwing token() is an auth failure, never a\n            // network failure.\n            throw markAuthSeamEscape(error);\n        }\n        if (token) {\n            headers.set('Authorization', `Bearer ${token}`);\n        }\n        if (this._protocolVersion) {\n            headers.set('mcp-protocol-version', this._protocolVersion);\n        }\n        return headers;\n    }\n\n    private _startOrAuth(): Promise<void> {\n        const eventSourceFetch = this._eventSourceInit?.fetch;\n        const fetchImpl = this._redirects(\n            (eventSourceFetch ? (this._dpop?.(eventSourceFetch as FetchLike) ?? eventSourceFetch) : (this._fetch ?? fetch)) as FetchLike\n        );\n        let redirect: string | undefined;\n        return new Promise((resolve, reject) => {\n            this._eventSource = new EventSource(this._url.href, {\n                ...this._eventSourceInit,\n                fetch: async (url, init) => {\n                    const headers = await this._commonHeaders();\n                    headers.set('Accept', 'text/event-stream');\n                    const response = await fetchImpl(url, {\n                        ...init,\n                        headers\n                    });\n                    redirect = this._unfollowedRedirect(url, response);\n\n                    if (response.status === 401) {\n                        this._last401Response = response;\n                        if (response.headers.has('www-authenticate')) {\n                            const { resourceMetadataUrl, scope } = extractWWWAuthenticateParams(response);\n                            this._resourceMetadataUrl = resourceMetadataUrl;\n                            this._scope = scope;\n                        }\n                    }\n\n                    return response;\n                }\n            });\n            this._abortController = new AbortController();\n\n            this._eventSource.onerror = event => {\n                if (event.code === 401 && this._authProvider) {\n                    if (this._authProvider.onUnauthorized && this._last401Response && !this._connectAuthRetried) {\n                        const response = this._last401Response;\n                        this._last401Response = undefined;\n                        this._connectAuthRetried = true;\n                        this._eventSource?.close();\n                        this._authProvider.onUnauthorized({ response, serverUrl: this._url, fetchFn: this._fetchWithInit }).then(\n                            // onUnauthorized succeeded → retry fresh. Its onerror handles its own onerror?.() + reject.\n                            () => this._startOrAuth().then(resolve, reject),\n                            // onUnauthorized failed → not yet reported. Auth-seam\n                            // stamp: covers the SDK's OAuth flow and custom\n                            // callbacks alike.\n                            (error: unknown) => {\n                                this._connectAuthRetried = false;\n                                markAuthSeamEscape(error);\n                                this.onerror?.(error as Error);\n                                reject(error);\n                            }\n                        );\n                        return;\n                    }\n                    const retried = this._connectAuthRetried;\n                    this._connectAuthRetried = false;\n                    const error = markAuthSeamEscape(\n                        retried\n                            ? new SdkHttpError(SdkErrorCode.ClientHttpAuthentication, 'Server returned 401 after re-authentication', {\n                                  status: 401,\n                                  statusText: this._last401Response?.statusText ?? ''\n                              })\n                            : new UnauthorizedError()\n                    );\n                    this._last401Response = undefined;\n                    reject(error);\n                    this.onerror?.(error);\n                    return;\n                }\n\n                // A retry that failed for another reason is over: a later 401 may refresh again.\n                this._connectAuthRetried = false;\n                const error = new SseError(event.code, redirect ?? event.message, event);\n                reject(error);\n                this.onerror?.(error);\n            };\n\n            this._eventSource.onopen = () => {\n                // The connection is open, but we need to wait for the endpoint to be received.\n                this._connectAuthRetried = false;\n            };\n\n            this._eventSource.addEventListener('endpoint', (event: Event) => {\n                const messageEvent = event as MessageEvent;\n\n                try {\n                    this._endpoint = new URL(messageEvent.data, this._url);\n                    if (this._endpoint.origin !== this._url.origin) {\n                        throw new Error(`Endpoint origin does not match connection origin: ${this._endpoint.origin}`);\n                    }\n                } catch (error) {\n                    reject(error);\n                    this.onerror?.(error as Error);\n\n                    void this.close();\n                    return;\n                }\n\n                resolve();\n            });\n\n            this._eventSource.onmessage = (event: Event) => {\n                const messageEvent = event as MessageEvent;\n                let message: JSONRPCMessage;\n                try {\n                    message = JSONRPCMessageSchema.parse(JSON.parse(messageEvent.data));\n                } catch (error) {\n                    this.onerror?.(error as Error);\n                    return;\n                }\n\n                this.onmessage?.(message);\n            };\n        });\n    }\n\n    async start() {\n        if (this._eventSource) {\n            throw new Error('SSEClientTransport already started! If using Client class, note that connect() calls start() automatically.');\n        }\n\n        return await this._startOrAuth();\n    }\n\n    /**\n     * Call this method after the user has finished authorizing via their user agent and is redirected back to the MCP client application. This will exchange the authorization code for an access token, enabling the next connection attempt to successfully auth.\n     *\n     * **Preferred:** pass the callback URL's `searchParams` directly. The SDK extracts `code`\n     * and `iss`, validates `iss` against the recorded issuer (RFC 9207) **before** reading any\n     * other parameter, and on mismatch throws an {@linkcode IssuerMismatchError} that carries\n     * none of the callback's `error`/`error_description`/`error_uri` text. The `(code, iss?)`\n     * positional form remains supported for back-compat.\n     *\n     * The SDK does **not** validate `state`; compare it to your stored value before calling\n     * `finishAuth`.\n     *\n     * @param callbackParams - The `URLSearchParams` from the authorization callback URL\n     *   (e.g. `new URL(callbackUrl).searchParams`). `code` and `iss` are read from it.\n     */\n    async finishAuth(callbackParams: URLSearchParams): Promise<void>;\n    /**\n     * @param authorizationCode - The `code` query parameter from the authorization callback URL.\n     * @param iss - The form-urldecoded `iss` query parameter from the same callback URL, if\n     *   present. Validated per RFC 9207 against the recorded issuer before the code is redeemed.\n     */\n    async finishAuth(authorizationCode: string, iss?: string): Promise<void>;\n    async finishAuth(codeOrParams: string | URLSearchParams, iss?: string): Promise<void> {\n        if (!this._oauthProvider) {\n            throw new UnauthorizedError('finishAuth requires an OAuthClientProvider');\n        }\n\n        const { authorizationCode, iss: issParam } = await resolveAuthorizationCallbackParams(\n            codeOrParams,\n            iss,\n            this._oauthProvider,\n            this._url,\n            { fetchFn: this._fetchWithInit, resourceMetadataUrl: this._resourceMetadataUrl }\n        );\n\n        const result = await auth(this._oauthProvider, {\n            serverUrl: this._url,\n            authorizationCode,\n            iss: issParam,\n            resourceMetadataUrl: this._resourceMetadataUrl,\n            scope: this._scope,\n            fetchFn: this._fetchWithInit,\n            skipIssuerMetadataValidation: this._skipIssuerMetadataValidation\n        });\n        if (result !== 'AUTHORIZED') {\n            throw new UnauthorizedError('Failed to authorize');\n        }\n    }\n\n    async close(): Promise<void> {\n        this._abortController?.abort();\n        this._eventSource?.close();\n        this.onclose?.();\n    }\n\n    async send(message: JSONRPCMessage): Promise<void> {\n        return this._send(message, false);\n    }\n\n    private async _send(message: JSONRPCMessage, isAuthRetry: boolean): Promise<void> {\n        if (!this._endpoint) {\n            throw new SdkError(SdkErrorCode.NotConnected, 'Not connected');\n        }\n\n        try {\n            const headers = await this._commonHeaders();\n            headers.set('content-type', 'application/json');\n            const init = {\n                ...this._requestInit,\n                method: 'POST',\n                headers,\n                body: JSON.stringify(message),\n                signal: this._abortController?.signal\n            };\n\n            const response = await this._redirects(this._fetch ?? fetch)(this._endpoint, init);\n            if (!response.ok) {\n                if (response.status === 401 && this._authProvider) {\n                    if (response.headers.has('www-authenticate')) {\n                        const { resourceMetadataUrl, scope } = extractWWWAuthenticateParams(response);\n                        this._resourceMetadataUrl = resourceMetadataUrl;\n                        this._scope = scope;\n                    }\n\n                    if (this._authProvider.onUnauthorized && !isAuthRetry) {\n                        try {\n                            await this._authProvider.onUnauthorized({\n                                response,\n                                serverUrl: this._url,\n                                fetchFn: this._fetchWithInit\n                            });\n                        } catch (error) {\n                            // Auth-seam stamp: covers the SDK's OAuth flow and\n                            // custom onUnauthorized callbacks alike.\n                            throw markAuthSeamEscape(error);\n                        }\n                        await response.text?.().catch(() => {});\n                        // Purposely _not_ awaited, so we don't call onerror twice\n                        return this._send(message, true);\n                    }\n                    await response.text?.().catch(() => {});\n                    if (isAuthRetry) {\n                        throw markAuthSeamEscape(\n                            new SdkHttpError(SdkErrorCode.ClientHttpAuthentication, 'Server returned 401 after re-authentication', {\n                                status: 401,\n                                statusText: response.statusText\n                            })\n                        );\n                    }\n                    throw markAuthSeamEscape(new UnauthorizedError());\n                }\n\n                const text = await response.text?.().catch(() => null);\n                throw new Error(\n                    `Error POSTing to endpoint (HTTP ${response.status}): ${this._unfollowedRedirect(this._endpoint, response) ?? text}`\n                );\n            }\n\n            // Release connection - POST responses don't have content we need\n            await response.text?.().catch(() => {});\n        } catch (error) {\n            this.onerror?.(error as Error);\n            throw error;\n        }\n    }\n\n    setProtocolVersion(version: string): void {\n        this._protocolVersion = version;\n    }\n}\n","import type { ReadableWritablePair } from 'node:stream/web';\n\nimport type { FetchLike, JSONRPCMessage, Transport } from '@modelcontextprotocol/core-internal';\nimport {\n    createFetchWithInit,\n    encodeMcpParamValue,\n    fetchLeavingRedirects,\n    fetchWithinOrigin,\n    isInitializedNotification,\n    isInitializeRequest,\n    isJSONRPCErrorResponse,\n    isJSONRPCRequest,\n    isJSONRPCResultResponse,\n    isModernProtocolVersion,\n    JSONRPCMessageSchema,\n    mcpNameSource,\n    mediaTypeEssence,\n    PROTOCOL_VERSION_META_KEY,\n    SdkError,\n    SdkErrorCode,\n    SdkHttpError,\n    unfollowedRedirect\n} from '@modelcontextprotocol/core-internal';\nimport { EventSourceParserStream } from 'eventsource-parser/stream';\n\nimport type { AuthProvider, OAuthClientProvider } from './auth';\nimport {\n    adaptOAuthProvider,\n    auth,\n    computeScopeUnion,\n    extractWWWAuthenticateParams,\n    isOAuthClientProvider,\n    isStrictScopeSuperset,\n    resolveAuthorizationCallbackParams,\n    UnauthorizedError\n} from './auth';\n// eslint-disable-next-line @typescript-eslint/no-unused-vars -- referenced via {@linkcode} in finishAuth JSDoc\nimport type { IssuerMismatchError } from './authErrors';\nimport { InsufficientScopeError } from './authErrors';\nimport { markAuthSeamEscape } from './authSeam';\nimport { withDpopFromProvider } from './middleware';\n\n/** Default cap on step-up re-authorization retries within a single send/stream-open. */\nconst DEFAULT_MAX_STEP_UP_RETRIES = 1;\n\n/** The parsed 403 `insufficient_scope` challenge handed to the step-up flow. */\ntype StepUpChallenge = { scope?: string; resourceMetadataUrl?: URL; errorDescription?: string; statusText?: string; text?: string | null };\n\n// Default reconnection options for StreamableHTTP connections\nconst DEFAULT_STREAMABLE_HTTP_RECONNECTION_OPTIONS: StreamableHTTPReconnectionOptions = {\n    initialReconnectionDelay: 1000,\n    maxReconnectionDelay: 30_000,\n    reconnectionDelayGrowFactor: 1.5,\n    maxRetries: 2\n};\n\n/**\n * Options for starting or authenticating an SSE connection\n */\nexport interface StartSSEOptions {\n    /**\n     * The resumption token used to continue long-running requests that were interrupted.\n     *\n     * This allows clients to reconnect and continue from where they left off.\n     */\n    resumptionToken?: string;\n\n    /**\n     * A callback that is invoked when the resumption token changes.\n     *\n     * This allows clients to persist the latest token for potential reconnection.\n     */\n    onresumptiontoken?: (token: string) => void;\n\n    /**\n     * Override Message ID to associate with the replay message\n     * so that the response can be associated with the new resumed request.\n     */\n    replayMessageId?: string | number;\n\n    /**\n     * The per-request abort signal supplied by the caller via\n     * `TransportSendOptions.requestSignal`. When this signal is aborted the\n     * originating POST and its SSE response stream are torn down\n     * intentionally — `_handleSseStream` treats it exactly like the\n     * transport-level abort: no `onerror`, no reconnect.\n     */\n    requestSignal?: AbortSignal;\n\n    /**\n     * The per-request stream-end callback supplied via\n     * `TransportSendOptions.onRequestStreamEnd`. Fired when the SSE response\n     * stream for the originating POST ends or errors for any non-deliberate\n     * reason (server closed, network dropped, reconnection exhausted) — never\n     * when `requestSignal` was aborted.\n     */\n    onRequestStreamEnd?: () => void;\n}\n\n/**\n * Configuration options for reconnection behavior of the {@linkcode StreamableHTTPClientTransport}.\n */\nexport interface StreamableHTTPReconnectionOptions {\n    /**\n     * Maximum backoff time between reconnection attempts in milliseconds.\n     * Default is 30000 (30 seconds).\n     */\n    maxReconnectionDelay: number;\n\n    /**\n     * Initial backoff time between reconnection attempts in milliseconds.\n     * Default is 1000 (1 second).\n     */\n    initialReconnectionDelay: number;\n\n    /**\n     * The factor by which the reconnection delay increases after each attempt.\n     * Default is 1.5.\n     */\n    reconnectionDelayGrowFactor: number;\n\n    /**\n     * Maximum number of reconnection attempts before giving up.\n     * Default is 2.\n     */\n    maxRetries: number;\n}\n\n/**\n * Custom scheduler for SSE stream reconnection attempts.\n *\n * Called instead of `setTimeout` when the transport needs to schedule a reconnection.\n * Useful in environments where `setTimeout` is unsuitable (serverless functions that\n * terminate before the timer fires, mobile apps that need platform background scheduling,\n * desktop apps handling sleep/wake).\n *\n * @param reconnect - Call this to perform the reconnection attempt.\n * @param delay - Suggested delay in milliseconds (from backoff calculation).\n * @param attemptCount - Zero-indexed retry attempt number.\n * @returns An optional cancel function. If returned, it will be called on\n * {@linkcode StreamableHTTPClientTransport.close | transport.close()} to abort the\n * pending reconnection.\n *\n * @example\n * ```ts source=\"./streamableHttp.examples.ts#ReconnectionScheduler_basicUsage\"\n * const scheduler: ReconnectionScheduler = (reconnect, delay) => {\n *     const id = platformBackgroundTask.schedule(reconnect, delay);\n *     return () => platformBackgroundTask.cancel(id);\n * };\n * ```\n */\nexport type ReconnectionScheduler = (reconnect: () => void, delay: number, attemptCount: number) => (() => void) | void;\n\n/**\n * Configuration options for the {@linkcode StreamableHTTPClientTransport}.\n */\nexport type StreamableHTTPClientTransportOptions = {\n    /**\n     * An OAuth client provider to use for authentication.\n     *\n     * {@linkcode AuthProvider.token | token()} is called before every request to obtain the\n     * bearer token. When the server responds with 401, {@linkcode AuthProvider.onUnauthorized | onUnauthorized()}\n     * is called (if provided) to refresh credentials, then the request is retried once. If\n     * the retry also gets 401, `SdkHttpError` (`SdkErrorCode.ClientHttpAuthentication`) is thrown.\n     * If `onUnauthorized` is not provided, {@linkcode UnauthorizedError} is thrown.\n     *\n     * For simple bearer tokens: `{ token: async () => myApiKey }`.\n     *\n     * For OAuth flows, pass an {@linkcode index.OAuthClientProvider | OAuthClientProvider} implementation\n     * directly — the transport adapts it to `AuthProvider` internally. Interactive flows: after\n     * {@linkcode UnauthorizedError}, redirect the user, then call\n     * {@linkcode StreamableHTTPClientTransport.finishAuth | finishAuth} with the authorization code before\n     * reconnecting.\n     */\n    authProvider?: AuthProvider | OAuthClientProvider;\n\n    /**\n     * Opt-out for the RFC 8414 §3.3 issuer-echo check during authorization-server\n     * metadata discovery. **Security-weakening** — see\n     * {@linkcode index.AuthOptions.skipIssuerMetadataValidation | AuthOptions.skipIssuerMetadataValidation}.\n     * Only honoured when {@linkcode StreamableHTTPClientTransportOptions.authProvider | authProvider}\n     * is an `OAuthClientProvider`.\n     */\n    skipIssuerMetadataValidation?: boolean;\n\n    /**\n     * Customizes HTTP requests to the server.\n     *\n     * `headers` are sent on every request, but the transport-managed headers take\n     * precedence over a same-named entry here: `Authorization` when\n     * {@linkcode StreamableHTTPClientTransportOptions.authProvider | authProvider} yields a\n     * token, `mcp-session-id`, and `mcp-protocol-version`. A caller-supplied `Authorization`\n     * value is therefore only sent while the provider has no token, which lets a static API\n     * key fall back to OAuth once the provider obtains one.\n     *\n     * A `redirect` of `'error'` or `'manual'` is passed to fetch as it is for the POST, GET and\n     * DELETE requests to the server URL. For the OAuth requests, and for any other value,\n     * `redirect` is consulted only when\n     * {@linkcode StreamableHTTPClientTransportOptions.redirectPolicy | redirectPolicy} is `'follow'`.\n     */\n    requestInit?: RequestInit;\n\n    /**\n     * Custom fetch implementation used for all network requests.\n     */\n    fetch?: FetchLike;\n\n    /**\n     * How a redirect of one of the transport's requests is handled, including the OAuth\n     * requests it makes for {@linkcode StreamableHTTPClientTransportOptions.authProvider | authProvider}.\n     * The option does not reach requests that a provider makes with a fetch of its own, such as\n     * those of the `assertion` callback of a `CrossAppAccessProvider`.\n     *\n     * - `'same-origin'` (default): a redirect is followed only when it stays within the origin\n     *   of the request and keeps the method, and any other redirect fails the request.\n     * - `'follow'`: redirects are left to the fetch implementation, as in earlier versions. It\n     *   follows them to any origin unless `requestInit.redirect` says otherwise.\n     *\n     * @default 'same-origin'\n     */\n    redirectPolicy?: 'same-origin' | 'follow';\n\n    /**\n     * Options to configure the reconnection behavior.\n     */\n    reconnectionOptions?: StreamableHTTPReconnectionOptions;\n\n    /**\n     * Custom scheduler for reconnection attempts. If not provided, `setTimeout` is used.\n     * See {@linkcode ReconnectionScheduler}.\n     */\n    reconnectionScheduler?: ReconnectionScheduler;\n\n    /**\n     * Session ID for the connection. This is used to identify the session on the server.\n     * When not provided and connecting to a server that supports session IDs, the server will generate a new session ID.\n     */\n    sessionId?: string;\n\n    /**\n     * The MCP protocol version to include in the `mcp-protocol-version` header on all requests.\n     * When reconnecting with a preserved `sessionId`, set this to the version negotiated during the original\n     * handshake so the reconnected transport continues sending the required header.\n     */\n    protocolVersion?: string;\n\n    /**\n     * How the transport reacts to a `403 Forbidden` response carrying\n     * `WWW-Authenticate: Bearer error=\"insufficient_scope\"`.\n     *\n     * - `'reauthorize'` (default): the transport runs the step-up authorization\n     *   flow — computes the union of the previously-requested scope and the\n     *   challenged scope, calls {@linkcode index.auth | auth()} (forcing a\n     *   fresh authorization request when the union strictly exceeds the current\n     *   token's granted scope, since refresh cannot widen scope per RFC 6749\n     *   §6), and retries the request once. Retries are bounded by\n     *   {@linkcode StreamableHTTPClientTransportOptions.maxStepUpRetries | maxStepUpRetries}.\n     *   If no {@linkcode index.OAuthClientProvider | OAuthClientProvider} is\n     *   configured, step-up cannot run and the transport throws\n     *   {@linkcode index.InsufficientScopeError | InsufficientScopeError} instead.\n     * - `'throw'`: the transport throws {@linkcode index.InsufficientScopeError | InsufficientScopeError}\n     *   carrying the challenge parameters and does not re-authorize. Use this\n     *   for `client_credentials` / m2m clients where re-authorization cannot\n     *   widen scope, or for interactive clients that want to gate the consent\n     *   prompt behind UX.\n     *\n     * @default 'reauthorize'\n     */\n    onInsufficientScope?: 'reauthorize' | 'throw';\n\n    /**\n     * Maximum number of step-up re-authorization attempts the transport makes\n     * per send (and per GET stream open) before giving up. Only consulted when\n     * {@linkcode StreamableHTTPClientTransportOptions.onInsufficientScope | onInsufficientScope}\n     * is `'reauthorize'`. Cross-request tracking (\"this resource+operation\n     * already failed N times across the session\") is host responsibility.\n     *\n     * @default 1\n     */\n    maxStepUpRetries?: number;\n};\n\n/**\n * Standard/auth header names the transport owns. The per-request\n * `TransportSendOptions.headers` carrier MUST NOT be able to override these —\n * they are derived from connection state (`authorization`, `mcp-session-id`)\n * or from the message body itself (`mcp-protocol-version`, `mcp-method`,\n * `mcp-name`), and a per-request override would let a caller produce a\n * header/body disagreement the server's SEP-2243 cross-checks reject.\n */\nconst RESERVED_REQUEST_HEADER_NAMES: ReadonlySet<string> = new Set([\n    'authorization',\n    'dpop',\n    'content-type',\n    'mcp-protocol-version',\n    'mcp-method',\n    'mcp-name',\n    'mcp-session-id'\n]);\n\n/**\n * `AbortSignal.any` with a manual fallback. `AbortSignal.any` landed in\n * Node 20.3; this package's `engines` floor is `>=20`, so 20.0–20.2 must be\n * served by the fallback combinator (a controller that aborts on the first\n * of `a` or `b`). The native path is preferred because it propagates the\n * originating signal's `reason` and participates in GC the way the spec\n * defines.\n */\nfunction anySignal(a: AbortSignal, b: AbortSignal): AbortSignal {\n    if (typeof AbortSignal.any === 'function') {\n        return AbortSignal.any([a, b]);\n    }\n    const controller = new AbortController();\n    if (a.aborted) return (controller.abort(a.reason), controller.signal);\n    if (b.aborted) return (controller.abort(b.reason), controller.signal);\n    // Standard polyfill shape: when EITHER input fires, remove the listener\n    // registered on the OTHER input too. `{once:true}` alone leaks the\n    // sibling listener — for `_send()`, `a` is the transport-lifetime signal,\n    // so every request-scoped `b` that aborts would otherwise leave one\n    // listener + closure pinned on `a` for the life of the transport.\n    const cleanup = (): void => {\n        a.removeEventListener('abort', onA);\n        b.removeEventListener('abort', onB);\n    };\n    function onA(): void {\n        cleanup();\n        controller.abort(a.reason);\n    }\n    function onB(): void {\n        cleanup();\n        controller.abort(b.reason);\n    }\n    a.addEventListener('abort', onA, { once: true });\n    b.addEventListener('abort', onB, { once: true });\n    return controller.signal;\n}\n\n/**\n * Client transport for Streamable HTTP: this implements the MCP Streamable HTTP transport specification.\n * It will connect to a server using HTTP `POST` for sending messages and HTTP `GET` with Server-Sent Events\n * for receiving messages.\n */\nexport class StreamableHTTPClientTransport implements Transport {\n    private _abortController?: AbortController;\n    private _url: URL;\n    private _resourceMetadataUrl?: URL;\n    private _scope?: string;\n    private _requestInit?: RequestInit;\n    private _authProvider?: AuthProvider;\n    private _oauthProvider?: OAuthClientProvider;\n    private _skipIssuerMetadataValidation?: boolean;\n    private _fetch?: FetchLike;\n    private _fetchWithInit: FetchLike;\n    private _redirectPolicy?: 'same-origin' | 'follow';\n    private _sessionId?: string;\n    private _reconnectionOptions: StreamableHTTPReconnectionOptions;\n    private _protocolVersion?: string;\n    private _onInsufficientScope: 'reauthorize' | 'throw';\n    private _maxStepUpRetries: number;\n    private _serverRetryMs?: number; // Server-provided retry delay from SSE retry field\n    private readonly _reconnectionScheduler?: ReconnectionScheduler;\n    private _cancelReconnection?: () => void;\n\n    onclose?: () => void;\n    onerror?: (error: Error) => void;\n    onmessage?: (message: JSONRPCMessage) => void;\n\n    /**\n     * Streamable HTTP opens one POST (and SSE response stream) per outbound\n     * request and honors `TransportSendOptions.requestSignal`. On a 2026-era\n     * connection the protocol layer aborts that per-request stream as the\n     * spec cancellation signal instead of POSTing `notifications/cancelled`.\n     */\n    readonly hasPerRequestStream = true;\n\n    constructor(url: URL, opts?: StreamableHTTPClientTransportOptions) {\n        this._url = url;\n        this._resourceMetadataUrl = undefined;\n        this._scope = undefined;\n        this._requestInit = opts?.requestInit;\n        this._skipIssuerMetadataValidation = opts?.skipIssuerMetadataValidation;\n        this._fetch = opts?.fetch;\n        if (isOAuthClientProvider(opts?.authProvider)) {\n            this._oauthProvider = opts.authProvider;\n            this._authProvider = adaptOAuthProvider(opts.authProvider, {\n                skipIssuerMetadataValidation: opts.skipIssuerMetadataValidation\n            });\n            // SEP-1932 / RFC 9449: sign resource-server requests with DPoP at the fetch layer, where\n            // the real method/URL/response of every request (POST, GET stream, DELETE) is in hand.\n            // `_fetchWithInit` below (handed to `auth()`) stays unwrapped — token-endpoint DPoP is\n            // executeTokenRequest's job.\n            if (opts.authProvider.dpop) {\n                this._fetch = withDpopFromProvider(opts.authProvider)(opts.fetch ?? fetch);\n            }\n        } else {\n            this._authProvider = opts?.authProvider;\n        }\n        this._redirectPolicy = opts?.redirectPolicy;\n        this._fetchWithInit = createFetchWithInit(opts?.fetch, opts?.requestInit);\n        if (this._redirectPolicy === 'follow') this._fetchWithInit = fetchLeavingRedirects(this._fetchWithInit);\n        this._sessionId = opts?.sessionId;\n        this._protocolVersion = opts?.protocolVersion;\n        this._reconnectionOptions = opts?.reconnectionOptions ?? DEFAULT_STREAMABLE_HTTP_RECONNECTION_OPTIONS;\n        this._reconnectionScheduler = opts?.reconnectionScheduler;\n        this._onInsufficientScope = opts?.onInsufficientScope ?? 'reauthorize';\n        this._maxStepUpRetries = Math.max(0, opts?.maxStepUpRetries ?? DEFAULT_MAX_STEP_UP_RETRIES);\n    }\n\n    /**\n     * SEP-2350 step-up: compute the union scope, decide whether refresh must be\n     * bypassed, and run {@linkcode auth}. Returns the auth result so the caller\n     * can decide whether to retry. Shared by the POST `_send` path and the GET\n     * `_startOrAuthSse` path so both apply the same `'throw'` short-circuit,\n     * the same superset-gated refresh bypass, and the same retry cap.\n     */\n    private async _stepUpAuthorize(challenge: StepUpChallenge, stepUpRetries: number): Promise<'AUTHORIZED' | 'REDIRECT'> {\n        // Auth-seam stamp, method-level: covers the InsufficientScopeError\n        // throws, the retry-limit SdkHttpError, the tokens() read, and every\n        // auth() escape (typed or not).\n        try {\n            return await this._stepUpAuthorizeInner(challenge, stepUpRetries);\n        } catch (error) {\n            throw markAuthSeamEscape(error);\n        }\n    }\n\n    private async _stepUpAuthorizeInner(challenge: StepUpChallenge, stepUpRetries: number): Promise<'AUTHORIZED' | 'REDIRECT'> {\n        if (this._onInsufficientScope === 'throw') {\n            throw new InsufficientScopeError({\n                requiredScope: challenge.scope,\n                resourceMetadataUrl: challenge.resourceMetadataUrl,\n                errorDescription: challenge.errorDescription\n            });\n        }\n        if (!this._oauthProvider) {\n            // No OAuth provider to drive step-up; surface the typed error so the\n            // host can act on it.\n            throw new InsufficientScopeError({\n                requiredScope: challenge.scope,\n                resourceMetadataUrl: challenge.resourceMetadataUrl,\n                errorDescription: challenge.errorDescription\n            });\n        }\n        if (stepUpRetries >= this._maxStepUpRetries) {\n            throw new SdkHttpError(\n                SdkErrorCode.ClientHttpForbidden,\n                `Server returned 403 insufficient_scope after step-up re-authorization (retry limit ${this._maxStepUpRetries} reached)`,\n                { status: 403, statusText: challenge.statusText ?? 'Forbidden', text: challenge.text }\n            );\n        }\n\n        if (challenge.resourceMetadataUrl) {\n            this._resourceMetadataUrl = challenge.resourceMetadataUrl;\n        }\n\n        // Spec step-up: union of previously-requested scope and challenged scope,\n        // so previously-granted permissions are not lost on re-authorization.\n        const tokens = await this._oauthProvider.tokens();\n        const unionScope = computeScopeUnion(this._scope, tokens?.scope, challenge.scope);\n        this._scope = unionScope;\n\n        // Superset-gated refresh bypass: refresh cannot widen scope (RFC 6749 §6),\n        // so when the union strictly exceeds what the current token was granted\n        // we must force a fresh authorization request.\n        const forceReauthorization = isStrictScopeSuperset(unionScope, tokens?.scope);\n\n        return auth(this._oauthProvider, {\n            serverUrl: this._url,\n            resourceMetadataUrl: this._resourceMetadataUrl,\n            scope: unionScope,\n            forceReauthorization,\n            fetchFn: this._fetchWithInit,\n            skipIssuerMetadataValidation: this._skipIssuerMetadataValidation\n        });\n    }\n\n    /** `baseFetch` with redirects handled as `redirectPolicy` says. */\n    private _redirects(baseFetch: FetchLike): FetchLike {\n        return this._redirectPolicy === 'follow' ? baseFetch : fetchWithinOrigin(baseFetch);\n    }\n\n    /** Error text for a redirect `response` that was not followed, or `undefined` for any other response. */\n    private _unfollowedRedirect(url: string | URL, response: Response): string | undefined {\n        const text = this._redirectPolicy === 'follow' ? undefined : unfollowedRedirect(url, response);\n        return text && `${text} (redirectPolicy: 'same-origin')`;\n    }\n\n    private async _commonHeaders(): Promise<Headers> {\n        // Start from the caller-supplied `requestInit.headers` and `set()` the\n        // transport-managed headers on top. `Headers.set` compares names\n        // case-insensitively, so Authorization / mcp-session-id / mcp-protocol-version\n        // replace a same-named caller entry whatever its spelling. (A plain-object\n        // spread would keep `authorization` and `Authorization` side by side, and the\n        // Fetch `Headers` constructor would then combine them into one two-token\n        // value.) This lets a stale static `Authorization` placeholder (e.g. an env-var\n        // API key) fall back to the OAuth token once the provider has one, and mirrors\n        // the per-request `RESERVED_REQUEST_HEADER_NAMES` guard in send(). See #2208.\n        // `|| undefined` keeps the old tolerance for a falsy `headers` value (e.g. `null`\n        // from a JS caller or a JSON config forwarded verbatim): the Fetch `Headers`\n        // constructor accepts `undefined` but throws on `null`.\n        const headers = new Headers(this._requestInit?.headers || undefined);\n        let token: string | undefined;\n        try {\n            token = await this._authProvider?.token();\n        } catch (error) {\n            // Auth-seam stamp: a throwing token() is an auth failure, never a\n            // network failure.\n            throw markAuthSeamEscape(error);\n        }\n        if (token) {\n            headers.set('Authorization', `Bearer ${token}`);\n        }\n        if (this._sessionId) {\n            headers.set('mcp-session-id', this._sessionId);\n        }\n        if (this._protocolVersion) {\n            headers.set('mcp-protocol-version', this._protocolVersion);\n        }\n        return headers;\n    }\n\n    /**\n     * Body-derived per-request headers: when an outgoing request carries a\n     * protocol-version claim in its `_meta` envelope (the version negotiation\n     * probe is the first such sender), `MCP-Protocol-Version` and `Mcp-Method`\n     * derive from the message itself. The connection-level version slot is\n     * neither consulted nor mutated; messages without an envelope claim are\n     * untouched, so no 2026 header can appear on a legacy exchange.\n     */\n    private _applyBodyDerivedHeaders(headers: Headers, message: JSONRPCMessage | JSONRPCMessage[]): void {\n        if (Array.isArray(message) || !isJSONRPCRequest(message)) {\n            return;\n        }\n        const meta = (message.params as { _meta?: Record<string, unknown> } | undefined)?._meta;\n        const envelopeVersion = meta?.[PROTOCOL_VERSION_META_KEY];\n        if (typeof envelopeVersion !== 'string') {\n            return;\n        }\n        headers.set('mcp-protocol-version', envelopeVersion);\n        headers.set('mcp-method', message.method);\n        // SEP-2243 standard headers, step 2 of the 5-step client algorithm:\n        // Mcp-Name mirrors `params.name` (tools/call, prompts/get),\n        // `params.uri` (resources/read), or — per SEP-2663's Streamable HTTP\n        // binding — `params.taskId` (tasks/get, tasks/update, tasks/cancel).\n        // `mcpNameSource` resolves the method → source-field mapping and the\n        // body value through the same `MCP_NAME_HEADER_SOURCE` table and\n        // extraction the SDK server validates with, so emission and\n        // validation cannot drift apart. The value is run through the same\n        // `=?base64?…?=` sentinel encoding the `Mcp-Param-*` codec uses so a\n        // non-ASCII name/URI/taskId (or one with leading/trailing whitespace,\n        // control characters, or CR/LF) cannot make `Headers.set()` throw a\n        // TypeError or silently normalize to a value that differs from the\n        // body. The spec's value-encoding rules apply to `Mcp-Name`; the SDK\n        // server's `validateStandardRequestHeaders` decodes the sentinel via\n        // `decodeMcpParamValue` before the `Mcp-Name` ↔ body cross-check.\n        const source = mcpNameSource(message.method, message.params);\n        if (source?.value !== undefined) {\n            headers.set('mcp-name', encodeMcpParamValue(source.value));\n        }\n    }\n\n    /**\n     * `true` when the outbound message is a single request carrying a\n     * modern-era protocol-version envelope claim — the same predicate that\n     * gates body-derived `mcp-method`/`mcp-name` emission. Used to confine the\n     * 400-body-as-ProtocolError delivery to modern-era exchanges only.\n     */\n    private _isModernEnvelopedRequest(message: JSONRPCMessage | JSONRPCMessage[]): boolean {\n        if (Array.isArray(message) || !isJSONRPCRequest(message)) return false;\n        const meta = (message.params as { _meta?: Record<string, unknown> } | undefined)?._meta;\n        const v = meta?.[PROTOCOL_VERSION_META_KEY];\n        return typeof v === 'string' && isModernProtocolVersion(v);\n    }\n\n    private async _startOrAuthSse(options: StartSSEOptions, isAuthRetry = false, stepUpRetries = 0): Promise<void> {\n        const { resumptionToken, requestSignal } = options;\n        // Same guard as `_handleSseStream`: a resurrected listen stream (the\n        // POST-SSE → GET reconnect path threads `requestSignal` through\n        // `StartSSEOptions`) must honour the per-request abort exactly as the\n        // original POST did — both as a fetch signal and as a \"do not surface\n        // onerror\" gate.\n        const isIntentionalAbort = (): boolean => this._abortController?.signal.aborted === true || requestSignal?.aborted === true;\n\n        try {\n            // Try to open an initial SSE stream with GET to listen for server messages\n            // This is optional according to the spec - server may not support it\n            const headers = await this._commonHeaders();\n            const userAccept = headers.get('accept');\n            const types = [...(userAccept?.split(',').map(s => s.trim().toLowerCase()) ?? []), 'text/event-stream'];\n            headers.set('accept', [...new Set(types)].join(', '));\n\n            // Include Last-Event-ID header for resumable streams if provided\n            if (resumptionToken) {\n                headers.set('last-event-id', resumptionToken);\n            }\n\n            const transportSignal = this._abortController?.signal;\n            const signal =\n                requestSignal !== undefined && transportSignal !== undefined\n                    ? anySignal(transportSignal, requestSignal)\n                    : (requestSignal ?? transportSignal);\n            const response = await this._redirects(this._fetch ?? fetch)(this._url, {\n                ...this._requestInit,\n                method: 'GET',\n                headers,\n                signal\n            });\n\n            if (!response.ok) {\n                if (response.status === 401 && this._authProvider) {\n                    if (response.headers.has('www-authenticate')) {\n                        const { resourceMetadataUrl, scope } = extractWWWAuthenticateParams(response);\n                        this._resourceMetadataUrl = resourceMetadataUrl;\n                        // Preserve any union accumulated by `_stepUpAuthorize` so a 401\n                        // mid-chain does not narrow `_scope` back to the challenge value.\n                        this._scope = computeScopeUnion(this._scope, scope);\n                    }\n\n                    if (this._authProvider.onUnauthorized && !isAuthRetry) {\n                        try {\n                            await this._authProvider.onUnauthorized({\n                                response,\n                                serverUrl: this._url,\n                                fetchFn: this._fetchWithInit\n                            });\n                        } catch (error) {\n                            // Auth-seam stamp: covers the SDK's OAuth flow and\n                            // custom onUnauthorized callbacks alike.\n                            throw markAuthSeamEscape(error);\n                        }\n                        await response.text?.().catch(() => {});\n                        // Purposely _not_ awaited, so we don't call onerror twice\n                        return this._startOrAuthSse(options, true, stepUpRetries);\n                    }\n                    await response.text?.().catch(() => {});\n                    if (isAuthRetry) {\n                        throw markAuthSeamEscape(\n                            new SdkHttpError(SdkErrorCode.ClientHttpAuthentication, 'Server returned 401 after re-authentication', {\n                                status: 401,\n                                statusText: response.statusText\n                            })\n                        );\n                    }\n                    throw markAuthSeamEscape(new UnauthorizedError());\n                }\n\n                if (response.status === 403) {\n                    const { resourceMetadataUrl, scope, error, errorDescription } = extractWWWAuthenticateParams(response);\n                    if (error === 'insufficient_scope') {\n                        const text = await response.text?.().catch(() => null);\n                        const result = await this._stepUpAuthorize(\n                            { scope, resourceMetadataUrl, errorDescription, statusText: response.statusText, text },\n                            stepUpRetries\n                        );\n                        if (result !== 'AUTHORIZED') {\n                            throw markAuthSeamEscape(new UnauthorizedError());\n                        }\n                        return this._startOrAuthSse(options, isAuthRetry, stepUpRetries + 1);\n                    }\n                }\n\n                await response.text?.().catch(() => {});\n\n                // 405 indicates that the server does not offer an SSE stream at GET endpoint\n                // This is an expected case that should not trigger an error\n                if (response.status === 405) {\n                    // A 405 on the standalone-GET path is benign (the caller\n                    // never had a per-request stream). On the POST→GET resume\n                    // path it is a TERMINAL non-resumable outcome for a\n                    // per-request stream the caller is observing — fire the\n                    // stream-end callback so the caller can settle (otherwise\n                    // a resumed listen subscription dead-ends silently). The\n                    // standalone-GET callers never pass `onRequestStreamEnd`,\n                    // so this is a no-op for them.\n                    options.onRequestStreamEnd?.();\n                    return;\n                }\n\n                const reason = this._unfollowedRedirect(this._url, response) ?? response.statusText;\n                throw new SdkHttpError(SdkErrorCode.ClientHttpFailedToOpenStream, `Failed to open SSE stream: ${reason}`, {\n                    status: response.status,\n                    statusText: response.statusText\n                });\n            }\n\n            this._handleSseStream(response.body, options, true);\n        } catch (error) {\n            if (!isIntentionalAbort()) {\n                this.onerror?.(error as Error);\n            }\n            throw error;\n        }\n    }\n\n    /**\n     * Calculates the next reconnection delay using a backoff algorithm\n     *\n     * @param attempt Current reconnection attempt count for the specific stream\n     * @returns Time to wait in milliseconds before next reconnection attempt\n     */\n    private _getNextReconnectionDelay(attempt: number): number {\n        // Use server-provided retry value if available\n        if (this._serverRetryMs !== undefined) {\n            return this._serverRetryMs;\n        }\n\n        // Fall back to exponential backoff\n        const initialDelay = this._reconnectionOptions.initialReconnectionDelay;\n        const growFactor = this._reconnectionOptions.reconnectionDelayGrowFactor;\n        const maxDelay = this._reconnectionOptions.maxReconnectionDelay;\n\n        // Cap at maximum delay\n        return Math.min(initialDelay * Math.pow(growFactor, attempt), maxDelay);\n    }\n\n    /**\n     * Schedule a reconnection attempt using server-provided retry interval or backoff\n     *\n     * @param lastEventId The ID of the last received event for resumability\n     * @param attemptCount Current reconnection attempt count for this specific stream\n     */\n    private _scheduleReconnection(options: StartSSEOptions, attemptCount = 0): void {\n        // Use provided options or default options\n        const maxRetries = this._reconnectionOptions.maxRetries;\n\n        // Check if we've exceeded maximum retry attempts\n        if (attemptCount >= maxRetries) {\n            this.onerror?.(new Error(`Maximum reconnection attempts (${maxRetries}) exceeded.`));\n            // The per-request stream is now definitively gone.\n            options.onRequestStreamEnd?.();\n            return;\n        }\n\n        // Calculate next delay based on current attempt count\n        const delay = this._getNextReconnectionDelay(attemptCount);\n\n        const reconnect = (): void => {\n            this._cancelReconnection = undefined;\n            // Honour BOTH the transport-wide abort and the per-request abort\n            // (a listen subscription closed during the backoff delay): do not\n            // resurrect a stream the caller already tore down.\n            if (this._abortController?.signal.aborted || options.requestSignal?.aborted) return;\n            this._startOrAuthSse(options).catch(error => {\n                if (this._abortController?.signal.aborted || options.requestSignal?.aborted) return;\n                this.onerror?.(new Error(`Failed to reconnect SSE stream: ${error instanceof Error ? error.message : String(error)}`));\n                try {\n                    this._scheduleReconnection(options, attemptCount + 1);\n                } catch (scheduleError) {\n                    this.onerror?.(scheduleError instanceof Error ? scheduleError : new Error(String(scheduleError)));\n                }\n            });\n        };\n\n        if (this._reconnectionScheduler) {\n            const cancel = this._reconnectionScheduler(reconnect, delay, attemptCount);\n            this._cancelReconnection = typeof cancel === 'function' ? cancel : undefined;\n        } else {\n            const handle = setTimeout(reconnect, delay);\n            this._cancelReconnection = () => clearTimeout(handle);\n        }\n    }\n\n    private _handleSseStream(stream: ReadableStream<Uint8Array> | null, options: StartSSEOptions, isReconnectable: boolean): void {\n        if (!stream) {\n            // A null body on a per-request stream (or its GET resume) is the\n            // same terminal non-resumable outcome as a 405 — fire the\n            // stream-end callback so the caller can settle. No-op for\n            // standalone-GET callers (they never pass `onRequestStreamEnd`).\n            options.onRequestStreamEnd?.();\n            return;\n        }\n        const { onresumptiontoken, replayMessageId, requestSignal, onRequestStreamEnd } = options;\n        // An intentional abort — transport-wide close OR a per-request abort\n        // (McpSubscription.close() aborting its `requestSignal`) — must read as\n        // a clean shutdown: no misleading \"SSE stream disconnected\" onerror,\n        // and no GET+Last-Event-ID reconnect that would resurrect a stream the\n        // caller just tore down.\n        const isIntentionalAbort = (): boolean => this._abortController?.signal.aborted === true || requestSignal?.aborted === true;\n\n        let lastEventId: string | undefined;\n        // Track whether we've received a priming event (event with ID)\n        // Per spec, server SHOULD send a priming event with ID before closing\n        let hasPrimingEvent = false;\n        // Track whether we've received a response - if so, no need to reconnect\n        // Reconnection is for when server disconnects BEFORE sending response\n        let receivedResponse = false;\n        const processStream = async () => {\n            // this is the closest we can get to trying to catch network errors\n            // if something happens reader will throw\n            try {\n                // Create a pipeline: binary stream -> text decoder -> SSE parser\n                const reader = stream\n                    .pipeThrough(new TextDecoderStream() as ReadableWritablePair<string, Uint8Array>)\n                    .pipeThrough(\n                        new EventSourceParserStream({\n                            onRetry: (retryMs: number) => {\n                                // Capture server-provided retry value for reconnection timing\n                                this._serverRetryMs = retryMs;\n                            }\n                        })\n                    )\n                    .getReader();\n\n                while (true) {\n                    const { value: event, done } = await reader.read();\n                    if (done) {\n                        break;\n                    }\n\n                    // Update last event ID if provided\n                    if (event.id) {\n                        lastEventId = event.id;\n                        // Mark that we've received a priming event - stream is now resumable\n                        hasPrimingEvent = true;\n                        onresumptiontoken?.(event.id);\n                    }\n\n                    // Skip events with no data (priming events, keep-alives)\n                    if (!event.data) {\n                        continue;\n                    }\n\n                    if (!event.event || event.event === 'message') {\n                        try {\n                            const message = JSONRPCMessageSchema.parse(JSON.parse(event.data));\n                            // Handle both success AND error responses for completion detection and ID remapping\n                            if (isJSONRPCResultResponse(message) || isJSONRPCErrorResponse(message)) {\n                                // Mark that we received a response - no need to reconnect for this request\n                                receivedResponse = true;\n                                if (replayMessageId !== undefined) {\n                                    message.id = replayMessageId;\n                                }\n                            }\n                            this.onmessage?.(message);\n                        } catch (error) {\n                            this.onerror?.(error as Error);\n                        }\n                    }\n                }\n\n                // Handle graceful server-side disconnect\n                // Server may close connection after sending event ID and retry field\n                // Reconnect if: already reconnectable (GET stream) OR received a priming event (POST stream with event ID)\n                // BUT don't reconnect if we already received a response - the request is complete\n                const canResume = isReconnectable || hasPrimingEvent;\n                const needsReconnect = canResume && !receivedResponse;\n                if (needsReconnect && this._abortController && !isIntentionalAbort()) {\n                    this._scheduleReconnection(\n                        {\n                            resumptionToken: lastEventId,\n                            onresumptiontoken,\n                            replayMessageId,\n                            requestSignal,\n                            onRequestStreamEnd\n                        },\n                        0\n                    );\n                } else if (!isIntentionalAbort()) {\n                    // The per-request stream ended without reconnecting (no\n                    // priming event for a POST stream, or response already\n                    // received). Not a deliberate abort — notify the caller.\n                    onRequestStreamEnd?.();\n                }\n            } catch (error) {\n                if (isIntentionalAbort()) {\n                    // The reader threw because we aborted it. Not an error; do\n                    // not surface onerror, do not reconnect.\n                    return;\n                }\n                // Handle stream errors - likely a network disconnect\n                this.onerror?.(new Error(`SSE stream disconnected: ${error}`));\n\n                // Attempt to reconnect if the stream disconnects unexpectedly and we aren't closing\n                // Reconnect if: already reconnectable (GET stream) OR received a priming event (POST stream with event ID)\n                // BUT don't reconnect if we already received a response - the request is complete\n                const canResume = isReconnectable || hasPrimingEvent;\n                const needsReconnect = canResume && !receivedResponse;\n                if (needsReconnect && this._abortController && !isIntentionalAbort()) {\n                    // Use the exponential backoff reconnection strategy\n                    try {\n                        this._scheduleReconnection(\n                            {\n                                resumptionToken: lastEventId,\n                                onresumptiontoken,\n                                replayMessageId,\n                                requestSignal,\n                                onRequestStreamEnd\n                            },\n                            0\n                        );\n                    } catch (error) {\n                        this.onerror?.(new Error(`Failed to reconnect: ${error instanceof Error ? error.message : String(error)}`));\n                        onRequestStreamEnd?.();\n                    }\n                } else {\n                    // Non-deliberate stream error without reconnection: the\n                    // per-request stream is gone — notify the caller.\n                    onRequestStreamEnd?.();\n                }\n            }\n        };\n        processStream();\n    }\n\n    async start() {\n        if (this._abortController) {\n            throw new Error(\n                'StreamableHTTPClientTransport already started! If using Client class, note that connect() calls start() automatically.'\n            );\n        }\n\n        this._abortController = new AbortController();\n    }\n\n    /**\n     * Call this method after the user has finished authorizing via their user agent and is redirected back to the MCP client application. This will exchange the authorization code for an access token, enabling the next connection attempt to successfully auth.\n     *\n     * **Preferred:** pass the callback URL's `searchParams` directly. The SDK extracts `code`\n     * and `iss`, validates `iss` against the recorded issuer (RFC 9207) **before** reading any\n     * other parameter, and on mismatch throws an {@linkcode IssuerMismatchError} that carries\n     * none of the callback's `error`/`error_description`/`error_uri` text — those are\n     * attacker-controlled in a mix-up attack and MUST NOT be displayed. The `(code, iss?)`\n     * positional form remains supported for back-compat.\n     *\n     * The SDK does **not** validate `state`; compare it to your stored value before calling\n     * `finishAuth`.\n     *\n     * @param callbackParams - The `URLSearchParams` from the authorization callback URL\n     *   (e.g. `new URL(callbackUrl).searchParams`). `code` and `iss` are read from it.\n     */\n    async finishAuth(callbackParams: URLSearchParams): Promise<void>;\n    /**\n     * @param authorizationCode - The `code` query parameter from the authorization callback URL.\n     * @param iss - The form-urldecoded `iss` query parameter from the same callback URL, if\n     *   present. Validated per RFC 9207 against the recorded issuer before the code is redeemed.\n     *   When the authorization server advertises `authorization_response_iss_parameter_supported: true`,\n     *   omitting this causes the exchange to be **rejected** with {@linkcode IssuerMismatchError}.\n     */\n    async finishAuth(authorizationCode: string, iss?: string): Promise<void>;\n    async finishAuth(codeOrParams: string | URLSearchParams, iss?: string): Promise<void> {\n        if (!this._oauthProvider) {\n            throw new UnauthorizedError('finishAuth requires an OAuthClientProvider');\n        }\n\n        const { authorizationCode, iss: issParam } = await resolveAuthorizationCallbackParams(\n            codeOrParams,\n            iss,\n            this._oauthProvider,\n            this._url,\n            { fetchFn: this._fetchWithInit, resourceMetadataUrl: this._resourceMetadataUrl }\n        );\n\n        const result = await auth(this._oauthProvider, {\n            serverUrl: this._url,\n            authorizationCode,\n            iss: issParam,\n            resourceMetadataUrl: this._resourceMetadataUrl,\n            scope: this._scope,\n            fetchFn: this._fetchWithInit,\n            skipIssuerMetadataValidation: this._skipIssuerMetadataValidation\n        });\n        if (result !== 'AUTHORIZED') {\n            throw new UnauthorizedError('Failed to authorize');\n        }\n    }\n\n    async close(): Promise<void> {\n        try {\n            this._cancelReconnection?.();\n        } finally {\n            this._cancelReconnection = undefined;\n            this._abortController?.abort();\n            this.onclose?.();\n        }\n    }\n\n    async send(\n        message: JSONRPCMessage | JSONRPCMessage[],\n        options?: {\n            resumptionToken?: string;\n            onresumptiontoken?: (token: string) => void;\n            requestSignal?: AbortSignal;\n            onRequestStreamEnd?: () => void;\n            headers?: Readonly<Record<string, string>>;\n        }\n    ): Promise<void> {\n        return this._send(message, options, false);\n    }\n\n    private async _send(\n        message: JSONRPCMessage | JSONRPCMessage[],\n        options:\n            | {\n                  resumptionToken?: string;\n                  onresumptiontoken?: (token: string) => void;\n                  requestSignal?: AbortSignal;\n                  onRequestStreamEnd?: () => void;\n                  headers?: Readonly<Record<string, string>>;\n              }\n            | undefined,\n        isAuthRetry: boolean,\n        stepUpRetries = 0\n    ): Promise<void> {\n        try {\n            const { resumptionToken, onresumptiontoken } = options || {};\n\n            if (resumptionToken) {\n                // If we have a last event ID, we need to reconnect the SSE stream.\n                // Thread `requestSignal` through so the resumed GET honours the\n                // same per-request abort as the original POST — modern-era\n                // cancel-via-stream-close routes through `requestSignal`, and\n                // without it a resumed long-running request would not cancel.\n                this._startOrAuthSse({\n                    resumptionToken,\n                    replayMessageId: isJSONRPCRequest(message) ? message.id : undefined,\n                    requestSignal: options?.requestSignal\n                }).catch(error => this.onerror?.(error));\n                return;\n            }\n\n            const headers = await this._commonHeaders();\n            this._applyBodyDerivedHeaders(headers, message);\n            // A new session starts \"without a session ID attached\" (2025-11-25 transports §Session Management).\n            const isHandshake = Array.isArray(message) ? message.some(m => isInitializeRequest(m)) : isInitializeRequest(message);\n            if (isHandshake) {\n                headers.delete('mcp-session-id');\n            }\n            // Per-request additional headers (the Client passes SEP-2243\n            // `Mcp-Param-*` here on a 2026-07-28 connection). Reserved\n            // standard/auth header names are skipped so a caller cannot\n            // accidentally override the body-derived or connection-level\n            // headers — `Headers.set` overwrites, so the only way to keep the\n            // transport-owned values authoritative is to refuse to write over\n            // them here.\n            if (options?.headers !== undefined) {\n                for (const [name, value] of Object.entries(options.headers)) {\n                    if (RESERVED_REQUEST_HEADER_NAMES.has(name.toLowerCase())) continue;\n                    headers.set(name, value);\n                }\n            }\n            headers.set('content-type', 'application/json');\n            const userAccept = headers.get('accept');\n            const types = [...(userAccept?.split(',').map(s => s.trim().toLowerCase()) ?? []), 'application/json', 'text/event-stream'];\n            headers.set('accept', [...new Set(types)].join(', '));\n\n            // Per-request abort: when the caller supplies a request-scoped\n            // signal (the `subscriptions/listen` driver), aborting it cancels\n            // this POST and its SSE response stream without closing the\n            // transport.\n            const transportSignal = this._abortController?.signal;\n            const signal =\n                options?.requestSignal !== undefined && transportSignal !== undefined\n                    ? anySignal(transportSignal, options.requestSignal)\n                    : (options?.requestSignal ?? transportSignal);\n            const init = {\n                ...this._requestInit,\n                method: 'POST',\n                headers,\n                body: JSON.stringify(message),\n                signal\n            };\n\n            const response = await this._redirects(this._fetch ?? fetch)(this._url, init);\n\n            // The spec assigns the session id \"at initialization time … on the HTTP response containing the InitializeResult\"; it is ignored everywhere else.\n            // Clients include only an id \"returned by the server during initialization\", so a sessionless handshake clears any stale id.\n            if (isHandshake && response.ok) {\n                this._sessionId = response.headers.get('mcp-session-id') || undefined;\n            }\n\n            if (!response.ok) {\n                if (response.status === 401 && this._authProvider) {\n                    // Store WWW-Authenticate params for interactive finishAuth() path\n                    if (response.headers.has('www-authenticate')) {\n                        const { resourceMetadataUrl, scope } = extractWWWAuthenticateParams(response);\n                        this._resourceMetadataUrl = resourceMetadataUrl;\n                        // Preserve any union accumulated by `_stepUpAuthorize` so a 401\n                        // mid-chain does not narrow `_scope` back to the challenge value.\n                        this._scope = computeScopeUnion(this._scope, scope);\n                    }\n\n                    if (this._authProvider.onUnauthorized && !isAuthRetry) {\n                        try {\n                            await this._authProvider.onUnauthorized({\n                                response,\n                                serverUrl: this._url,\n                                fetchFn: this._fetchWithInit\n                            });\n                        } catch (error) {\n                            // Auth-seam stamp: covers the SDK's OAuth flow and\n                            // custom onUnauthorized callbacks alike.\n                            throw markAuthSeamEscape(error);\n                        }\n                        await response.text?.().catch(() => {});\n                        // Purposely _not_ awaited, so we don't call onerror twice\n                        return this._send(message, options, true, stepUpRetries);\n                    }\n                    await response.text?.().catch(() => {});\n                    if (isAuthRetry) {\n                        throw markAuthSeamEscape(\n                            new SdkHttpError(SdkErrorCode.ClientHttpAuthentication, 'Server returned 401 after re-authentication', {\n                                status: 401,\n                                statusText: response.statusText\n                            })\n                        );\n                    }\n                    throw markAuthSeamEscape(new UnauthorizedError());\n                }\n\n                const text = await response.text?.().catch(() => null);\n\n                if (response.status === 403) {\n                    const { resourceMetadataUrl, scope, error, errorDescription } = extractWWWAuthenticateParams(response);\n\n                    if (error === 'insufficient_scope') {\n                        const result = await this._stepUpAuthorize(\n                            { scope, resourceMetadataUrl, errorDescription, statusText: response.statusText, text },\n                            stepUpRetries\n                        );\n                        if (result !== 'AUTHORIZED') {\n                            throw markAuthSeamEscape(new UnauthorizedError());\n                        }\n                        return this._send(message, options, isAuthRetry, stepUpRetries + 1);\n                    }\n                }\n\n                // SEP-2243 (and the rest of the inbound validation ladder)\n                // emit ladder rejections as HTTP 400 carrying a JSON-RPC error\n                // response body. Surface those in-band so `Protocol._onresponse`\n                // converts them to a typed `ProtocolError` matched to the\n                // pending request id — instead of an opaque transport error.\n                // Any 400 whose body is not a well-formed JSON-RPC error\n                // response (or whose id does not match an outstanding request)\n                // still falls through to the generic `SdkHttpError`.\n                //\n                // Modern-era only: gated on the outbound message carrying a\n                // 2026-07-28 envelope claim (the same gate the body-derived\n                // `mcp-method`/`mcp-name` headers use), so a legacy-era\n                // exchange keeps surfacing 400 as `SdkHttpError` exactly as\n                // before — the changeset's \"legacy-era paths are unchanged\"\n                // claim stays true and existing\n                // `e instanceof SdkHttpError && e.status === 400` callers do\n                // not silently stop matching.\n                if (response.status === 400 && typeof text === 'string' && this._isModernEnvelopedRequest(message)) {\n                    try {\n                        const parsed = JSONRPCMessageSchema.parse(JSON.parse(text));\n                        const requests = (Array.isArray(message) ? message : [message]).filter(m => isJSONRPCRequest(m));\n                        if (isJSONRPCErrorResponse(parsed) && requests.some(r => r.id === parsed.id)) {\n                            this.onmessage?.(parsed);\n                            return;\n                        }\n                    } catch {\n                        // not a JSON-RPC error body — fall through to the generic SdkHttpError below.\n                    }\n                }\n\n                const reason = this._unfollowedRedirect(this._url, response) ?? text;\n                throw new SdkHttpError(SdkErrorCode.ClientHttpNotImplemented, `Error POSTing to endpoint: ${reason}`, {\n                    status: response.status,\n                    statusText: response.statusText,\n                    text\n                });\n            }\n\n            // If the response is 202 Accepted, there's no body to process\n            if (response.status === 202) {\n                await response.text?.().catch(() => {});\n                // if the accepted notification is initialized, we start the SSE stream\n                // if it's supported by the server\n                if (isInitializedNotification(message)) {\n                    // Start without a lastEventId since this is a fresh connection\n                    this._startOrAuthSse({ resumptionToken: undefined }).catch(error => this.onerror?.(error));\n                }\n                return;\n            }\n\n            // Get original message(s) for detecting request IDs\n            const messages = Array.isArray(message) ? message : [message];\n\n            const hasRequests = messages.some(msg => 'method' in msg && 'id' in msg && msg.id !== undefined);\n\n            // Check the response type (parsed media type — see mediaTypeEssence)\n            const contentType = response.headers.get('content-type');\n            const responseMediaType = mediaTypeEssence(contentType);\n\n            if (hasRequests) {\n                if (responseMediaType === 'text/event-stream') {\n                    // Handle SSE stream responses for requests\n                    // We use the same handler as standalone streams, which now supports\n                    // reconnection with the last event ID\n                    this._handleSseStream(\n                        response.body,\n                        {\n                            onresumptiontoken,\n                            requestSignal: options?.requestSignal,\n                            onRequestStreamEnd: options?.onRequestStreamEnd\n                        },\n                        false\n                    );\n                } else if (responseMediaType === 'application/json') {\n                    // For non-streaming servers, we might get direct JSON responses\n                    const data = await response.json();\n                    const responseMessages = Array.isArray(data)\n                        ? data.map(msg => JSONRPCMessageSchema.parse(msg))\n                        : [JSONRPCMessageSchema.parse(data)];\n\n                    for (const msg of responseMessages) {\n                        this.onmessage?.(msg);\n                    }\n                } else {\n                    await response.text?.().catch(() => {});\n                    throw new SdkError(SdkErrorCode.ClientHttpUnexpectedContent, `Unexpected content type: ${contentType}`, {\n                        contentType\n                    });\n                }\n            } else {\n                // No requests in message but got 200 OK - still need to release connection\n                await response.text?.().catch(() => {});\n            }\n        } catch (error) {\n            // Intentional per-request abort BEFORE response headers (the\n            // `subscriptions/listen` driver aborting its `requestSignal`):\n            // fetch rejects with AbortError. Same guard as\n            // `_handleSseStream`'s `isIntentionalAbort` — do not surface a\n            // misleading onerror; still rethrow so `listen()`'s send-catch\n            // settles the per-subscription state machine.\n            if (options?.requestSignal?.aborted !== true) {\n                this.onerror?.(error as Error);\n            }\n            throw error;\n        }\n    }\n\n    get sessionId(): string | undefined {\n        return this._sessionId;\n    }\n\n    /**\n     * Terminates the current session by sending a `DELETE` request to the server.\n     *\n     * Clients that no longer need a particular session\n     * (e.g., because the user is leaving the client application) SHOULD send an\n     * HTTP `DELETE` to the MCP endpoint with the `Mcp-Session-Id` header to explicitly\n     * terminate the session.\n     *\n     * The server MAY respond with HTTP `405 Method Not Allowed`, indicating that\n     * the server does not allow clients to terminate sessions.\n     */\n    async terminateSession(): Promise<void> {\n        if (!this._sessionId) {\n            return; // No session to terminate\n        }\n\n        try {\n            const headers = await this._commonHeaders();\n\n            const init = {\n                ...this._requestInit,\n                method: 'DELETE',\n                headers,\n                signal: this._abortController?.signal\n            };\n\n            const response = await this._redirects(this._fetch ?? fetch)(this._url, init);\n            await response.text?.().catch(() => {});\n\n            // We specifically handle 405 as a valid response according to the spec,\n            // meaning the server does not support explicit session termination\n            if (!response.ok && response.status !== 405) {\n                throw new SdkHttpError(\n                    SdkErrorCode.ClientHttpFailedToTerminateSession,\n                    `Failed to terminate session: ${this._unfollowedRedirect(this._url, response) ?? response.statusText}`,\n                    {\n                        status: response.status,\n                        statusText: response.statusText\n                    }\n                );\n            }\n\n            this._sessionId = undefined;\n        } catch (error) {\n            this.onerror?.(error as Error);\n            throw error;\n        }\n    }\n\n    setProtocolVersion(version: string): void {\n        this._protocolVersion = version;\n    }\n    get protocolVersion(): string | undefined {\n        return this._protocolVersion;\n    }\n\n    /**\n     * Resume an SSE stream from a previous event ID.\n     * Opens a `GET` SSE connection with `Last-Event-ID` header to replay missed events.\n     *\n     * @param lastEventId The event ID to resume from\n     * @param options Optional callback to receive new resumption tokens\n     */\n    async resumeStream(lastEventId: string, options?: { onresumptiontoken?: (token: string) => void }): Promise<void> {\n        await this._startOrAuthSse({\n            resumptionToken: lastEventId,\n            onresumptiontoken: options?.onresumptiontoken\n        });\n    }\n}\n","import { DefaultJsonSchemaValidator } from '@modelcontextprotocol/client/_shims';\nimport type { JsonSchemaType, jsonSchemaValidator, StandardSchemaWithJSON } from '@modelcontextprotocol/core-internal';\nimport { fromJsonSchema as coreFromJsonSchema } from '@modelcontextprotocol/core-internal';\n\nlet _defaultValidator: jsonSchemaValidator | undefined;\n\nexport function fromJsonSchema<T = unknown>(schema: JsonSchemaType, validator?: jsonSchemaValidator): StandardSchemaWithJSON<T, T> {\n    return coreFromJsonSchema<T>(schema, validator ?? (_defaultValidator ??= new DefaultJsonSchemaValidator()));\n}\n","import { theme } from '../ui/theme.js'\nimport { symbols } from '../ui/symbols.js'\nimport {\n  ProtocolError,\n  MissingRequiredClientCapabilityError,\n  UnsupportedProtocolVersionError,\n} from '@modelcontextprotocol/client'\n\n// The SDK does not export a dedicated class for -32020 (HeaderMismatch) — it\n// surfaces as a plain ProtocolError with this code.\nconst HEADER_MISMATCH_CODE = -32020\n\nexport const EXIT = {\n  OK: 0,\n  USER: 1,\n  CONNECTION: 2,\n  SERVER: 3,\n} as const\n\nexport interface CliErrorOptions {\n  hint?: string\n  code?: number\n}\n\nexport function cliError(message: string, opts: CliErrorOptions = {}): never {\n  process.stderr.write(`${theme.error(symbols.failure)} ${theme.error(message)}\\n`)\n  if (opts.hint) {\n    process.stderr.write(`  ${theme.muted(opts.hint)}\\n`)\n  }\n  process.exit(opts.code ?? EXIT.USER)\n}\n\nexport function formatError(err: unknown): string {\n  if (err instanceof UnsupportedProtocolVersionError) {\n    return `The server does not support protocol version \"${err.requested}\". It supports: ${err.supported.join(', ')}. Change or drop --pin.`\n  }\n  if (err instanceof MissingRequiredClientCapabilityError) {\n    const capabilities = Object.keys(err.requiredCapabilities)\n    if (capabilities.length > 0) {\n      return `The server requires a client capability. This CLI did not declare these capabilities: ${capabilities.join(', ')}.`\n    }\n    return `The server requires a client capability. This CLI did not declare it.`\n  }\n  if (err instanceof ProtocolError && err.code === HEADER_MISMATCH_CODE) {\n    return `The server rejected the request. The protocol version header does not match the request body.`\n  }\n  if (err instanceof Error) {\n    const msg = err.message.toLowerCase()\n    if (msg.includes('econnrefused') || msg.includes('connection refused')) {\n      return `Connection refused — is the server running?`\n    }\n    if (msg.includes('unauthorized') || msg.includes('401')) {\n      return `Authentication failed — check your --auth token`\n    }\n    if (msg.includes('not found') || msg.includes('404')) {\n      return err.message\n    }\n    return err.message\n  }\n  return String(err)\n}\n","/* MAIN */\nconst getCodePointsLength = (() => {\n    const SURROGATE_PAIR_RE = /[\\uD800-\\uDBFF][\\uDC00-\\uDFFF]/g;\n    return (input) => {\n        let surrogatePairsNr = 0;\n        SURROGATE_PAIR_RE.lastIndex = 0;\n        while (SURROGATE_PAIR_RE.test(input)) {\n            surrogatePairsNr += 1;\n        }\n        return input.length - surrogatePairsNr;\n    };\n})();\nconst isFullWidth = (x) => {\n    return x === 0x3000 || x >= 0xFF01 && x <= 0xFF60 || x >= 0xFFE0 && x <= 0xFFE6;\n};\nconst isWideNotCJKTNotEmoji = (x) => {\n    return x === 0x231B || x === 0x2329 || x >= 0x2FF0 && x <= 0x2FFF || x >= 0x3001 && x <= 0x303E || x >= 0x3099 && x <= 0x30FF || x >= 0x3105 && x <= 0x312F || x >= 0x3131 && x <= 0x318E || x >= 0x3190 && x <= 0x31E3 || x >= 0x31EF && x <= 0x321E || x >= 0x3220 && x <= 0x3247 || x >= 0x3250 && x <= 0x4DBF || x >= 0xFE10 && x <= 0xFE19 || x >= 0xFE30 && x <= 0xFE52 || x >= 0xFE54 && x <= 0xFE66 || x >= 0xFE68 && x <= 0xFE6B || x >= 0x1F200 && x <= 0x1F202 || x >= 0x1F210 && x <= 0x1F23B || x >= 0x1F240 && x <= 0x1F248 || x >= 0x20000 && x <= 0x2FFFD || x >= 0x30000 && x <= 0x3FFFD;\n};\n/* EXPORT */\nexport { getCodePointsLength, isFullWidth, isWideNotCJKTNotEmoji };\n","/* IMPORT */\nimport { getCodePointsLength, isFullWidth, isWideNotCJKTNotEmoji } from './utils.js';\n/* HELPERS */\nconst ANSI_RE = /[\\u001b\\u009b][[()#;?]*(?:[0-9]{1,4}(?:;[0-9]{0,4})*)?[0-9A-ORZcf-nqry=><]|\\u001b\\]8;[^;]*;.*?(?:\\u0007|\\u001b\\u005c)/y;\nconst CONTROL_RE = /[\\x00-\\x08\\x0A-\\x1F\\x7F-\\x9F]{1,1000}/y;\nconst CJKT_WIDE_RE = /(?:(?![\\uFF61-\\uFF9F\\uFF00-\\uFFEF])[\\p{Script=Han}\\p{Script=Hiragana}\\p{Script=Katakana}\\p{Script=Hangul}\\p{Script=Tangut}]){1,1000}/yu;\nconst TAB_RE = /\\t{1,1000}/y;\nconst EMOJI_RE = /[\\u{1F1E6}-\\u{1F1FF}]{2}|\\u{1F3F4}[\\u{E0061}-\\u{E007A}]{2}[\\u{E0030}-\\u{E0039}\\u{E0061}-\\u{E007A}]{1,3}\\u{E007F}|(?:\\p{Emoji}\\uFE0F\\u20E3?|\\p{Emoji_Modifier_Base}\\p{Emoji_Modifier}?|\\p{Emoji_Presentation})(?:\\u200D(?:\\p{Emoji_Modifier_Base}\\p{Emoji_Modifier}?|\\p{Emoji_Presentation}|\\p{Emoji}\\uFE0F\\u20E3?))*/yu;\nconst LATIN_RE = /(?:[\\x20-\\x7E\\xA0-\\xFF](?!\\uFE0F)){1,1000}/y;\nconst MODIFIER_RE = /\\p{M}+/gu;\nconst NO_TRUNCATION = { limit: Infinity, ellipsis: '' };\n/* MAIN */\nconst getStringTruncatedWidth = (input, truncationOptions = {}, widthOptions = {}) => {\n    /* CONSTANTS */\n    const LIMIT = truncationOptions.limit ?? Infinity;\n    const ELLIPSIS = truncationOptions.ellipsis ?? '';\n    const ELLIPSIS_WIDTH = truncationOptions?.ellipsisWidth ?? (ELLIPSIS ? getStringTruncatedWidth(ELLIPSIS, NO_TRUNCATION, widthOptions).width : 0);\n    const ANSI_WIDTH = 0;\n    const CONTROL_WIDTH = widthOptions.controlWidth ?? 0;\n    const TAB_WIDTH = widthOptions.tabWidth ?? 8;\n    const EMOJI_WIDTH = widthOptions.emojiWidth ?? 2;\n    const FULL_WIDTH_WIDTH = 2;\n    const REGULAR_WIDTH = widthOptions.regularWidth ?? 1;\n    const WIDE_WIDTH = widthOptions.wideWidth ?? FULL_WIDTH_WIDTH;\n    const PARSE_BLOCKS = [\n        [LATIN_RE, REGULAR_WIDTH],\n        [ANSI_RE, ANSI_WIDTH],\n        [CONTROL_RE, CONTROL_WIDTH],\n        [TAB_RE, TAB_WIDTH],\n        [EMOJI_RE, EMOJI_WIDTH],\n        [CJKT_WIDE_RE, WIDE_WIDTH],\n    ];\n    /* STATE */\n    let indexPrev = 0;\n    let index = 0;\n    let length = input.length;\n    let lengthExtra = 0;\n    let truncationEnabled = false;\n    let truncationIndex = length;\n    let truncationLimit = Math.max(0, LIMIT - ELLIPSIS_WIDTH);\n    let unmatchedStart = 0;\n    let unmatchedEnd = 0;\n    let width = 0;\n    let widthExtra = 0;\n    /* PARSE LOOP */\n    outer: while (true) {\n        /* UNMATCHED */\n        if ((unmatchedEnd > unmatchedStart) || (index >= length && index > indexPrev)) {\n            const unmatched = input.slice(unmatchedStart, unmatchedEnd) || input.slice(indexPrev, index);\n            lengthExtra = 0;\n            for (const char of unmatched.replaceAll(MODIFIER_RE, '')) {\n                const codePoint = char.codePointAt(0) || 0;\n                if (isFullWidth(codePoint)) {\n                    widthExtra = FULL_WIDTH_WIDTH;\n                }\n                else if (isWideNotCJKTNotEmoji(codePoint)) {\n                    widthExtra = WIDE_WIDTH;\n                }\n                else {\n                    widthExtra = REGULAR_WIDTH;\n                }\n                if ((width + widthExtra) > truncationLimit) {\n                    truncationIndex = Math.min(truncationIndex, Math.max(unmatchedStart, indexPrev) + lengthExtra);\n                }\n                if ((width + widthExtra) > LIMIT) {\n                    truncationEnabled = true;\n                    break outer;\n                }\n                lengthExtra += char.length;\n                width += widthExtra;\n            }\n            unmatchedStart = unmatchedEnd = 0;\n        }\n        /* EXITING */\n        if (index >= length) {\n            break outer;\n        }\n        /* PARSE BLOCKS */\n        for (let i = 0, l = PARSE_BLOCKS.length; i < l; i++) {\n            const [BLOCK_RE, BLOCK_WIDTH] = PARSE_BLOCKS[i];\n            BLOCK_RE.lastIndex = index;\n            if (BLOCK_RE.test(input)) {\n                lengthExtra = BLOCK_RE === CJKT_WIDE_RE ? getCodePointsLength(input.slice(index, BLOCK_RE.lastIndex)) : BLOCK_RE === EMOJI_RE ? 1 : BLOCK_RE.lastIndex - index;\n                widthExtra = lengthExtra * BLOCK_WIDTH;\n                if ((width + widthExtra) > truncationLimit) {\n                    truncationIndex = Math.min(truncationIndex, index + Math.floor((truncationLimit - width) / BLOCK_WIDTH));\n                }\n                if ((width + widthExtra) > LIMIT) {\n                    truncationEnabled = true;\n                    break outer;\n                }\n                width += widthExtra;\n                unmatchedStart = indexPrev;\n                unmatchedEnd = index;\n                index = indexPrev = BLOCK_RE.lastIndex;\n                continue outer;\n            }\n        }\n        /* UNMATCHED INDEX */\n        index += 1;\n    }\n    /* RETURN */\n    return {\n        width: truncationEnabled ? truncationLimit : width,\n        index: truncationEnabled ? truncationIndex : length,\n        truncated: truncationEnabled,\n        ellipsed: truncationEnabled && LIMIT >= ELLIPSIS_WIDTH\n    };\n};\n/* EXPORT */\nexport default getStringTruncatedWidth;\n","/* IMPORT */\nimport fastStringTruncatedWidth from 'fast-string-truncated-width';\n/* HELPERS */\nconst NO_TRUNCATION = {\n    limit: Infinity,\n    ellipsis: '',\n    ellipsisWidth: 0,\n};\n/* MAIN */\nconst fastStringWidth = (input, options = {}) => {\n    return fastStringTruncatedWidth(input, NO_TRUNCATION, options).width;\n};\n/* EXPORT */\nexport default fastStringWidth;\n","import stringWidth from 'fast-string-width';\nconst ESC = '\\x1B';\nconst CSI = '\\x9B';\nconst END_CODE = 39;\nconst ANSI_ESCAPE_BELL = '\\u0007';\nconst ANSI_CSI = '[';\nconst ANSI_OSC = ']';\nconst ANSI_SGR_TERMINATOR = 'm';\nconst ANSI_ESCAPE_LINK = `${ANSI_OSC}8;;`;\nconst GROUP_REGEX = new RegExp(`(?:\\\\${ANSI_CSI}(?<code>\\\\d+)m|\\\\${ANSI_ESCAPE_LINK}(?<uri>.*)${ANSI_ESCAPE_BELL})`, 'y');\nconst getClosingCode = (openingCode) => {\n    if (openingCode >= 30 && openingCode <= 37)\n        return 39;\n    if (openingCode >= 90 && openingCode <= 97)\n        return 39;\n    if (openingCode >= 40 && openingCode <= 47)\n        return 49;\n    if (openingCode >= 100 && openingCode <= 107)\n        return 49;\n    if (openingCode === 1 || openingCode === 2)\n        return 22;\n    if (openingCode === 3)\n        return 23;\n    if (openingCode === 4)\n        return 24;\n    if (openingCode === 7)\n        return 27;\n    if (openingCode === 8)\n        return 28;\n    if (openingCode === 9)\n        return 29;\n    if (openingCode === 0)\n        return 0;\n    return undefined;\n};\nconst wrapAnsiCode = (code) => `${ESC}${ANSI_CSI}${code}${ANSI_SGR_TERMINATOR}`;\nconst wrapAnsiHyperlink = (url) => `${ESC}${ANSI_ESCAPE_LINK}${url}${ANSI_ESCAPE_BELL}`;\nconst wrapWord = (rows, word, columns) => {\n    const characters = word[Symbol.iterator]();\n    let isInsideEscape = false;\n    let isInsideLinkEscape = false;\n    let lastRow = rows.at(-1);\n    let visible = lastRow === undefined ? 0 : stringWidth(lastRow);\n    let currentCharacter = characters.next();\n    let nextCharacter = characters.next();\n    let rawCharacterIndex = 0;\n    while (!currentCharacter.done) {\n        const character = currentCharacter.value;\n        const characterLength = stringWidth(character);\n        if (visible + characterLength <= columns) {\n            rows[rows.length - 1] += character;\n        }\n        else {\n            rows.push(character);\n            visible = 0;\n        }\n        if (character === ESC || character === CSI) {\n            isInsideEscape = true;\n            isInsideLinkEscape = word.startsWith(ANSI_ESCAPE_LINK, rawCharacterIndex + 1);\n        }\n        if (isInsideEscape) {\n            if (isInsideLinkEscape) {\n                if (character === ANSI_ESCAPE_BELL) {\n                    isInsideEscape = false;\n                    isInsideLinkEscape = false;\n                }\n            }\n            else if (character === ANSI_SGR_TERMINATOR) {\n                isInsideEscape = false;\n            }\n        }\n        else {\n            visible += characterLength;\n            if (visible === columns && !nextCharacter.done) {\n                rows.push('');\n                visible = 0;\n            }\n        }\n        currentCharacter = nextCharacter;\n        nextCharacter = characters.next();\n        rawCharacterIndex += character.length;\n    }\n    lastRow = rows.at(-1);\n    if (!visible && lastRow !== undefined && lastRow.length && rows.length > 1) {\n        rows[rows.length - 2] += rows.pop();\n    }\n};\nconst stringVisibleTrimSpacesRight = (string) => {\n    const words = string.split(' ');\n    let last = words.length;\n    while (last) {\n        if (stringWidth(words[last - 1])) {\n            break;\n        }\n        last--;\n    }\n    if (last === words.length) {\n        return string;\n    }\n    return words.slice(0, last).join(' ') + words.slice(last).join('');\n};\nconst exec = (string, columns, options = {}) => {\n    if (options.trim !== false && string.trim() === '') {\n        return '';\n    }\n    let returnValue = '';\n    let escapeCode;\n    let escapeUrl;\n    const words = string.split(' ');\n    let rows = [''];\n    let rowLength = 0;\n    for (let index = 0; index < words.length; index++) {\n        const word = words[index];\n        if (options.trim !== false) {\n            const row = rows.at(-1) ?? '';\n            const trimmed = row.trimStart();\n            if (row.length !== trimmed.length) {\n                rows[rows.length - 1] = trimmed;\n                rowLength = stringWidth(trimmed);\n            }\n        }\n        if (index !== 0) {\n            if (rowLength >= columns &&\n                (options.wordWrap === false || options.trim === false)) {\n                rows.push('');\n                rowLength = 0;\n            }\n            if (rowLength || options.trim === false) {\n                rows[rows.length - 1] += ' ';\n                rowLength++;\n            }\n        }\n        const wordLength = stringWidth(word);\n        if (options.hard && wordLength > columns) {\n            const remainingColumns = columns - rowLength;\n            const breaksStartingThisLine = 1 + Math.floor((wordLength - remainingColumns - 1) / columns);\n            const breaksStartingNextLine = Math.floor((wordLength - 1) / columns);\n            if (breaksStartingNextLine < breaksStartingThisLine) {\n                rows.push('');\n            }\n            wrapWord(rows, word, columns);\n            rowLength = stringWidth(rows.at(-1) ?? '');\n            continue;\n        }\n        if (rowLength + wordLength > columns && rowLength && wordLength) {\n            if (options.wordWrap === false && rowLength < columns) {\n                wrapWord(rows, word, columns);\n                rowLength = stringWidth(rows.at(-1) ?? '');\n                continue;\n            }\n            rows.push('');\n            rowLength = 0;\n        }\n        if (rowLength + wordLength > columns && options.wordWrap === false) {\n            wrapWord(rows, word, columns);\n            rowLength = stringWidth(rows.at(-1) ?? '');\n            continue;\n        }\n        rows[rows.length - 1] += word;\n        rowLength += wordLength;\n    }\n    if (options.trim !== false) {\n        rows = rows.map((row) => stringVisibleTrimSpacesRight(row));\n    }\n    const preString = rows.join('\\n');\n    let inSurrogate = false;\n    for (let i = 0; i < preString.length; i++) {\n        const character = preString[i];\n        returnValue += character;\n        if (!inSurrogate) {\n            inSurrogate = character >= '\\ud800' && character <= '\\udbff';\n            if (inSurrogate) {\n                continue;\n            }\n        }\n        else {\n            inSurrogate = false;\n        }\n        if (character === ESC || character === CSI) {\n            GROUP_REGEX.lastIndex = i + 1;\n            const groupsResult = GROUP_REGEX.exec(preString);\n            const groups = groupsResult?.groups;\n            if (groups?.code !== undefined) {\n                const code = Number.parseFloat(groups.code);\n                escapeCode = code === END_CODE ? undefined : code;\n            }\n            else if (groups?.uri !== undefined) {\n                escapeUrl = groups.uri.length === 0 ? undefined : groups.uri;\n            }\n        }\n        if (preString[i + 1] === '\\n') {\n            if (escapeUrl) {\n                returnValue += wrapAnsiHyperlink('');\n            }\n            const closingCode = escapeCode ? getClosingCode(escapeCode) : undefined;\n            if (escapeCode && closingCode) {\n                returnValue += wrapAnsiCode(closingCode);\n            }\n        }\n        else if (character === '\\n') {\n            if (escapeCode && getClosingCode(escapeCode)) {\n                returnValue += wrapAnsiCode(escapeCode);\n            }\n            if (escapeUrl) {\n                returnValue += wrapAnsiHyperlink(escapeUrl);\n            }\n        }\n    }\n    return returnValue;\n};\nconst CRLF_OR_LF = /\\r?\\n/;\nexport function wrapAnsi(string, columns, options) {\n    return String(string)\n        .normalize()\n        .split(CRLF_OR_LF)\n        .map((line) => exec(line, columns, options))\n        .join('\\n');\n}\n","'use strict';\n\nconst ESC = '\\x1B';\nconst CSI = `${ESC}[`;\nconst beep = '\\u0007';\n\nconst cursor = {\n  to(x, y) {\n    if (!y) return `${CSI}${x + 1}G`;\n    return `${CSI}${y + 1};${x + 1}H`;\n  },\n  move(x, y) {\n    let ret = '';\n\n    if (x < 0) ret += `${CSI}${-x}D`;\n    else if (x > 0) ret += `${CSI}${x}C`;\n\n    if (y < 0) ret += `${CSI}${-y}A`;\n    else if (y > 0) ret += `${CSI}${y}B`;\n\n    return ret;\n  },\n  up: (count = 1) => `${CSI}${count}A`,\n  down: (count = 1) => `${CSI}${count}B`,\n  forward: (count = 1) => `${CSI}${count}C`,\n  backward: (count = 1) => `${CSI}${count}D`,\n  nextLine: (count = 1) => `${CSI}E`.repeat(count),\n  prevLine: (count = 1) => `${CSI}F`.repeat(count),\n  left: `${CSI}G`,\n  hide: `${CSI}?25l`,\n  show: `${CSI}?25h`,\n  save: `${ESC}7`,\n  restore: `${ESC}8`\n}\n\nconst scroll = {\n  up: (count = 1) => `${CSI}S`.repeat(count),\n  down: (count = 1) => `${CSI}T`.repeat(count)\n}\n\nconst erase = {\n  screen: `${CSI}2J`,\n  up: (count = 1) => `${CSI}1J`.repeat(count),\n  down: (count = 1) => `${CSI}J`.repeat(count),\n  line: `${CSI}2K`,\n  lineEnd: `${CSI}K`,\n  lineStart: `${CSI}1K`,\n  lines(count) {\n    let clear = '';\n    for (let i = 0; i < count; i++)\n      clear += this.line + (i < count - 1 ? cursor.up() : '');\n    if (count)\n      clear += cursor.left;\n    return clear;\n  }\n}\n\nmodule.exports = { cursor, scroll, erase, beep };\n","import { styleText } from 'node:util';\nimport { stdout, stdin } from 'node:process';\nimport * as l from 'node:readline';\nimport l__default from 'node:readline';\nimport { wrapAnsi } from 'fast-wrap-ansi';\nimport { cursor, erase } from 'sisteransi';\nimport { ReadStream } from 'node:tty';\n\nfunction findCursor(s, o, l) {\n  if (!l.some((r) => !r.disabled))\n    return s;\n  const t = s + o, n = Math.max(l.length - 1, 0), e = t < 0 ? n : t > n ? 0 : t;\n  return l[e]?.disabled ? findCursor(e, o < 0 ? -1 : 1, l) : e;\n}\nfunction findTextCursor(s, o, l, i) {\n  const t = i.split(`\n`);\n  let n = 0, e = s;\n  for (const r of t) {\n    if (e <= r.length)\n      break;\n    e -= r.length + 1, n++;\n  }\n  for (n = Math.max(0, Math.min(t.length - 1, n + l)), e = Math.min(e, t[n].length) + o; e < 0 && n > 0; )\n    n--, e += t[n].length + 1;\n  for (; e > t[n].length && n < t.length - 1; )\n    e -= t[n].length + 1, n++;\n  e = Math.max(0, Math.min(t[n].length, e));\n  let h = 0;\n  for (let r = 0; r < n; r++)\n    h += t[r].length + 1;\n  return h + e;\n}\n\nconst a$1 = [\"up\", \"down\", \"left\", \"right\", \"space\", \"enter\", \"cancel\"], t = [\n  \"January\",\n  \"February\",\n  \"March\",\n  \"April\",\n  \"May\",\n  \"June\",\n  \"July\",\n  \"August\",\n  \"September\",\n  \"October\",\n  \"November\",\n  \"December\"\n];\nconst settings = {\n  actions: new Set(a$1),\n  aliases: /* @__PURE__ */ new Map([\n    // vim support\n    [\"k\", \"up\"],\n    [\"j\", \"down\"],\n    [\"h\", \"left\"],\n    [\"l\", \"right\"],\n    [\"\u0003\", \"cancel\"],\n    // opinionated defaults!\n    [\"escape\", \"cancel\"]\n  ]),\n  messages: {\n    cancel: \"Canceled\",\n    error: \"Something went wrong\"\n  },\n  withGuide: true,\n  date: {\n    monthNames: [...t],\n    messages: {\n      required: \"Please enter a valid date\",\n      invalidMonth: \"There are only 12 months in a year\",\n      invalidDay: (n, e) => `There are only ${n} days in ${e}`,\n      afterMin: (n) => `Date must be on or after ${n.toISOString().slice(0, 10)}`,\n      beforeMax: (n) => `Date must be on or before ${n.toISOString().slice(0, 10)}`\n    }\n  }\n};\nfunction updateSettings(n) {\n  if (n.aliases !== void 0) {\n    const e = n.aliases;\n    for (const s in e) {\n      if (!Object.hasOwn(e, s)) continue;\n      const i = e[s];\n      i === void 0 || !settings.actions.has(i) || settings.aliases.has(s) || settings.aliases.set(s, i);\n    }\n  }\n  if (n.messages !== void 0) {\n    const e = n.messages;\n    e.cancel !== void 0 && (settings.messages.cancel = e.cancel), e.error !== void 0 && (settings.messages.error = e.error);\n  }\n  if (n.withGuide !== void 0 && (settings.withGuide = n.withGuide !== false), n.date !== void 0) {\n    const e = n.date;\n    e.monthNames !== void 0 && (settings.date.monthNames = [...e.monthNames]), e.messages !== void 0 && (e.messages.required !== void 0 && (settings.date.messages.required = e.messages.required), e.messages.invalidMonth !== void 0 && (settings.date.messages.invalidMonth = e.messages.invalidMonth), e.messages.invalidDay !== void 0 && (settings.date.messages.invalidDay = e.messages.invalidDay), e.messages.afterMin !== void 0 && (settings.date.messages.afterMin = e.messages.afterMin), e.messages.beforeMax !== void 0 && (settings.date.messages.beforeMax = e.messages.beforeMax));\n  }\n}\nfunction isActionKey(n, e) {\n  if (typeof n == \"string\")\n    return settings.aliases.get(n) === e;\n  for (const s of n)\n    if (s !== void 0 && isActionKey(s, e))\n      return true;\n  return false;\n}\n\nfunction diffLines(i, s) {\n  if (i === s) return;\n  const e = i.split(`\n`), t = s.split(`\n`), r = Math.max(e.length, t.length), f = [];\n  for (let n = 0; n < r; n++)\n    e[n] !== t[n] && f.push(n);\n  return {\n    lines: f,\n    numLinesBefore: e.length,\n    numLinesAfter: t.length,\n    numLines: r\n  };\n}\n\nconst R = globalThis.process.platform.startsWith(\"win\");\nconst CANCEL_SYMBOL = Symbol(\"clack:cancel\");\nfunction isCancel(e) {\n  return e === CANCEL_SYMBOL;\n}\nfunction setRawMode(e, r) {\n  const o = e;\n  o.isTTY && o.setRawMode(r);\n}\nfunction block({\n  input: e = stdin,\n  output: r = stdout,\n  overwrite: o = true,\n  hideCursor: t = true\n} = {}) {\n  const s = l.createInterface({\n    input: e,\n    output: r,\n    prompt: \"\",\n    tabSize: 1\n  });\n  l.emitKeypressEvents(e, s), e instanceof ReadStream && e.isTTY && e.setRawMode(true);\n  const n = (f, { name: a, sequence: p }) => {\n    const c = String(f);\n    if (isActionKey([c, a, p], \"cancel\")) {\n      t && r.write(cursor.show), process.exit(0);\n      return;\n    }\n    if (!o) return;\n    const i = a === \"return\" ? 0 : -1, m = a === \"return\" ? -1 : 0;\n    l.moveCursor(r, i, m, () => {\n      l.clearLine(r, 1, () => {\n        e.once(\"keypress\", n);\n      });\n    });\n  };\n  return t && r.write(cursor.hide), e.once(\"keypress\", n), () => {\n    e.off(\"keypress\", n), t && r.write(cursor.show), e instanceof ReadStream && e.isTTY && !R && e.setRawMode(false), s.terminal = false, s.close();\n  };\n}\nconst getColumns = (e) => \"columns\" in e && typeof e.columns == \"number\" ? e.columns : 80, getRows = (e) => \"rows\" in e && typeof e.rows == \"number\" ? e.rows : 20;\nfunction wrapTextWithPrefix(e, r, o, t = o, s = o, n) {\n  const f = getColumns(e ?? stdout);\n  return wrapAnsi(r, f - o.length, {\n    hard: true,\n    trim: false\n  }).split(`\n`).map((c, i, m) => {\n    const d = n ? n(c, i) : c;\n    return i === 0 ? `${t}${d}` : i === m.length - 1 ? `${s}${d}` : `${o}${d}`;\n  }).join(`\n`);\n}\n\nfunction runValidation(e, n) {\n  if (\"~standard\" in e) {\n    const a = e[\"~standard\"].validate(n);\n    if (a instanceof Promise)\n      throw new TypeError(\n        \"Schema validation must be synchronous. Update `validate()` and remove any asynchronous logic.\"\n      );\n    return a.issues?.at(0)?.message;\n  }\n  return e(n);\n}\n\nclass V {\n  input;\n  output;\n  _abortSignal;\n  rl;\n  opts;\n  _render;\n  _track = false;\n  _prevFrame = \"\";\n  _subscribers = /* @__PURE__ */ new Map();\n  _cursor = 0;\n  state = \"initial\";\n  error = \"\";\n  value;\n  userInput = \"\";\n  constructor(t, e = true) {\n    const { input: i = stdin, output: n = stdout, render: s, signal: r, ...o } = t;\n    this.opts = o, this.onKeypress = this.onKeypress.bind(this), this.close = this.close.bind(this), this.render = this.render.bind(this), this._render = s.bind(this), this._track = e, this._abortSignal = r, this.input = i, this.output = n;\n  }\n  /**\n   * Unsubscribe all listeners\n   */\n  unsubscribe() {\n    this._subscribers.clear();\n  }\n  /**\n   * Set a subscriber with opts\n   * @param event - The event name\n   */\n  setSubscriber(t, e) {\n    const i = this._subscribers.get(t) ?? [];\n    i.push(e), this._subscribers.set(t, i);\n  }\n  /**\n   * Subscribe to an event\n   * @param event - The event name\n   * @param cb - The callback\n   */\n  on(t, e) {\n    this.setSubscriber(t, { cb: e });\n  }\n  /**\n   * Subscribe to an event once\n   * @param event - The event name\n   * @param cb - The callback\n   */\n  once(t, e) {\n    this.setSubscriber(t, { cb: e, once: true });\n  }\n  /**\n   * Emit an event with data\n   * @param event - The event name\n   * @param data - The data to pass to the callback\n   */\n  emit(t, ...e) {\n    const i = this._subscribers.get(t) ?? [], n = [];\n    for (const s of i)\n      s.cb(...e), s.once && n.push(() => i.splice(i.indexOf(s), 1));\n    for (const s of n)\n      s();\n  }\n  prompt() {\n    return new Promise((t) => {\n      if (this._abortSignal) {\n        if (this._abortSignal.aborted)\n          return this.state = \"cancel\", this.close(), t(CANCEL_SYMBOL);\n        this._abortSignal.addEventListener(\n          \"abort\",\n          () => {\n            this.state = \"cancel\", this.close();\n          },\n          { once: true }\n        );\n      }\n      this.rl = l__default.createInterface({\n        input: this.input,\n        tabSize: 2,\n        prompt: \"\",\n        escapeCodeTimeout: 50,\n        terminal: true\n      }), this.rl.prompt(), this.opts.initialUserInput !== void 0 && this._setUserInput(this.opts.initialUserInput, true), this.input.on(\"keypress\", this.onKeypress), setRawMode(this.input, true), this.output.on(\"resize\", this.render), this.render(), this.once(\"submit\", () => {\n        this.output.write(cursor.show), this.output.off(\"resize\", this.render), setRawMode(this.input, false), t(this.value);\n      }), this.once(\"cancel\", () => {\n        this.output.write(cursor.show), this.output.off(\"resize\", this.render), setRawMode(this.input, false), t(CANCEL_SYMBOL);\n      });\n    });\n  }\n  _isActionKey(t, e) {\n    return t === \"\t\";\n  }\n  _shouldSubmit(t, e) {\n    return true;\n  }\n  _setValue(t) {\n    this.value = t, this.emit(\"value\", this.value);\n  }\n  _setUserInput(t, e) {\n    this.userInput = t ?? \"\", this.emit(\"userInput\", this.userInput), e && this._track && this.rl && (this.rl.write(this.userInput), this._cursor = this.rl.cursor);\n  }\n  _clearUserInput() {\n    this.rl?.write(null, { ctrl: true, name: \"u\" }), this._setUserInput(\"\");\n  }\n  onKeypress(t, e) {\n    if (this._track && e.name !== \"return\" && (e.name && this._isActionKey(t, e) && this.rl?.write(null, { ctrl: true, name: \"h\" }), this._cursor = this.rl?.cursor ?? 0, this._setUserInput(this.rl?.line)), this.state === \"error\" && (this.state = \"active\"), e?.name && (!this._track && settings.aliases.has(e.name) && this.emit(\"cursor\", settings.aliases.get(e.name)), settings.actions.has(e.name) && this.emit(\"cursor\", e.name)), t && (t.toLowerCase() === \"y\" || t.toLowerCase() === \"n\") && this.emit(\"confirm\", t.toLowerCase() === \"y\"), this.emit(\"key\", t, e), e?.name === \"return\" && this._shouldSubmit(t, e)) {\n      if (this.opts.validate) {\n        const i = runValidation(this.opts.validate, this.value);\n        i && (this.error = i instanceof Error ? i.message : i, this.state = \"error\", this.rl?.write(this.userInput));\n      }\n      this.state !== \"error\" && (this.state = \"submit\");\n    }\n    isActionKey([t, e?.name, e?.sequence], \"cancel\") && (this.state = \"cancel\"), (this.state === \"submit\" || this.state === \"cancel\") && this.emit(\"finalize\"), this.render(), (this.state === \"submit\" || this.state === \"cancel\") && this.close();\n  }\n  close() {\n    this.input.unpipe(), this.input.removeListener(\"keypress\", this.onKeypress), this.output.write(`\n`), setRawMode(this.input, false), this.rl?.close(), this.rl = void 0, this.emit(`${this.state}`, this.value), this.unsubscribe();\n  }\n  restoreCursor() {\n    const t = wrapAnsi(this._prevFrame, process.stdout.columns, { hard: true, trim: false }).split(`\n`).length - 1;\n    this.output.write(cursor.move(-999, t * -1));\n  }\n  render() {\n    const t = wrapAnsi(this._render(this) ?? \"\", process.stdout.columns, {\n      hard: true,\n      trim: false\n    });\n    if (t !== this._prevFrame) {\n      if (this.state === \"initial\")\n        this.output.write(cursor.hide);\n      else {\n        const e = diffLines(this._prevFrame, t), i = getRows(this.output);\n        if (this.restoreCursor(), e) {\n          const n = Math.max(0, e.numLinesAfter - i), s = Math.max(0, e.numLinesBefore - i);\n          let r = e.lines.find((o) => o >= n);\n          if (r === void 0) {\n            this._prevFrame = t;\n            return;\n          }\n          if (e.lines.length === 1) {\n            this.output.write(cursor.move(0, r - s)), this.output.write(erase.lines(1));\n            const o = t.split(`\n`);\n            this.output.write(o[r]), this._prevFrame = t, this.output.write(cursor.move(0, o.length - r - 1));\n            return;\n          } else if (e.lines.length > 1) {\n            if (n < s)\n              r = n;\n            else {\n              const h = r - s;\n              h > 0 && this.output.write(cursor.move(0, h));\n            }\n            this.output.write(erase.down());\n            const f = t.split(`\n`).slice(r);\n            this.output.write(f.join(`\n`)), this._prevFrame = t;\n            return;\n          }\n        }\n        this.output.write(erase.down());\n      }\n      this.output.write(t), this.state === \"initial\" && (this.state = \"active\"), this._prevFrame = t;\n    }\n  }\n}\n\nfunction p$1(l, e) {\n  if (l === void 0 || e.length === 0)\n    return 0;\n  const i = e.findIndex((s) => s.value === l);\n  return i !== -1 ? i : 0;\n}\nfunction g(l, e) {\n  return (e.label ?? String(e.value)).toLowerCase().includes(l.toLowerCase());\n}\nfunction m(l, e) {\n  if (e)\n    return l ? e : e[0];\n}\nlet T$1 = class T extends V {\n  filteredOptions;\n  multiple;\n  isNavigating = false;\n  selectedValues = [];\n  focusedValue;\n  #e = 0;\n  #s = \"\";\n  #t;\n  #i;\n  #n;\n  get cursor() {\n    return this.#e;\n  }\n  get userInputWithCursor() {\n    if (!this.userInput)\n      return styleText([\"inverse\", \"hidden\"], \"_\");\n    if (this._cursor >= this.userInput.length)\n      return `${this.userInput}\\u2588`;\n    const e = this.userInput.slice(0, this.cursor), t = this.userInput.slice(this.cursor, this.cursor + 1), i = this.userInput.slice(this.cursor + 1);\n    return `${e}${styleText(\"inverse\", t)}${i}`;\n  }\n  get options() {\n    return typeof this.#i == \"function\" ? this.#i() : this.#i;\n  }\n  constructor(e) {\n    super(e), this.#i = e.options, this.#n = e.placeholder;\n    const t = this.options;\n    this.filteredOptions = [...t], this.multiple = e.multiple === true, this.#t = typeof e.options == \"function\" ? e.filter : e.filter ?? g;\n    let i;\n    if (e.initialValue && Array.isArray(e.initialValue) ? this.multiple ? i = e.initialValue : i = e.initialValue.slice(0, 1) : !this.multiple && this.options.length > 0 && (i = [this.options[0]?.value]), i)\n      for (const s of i) {\n        const n = t.findIndex((o) => o.value === s);\n        n !== -1 && (this.toggleSelected(s), this.#e = n);\n      }\n    this.focusedValue = this.options[this.#e]?.value, this.on(\"key\", (s, n) => this.#l(s, n)), this.on(\"userInput\", (s) => this.#u(s));\n  }\n  _isActionKey(e, t) {\n    return e === \"\t\" || this.multiple && this.isNavigating && t.name === \"space\" && e !== void 0 && e !== \"\";\n  }\n  #l(e, t) {\n    const i = t.name === \"up\", s = t.name === \"down\", n = t.name === \"return\", o = this.userInput === \"\" || this.userInput === \"\t\", u = this.#n, a = this.options, f = u !== void 0 && u !== \"\" && a.some(\n      (r) => !r.disabled && (this.#t ? this.#t(u, r) : true)\n    );\n    if (t.name === \"tab\" && o && f) {\n      this.userInput === \"\t\" && this._clearUserInput(), this._setUserInput(u, true), this.isNavigating = false;\n      return;\n    }\n    i || s ? (this.#e = findCursor(this.#e, i ? -1 : 1, this.filteredOptions), this.focusedValue = this.filteredOptions[this.#e]?.value, this.multiple || (this.selectedValues = [this.focusedValue]), this.isNavigating = true) : n ? this.value = m(this.multiple, this.selectedValues) : this.multiple ? this.focusedValue !== void 0 && (t.name === \"tab\" || this.isNavigating && t.name === \"space\") ? this.toggleSelected(this.focusedValue) : this.isNavigating = false : (this.focusedValue && (this.selectedValues = [this.focusedValue]), this.isNavigating = false);\n  }\n  deselectAll() {\n    this.selectedValues = [];\n  }\n  toggleSelected(e) {\n    this.filteredOptions.length !== 0 && (this.multiple ? this.selectedValues.includes(e) ? this.selectedValues = this.selectedValues.filter((t) => t !== e) : this.selectedValues = [...this.selectedValues, e] : this.selectedValues = [e]);\n  }\n  #u(e) {\n    if (e !== this.#s) {\n      this.#s = e;\n      const t = this.options;\n      e && this.#t ? this.filteredOptions = t.filter((n) => this.#t?.(e, n)) : this.filteredOptions = [...t];\n      const i = p$1(this.focusedValue, this.filteredOptions);\n      this.#e = findCursor(i, 0, this.filteredOptions);\n      const s = this.filteredOptions[this.#e];\n      s && !s.disabled ? this.focusedValue = s.value : this.focusedValue = void 0, this.multiple || (this.focusedValue !== void 0 ? this.toggleSelected(this.focusedValue) : this.deselectAll());\n    }\n  }\n};\n\nclass r extends V {\n  get cursor() {\n    return this.value ? 0 : 1;\n  }\n  get _value() {\n    return this.cursor === 0;\n  }\n  constructor(t) {\n    super(t, false), this.value = !!t.initialValue, this.on(\"userInput\", () => {\n      this.value = this._value;\n    }), this.on(\"confirm\", (i) => {\n      this.output.write(cursor.move(0, -1)), this.value = i, this.state = \"submit\", this.close();\n    }), this.on(\"cursor\", () => {\n      this.value = !this.value;\n    });\n  }\n}\n\nconst _ = {\n  Y: { type: \"year\", len: 4 },\n  M: { type: \"month\", len: 2 },\n  D: { type: \"day\", len: 2 }\n};\nfunction M(r) {\n  return [...r].map((t) => _[t]);\n}\nfunction P(r) {\n  const i = new Intl.DateTimeFormat(r, {\n    year: \"numeric\",\n    month: \"2-digit\",\n    day: \"2-digit\"\n  }).formatToParts(new Date(2e3, 0, 15)), s = [];\n  let n = \"/\";\n  for (const e of i)\n    e.type === \"literal\" ? n = e.value.trim() || e.value : (e.type === \"year\" || e.type === \"month\" || e.type === \"day\") && s.push({ type: e.type, len: e.type === \"year\" ? 4 : 2 });\n  return { segments: s, separator: n };\n}\nfunction p(r) {\n  return Number.parseInt((r || \"0\").replace(/_/g, \"0\"), 10) || 0;\n}\nfunction f(r) {\n  return {\n    year: p(r.year),\n    month: p(r.month),\n    day: p(r.day)\n  };\n}\nfunction c(r, t) {\n  return new Date(r || 2001, t || 1, 0).getDate();\n}\nfunction b(r) {\n  const { year: t, month: i, day: s } = f(r);\n  if (!t || t < 0 || t > 9999 || !i || i < 1 || i > 12 || !s || s < 1) return;\n  const n = new Date(Date.UTC(t, i - 1, s));\n  if (!(n.getUTCFullYear() !== t || n.getUTCMonth() !== i - 1 || n.getUTCDate() !== s))\n    return { year: t, month: i, day: s };\n}\nfunction C(r) {\n  const t = b(r);\n  return t ? new Date(Date.UTC(t.year, t.month - 1, t.day)) : void 0;\n}\nfunction T(r, t, i, s) {\n  const n = i ? {\n    year: i.getUTCFullYear(),\n    month: i.getUTCMonth() + 1,\n    day: i.getUTCDate()\n  } : null, e = s ? {\n    year: s.getUTCFullYear(),\n    month: s.getUTCMonth() + 1,\n    day: s.getUTCDate()\n  } : null;\n  return r === \"year\" ? { min: n?.year ?? 1, max: e?.year ?? 9999 } : r === \"month\" ? {\n    min: n && t.year === n.year ? n.month : 1,\n    max: e && t.year === e.year ? e.month : 12\n  } : {\n    min: n && t.year === n.year && t.month === n.month ? n.day : 1,\n    max: e && t.year === e.year && t.month === e.month ? e.day : c(t.year, t.month)\n  };\n}\nclass U extends V {\n  #i;\n  #o;\n  #t;\n  #h;\n  #u;\n  #e = { segmentIndex: 0, positionInSegment: 0 };\n  #n = true;\n  #s = null;\n  inlineError = \"\";\n  get segmentCursor() {\n    return { ...this.#e };\n  }\n  get segmentValues() {\n    return { ...this.#t };\n  }\n  get segments() {\n    return this.#i;\n  }\n  get separator() {\n    return this.#o;\n  }\n  get formattedValue() {\n    return this.#l(this.#t);\n  }\n  #l(t) {\n    return this.#i.map((i) => t[i.type]).join(this.#o);\n  }\n  #r() {\n    this._setUserInput(this.#l(this.#t)), this._setValue(C(this.#t) ?? void 0);\n  }\n  constructor(t) {\n    const i = t.format ? { segments: M(t.format), separator: t.separator ?? \"/\" } : P(t.locale), s = t.separator ?? i.separator, n = t.format ? M(t.format) : i.segments, e = t.initialValue ?? t.defaultValue, m = e ? {\n      year: String(e.getUTCFullYear()).padStart(4, \"0\"),\n      month: String(e.getUTCMonth() + 1).padStart(2, \"0\"),\n      day: String(e.getUTCDate()).padStart(2, \"0\")\n    } : { year: \"____\", month: \"__\", day: \"__\" }, o = n.map((a) => m[a.type]).join(s);\n    super({ ...t, initialUserInput: o }, false), this.#i = n, this.#o = s, this.#t = m, this.#h = t.minDate, this.#u = t.maxDate, this.#r(), this.on(\"cursor\", (a) => this.#f(a)), this.on(\"key\", (a, u) => this.#y(a, u)), this.on(\"finalize\", () => this.#p(t));\n  }\n  #a() {\n    const t = Math.max(0, Math.min(this.#e.segmentIndex, this.#i.length - 1)), i = this.#i[t];\n    if (i)\n      return this.#e.positionInSegment = Math.max(\n        0,\n        Math.min(this.#e.positionInSegment, i.len - 1)\n      ), { segment: i, index: t };\n  }\n  #m(t) {\n    this.inlineError = \"\", this.#s = null;\n    const i = this.#a();\n    i && (this.#e.segmentIndex = Math.max(\n      0,\n      Math.min(this.#i.length - 1, i.index + t)\n    ), this.#e.positionInSegment = 0, this.#n = true);\n  }\n  #d(t) {\n    const i = this.#a();\n    if (!i) return;\n    const { segment: s } = i, n = this.#t[s.type], e = !n || n.replace(/_/g, \"\") === \"\", m = Number.parseInt((n || \"0\").replace(/_/g, \"0\"), 10) || 0, o = T(\n      s.type,\n      f(this.#t),\n      this.#h,\n      this.#u\n    );\n    let a;\n    e ? a = t === 1 ? o.min : o.max : a = Math.max(Math.min(o.max, m + t), o.min), this.#t = {\n      ...this.#t,\n      [s.type]: a.toString().padStart(s.len, \"0\")\n    }, this.#n = true, this.#s = null, this.#r();\n  }\n  #f(t) {\n    if (t)\n      switch (t) {\n        case \"right\":\n          return this.#m(1);\n        case \"left\":\n          return this.#m(-1);\n        case \"up\":\n          return this.#d(1);\n        case \"down\":\n          return this.#d(-1);\n      }\n  }\n  #y(t, i) {\n    if (i?.name === \"backspace\" || i?.sequence === \"\\x7F\" || i?.sequence === \"\\b\" || t === \"\\x7F\" || t === \"\\b\") {\n      this.inlineError = \"\";\n      const n = this.#a();\n      if (!n) return;\n      if (!this.#t[n.segment.type].replace(/_/g, \"\")) {\n        this.#m(-1);\n        return;\n      }\n      this.#t[n.segment.type] = \"_\".repeat(n.segment.len), this.#n = true, this.#e.positionInSegment = 0, this.#r();\n      return;\n    }\n    if (i?.name === \"tab\") {\n      this.inlineError = \"\";\n      const n = this.#a();\n      if (!n) return;\n      const e = i.shift ? -1 : 1, m = n.index + e;\n      m >= 0 && m < this.#i.length && (this.#e.segmentIndex = m, this.#e.positionInSegment = 0, this.#n = true);\n      return;\n    }\n    if (t && /^[0-9]$/.test(t)) {\n      const n = this.#a();\n      if (!n) return;\n      const { segment: e } = n, m = !this.#t[e.type].replace(/_/g, \"\");\n      if (this.#n && this.#s !== null && !m) {\n        const h = this.#s + t, d = { ...this.#t, [e.type]: h }, g = this.#g(d, e);\n        if (g) {\n          this.inlineError = g, this.#s = null, this.#n = false;\n          return;\n        }\n        this.inlineError = \"\", this.#t[e.type] = h, this.#s = null, this.#n = false, this.#r(), n.index < this.#i.length - 1 && (this.#e.segmentIndex = n.index + 1, this.#e.positionInSegment = 0, this.#n = true);\n        return;\n      }\n      this.#n && !m && (this.#t[e.type] = \"_\".repeat(e.len), this.#e.positionInSegment = 0), this.#n = false, this.#s = null;\n      const o = this.#t[e.type], a = o.indexOf(\"_\"), u = a >= 0 ? a : Math.min(this.#e.positionInSegment, e.len - 1);\n      if (u < 0 || u >= e.len) return;\n      let l = o.slice(0, u) + t + o.slice(u + 1), D = false;\n      if (u === 0 && o === \"__\" && (e.type === \"month\" || e.type === \"day\")) {\n        const h = Number.parseInt(t, 10);\n        l = `0${t}`, D = h <= (e.type === \"month\" ? 1 : 2);\n      }\n      if (e.type === \"year\" && (l = (o.replace(/_/g, \"\") + t).padStart(e.len, \"_\")), !l.includes(\"_\")) {\n        const h = { ...this.#t, [e.type]: l }, d = this.#g(h, e);\n        if (d) {\n          this.inlineError = d;\n          return;\n        }\n      }\n      this.inlineError = \"\", this.#t[e.type] = l;\n      const y = l.includes(\"_\") ? void 0 : b(this.#t);\n      if (y) {\n        const { year: h, month: d } = y, g = c(h, d);\n        this.#t = {\n          year: String(Math.max(0, Math.min(9999, h))).padStart(4, \"0\"),\n          month: String(Math.max(1, Math.min(12, d))).padStart(2, \"0\"),\n          day: String(Math.max(1, Math.min(g, y.day))).padStart(2, \"0\")\n        };\n      }\n      this.#r();\n      const S = l.indexOf(\"_\");\n      D ? (this.#n = true, this.#s = t) : S >= 0 ? this.#e.positionInSegment = S : a >= 0 && n.index < this.#i.length - 1 ? (this.#e.segmentIndex = n.index + 1, this.#e.positionInSegment = 0, this.#n = true) : this.#e.positionInSegment = Math.min(u + 1, e.len - 1);\n    }\n  }\n  #g(t, i) {\n    const { month: s, day: n } = f(t);\n    if (i.type === \"month\" && (s < 0 || s > 12))\n      return settings.date.messages.invalidMonth;\n    if (i.type === \"day\" && (n < 0 || n > 31))\n      return settings.date.messages.invalidDay(31, \"any month\");\n  }\n  #p(t) {\n    const { year: i, month: s, day: n } = f(this.#t);\n    if (i && s && n) {\n      const e = c(i, s);\n      this.#t = {\n        ...this.#t,\n        day: String(Math.min(n, e)).padStart(2, \"0\")\n      };\n    }\n    this.value = C(this.#t) ?? t.defaultValue ?? void 0;\n  }\n}\n\nlet u$2 = class u extends V {\n  options;\n  cursor = 0;\n  #t;\n  getGroupItems(t) {\n    return this.options.filter((r) => r.group === t);\n  }\n  isGroupSelected(t) {\n    const r = this.getGroupItems(t), e = this.value;\n    return e === void 0 ? false : r.every((s) => e.includes(s.value));\n  }\n  toggleValue() {\n    const t = this.options[this.cursor];\n    if (t !== void 0)\n      if (this.value === void 0 && (this.value = []), t.group === true) {\n        const r = t.value, e = this.getGroupItems(r);\n        this.isGroupSelected(r) ? this.value = this.value.filter(\n          (s) => e.findIndex((i) => i.value === s) === -1\n        ) : this.value = [...this.value, ...e.map((s) => s.value)], this.value = Array.from(new Set(this.value));\n      } else {\n        const r = this.value.includes(t.value);\n        this.value = r ? this.value.filter((e) => e !== t.value) : [...this.value, t.value];\n      }\n  }\n  constructor(t) {\n    super(t, false);\n    const { options: r } = t;\n    this.#t = t.selectableGroups !== false, this.options = Object.entries(r).flatMap(([e, s]) => [\n      { value: e, group: true, label: e },\n      ...s.map((i) => ({ ...i, group: e }))\n    ]), this.value = [...t.initialValues ?? []], this.cursor = Math.max(\n      this.options.findIndex(({ value: e }) => e === t.cursorAt),\n      this.#t ? 0 : 1\n    ), this.on(\"cursor\", (e) => {\n      switch (e) {\n        case \"left\":\n        case \"up\": {\n          this.cursor = this.cursor === 0 ? this.options.length - 1 : this.cursor - 1;\n          const s = this.options[this.cursor]?.group === true;\n          !this.#t && s && (this.cursor = this.cursor === 0 ? this.options.length - 1 : this.cursor - 1);\n          break;\n        }\n        case \"down\":\n        case \"right\": {\n          this.cursor = this.cursor === this.options.length - 1 ? 0 : this.cursor + 1;\n          const s = this.options[this.cursor]?.group === true;\n          !this.#t && s && (this.cursor = this.cursor === this.options.length - 1 ? 0 : this.cursor + 1);\n          break;\n        }\n        case \"space\":\n          this.toggleValue();\n          break;\n      }\n    });\n  }\n};\n\nconst o = /* @__PURE__ */ new Set([\"up\", \"down\", \"left\", \"right\"]);\nclass h extends V {\n  #t = false;\n  #s;\n  focused = \"editor\";\n  get userInputWithCursor() {\n    if (this.state === \"submit\")\n      return this.userInput;\n    const t = this.userInput;\n    if (this.cursor >= t.length)\n      return `${t}\\u2588`;\n    const s = t.slice(0, this.cursor), r = t.slice(this.cursor, this.cursor + 1), i = t.slice(this.cursor + 1);\n    return r === `\n` ? `${s}\\u2588\n${i}` : `${s}${styleText(\"inverse\", r)}${i}`;\n  }\n  get cursor() {\n    return this._cursor;\n  }\n  #r(t) {\n    if (this.userInput.length === 0) {\n      this._setUserInput(t);\n      return;\n    }\n    this._setUserInput(\n      this.userInput.slice(0, this.cursor) + t + this.userInput.slice(this.cursor)\n    );\n  }\n  #i(t) {\n    const s = this.value ?? \"\";\n    switch (t) {\n      case \"up\":\n        this._cursor = findTextCursor(this._cursor, 0, -1, s);\n        return;\n      case \"down\":\n        this._cursor = findTextCursor(this._cursor, 0, 1, s);\n        return;\n      case \"left\":\n        this._cursor = findTextCursor(this._cursor, -1, 0, s);\n        return;\n      case \"right\":\n        this._cursor = findTextCursor(this._cursor, 1, 0, s);\n        return;\n    }\n  }\n  _shouldSubmit(t, s) {\n    if (this.#s)\n      return this.focused === \"submit\" ? true : (this.#r(`\n`), this._cursor++, false);\n    const r = this.#t;\n    return this.#t = true, r && this.cursor === this.userInput.length ? (this.userInput[this.cursor - 1] === `\n` && (this._setUserInput(\n      this.userInput.slice(0, this.cursor - 1) + this.userInput.slice(this.cursor)\n    ), this._cursor--), true) : (this.#r(`\n`), this._cursor++, false);\n  }\n  constructor(t) {\n    const s = t.initialUserInput ?? t.initialValue;\n    super(\n      {\n        ...t,\n        initialUserInput: s\n      },\n      false\n    ), s !== void 0 && (this._cursor = s.length), this.#s = t.showSubmit ?? false, this.on(\"key\", (r, i) => {\n      if (i?.name && o.has(i.name)) {\n        this.#t = false, this.#i(i.name);\n        return;\n      }\n      if (r === \"\t\" && this.#s) {\n        this.focused = this.focused === \"editor\" ? \"submit\" : \"editor\";\n        return;\n      }\n      if (i?.name !== \"return\") {\n        if (this.#t = false, i?.name === \"backspace\" && this.cursor > 0) {\n          this._setUserInput(\n            this.userInput.slice(0, this.cursor - 1) + this.userInput.slice(this.cursor)\n          ), this._cursor--;\n          return;\n        }\n        if (i?.name === \"delete\" && this.cursor < this.userInput.length) {\n          this._setUserInput(\n            this.userInput.slice(0, this.cursor) + this.userInput.slice(this.cursor + 1)\n          );\n          return;\n        }\n        r && (this.#s && this.focused === \"submit\" && (this.focused = \"editor\"), this.#r(r ?? \"\"), this._cursor++);\n      }\n    }), this.on(\"userInput\", (r) => {\n      this._setValue(r);\n    }), this.on(\"finalize\", () => {\n      this.value || (this.value = t.defaultValue), this.value === void 0 && (this.value = \"\");\n    });\n  }\n}\n\nclass a extends V {\n  options;\n  cursor = 0;\n  get _value() {\n    return this.options[this.cursor]?.value;\n  }\n  get _enabledOptions() {\n    return this.options.filter((e) => e.disabled !== true);\n  }\n  toggleAll() {\n    const e = this._enabledOptions, i = this.value !== void 0 && this.value.length === e.length;\n    this.value = i ? [] : e.map((t) => t.value);\n  }\n  toggleInvert() {\n    const e = this.value;\n    if (!e)\n      return;\n    const i = this._enabledOptions.filter((t) => !e.includes(t.value));\n    this.value = i.map((t) => t.value);\n  }\n  toggleValue() {\n    this.value === void 0 && (this.value = []);\n    const e = this.value.includes(this._value);\n    this.value = e ? this.value.filter((i) => i !== this._value) : [...this.value, this._value];\n  }\n  constructor(e) {\n    super(e, false), this.options = e.options, this.value = [...e.initialValues ?? []];\n    const i = Math.max(\n      this.options.findIndex(({ value: t }) => t === e.cursorAt),\n      0\n    );\n    this.cursor = this.options[i]?.disabled ? findCursor(i, 1, this.options) : i, this.on(\"key\", (t, l) => {\n      l.name === \"a\" && this.toggleAll(), l.name === \"i\" && this.toggleInvert();\n    }), this.on(\"cursor\", (t) => {\n      switch (t) {\n        case \"left\":\n        case \"up\":\n          this.cursor = findCursor(this.cursor, -1, this.options);\n          break;\n        case \"down\":\n        case \"right\":\n          this.cursor = findCursor(this.cursor, 1, this.options);\n          break;\n        case \"space\":\n          this.toggleValue();\n          break;\n      }\n    });\n  }\n}\n\nlet u$1 = class u extends V {\n  _mask = \"\\u2022\";\n  get cursor() {\n    return this._cursor;\n  }\n  get masked() {\n    return this.userInput.replaceAll(/./g, this._mask);\n  }\n  get userInputWithCursor() {\n    if (this.state === \"submit\" || this.state === \"cancel\")\n      return this.masked;\n    const t = this.userInput;\n    if (this.cursor >= t.length)\n      return `${this.masked}${styleText([\"inverse\", \"hidden\"], \"_\")}`;\n    const s = this.masked, r = s.slice(0, this.cursor), i = s.slice(this.cursor, this.cursor + 1), o = s.slice(this.cursor + 1);\n    return `${r}${styleText(\"inverse\", i)}${o}`;\n  }\n  clear() {\n    this._clearUserInput();\n  }\n  constructor({ mask: t, ...s }) {\n    super(s), this._mask = t ?? \"\\u2022\", this.on(\"userInput\", (r) => {\n      this._setValue(r);\n    }), this.on(\"finalize\", () => {\n      this.value === void 0 && (this.value = \"\");\n    });\n  }\n};\n\nlet n$1 = class n extends V {\n  options;\n  cursor = 0;\n  get _selectedValue() {\n    return this.options[this.cursor];\n  }\n  changeValue() {\n    const e = this._selectedValue;\n    this.value = e === void 0 ? void 0 : e.value;\n  }\n  constructor(e) {\n    super(e, false), this.options = e.options;\n    const o = this.options.findIndex(({ value: s }) => s === e.initialValue), t = o === -1 ? 0 : o;\n    this.cursor = this.options[t]?.disabled ? findCursor(t, 1, this.options) : t, this.changeValue(), this.on(\"cursor\", (s) => {\n      switch (s) {\n        case \"left\":\n        case \"up\":\n          this.cursor = findCursor(this.cursor, -1, this.options);\n          break;\n        case \"down\":\n        case \"right\":\n          this.cursor = findCursor(this.cursor, 1, this.options);\n          break;\n      }\n      this.changeValue();\n    });\n  }\n};\n\nclass u extends V {\n  options;\n  cursor = 0;\n  constructor(t) {\n    super(t, false), this.options = t.options;\n    const s = t.caseSensitive === true, i = this.options.map(({ value: [e] }) => s ? e : e?.toLowerCase());\n    this.cursor = Math.max(i.indexOf(t.initialValue), 0), this.on(\"key\", (e) => {\n      if (!e)\n        return;\n      const o = s ? e : e.toLowerCase();\n      if (!i.includes(o))\n        return;\n      const n = this.options.find(({ value: [r] }) => s ? r === o : r?.toLowerCase() === o);\n      n && (this.value = n.value, this.state = \"submit\", this.emit(\"submit\"));\n    });\n  }\n}\n\nclass n extends V {\n  get userInputWithCursor() {\n    if (this.state === \"submit\")\n      return this.userInput;\n    const t = this.userInput;\n    if (this.cursor >= t.length)\n      return `${this.userInput}\\u2588`;\n    const r = t.slice(0, this.cursor), s = t.slice(this.cursor, this.cursor + 1), e = t.slice(this.cursor + 1);\n    return `${r}${styleText(\"inverse\", s)}${e}`;\n  }\n  get cursor() {\n    return this._cursor;\n  }\n  constructor(t) {\n    super({\n      ...t,\n      initialUserInput: t.initialUserInput ?? t.initialValue\n    }), this.on(\"userInput\", (r) => {\n      this._setValue(r);\n    }), this.on(\"finalize\", () => {\n      this.value || (this.value = t.defaultValue), this.value === void 0 && (this.value = \"\");\n    });\n  }\n}\n\nexport { T$1 as AutocompletePrompt, r as ConfirmPrompt, U as DatePrompt, u$2 as GroupMultiSelectPrompt, h as MultiLinePrompt, a as MultiSelectPrompt, u$1 as PasswordPrompt, V as Prompt, u as SelectKeyPrompt, n$1 as SelectPrompt, n as TextPrompt, block, getColumns, getRows, isCancel, runValidation, settings, updateSettings, wrapTextWithPrefix };\n","import { getColumns, getRows, AutocompletePrompt, settings, ConfirmPrompt, wrapTextWithPrefix, DatePrompt, runValidation, isCancel, MultiSelectPrompt, GroupMultiSelectPrompt, MultiLinePrompt, PasswordPrompt, block, SelectPrompt, SelectKeyPrompt, TextPrompt } from '@clack/core';\nexport { isCancel, settings, updateSettings } from '@clack/core';\nimport { styleText, stripVTControlCharacters } from 'node:util';\nimport process$1 from 'node:process';\nimport { wrapAnsi } from 'fast-wrap-ansi';\nimport l from 'fast-string-width';\nimport { existsSync, lstatSync, readdirSync } from 'node:fs';\nimport { dirname, join } from 'node:path';\nimport { cursor, erase } from 'sisteransi';\n\nfunction isUnicodeSupported() {\n\tif (process$1.platform !== 'win32') {\n\t\treturn process$1.env.TERM !== 'linux'; // Linux console (kernel)\n\t}\n\n\treturn Boolean(process$1.env.CI)\n\t\t|| Boolean(process$1.env.WT_SESSION) // Windows Terminal\n\t\t|| Boolean(process$1.env.TERMINUS_SUBLIME) // Terminus (<0.2.27)\n\t\t|| process$1.env.ConEmuTask === '{cmd::Cmder}' // ConEmu and cmder\n\t\t|| process$1.env.TERM_PROGRAM === 'Terminus-Sublime'\n\t\t|| process$1.env.TERM_PROGRAM === 'vscode'\n\t\t|| process$1.env.TERM === 'xterm-256color'\n\t\t|| process$1.env.TERM === 'alacritty'\n\t\t|| process$1.env.TERMINAL_EMULATOR === 'JetBrains-JediTerm';\n}\n\nconst unicode = isUnicodeSupported(), isCI = () => process.env.CI === \"true\", isTTY = (o) => o.isTTY === true, unicodeOr = (o, e) => unicode ? o : e, S_STEP_ACTIVE = unicodeOr(\"\\u25C6\", \"*\"), S_STEP_CANCEL = unicodeOr(\"\\u25A0\", \"x\"), S_STEP_ERROR = unicodeOr(\"\\u25B2\", \"x\"), S_STEP_SUBMIT = unicodeOr(\"\\u25C7\", \"o\"), S_BAR_START = unicodeOr(\"\\u250C\", \"T\"), S_BAR = unicodeOr(\"\\u2502\", \"|\"), S_BAR_END = unicodeOr(\"\\u2514\", \"\\u2014\"), S_BAR_START_RIGHT = unicodeOr(\"\\u2510\", \"T\"), S_BAR_END_RIGHT = unicodeOr(\"\\u2518\", \"\\u2014\"), S_RADIO_ACTIVE = unicodeOr(\"\\u25CF\", \">\"), S_RADIO_INACTIVE = unicodeOr(\"\\u25CB\", \" \"), S_CHECKBOX_ACTIVE = unicodeOr(\"\\u25FB\", \"[\\u2022]\"), S_CHECKBOX_SELECTED = unicodeOr(\"\\u25FC\", \"[+]\"), S_CHECKBOX_INACTIVE = unicodeOr(\"\\u25FB\", \"[ ]\"), S_PASSWORD_MASK = unicodeOr(\"\\u25AA\", \"\\u2022\"), S_BAR_H = unicodeOr(\"\\u2500\", \"-\"), S_CORNER_TOP_RIGHT = unicodeOr(\"\\u256E\", \"+\"), S_CONNECT_LEFT = unicodeOr(\"\\u251C\", \"+\"), S_CORNER_BOTTOM_RIGHT = unicodeOr(\"\\u256F\", \"+\"), S_CORNER_BOTTOM_LEFT = unicodeOr(\"\\u2570\", \"+\"), S_CORNER_TOP_LEFT = unicodeOr(\"\\u256D\", \"+\"), S_INFO = unicodeOr(\"\\u25CF\", \"\\u2022\"), S_SUCCESS = unicodeOr(\"\\u25C6\", \"*\"), S_WARN = unicodeOr(\"\\u25B2\", \"!\"), S_ERROR = unicodeOr(\"\\u25A0\", \"x\"), symbol = (o) => {\n  switch (o) {\n    case \"initial\":\n    case \"active\":\n      return styleText(\"cyan\", S_STEP_ACTIVE);\n    case \"cancel\":\n      return styleText(\"red\", S_STEP_CANCEL);\n    case \"error\":\n      return styleText(\"yellow\", S_STEP_ERROR);\n    case \"submit\":\n      return styleText(\"green\", S_STEP_SUBMIT);\n  }\n}, symbolBar = (o) => {\n  switch (o) {\n    case \"initial\":\n    case \"active\":\n      return styleText(\"cyan\", S_BAR);\n    case \"cancel\":\n      return styleText(\"red\", S_BAR);\n    case \"error\":\n      return styleText(\"yellow\", S_BAR);\n    case \"submit\":\n      return styleText(\"green\", S_BAR);\n  }\n};\nfunction formatInstructionFooter(o, e) {\n  const r = [`${e ? `${styleText(\"cyan\", S_BAR)}  ` : \"\"}${o.join(\" \\u2022 \")}`];\n  return e && r.push(styleText(\"cyan\", S_BAR_END)), r;\n}\n\nconst I = (l, e, w, p, b, C = false) => {\n  let r = e, O = 0;\n  if (C)\n    for (let i = p - 1; i >= w; i--) {\n      const m = l[i];\n      if (m && (r -= m.length), O++, r <= b) break;\n    }\n  else\n    for (let i = w; i < p; i++) {\n      const m = l[i];\n      if (m && (r -= m.length), O++, r <= b) break;\n    }\n  return { lineCount: r, removals: O };\n};\nconst limitOptions = ({\n  cursor: l,\n  options: e,\n  style: w,\n  output: p = process.stdout,\n  maxItems: b = Number.POSITIVE_INFINITY,\n  columnPadding: C = 0,\n  rowPadding: r = 4\n}) => {\n  const i = getColumns(p) - C, m = getRows(p), M = styleText(\"dim\", \"...\"), v = Math.max(m - r, 0), a = Math.max(Math.min(b, v), 5);\n  let f = 0;\n  l >= a - 3 && (f = Math.max(\n    Math.min(l - a + 3, e.length - a),\n    0\n  ));\n  let d = a < e.length && f > 0, c = a < e.length && f + a < e.length;\n  const W = Math.min(\n    f + a,\n    e.length\n  ), s = [];\n  let g = 0;\n  d && g++, c && g++;\n  const T = f + (d ? 1 : 0), y = W - (c ? 1 : 0);\n  for (let t = T; t < y; t++) {\n    const n = e[t], o = n ? w(n, t === l) : \"\", h = wrapAnsi(o, i, {\n      hard: true,\n      trim: false\n    }).split(`\n`);\n    s.push(h), g += h.length;\n  }\n  if (g > v) {\n    let t = 0, n = 0, o = g;\n    const h = l - T;\n    let u = v;\n    const L = () => I(s, o, 0, h, u), E = () => I(\n      s,\n      o,\n      h + 1,\n      s.length,\n      u,\n      true\n    );\n    d ? ({ lineCount: o, removals: t } = L(), o > u && (c || (u -= 1), { lineCount: o, removals: n } = E())) : (c || (u -= 1), { lineCount: o, removals: n } = E(), o > u && (u -= 1, { lineCount: o, removals: t } = L())), t > 0 && (d = true, s.splice(0, t)), n > 0 && (c = true, s.splice(s.length - n, n));\n  }\n  const x = [];\n  d && x.push(M);\n  for (const t of s)\n    for (const n of t)\n      x.push(n);\n  return c && x.push(M), x;\n};\n\nfunction P(t) {\n  return t.label ?? String(t.value ?? \"\");\n}\nfunction E(t, c) {\n  if (!t)\n    return true;\n  const n = (c.label ?? String(c.value ?? \"\")).toLowerCase(), i = (c.hint ?? \"\").toLowerCase(), l = String(c.value).toLowerCase(), o = t.toLowerCase();\n  return n.includes(o) || i.includes(o) || l.includes(o);\n}\nfunction N(t, c) {\n  const n = [];\n  for (const i of c)\n    t.includes(i.value) && n.push(i);\n  return n;\n}\nconst autocomplete = (t) => new AutocompletePrompt({\n  options: t.options,\n  initialValue: t.initialValue ? [t.initialValue] : void 0,\n  initialUserInput: t.initialUserInput,\n  placeholder: t.placeholder,\n  filter: t.filter ?? ((n, i) => E(n, i)),\n  signal: t.signal,\n  input: t.input,\n  output: t.output,\n  validate: t.validate,\n  render() {\n    const n = t.withGuide ?? settings.withGuide, i = n ? [`${styleText(\"gray\", S_BAR)}`, `${symbol(this.state)}  ${t.message}`] : [`${symbol(this.state)}  ${t.message}`], l = this.userInput, o = this.options, m = t.placeholder, p = l === \"\" && m !== void 0, $ = (r, s) => {\n      const a = P(r), u = r.hint && r.value === this.focusedValue ? styleText(\"dim\", ` (${r.hint})`) : \"\";\n      switch (s) {\n        case \"active\":\n          return `${styleText(\"green\", S_RADIO_ACTIVE)} ${a}${u}`;\n        case \"inactive\":\n          return `${styleText(\"dim\", S_RADIO_INACTIVE)} ${styleText(\"dim\", a)}`;\n        case \"disabled\":\n          return `${styleText(\"gray\", S_RADIO_INACTIVE)} ${styleText([\"strikethrough\", \"gray\"], a)}`;\n      }\n    };\n    switch (this.state) {\n      case \"submit\": {\n        const r = N(this.selectedValues, o), s = r.length > 0 ? `  ${styleText(\"dim\", r.map(P).join(\", \"))}` : \"\", a = n ? styleText(\"gray\", S_BAR) : \"\";\n        return `${i.join(`\n`)}\n${a}${s}`;\n      }\n      case \"cancel\": {\n        const r = l ? `  ${styleText([\"strikethrough\", \"dim\"], l)}` : \"\", s = n ? styleText(\"gray\", S_BAR) : \"\";\n        return `${i.join(`\n`)}\n${s}${r}`;\n      }\n      default: {\n        const r = this.state === \"error\" ? \"yellow\" : \"cyan\", s = n ? `${styleText(r, S_BAR)}  ` : \"\", a = n ? styleText(r, S_BAR_END) : \"\";\n        let u = \"\";\n        if (this.isNavigating || p) {\n          const d = p ? m : l;\n          u = d !== \"\" ? ` ${styleText(\"dim\", d)}` : \"\";\n        } else\n          u = ` ${this.userInputWithCursor}`;\n        const V = this.filteredOptions.length !== o.length ? styleText(\n          \"dim\",\n          ` (${this.filteredOptions.length} match${this.filteredOptions.length === 1 ? \"\" : \"es\"})`\n        ) : \"\", y = this.filteredOptions.length === 0 && l ? [`${s}${styleText(\"yellow\", \"No matches found\")}`] : [], b = this.state === \"error\" ? [`${s}${styleText(\"yellow\", this.error)}`] : [];\n        n && i.push(`${s.trimEnd()}`), i.push(\n          `${s}${styleText(\"dim\", \"Search:\")}${u}${V}`,\n          ...y,\n          ...b\n        );\n        const v = [\n          `${styleText(\"dim\", \"\\u2191/\\u2193\")} to select`,\n          `${styleText(\"dim\", \"Enter:\")} confirm`,\n          `${styleText(\"dim\", \"Type:\")} to search`\n        ], g = [`${s}${v.join(\" \\u2022 \")}`, a], O = this.filteredOptions.length === 0 ? [] : limitOptions({\n          cursor: this.cursor,\n          options: this.filteredOptions,\n          columnPadding: n ? 3 : 0,\n          // for `|  ` when guide is shown\n          rowPadding: i.length + g.length,\n          style: (d, f) => $(\n            d,\n            d.disabled ? \"disabled\" : f ? \"active\" : \"inactive\"\n          ),\n          maxItems: t.maxItems,\n          output: t.output\n        });\n        return [\n          ...i,\n          ...O.map((d) => `${s}${d}`),\n          ...g\n        ].join(`\n`);\n      }\n    }\n  }\n}).prompt(), autocompleteMultiselect = (t) => {\n  const c = (i, l, o, m) => {\n    const p = o.includes(i.value), $ = i.label ?? String(i.value ?? \"\"), r = i.hint && m !== void 0 && i.value === m ? styleText(\"dim\", ` (${i.hint})`) : \"\", s = p ? styleText(\"green\", S_CHECKBOX_SELECTED) : styleText(\"dim\", S_CHECKBOX_INACTIVE);\n    return i.disabled ? `${styleText(\"gray\", S_CHECKBOX_INACTIVE)} ${styleText([\"strikethrough\", \"gray\"], $)}` : l ? `${s} ${$}${r}` : `${s} ${styleText(\"dim\", $)}`;\n  }, n = new AutocompletePrompt({\n    options: t.options,\n    multiple: true,\n    placeholder: t.placeholder,\n    filter: t.filter ?? ((i, l) => E(i, l)),\n    validate: () => {\n      if (t.required && n.selectedValues.length === 0)\n        return \"Please select at least one item\";\n    },\n    initialValue: t.initialValues,\n    signal: t.signal,\n    input: t.input,\n    output: t.output,\n    render() {\n      const i = t.withGuide ?? settings.withGuide, l = `${i ? `${styleText(\"gray\", S_BAR)}\n` : \"\"}${symbol(this.state)}  ${t.message}\n`, o = this.userInput, m = t.placeholder, p = o === \"\" && m !== void 0, $ = this.isNavigating || p ? styleText(\"dim\", p ? m : o) : this.userInputWithCursor, r = this.options, s = this.filteredOptions.length !== r.length ? styleText(\n        \"dim\",\n        ` (${this.filteredOptions.length} match${this.filteredOptions.length === 1 ? \"\" : \"es\"})`\n      ) : \"\";\n      switch (this.state) {\n        case \"submit\":\n          return `${l}${i ? `${styleText(\"gray\", S_BAR)}  ` : \"\"}${styleText(\n            \"dim\",\n            `${this.selectedValues.length} items selected`\n          )}`;\n        case \"cancel\":\n          return `${l}${i ? `${styleText(\"gray\", S_BAR)}  ` : \"\"}${styleText(\n            [\"strikethrough\", \"dim\"],\n            o\n          )}`;\n        default: {\n          const a = this.state === \"error\" ? \"yellow\" : \"cyan\", u = i ? `${styleText(a, S_BAR)}  ` : \"\", V = i ? styleText(a, S_BAR_END) : \"\", y = [\n            `${styleText(\"dim\", \"\\u2191/\\u2193\")} to navigate`,\n            `${styleText(\"dim\", this.isNavigating ? \"Space/Tab:\" : \"Tab:\")} select`,\n            `${styleText(\"dim\", \"Enter:\")} confirm`,\n            `${styleText(\"dim\", \"Type:\")} to search`\n          ], b = this.filteredOptions.length === 0 && o ? [`${u}${styleText(\"yellow\", \"No matches found\")}`] : [], v = this.state === \"error\" ? [`${u}${styleText(\"yellow\", this.error)}`] : [], g = [\n            ...`${l}${i ? styleText(a, S_BAR) : \"\"}`.split(`\n`),\n            `${u}${styleText(\"dim\", \"Search:\")} ${$}${s}`,\n            ...b,\n            ...v\n          ], O = [`${u}${y.join(\" \\u2022 \")}`, V], d = limitOptions({\n            cursor: this.cursor,\n            options: this.filteredOptions,\n            style: (f, _) => c(f, _, this.selectedValues, this.focusedValue),\n            maxItems: t.maxItems,\n            output: t.output,\n            rowPadding: g.length + O.length\n          });\n          return [\n            ...g,\n            ...d.map((f) => `${u}${f}`),\n            ...O\n          ].join(`\n`);\n        }\n      }\n    }\n  });\n  return n.prompt();\n};\n\nconst J = [\n  S_CORNER_TOP_LEFT,\n  S_CORNER_TOP_RIGHT,\n  S_CORNER_BOTTOM_LEFT,\n  S_CORNER_BOTTOM_RIGHT\n], K = [S_BAR_START, S_BAR_START_RIGHT, S_BAR_END, S_BAR_END_RIGHT];\nfunction A$1(n, e, t, o) {\n  let i = t, f = t;\n  return o === \"center\" ? i = Math.floor((e - n) / 2) : o === \"right\" && (i = e - n - t), f = e - i - n, [i, f];\n}\nconst Q = (n) => n;\nconst box = (n = \"\", e = \"\", t) => {\n  const o = t?.output ?? process.stdout, i = getColumns(o), R = 1 * 2, u = t?.titlePadding ?? 1, h = t?.contentPadding ?? 2, w = t?.width === void 0 || t.width === \"auto\" ? 1 : Math.min(1, t.width), m = t?.withGuide ?? settings.withGuide ? `${S_BAR} ` : \"\", b = t?.formatBorder ?? Q, a = (t?.rounded ? J : K).map(b), _ = b(S_BAR_H), B = b(S_BAR), p = l(m), x = l(e), O = i - p;\n  let r = Math.floor(i * w) - p;\n  if (t?.width === \"auto\") {\n    const c = n.split(`\n`);\n    let s = x + u * 2;\n    for (const G of c) {\n      const P = l(G) + h * 2;\n      P > s && (s = P);\n    }\n    const g = s + R;\n    g < r && (r = g);\n  }\n  r % 2 !== 0 && (r < O ? r++ : r--);\n  const d = r - R, S = d - u * 2, T = x > S ? `${e.slice(0, S - 3)}...` : e, [y, W] = A$1(\n    l(T),\n    d,\n    u,\n    t?.titleAlign\n  ), L = wrapAnsi(n, d - h * 2, {\n    hard: true,\n    trim: false\n  });\n  o.write(\n    `${m}${a[0]}${_.repeat(y)}${T}${_.repeat(W)}${a[1]}\n`\n  );\n  const E = L.split(`\n`);\n  for (const c of E) {\n    const [s, g] = A$1(\n      l(c),\n      d,\n      h,\n      t?.contentAlign\n    );\n    o.write(\n      `${m}${B}${\" \".repeat(s)}${c}${\" \".repeat(g)}${B}\n`\n    );\n  }\n  o.write(`${m}${a[2]}${_.repeat(d)}${a[3]}\n`);\n};\n\nconst confirm = (i) => {\n  const a = i.active ?? \"Yes\", s = i.inactive ?? \"No\";\n  return new ConfirmPrompt({\n    active: a,\n    inactive: s,\n    signal: i.signal,\n    input: i.input,\n    output: i.output,\n    initialValue: i.initialValue ?? true,\n    render() {\n      const e = i.withGuide ?? settings.withGuide, u = `${symbol(this.state)}  `, l = e ? `${styleText(\"gray\", S_BAR)}  ` : \"\", f = wrapTextWithPrefix(\n        i.output,\n        i.message,\n        l,\n        u\n      ), o = `${e ? `${styleText(\"gray\", S_BAR)}\n` : \"\"}${f}\n`, c = this.value ? a : s;\n      switch (this.state) {\n        case \"submit\": {\n          const r = e ? `${styleText(\"gray\", S_BAR)}  ` : \"\";\n          return `${o}${r}${styleText(\"dim\", c)}`;\n        }\n        case \"cancel\": {\n          const r = e ? `${styleText(\"gray\", S_BAR)}  ` : \"\";\n          return `${o}${r}${styleText([\"strikethrough\", \"dim\"], c)}${e ? `\n${styleText(\"gray\", S_BAR)}` : \"\"}`;\n        }\n        default: {\n          const r = e ? `${styleText(\"cyan\", S_BAR)}  ` : \"\", g = e ? styleText(\"cyan\", S_BAR_END) : \"\";\n          return `${o}${r}${this.value ? `${styleText(\"green\", S_RADIO_ACTIVE)} ${a}` : `${styleText(\"dim\", S_RADIO_INACTIVE)} ${styleText(\"dim\", a)}`}${i.vertical ? e ? `\n${styleText(\"cyan\", S_BAR)}  ` : `\n` : ` ${styleText(\"dim\", \"/\")} `}${this.value ? `${styleText(\"dim\", S_RADIO_INACTIVE)} ${styleText(\"dim\", s)}` : `${styleText(\"green\", S_RADIO_ACTIVE)} ${s}`}\n${g}\n`;\n        }\n      }\n    }\n  }).prompt();\n};\n\nconst date = (e) => {\n  const r = e.validate;\n  return new DatePrompt({\n    ...e,\n    validate(t) {\n      if (t === void 0)\n        return e.defaultValue !== void 0 ? void 0 : r ? runValidation(r, t) : settings.date.messages.required;\n      const o = (i) => i.toISOString().slice(0, 10);\n      if (e.minDate && o(t) < o(e.minDate))\n        return settings.date.messages.afterMin(e.minDate);\n      if (e.maxDate && o(t) > o(e.maxDate))\n        return settings.date.messages.beforeMax(e.maxDate);\n      if (r) return runValidation(r, t);\n    },\n    render() {\n      const t = (e?.withGuide ?? settings.withGuide) !== false, i = `${`${t ? `${styleText(\"gray\", S_BAR)}\n` : \"\"}${symbol(this.state)}  `}${e.message}\n`, l = this.state !== \"initial\" ? this.state : \"active\", d = b(this, l), c = this.value instanceof Date ? this.formattedValue : \"\";\n      switch (this.state) {\n        case \"error\": {\n          const a = this.error ? `  ${styleText(\"yellow\", this.error)}` : \"\", s = t ? `${styleText(\"yellow\", S_BAR)}  ` : \"\", f = t ? styleText(\"yellow\", S_BAR_END) : \"\";\n          return `${i.trim()}\n${s}${d}\n${f}${a}\n`;\n        }\n        case \"submit\": {\n          const a = c ? `  ${styleText(\"dim\", c)}` : \"\", s = t ? styleText(\"gray\", S_BAR) : \"\";\n          return `${i}${s}${a}`;\n        }\n        case \"cancel\": {\n          const a = c ? `  ${styleText([\"strikethrough\", \"dim\"], c)}` : \"\", s = t ? styleText(\"gray\", S_BAR) : \"\";\n          return `${i}${s}${a}${c.trim() ? `\n${s}` : \"\"}`;\n        }\n        default: {\n          const a = t ? `${styleText(\"cyan\", S_BAR)}  ` : \"\", s = t ? styleText(\"cyan\", S_BAR_END) : \"\", f = t ? `${styleText(\"cyan\", S_BAR)}  ` : \"\", g = this.inlineError ? `\n${f}${styleText(\"yellow\", this.inlineError)}` : \"\";\n          return `${i}${a}${d}${g}\n${s}\n`;\n        }\n      }\n    }\n  }).prompt();\n};\nfunction b(e, r) {\n  const t = e.segmentValues, o = e.segmentCursor;\n  if (r === \"submit\" || r === \"cancel\")\n    return e.formattedValue;\n  const i = styleText(\"gray\", e.separator);\n  return e.segments.map((l, d) => {\n    const c = d === o.segmentIndex && ![\"submit\", \"cancel\"].includes(r), a = p[l.type];\n    return x(t[l.type], { isActive: c, label: a });\n  }).join(i);\n}\nfunction x(e, r) {\n  const t = !e || e.replace(/_/g, \"\") === \"\";\n  return r.isActive ? styleText(\"inverse\", t ? r.label : e.replace(/_/g, \" \")) : t ? styleText(\"dim\", r.label) : e.replace(/_/g, styleText(\"dim\", \" \"));\n}\nconst p = {\n  year: \"yyyy\",\n  month: \"mm\",\n  day: \"dd\"\n};\n\nconst group = async (o, r) => {\n  const t = {}, p = Object.keys(o);\n  for (const e of p) {\n    const i = o[e], n = await i({ results: t })?.catch((a) => {\n      throw a;\n    });\n    if (typeof r?.onCancel == \"function\" && isCancel(n)) {\n      t[e] = \"canceled\", r.onCancel({ results: t });\n      continue;\n    }\n    t[e] = n;\n  }\n  return t;\n};\n\nconst MULTISELECT_INSTRUCTIONS = [\n  `${styleText(\"dim\", \"\\u2191/\\u2193\")} to navigate`,\n  `${styleText(\"dim\", \"Space:\")} select`,\n  `${styleText(\"dim\", \"Enter:\")} confirm`\n];\nconst m = (i, u) => i.split(`\n`).map((d) => u(d)).join(`\n`);\nconst multiselect = (i) => {\n  const u = (t, a) => {\n    const r = t.label ?? String(t.value);\n    return a === \"disabled\" ? `${styleText(\"gray\", S_CHECKBOX_INACTIVE)} ${m(r, (o) => styleText([\"strikethrough\", \"gray\"], o))}${t.hint ? ` ${styleText(\"dim\", `(${t.hint ?? \"disabled\"})`)}` : \"\"}` : a === \"active\" ? `${styleText(\"cyan\", S_CHECKBOX_ACTIVE)} ${r}${t.hint ? ` ${styleText(\"dim\", `(${t.hint})`)}` : \"\"}` : a === \"selected\" ? `${styleText(\"green\", S_CHECKBOX_SELECTED)} ${m(r, (o) => styleText(\"dim\", o))}${t.hint ? ` ${styleText(\"dim\", `(${t.hint})`)}` : \"\"}` : a === \"cancelled\" ? `${m(r, (o) => styleText([\"strikethrough\", \"dim\"], o))}` : a === \"active-selected\" ? `${styleText(\"green\", S_CHECKBOX_SELECTED)} ${r}${t.hint ? ` ${styleText(\"dim\", `(${t.hint})`)}` : \"\"}` : a === \"submitted\" ? `${m(r, (o) => styleText(\"dim\", o))}` : `${styleText(\"dim\", S_CHECKBOX_INACTIVE)} ${m(r, (o) => styleText(\"dim\", o))}`;\n  }, d = i.required ?? true, v = i.showInstructions ?? true;\n  return new MultiSelectPrompt({\n    options: i.options,\n    signal: i.signal,\n    input: i.input,\n    output: i.output,\n    initialValues: i.initialValues,\n    required: d,\n    cursorAt: i.cursorAt,\n    validate(t) {\n      if (d && (t === void 0 || t.length === 0))\n        return `Please select at least one option.\n${styleText(\n          \"reset\",\n          styleText(\n            \"dim\",\n            `Press ${styleText([\"gray\", \"bgWhite\", \"inverse\"], \" space \")} to select, ${styleText(\n              \"gray\",\n              styleText(\"bgWhite\", styleText(\"inverse\", \" enter \"))\n            )} to submit`\n          )\n        )}`;\n    },\n    render() {\n      const t = i.withGuide ?? settings.withGuide, a = wrapTextWithPrefix(\n        i.output,\n        i.message,\n        t ? `${symbolBar(this.state)}  ` : \"\",\n        `${symbol(this.state)}  `\n      ), r = `${t ? `${styleText(\"gray\", S_BAR)}\n` : \"\"}${a}\n`, o = this.value ?? [], p = (n, l) => {\n        if (n.disabled)\n          return u(n, \"disabled\");\n        const s = o.includes(n.value);\n        return l && s ? u(n, \"active-selected\") : s ? u(n, \"selected\") : u(n, l ? \"active\" : \"inactive\");\n      };\n      switch (this.state) {\n        case \"submit\": {\n          const n = this.options.filter(({ value: s }) => o.includes(s)).map((s) => u(s, \"submitted\")).join(styleText(\"dim\", \", \")) || styleText(\"dim\", \"none\"), l = wrapTextWithPrefix(\n            i.output,\n            n,\n            t ? `${styleText(\"gray\", S_BAR)}  ` : \"\"\n          );\n          return `${r}${l}`;\n        }\n        case \"cancel\": {\n          const n = this.options.filter(({ value: s }) => o.includes(s)).map((s) => u(s, \"cancelled\")).join(styleText(\"dim\", \", \"));\n          if (n.trim() === \"\")\n            return `${r}${styleText(\"gray\", S_BAR)}`;\n          const l = wrapTextWithPrefix(\n            i.output,\n            n,\n            t ? `${styleText(\"gray\", S_BAR)}  ` : \"\"\n          );\n          return `${r}${l}${t ? `\n${styleText(\"gray\", S_BAR)}` : \"\"}`;\n        }\n        case \"error\": {\n          const n = t ? `${styleText(\"yellow\", S_BAR)}  ` : \"\", l = this.error.split(`\n`).map(\n            ($, C) => C === 0 ? `${t ? `${styleText(\"yellow\", S_BAR_END)}  ` : \"\"}${styleText(\"yellow\", $)}` : `   ${$}`\n          ).join(`\n`), s = r.split(`\n`).length, h = l.split(`\n`).length + 1;\n          return `${r}${n}${limitOptions({\n            output: i.output,\n            options: this.options,\n            cursor: this.cursor,\n            maxItems: i.maxItems,\n            columnPadding: n.length,\n            rowPadding: s + h,\n            style: p\n          }).join(`\n${n}`)}\n${l}\n`;\n        }\n        default: {\n          const n = t ? `${styleText(\"cyan\", S_BAR)}  ` : \"\", l = r.split(`\n`).length, s = v ? formatInstructionFooter(MULTISELECT_INSTRUCTIONS, t) : t ? [styleText(\"cyan\", S_BAR_END)] : [], h = s.join(`\n`), $ = s.length + 1;\n          return `${r}${n}${limitOptions({\n            output: i.output,\n            options: this.options,\n            cursor: this.cursor,\n            maxItems: i.maxItems,\n            columnPadding: n.length,\n            rowPadding: l + $,\n            style: p\n          }).join(`\n${n}`)}\n${h}\n`;\n        }\n      }\n    }\n  }).prompt();\n};\n\nconst groupMultiselect = (o) => {\n  const { selectableGroups: h = true, groupSpacing: x = 0 } = o, m = (n, l, g = []) => {\n    const a = n.label ?? String(n.value), t = typeof n.group == \"string\", s = t && (g[g.indexOf(n) + 1] ?? { group: true }), u = t && s && s.group === true;\n    let r = \"\", c = \"\";\n    t && (h ? (r = u ? `${S_BAR_END} ` : `${S_BAR} `, c = u ? \"  \" : `${S_BAR} `) : r = \"  \");\n    let i = \"\";\n    if (x > 0 && !t && (i = `\n`.repeat(x)), l === \"active\")\n      return wrapTextWithPrefix(\n        o.output,\n        `${a}${n.hint ? ` ${styleText(\"dim\", `(${n.hint})`)}` : \"\"}`,\n        `${i}${styleText(\"dim\", r)} `,\n        `${i}${styleText(\"dim\", r)}${styleText(\"cyan\", S_CHECKBOX_ACTIVE)} `,\n        `${i}${styleText(\"dim\", c)} `\n      );\n    if (l === \"group-active\")\n      return wrapTextWithPrefix(\n        o.output,\n        a,\n        `${i}${r} `,\n        `${i}${r}${styleText(\"cyan\", S_CHECKBOX_ACTIVE)} `,\n        `${i}${c} `,\n        (d) => styleText(\"dim\", d)\n      );\n    if (l === \"group-active-selected\")\n      return wrapTextWithPrefix(\n        o.output,\n        a,\n        `${i}${r} `,\n        `${i}${r}${styleText(\"green\", S_CHECKBOX_SELECTED)} `,\n        `${i}${c} `,\n        (d) => styleText(\"dim\", d)\n      );\n    if (l === \"selected\") {\n      const d = t || h ? styleText(\"green\", S_CHECKBOX_SELECTED) : \"\";\n      return wrapTextWithPrefix(\n        o.output,\n        `${a}${n.hint ? ` (${n.hint})` : \"\"}`,\n        `${i}${styleText(\"dim\", r)} `,\n        `${i}${styleText(\"dim\", r)}${d} `,\n        `${i}${styleText(\"dim\", c)} `,\n        (S) => styleText(\"dim\", S)\n      );\n    }\n    if (l === \"cancelled\")\n      return `${styleText([\"strikethrough\", \"dim\"], a)}`;\n    if (l === \"active-selected\")\n      return wrapTextWithPrefix(\n        o.output,\n        `${a}${n.hint ? ` ${styleText(\"dim\", `(${n.hint})`)}` : \"\"}`,\n        `${i}${styleText(\"dim\", r)} `,\n        `${i}${styleText(\"dim\", r)}${styleText(\"green\", S_CHECKBOX_SELECTED)} `,\n        `${i}${styleText(\"dim\", c)} `\n      );\n    if (l === \"submitted\")\n      return `${styleText(\"dim\", a)}`;\n    const f = t || h ? styleText(\"dim\", S_CHECKBOX_INACTIVE) : \"\";\n    return wrapTextWithPrefix(\n      o.output,\n      a,\n      `${i}${styleText(\"dim\", r)} `,\n      `${i}${styleText(\"dim\", r)}${f} `,\n      `${i}${styleText(\"dim\", c)} `,\n      (d) => styleText(\"dim\", d)\n    );\n  }, y = o.required ?? true, I = o.showInstructions ?? true;\n  return new GroupMultiSelectPrompt({\n    options: o.options,\n    signal: o.signal,\n    input: o.input,\n    output: o.output,\n    initialValues: o.initialValues,\n    required: y,\n    cursorAt: o.cursorAt,\n    selectableGroups: h,\n    validate(n) {\n      if (y && (n === void 0 || n.length === 0))\n        return `Please select at least one option.\n${styleText(\n          \"reset\",\n          styleText(\n            \"dim\",\n            `Press ${styleText([\"gray\", \"bgWhite\", \"inverse\"], \" space \")} to select, ${styleText(\n              \"gray\",\n              styleText([\"bgWhite\", \"inverse\"], \" enter \")\n            )} to submit`\n          )\n        )}`;\n    },\n    render() {\n      const n = o.withGuide ?? settings.withGuide, l = `${n ? `${styleText(\"gray\", S_BAR)}\n` : \"\"}${symbol(this.state)}  ${o.message}\n`, g = this.value ?? [], a = (t, s) => {\n        const u = this.options, r = g.includes(t.value) || t.group === true && this.isGroupSelected(`${t.value}`);\n        return !s && typeof t.group == \"string\" && this.options[this.cursor]?.value === t.group ? m(t, r ? \"group-active-selected\" : \"group-active\", u) : s && r ? m(t, \"active-selected\", u) : r ? m(t, \"selected\", u) : m(t, s ? \"active\" : \"inactive\", u);\n      };\n      switch (this.state) {\n        case \"submit\": {\n          const t = this.options.filter(({ value: u }) => g.includes(u)).map((u) => m(u, \"submitted\")), s = t.length === 0 ? \"\" : `  ${t.join(styleText(\"dim\", \", \"))}`;\n          return `${l}${n ? styleText(\"gray\", S_BAR) : \"\"}${s}`;\n        }\n        case \"cancel\": {\n          const t = this.options.filter(({ value: s }) => g.includes(s)).map((s) => m(s, \"cancelled\")).join(styleText(\"dim\", \", \"));\n          return `${l}${n ? `${styleText(\"gray\", S_BAR)}  ` : \"\"}${t.trim() ? `${t}${n ? `\n${styleText(\"gray\", S_BAR)}` : \"\"}` : \"\"}`;\n        }\n        case \"error\": {\n          const t = n ? `${styleText(\"yellow\", S_BAR)}  ` : \"\", s = this.error.split(`\n`).map(\n            (i, f) => f === 0 ? `${n ? `${styleText(\"yellow\", S_BAR_END)}  ` : \"\"}${styleText(\"yellow\", i)}` : `   ${i}`\n          ).join(`\n`), u = l.split(`\n`).length, r = s.split(`\n`).length + 1, c = limitOptions({\n            output: o.output,\n            options: this.options,\n            cursor: this.cursor,\n            maxItems: o.maxItems,\n            columnPadding: t.length,\n            rowPadding: u + r,\n            style: a\n          }).join(`\n${t}`);\n          return `${l}${t}${c}\n${s}\n`;\n        }\n        default: {\n          const t = n ? `${styleText(\"cyan\", S_BAR)}  ` : \"\", s = l.split(`\n`).length, u = I ? formatInstructionFooter(MULTISELECT_INSTRUCTIONS, n) : n ? [styleText(\"cyan\", S_BAR_END)] : [], r = u.join(`\n`), c = u.length + 1, i = limitOptions({\n            output: o.output,\n            options: this.options,\n            cursor: this.cursor,\n            maxItems: o.maxItems,\n            columnPadding: t.length,\n            rowPadding: s + c,\n            style: a\n          }).join(`\n${t}`);\n          return `${l}${t}${i}\n${r}\n`;\n        }\n      }\n    }\n  }).prompt();\n};\n\nconst log = {\n  message: (s = [], {\n    symbol: e = styleText(\"gray\", S_BAR),\n    secondarySymbol: r = styleText(\"gray\", S_BAR),\n    output: m = process.stdout,\n    spacing: l = 1,\n    withGuide: c\n  } = {}) => {\n    const t = [], o = c ?? settings.withGuide, f = o ? r : \"\", O = o ? `${e}  ` : \"\", u = o ? `${r}  ` : \"\";\n    for (let i = 0; i < l; i++)\n      t.push(f);\n    const g = Array.isArray(s) ? s : s.split(`\n`);\n    if (g.length > 0) {\n      const [i, ...y] = g;\n      i.length > 0 ? t.push(`${O}${i}`) : t.push(o ? e : \"\");\n      for (const p of y)\n        p.length > 0 ? t.push(`${u}${p}`) : t.push(o ? r : \"\");\n    }\n    m.write(`${t.join(`\n`)}\n`);\n  },\n  info: (s, e) => {\n    log.message(s, { ...e, symbol: styleText(\"blue\", S_INFO) });\n  },\n  success: (s, e) => {\n    log.message(s, { ...e, symbol: styleText(\"green\", S_SUCCESS) });\n  },\n  step: (s, e) => {\n    log.message(s, { ...e, symbol: styleText(\"green\", S_STEP_SUBMIT) });\n  },\n  warn: (s, e) => {\n    log.message(s, { ...e, symbol: styleText(\"yellow\", S_WARN) });\n  },\n  /** alias for `log.warn()`. */\n  warning: (s, e) => {\n    log.warn(s, e);\n  },\n  error: (s, e) => {\n    log.message(s, { ...e, symbol: styleText(\"red\", S_ERROR) });\n  }\n};\n\nconst cancel = (o = \"\", t) => {\n  const i = t?.output ?? process.stdout, e = t?.withGuide ?? settings.withGuide ? `${styleText(\"gray\", S_BAR_END)}  ` : \"\";\n  i.write(`${e}${styleText(\"red\", o)}\n\n`);\n}, intro = (o = \"\", t) => {\n  const i = t?.output ?? process.stdout, e = t?.withGuide ?? settings.withGuide ? `${styleText(\"gray\", S_BAR_START)}  ` : \"\";\n  i.write(`${e}${o}\n`);\n}, outro = (o = \"\", t) => {\n  const i = t?.output ?? process.stdout, e = t?.withGuide ?? settings.withGuide ? `${styleText(\"gray\", S_BAR)}\n${styleText(\"gray\", S_BAR_END)}  ` : \"\";\n  i.write(`${e}${o}\n\n`);\n};\n\nconst multiline = (e) => new MultiLinePrompt({\n  validate: e.validate,\n  placeholder: e.placeholder,\n  defaultValue: e.defaultValue,\n  initialValue: e.initialValue,\n  showSubmit: e.showSubmit,\n  output: e.output,\n  signal: e.signal,\n  input: e.input,\n  render() {\n    const i = e?.withGuide ?? settings.withGuide, o = `${`${i ? `${styleText(\"gray\", S_BAR)}\n` : \"\"}${symbol(this.state)}  `}${e.message}\n`, m = e.placeholder && e.placeholder.length > 0 ? (\n      // biome-ignore lint/style/noNonNullAssertion: guarded by placeholder.length > 0\n      styleText(\"inverse\", e.placeholder[0]) + styleText(\"dim\", e.placeholder.slice(1))\n    ) : styleText([\"inverse\", \"hidden\"], \"_\"), a = this.userInput ? this.userInputWithCursor : m, l = this.value ?? \"\", c = e.showSubmit ? `\n  ${styleText(this.focused === \"submit\" ? \"cyan\" : \"dim\", \"[ submit ]\")}` : \"\";\n    switch (this.state) {\n      case \"error\": {\n        const n = `${styleText(\"yellow\", S_BAR)}  `, r = i ? wrapTextWithPrefix(e.output, a, n, void 0) : a, u = styleText(\"yellow\", S_BAR_END);\n        return `${o}${r}\n${u}  ${styleText(\"yellow\", this.error)}${c}\n`;\n      }\n      case \"submit\": {\n        const n = `${styleText(\"gray\", S_BAR)}  `, r = i ? wrapTextWithPrefix(\n          e.output,\n          l,\n          n,\n          void 0,\n          void 0,\n          (u) => styleText(\"dim\", u)\n        ) : l ? styleText(\"dim\", l) : \"\";\n        return `${o}${r}`;\n      }\n      case \"cancel\": {\n        const n = `${styleText(\"gray\", S_BAR)}  `, r = i ? wrapTextWithPrefix(\n          e.output,\n          l,\n          n,\n          void 0,\n          void 0,\n          (u) => styleText([\"strikethrough\", \"dim\"], u)\n        ) : l ? styleText([\"strikethrough\", \"dim\"], l) : \"\";\n        return `${o}${r}`;\n      }\n      default: {\n        const n = i ? `${styleText(\"cyan\", S_BAR)}  ` : \"\", r = i ? styleText(\"cyan\", S_BAR_END) : \"\", u = i ? wrapTextWithPrefix(e.output, a, n) : a;\n        return `${o}${u}\n${r}${c}\n`;\n      }\n    }\n  }\n}).prompt();\n\nconst W$1 = (o) => o, C = (o, e, s) => {\n  const a = {\n    hard: true,\n    trim: false\n  }, i = wrapAnsi(o, e, a).split(`\n`), c = i.reduce((n, t) => Math.max(l(t), n), 0), u = i.map(s).reduce((n, t) => Math.max(l(t), n), 0), g = e - (u - c);\n  return wrapAnsi(o, g, a);\n};\nconst note = (o = \"\", e = \"\", s) => {\n  const a = s?.output ?? process$1.stdout, i = s?.withGuide ?? settings.withGuide, c = s?.format ?? W$1, g = [\"\", ...C(o, getColumns(a) - 6, c).split(`\n`).map(c), \"\"], n = l(e), t = Math.max(\n    g.reduce((m, F) => {\n      const O = l(F);\n      return O > m ? O : m;\n    }, 0),\n    n\n  ) + 2, h = g.map(\n    (m) => `${styleText(\"gray\", S_BAR)}  ${m}${\" \".repeat(t - l(m))}${styleText(\"gray\", S_BAR)}`\n  ).join(`\n`), T = i ? `${styleText(\"gray\", S_BAR)}\n` : \"\", l$1 = i ? S_CONNECT_LEFT : S_CORNER_BOTTOM_LEFT;\n  a.write(\n    `${T}${styleText(\"green\", S_STEP_SUBMIT)}  ${styleText(\"reset\", e)} ${styleText(\n      \"gray\",\n      S_BAR_H.repeat(Math.max(t - n - 1, 1)) + S_CORNER_TOP_RIGHT\n    )}\n${h}\n${styleText(\"gray\", l$1 + S_BAR_H.repeat(t + 2) + S_CORNER_BOTTOM_RIGHT)}\n`\n  );\n};\n\nconst password = (r) => new PasswordPrompt({\n  validate: r.validate,\n  mask: r.mask ?? S_PASSWORD_MASK,\n  signal: r.signal,\n  input: r.input,\n  output: r.output,\n  render() {\n    const e = r.withGuide ?? settings.withGuide, o = `${e ? `${styleText(\"gray\", S_BAR)}\n` : \"\"}${symbol(this.state)}  ${r.message}\n`, c = this.userInputWithCursor, i = this.masked;\n    switch (this.state) {\n      case \"error\": {\n        const s = e ? `${styleText(\"yellow\", S_BAR)}  ` : \"\", n = e ? `${styleText(\"yellow\", S_BAR_END)}  ` : \"\", l = i ?? \"\";\n        return r.clearOnError && this.clear(), `${o.trim()}\n${s}${l}\n${n}${styleText(\"yellow\", this.error)}\n`;\n      }\n      case \"submit\": {\n        const s = e ? `${styleText(\"gray\", S_BAR)}  ` : \"\", n = i ? styleText(\"dim\", i) : \"\";\n        return `${o}${s}${n}`;\n      }\n      case \"cancel\": {\n        const s = e ? `${styleText(\"gray\", S_BAR)}  ` : \"\", n = i ? styleText([\"strikethrough\", \"dim\"], i) : \"\";\n        return `${o}${s}${n}${i && e ? `\n${styleText(\"gray\", S_BAR)}` : \"\"}`;\n      }\n      default: {\n        const s = e ? `${styleText(\"cyan\", S_BAR)}  ` : \"\", n = e ? styleText(\"cyan\", S_BAR_END) : \"\";\n        return `${o}${s}${c}\n${n}\n`;\n      }\n    }\n  }\n}).prompt();\n\nconst path = (e) => {\n  const a = e.validate;\n  return autocomplete({\n    ...e,\n    initialUserInput: e.initialValue ?? e.root ?? process.cwd(),\n    maxItems: 5,\n    validate(t) {\n      if (!Array.isArray(t)) {\n        if (!t)\n          return \"Please select a path\";\n        if (a)\n          return runValidation(a, t);\n      }\n    },\n    options() {\n      const t = this.userInput;\n      if (t === \"\")\n        return [];\n      try {\n        let i;\n        existsSync(t) ? lstatSync(t).isDirectory() && (!e.directory || t.endsWith(\"/\")) ? i = t : i = dirname(t) : i = dirname(t);\n        const c = t.length > 1 && t.endsWith(\"/\") ? t.slice(0, -1) : t;\n        return readdirSync(i).map((r) => {\n          const n = join(i, r), m = lstatSync(n);\n          return {\n            name: r,\n            path: n,\n            isDirectory: m.isDirectory()\n          };\n        }).filter(\n          ({ path: r, isDirectory: n }) => r.startsWith(c) && (n || !e.directory)\n        ).map((r) => ({\n          value: r.path\n        }));\n      } catch {\n        return [];\n      }\n    }\n  });\n};\n\nconst W = (l) => styleText(\"magenta\", l);\nconst spinner = ({\n  indicator: l = \"dots\",\n  onCancel: h,\n  output: n = process.stdout,\n  cancelMessage: G,\n  errorMessage: O,\n  frames: E = unicode ? [\"\\u25D2\", \"\\u25D0\", \"\\u25D3\", \"\\u25D1\"] : [\"\\u2022\", \"o\", \"O\", \"0\"],\n  delay: F = unicode ? 80 : 120,\n  signal: m,\n  ...I\n} = {}) => {\n  const u = isCI();\n  let M, T, d = false, S = false, s = \"\", p, w = performance.now();\n  const x = getColumns(n), k = I?.styleFrame ?? W, g = (e) => {\n    const r = e > 1 ? O ?? settings.messages.error : G ?? settings.messages.cancel;\n    S = e === 1, d && (a(r, e), S && typeof h == \"function\" && h());\n  }, f = () => g(2), i = () => g(1), A = () => {\n    process.on(\"uncaughtExceptionMonitor\", f), process.on(\"unhandledRejection\", f), process.on(\"SIGINT\", i), process.on(\"SIGTERM\", i), process.on(\"exit\", g), m && m.addEventListener(\"abort\", i);\n  }, H = () => {\n    process.removeListener(\"uncaughtExceptionMonitor\", f), process.removeListener(\"unhandledRejection\", f), process.removeListener(\"SIGINT\", i), process.removeListener(\"SIGTERM\", i), process.removeListener(\"exit\", g), m && m.removeEventListener(\"abort\", i);\n  }, y = () => {\n    if (p === void 0) return;\n    u && n.write(`\n`);\n    const r = wrapAnsi(p, x, {\n      hard: true,\n      trim: false\n    }).split(`\n`);\n    r.length > 1 && n.write(cursor.up(r.length - 1)), n.write(cursor.to(0)), n.write(erase.down());\n  }, C = (e) => e.replace(/\\.+$/, \"\"), _ = (e) => {\n    const r = (performance.now() - e) / 1e3, t = Math.floor(r / 60), o = Math.floor(r % 60);\n    return t > 0 ? `[${t}m ${o}s]` : `[${o}s]`;\n  }, N = I.withGuide ?? settings.withGuide, P = (e = \"\") => {\n    d = true, M = block({ output: n }), s = C(e), w = performance.now(), N && n.write(`${styleText(\"gray\", S_BAR)}\n`);\n    let r = 0, t = 0;\n    A(), T = setInterval(() => {\n      if (u && s === p)\n        return;\n      y(), p = s;\n      const o = k(E[r]);\n      let v;\n      if (u)\n        v = `${o}  ${s}...`;\n      else if (l === \"timer\")\n        v = `${o}  ${s} ${_(w)}`;\n      else {\n        const B = \".\".repeat(Math.floor(t)).slice(0, 3);\n        v = `${o}  ${s}${B}`;\n      }\n      const j = wrapAnsi(v, x, {\n        hard: true,\n        trim: false\n      });\n      n.write(j), r = r + 1 < E.length ? r + 1 : 0, t = t < 4 ? t + 0.125 : 0;\n    }, F);\n  }, a = (e = \"\", r = 0, t = false) => {\n    if (!d) return;\n    d = false, clearInterval(T), y();\n    const o = r === 0 ? styleText(\"green\", S_STEP_SUBMIT) : r === 1 ? styleText(\"red\", S_STEP_CANCEL) : styleText(\"red\", S_STEP_ERROR);\n    s = e ?? s, t || (l === \"timer\" ? n.write(`${o}  ${s} ${_(w)}\n`) : n.write(`${o}  ${s}\n`)), H(), M();\n  };\n  return {\n    start: P,\n    stop: (e = \"\") => a(e, 0),\n    message: (e = \"\") => {\n      s = C(e ?? s);\n    },\n    cancel: (e = \"\") => a(e, 1),\n    error: (e = \"\") => a(e, 2),\n    clear: () => a(\"\", 0, true),\n    get isCancelled() {\n      return S;\n    }\n  };\n};\n\nconst u = {\n  light: unicodeOr(\"\\u2500\", \"-\"),\n  heavy: unicodeOr(\"\\u2501\", \"=\"),\n  block: unicodeOr(\"\\u2588\", \"#\")\n};\nfunction progress({\n  style: o = \"heavy\",\n  max: d = 100,\n  size: v = 40,\n  ...x\n} = {}) {\n  const r = spinner(x);\n  let a = 0, n = \"\";\n  const c = Math.max(1, d), l = Math.max(1, v), S = (t) => {\n    switch (t) {\n      case \"initial\":\n      case \"active\":\n        return (e) => styleText(\"magenta\", e);\n      case \"error\":\n      case \"cancel\":\n        return (e) => styleText(\"red\", e);\n      case \"submit\":\n        return (e) => styleText(\"green\", e);\n      default:\n        return (e) => styleText(\"magenta\", e);\n    }\n  }, p = (t, e) => {\n    const m = Math.floor(a / c * l);\n    return `${S(t)(u[o].repeat(m))}${styleText(\"dim\", u[o].repeat(l - m))} ${e}`;\n  }, h = (t = \"\") => {\n    n = t, r.start(p(\"initial\", t));\n  }, g = (t = 1, e) => {\n    a = Math.min(c, t + a), r.message(p(\"active\", e ?? n)), n = e ?? n;\n  };\n  return {\n    start: h,\n    stop: r.stop,\n    cancel: r.cancel,\n    error: r.error,\n    clear: r.clear,\n    advance: g,\n    isCancelled: r.isCancelled,\n    message: (t) => g(0, t)\n  };\n}\n\nconst SELECT_INSTRUCTIONS = [\n  `${styleText(\"dim\", \"\\u2191/\\u2193\")} to navigate`,\n  `${styleText(\"dim\", \"Enter:\")} confirm`\n];\nconst c = (t, o) => t.includes(`\n`) ? t.split(`\n`).map((d) => o(d)).join(`\n`) : o(t);\nconst select = (t) => {\n  const o = (n, m) => {\n    if (n === void 0)\n      return \"\";\n    const s = n.label ?? String(n.value);\n    switch (m) {\n      case \"disabled\":\n        return `${styleText(\"gray\", S_RADIO_INACTIVE)} ${c(s, (i) => styleText(\"gray\", i))}${n.hint ? ` ${styleText(\"dim\", `(${n.hint ?? \"disabled\"})`)}` : \"\"}`;\n      case \"selected\":\n        return `${c(s, (i) => styleText(\"dim\", i))}`;\n      case \"active\":\n        return `${styleText(\"green\", S_RADIO_ACTIVE)} ${s}${n.hint ? ` ${styleText(\"dim\", `(${n.hint})`)}` : \"\"}`;\n      case \"cancelled\":\n        return `${c(s, (i) => styleText([\"strikethrough\", \"dim\"], i))}`;\n      default:\n        return `${styleText(\"dim\", S_RADIO_INACTIVE)} ${c(s, (i) => styleText(\"dim\", i))}`;\n    }\n  }, d = t.showInstructions ?? true;\n  return new SelectPrompt({\n    options: t.options,\n    signal: t.signal,\n    input: t.input,\n    output: t.output,\n    initialValue: t.initialValue,\n    render() {\n      const n = t.withGuide ?? settings.withGuide, m = `${symbol(this.state)}  `, s = `${symbolBar(this.state)}  `, i = wrapTextWithPrefix(\n        t.output,\n        t.message,\n        s,\n        m\n      ), u = `${n ? `${styleText(\"gray\", S_BAR)}\n` : \"\"}${i}\n`;\n      switch (this.state) {\n        case \"submit\": {\n          const r = n ? `${styleText(\"gray\", S_BAR)}  ` : \"\", a = wrapTextWithPrefix(\n            t.output,\n            o(this.options[this.cursor], \"selected\"),\n            r\n          );\n          return `${u}${a}`;\n        }\n        case \"cancel\": {\n          const r = n ? `${styleText(\"gray\", S_BAR)}  ` : \"\", a = wrapTextWithPrefix(\n            t.output,\n            o(this.options[this.cursor], \"cancelled\"),\n            r\n          );\n          return `${u}${a}${n ? `\n${styleText(\"gray\", S_BAR)}` : \"\"}`;\n        }\n        default: {\n          const r = n ? `${styleText(\"cyan\", S_BAR)}  ` : \"\", a = u.split(`\n`).length, p = d ? formatInstructionFooter(SELECT_INSTRUCTIONS, n) : n ? [styleText(\"cyan\", S_BAR_END)] : [], b = p.join(`\n`), f = p.length + 1;\n          return `${u}${r}${limitOptions({\n            output: t.output,\n            cursor: this.cursor,\n            options: this.options,\n            maxItems: t.maxItems,\n            columnPadding: r.length,\n            rowPadding: a + f,\n            style: (g, x) => o(g, g.disabled ? \"disabled\" : x ? \"active\" : \"inactive\")\n          }).join(`\n${r}`)}\n${b}\n`;\n        }\n      }\n    }\n  }).prompt();\n};\n\nconst selectKey = (t) => {\n  const l = (e, a = \"inactive\") => {\n    if (e === void 0)\n      return \"\";\n    const n = e.label ?? String(e.value);\n    return a === \"selected\" ? `${styleText(\"dim\", n)}` : a === \"cancelled\" ? `${styleText([\"strikethrough\", \"dim\"], n)}` : a === \"active\" ? `${styleText([\"bgCyan\", \"gray\"], ` ${e.value} `)} ${n}${e.hint ? ` ${styleText(\"dim\", `(${e.hint})`)}` : \"\"}` : `${styleText([\"gray\", \"bgWhite\", \"inverse\"], ` ${e.value} `)} ${n}${e.hint ? ` ${styleText(\"dim\", `(${e.hint})`)}` : \"\"}`;\n  };\n  return new SelectKeyPrompt({\n    options: t.options,\n    signal: t.signal,\n    input: t.input,\n    output: t.output,\n    initialValue: t.initialValue,\n    caseSensitive: t.caseSensitive,\n    render() {\n      const e = t.withGuide ?? settings.withGuide, a = `${e ? `${styleText(\"gray\", S_BAR)}\n` : \"\"}${symbol(this.state)}  ${t.message}\n`;\n      switch (this.state) {\n        case \"submit\": {\n          const n = e ? `${styleText(\"gray\", S_BAR)}  ` : \"\", s = this.options.find((u) => u.value === this.value) ?? t.options[0], c = wrapTextWithPrefix(\n            t.output,\n            l(s, \"selected\"),\n            n\n          );\n          return `${a}${c}`;\n        }\n        case \"cancel\": {\n          const n = e ? `${styleText(\"gray\", S_BAR)}  ` : \"\", s = wrapTextWithPrefix(\n            t.output,\n            l(this.options[0], \"cancelled\"),\n            n\n          );\n          return `${a}${s}${e ? `\n${styleText(\"gray\", S_BAR)}` : \"\"}`;\n        }\n        default: {\n          const n = e ? `${styleText(\"cyan\", S_BAR)}  ` : \"\", s = e ? styleText(\"cyan\", S_BAR_END) : \"\", c = this.options.map(\n            (u, d) => wrapTextWithPrefix(\n              t.output,\n              l(u, d === this.cursor ? \"active\" : \"inactive\"),\n              n\n            )\n          ).join(`\n`);\n          return `${a}${c}\n${s}\n`;\n        }\n      }\n    }\n  }).prompt();\n};\n\nconst i = `${styleText(\"gray\", S_BAR)}  `;\nconst stream = {\n  message: async (e, { symbol: l = styleText(\"gray\", S_BAR) } = {}) => {\n    process.stdout.write(`${styleText(\"gray\", S_BAR)}\n${l}  `);\n    let s = 3;\n    for await (let r of e) {\n      r = r.replace(/\\n/g, `\n${i}`), r.includes(`\n`) && (s = 3 + stripVTControlCharacters(r.slice(r.lastIndexOf(`\n`))).length);\n      const o = stripVTControlCharacters(r).length;\n      s + o < process.stdout.columns ? (s += o, process.stdout.write(r)) : (process.stdout.write(`\n${i}${r.trimStart()}`), s = 3 + stripVTControlCharacters(r.trimStart()).length);\n    }\n    process.stdout.write(`\n`);\n  },\n  info: (e) => stream.message(e, { symbol: styleText(\"blue\", S_INFO) }),\n  success: (e) => stream.message(e, { symbol: styleText(\"green\", S_SUCCESS) }),\n  step: (e) => stream.message(e, { symbol: styleText(\"green\", S_STEP_SUBMIT) }),\n  warn: (e) => stream.message(e, { symbol: styleText(\"yellow\", S_WARN) }),\n  /** alias for `log.warn()`. */\n  warning: (e) => stream.warn(e),\n  error: (e) => stream.message(e, { symbol: styleText(\"red\", S_ERROR) })\n};\n\nconst tasks = async (o, e) => {\n  for (const t of o) {\n    if (t.enabled === false) continue;\n    const s = spinner(e);\n    s.start(t.title);\n    const n = await t.task(s.message);\n    s.stop(n || t.title);\n  }\n};\n\nconst A = (l) => l.replace(/\\x1b\\[(?:\\d+;)*\\d*[ABCDEFGHfJKSTsu]|\\x1b\\[(s|u)/g, \"\");\nconst taskLog = (l) => {\n  const r = l.output ?? process.stdout, O = getColumns(r), i = styleText(\"gray\", S_BAR), p = l.spacing ?? 1, k = 3, m = l.retainLog === true, d = !isCI() && isTTY(r);\n  r.write(`${i}\n`), r.write(`${styleText(\"green\", S_STEP_SUBMIT)}  ${l.title}\n`);\n  for (let e = 0; e < p; e++)\n    r.write(`${i}\n`);\n  const n = [\n    {\n      value: \"\",\n      full: \"\"\n    }\n  ];\n  let v = false;\n  const f = (e) => {\n    if (n.length === 0)\n      return;\n    let s = 0;\n    e && (s += p + 2);\n    for (const t of n) {\n      const { value: o, result: a } = t;\n      let g = a?.message ?? o;\n      if (g.length === 0)\n        continue;\n      a === void 0 && t.header !== void 0 && t.header !== \"\" && (g += `\n${t.header}`);\n      const E = g.split(`\n`).reduce((b, w) => w === \"\" ? b + 1 : b + Math.ceil((w.length + k) / O), 0);\n      s += E;\n    }\n    s > 0 && (s += 1, r.write(erase.lines(s)));\n  }, h = (e, s, t) => {\n    const o = t ? `${e.full}\n${e.value}` : e.value;\n    e.header !== void 0 && e.header !== \"\" && log.message(\n      e.header.split(`\n`).map((a) => styleText(\"bold\", a)),\n      {\n        output: r,\n        secondarySymbol: i,\n        symbol: i,\n        spacing: 0\n      }\n    ), log.message(\n      o.split(`\n`).map((a) => styleText(\"dim\", a)),\n      {\n        output: r,\n        secondarySymbol: i,\n        symbol: i,\n        spacing: s ?? p\n      }\n    );\n  }, T = () => {\n    for (const e of n) {\n      const { header: s, value: t, full: o } = e;\n      (s === void 0 || s.length === 0) && t.length === 0 || h(e, void 0, m === true && o.length > 0);\n    }\n  }, L = (e, s, t) => {\n    if (f(false), (t?.raw !== true || !v) && e.value !== \"\" && (e.value += `\n`), e.value += A(s), v = t?.raw === true, l.limit !== void 0) {\n      const o = e.value.split(`\n`), a = o.length - l.limit;\n      if (a > 0) {\n        const g = o.splice(0, a);\n        m && (e.full += (e.full === \"\" ? \"\" : `\n`) + g.join(`\n`));\n      }\n      e.value = o.join(`\n`);\n    }\n    d && y();\n  }, y = () => {\n    for (const e of n)\n      e.result ? e.result.status === \"error\" ? log.error(e.result.message, { output: r, secondarySymbol: i, spacing: 0 }) : log.success(e.result.message, { output: r, secondarySymbol: i, spacing: 0 }) : e.value !== \"\" && h(e, 0);\n  }, B = (e, s) => {\n    f(false), e.result = s, d && y();\n  };\n  return {\n    message(e, s) {\n      L(n[0], e, s);\n    },\n    group(e) {\n      const s = {\n        header: e,\n        value: \"\",\n        full: \"\"\n      };\n      return n.push(s), {\n        message(t, o) {\n          L(s, t, o);\n        },\n        error(t) {\n          B(s, {\n            status: \"error\",\n            message: t\n          });\n        },\n        success(t) {\n          B(s, {\n            status: \"success\",\n            message: t\n          });\n        }\n      };\n    },\n    error(e, s) {\n      f(true), log.error(e, { output: r, secondarySymbol: i, spacing: 1 }), s?.showLog !== false && T(), n.splice(1, n.length - 1), n[0].value = \"\", n[0].full = \"\";\n    },\n    success(e, s) {\n      f(true), log.success(e, { output: r, secondarySymbol: i, spacing: 1 }), s?.showLog === true && T(), n.splice(1, n.length - 1), n[0].value = \"\", n[0].full = \"\";\n    }\n  };\n};\n\nconst text = (e) => new TextPrompt({\n  validate: e.validate,\n  placeholder: e.placeholder,\n  defaultValue: e.defaultValue,\n  initialValue: e.initialValue,\n  output: e.output,\n  signal: e.signal,\n  input: e.input,\n  render() {\n    const i = e?.withGuide ?? settings.withGuide, s = `${`${i ? `${styleText(\"gray\", S_BAR)}\n` : \"\"}${symbol(this.state)}  `}${e.message}\n`, c = e.placeholder && e.placeholder.length > 0 ? (\n      // biome-ignore lint/style/noNonNullAssertion: guarded by placeholder.length > 0\n      styleText(\"inverse\", e.placeholder[0]) + styleText(\"dim\", e.placeholder.slice(1))\n    ) : styleText([\"inverse\", \"hidden\"], \"_\"), o = this.userInput ? this.userInputWithCursor : c, l = this.value ?? \"\";\n    switch (this.state) {\n      case \"error\": {\n        const n = this.error ? `  ${styleText(\"yellow\", this.error)}` : \"\", r = i ? `${styleText(\"yellow\", S_BAR)}  ` : \"\", d = i ? styleText(\"yellow\", S_BAR_END) : \"\";\n        return `${s.trim()}\n${r}${o}\n${d}${n}\n`;\n      }\n      case \"submit\": {\n        const n = l ? `  ${styleText(\"dim\", l)}` : \"\", r = i ? styleText(\"gray\", S_BAR) : \"\";\n        return `${s}${r}${n}`;\n      }\n      case \"cancel\": {\n        const n = l ? `  ${styleText([\"strikethrough\", \"dim\"], l)}` : \"\", r = i ? styleText(\"gray\", S_BAR) : \"\";\n        return `${s}${r}${n}${l.trim() ? `\n${r}` : \"\"}`;\n      }\n      default: {\n        const n = i ? `${styleText(\"cyan\", S_BAR)}  ` : \"\", r = i ? styleText(\"cyan\", S_BAR_END) : \"\";\n        return `${s}${n}${o}\n${r}\n`;\n      }\n    }\n  }\n}).prompt();\n\nexport { MULTISELECT_INSTRUCTIONS, SELECT_INSTRUCTIONS, S_BAR, S_BAR_END, S_BAR_END_RIGHT, S_BAR_H, S_BAR_START, S_BAR_START_RIGHT, S_CHECKBOX_ACTIVE, S_CHECKBOX_INACTIVE, S_CHECKBOX_SELECTED, S_CONNECT_LEFT, S_CORNER_BOTTOM_LEFT, S_CORNER_BOTTOM_RIGHT, S_CORNER_TOP_LEFT, S_CORNER_TOP_RIGHT, S_ERROR, S_INFO, S_PASSWORD_MASK, S_RADIO_ACTIVE, S_RADIO_INACTIVE, S_STEP_ACTIVE, S_STEP_CANCEL, S_STEP_ERROR, S_STEP_SUBMIT, S_SUCCESS, S_WARN, autocomplete, autocompleteMultiselect, box, cancel, confirm, date, formatInstructionFooter, group, groupMultiselect, intro, isCI, isTTY, limitOptions, log, multiline, multiselect, note, outro, password, path, progress, select, selectKey, spinner, stream, symbol, symbolBar, taskLog, tasks, text, unicode, unicodeOr };\n","import { spinner as clackSpinner } from '@clack/prompts'\nimport { theme } from './theme.js'\nimport { symbols } from './symbols.js'\nimport { isQuiet } from './output.js'\n\nconst SNIFF = ['listening', 'started', 'running']\n\n// A stdio child never emits any SNIFF word (they only ever appear in an HTTP\n// server's \"listening\" line), and an HTTP child with FASTMCP_LOG_LEVEL set to\n// warn/silent never prints one either. Without a deadline, the buffer above\n// would hold every line for the entire process lifetime and the user would\n// see nothing. When this fires with startup still undetected, stop animating\n// and let output stream live from then on.\nconst FLUSH_DEADLINE_MS = 10_000\n\n/**\n * Startup feedback for spawned servers. While animating, child stderr is\n * buffered so log lines do not tear the spinner row; everything flushes the\n * moment startup is detected (sniff word on stderr, or any stdout byte), or\n * once FLUSH_DEADLINE_MS passes without detection, whichever comes first.\n * Child stdout always passes straight through: it may be protocol traffic.\n */\nexport function createStartupReporter(opts: { animate: boolean }): {\n  onStdout(text: string): void\n  onStderr(text: string): void\n  fail(): void\n  done: boolean\n} {\n  const animate = opts.animate && process.stdout.isTTY === true && !isQuiet()\n  const buffered: string[] = []\n  let spin: ReturnType<typeof clackSpinner> | null = null\n  let deadlineTimer: ReturnType<typeof setTimeout> | null = null\n  if (animate) {\n    // Decoration always belongs on stderr in this CLI: the child's real\n    // stdout may be protocol traffic, and the spinner must never share\n    // that stream (clack defaults its own output to stdout otherwise).\n    spin = clackSpinner({ output: process.stderr })\n    spin.start(theme.muted(`${symbols.info} Starting server${symbols.ellipsis}`))\n    deadlineTimer = setTimeout(() => {\n      if (state.done || !spin) return\n      spin.stop(theme.muted(`still waiting for the server${symbols.ellipsis}`))\n      spin = null\n      for (const chunk of buffered.splice(0)) process.stderr.write(chunk)\n    }, FLUSH_DEADLINE_MS)\n    // Never hold the process open just to fire this deadline.\n    deadlineTimer.unref()\n  }\n  const state = {\n    done: false,\n    finish(ok: boolean): void {\n      if (state.done) return\n      state.done = true\n      if (deadlineTimer) { clearTimeout(deadlineTimer); deadlineTimer = null }\n      if (spin) {\n        if (ok) spin.stop(theme.success(`${symbols.success} Server started`))\n        else spin.error(theme.error(`${symbols.failure} Server exited before starting`))\n      } else if (!isQuiet()) {\n        process.stderr.write(ok ? `${theme.success(symbols.success)} Server started\\n` : `${theme.error(symbols.failure)} Server exited before starting\\n`)\n      }\n      for (const chunk of buffered.splice(0)) process.stderr.write(chunk)\n    },\n    onStdout(text: string): void {\n      state.finish(true)\n      process.stdout.write(text)\n    },\n    onStderr(text: string): void {\n      const hit = SNIFF.some((w) => text.includes(w))\n      if (!state.done && spin && !hit) { buffered.push(text); return }\n      if (hit) state.finish(true)\n      process.stderr.write(text)\n    },\n    fail(): void { state.finish(false) },\n  }\n  return state\n}\n","import { lstat, readdir, realpath, stat } from 'node:fs/promises';\nimport { join as pjoin, relative as prelative, resolve as presolve, sep as psep } from 'node:path';\nimport { Readable } from 'node:stream';\nexport const EntryTypes = {\n    FILE_TYPE: 'files',\n    DIR_TYPE: 'directories',\n    FILE_DIR_TYPE: 'files_directories',\n    EVERYTHING_TYPE: 'all',\n};\nconst defaultOptions = {\n    root: '.',\n    fileFilter: (_entryInfo) => true,\n    directoryFilter: (_entryInfo) => true,\n    type: EntryTypes.FILE_TYPE,\n    lstat: false,\n    depth: 2147483648,\n    alwaysStat: false,\n    highWaterMark: 4096,\n};\nObject.freeze(defaultOptions);\nconst RECURSIVE_ERROR_CODE = 'READDIRP_RECURSIVE_ERROR';\nconst NORMAL_FLOW_ERRORS = new Set(['ENOENT', 'EPERM', 'EACCES', 'ELOOP', RECURSIVE_ERROR_CODE]);\nconst ALL_TYPES = [\n    EntryTypes.DIR_TYPE,\n    EntryTypes.EVERYTHING_TYPE,\n    EntryTypes.FILE_DIR_TYPE,\n    EntryTypes.FILE_TYPE,\n];\nconst DIR_TYPES = new Set([\n    EntryTypes.DIR_TYPE,\n    EntryTypes.EVERYTHING_TYPE,\n    EntryTypes.FILE_DIR_TYPE,\n]);\nconst FILE_TYPES = new Set([\n    EntryTypes.EVERYTHING_TYPE,\n    EntryTypes.FILE_DIR_TYPE,\n    EntryTypes.FILE_TYPE,\n]);\nconst isNormalFlowError = (error) => NORMAL_FLOW_ERRORS.has(error.code);\nconst wantBigintFsStats = process.platform === 'win32';\nconst emptyFn = (_entryInfo) => true;\nconst normalizeFilter = (filter) => {\n    if (filter === undefined)\n        return emptyFn;\n    if (typeof filter === 'function')\n        return filter;\n    if (typeof filter === 'string') {\n        const fl = filter.trim();\n        return (entry) => entry.basename === fl;\n    }\n    if (Array.isArray(filter)) {\n        const trItems = filter.map((item) => item.trim());\n        return (entry) => trItems.some((f) => entry.basename === f);\n    }\n    return emptyFn;\n};\n/** Readable readdir stream, emitting new files as they're being listed. */\nexport class ReaddirpStream extends Readable {\n    parents;\n    reading;\n    parent;\n    _stat;\n    _maxDepth;\n    _wantsDir;\n    _wantsFile;\n    _wantsEverything;\n    _root;\n    _isDirent;\n    _statsProp;\n    _rdOptions;\n    _fileFilter;\n    _directoryFilter;\n    constructor(options = {}) {\n        super({\n            objectMode: true,\n            autoDestroy: true,\n            highWaterMark: options.highWaterMark,\n        });\n        const opts = { ...defaultOptions, ...options };\n        const { root, type } = opts;\n        this._fileFilter = normalizeFilter(opts.fileFilter);\n        this._directoryFilter = normalizeFilter(opts.directoryFilter);\n        const statMethod = opts.lstat ? lstat : stat;\n        // Use bigint stats if it's windows and stat() supports options (node 10+).\n        if (wantBigintFsStats) {\n            this._stat = (path) => statMethod(path, { bigint: true });\n        }\n        else {\n            this._stat = statMethod;\n        }\n        this._maxDepth =\n            opts.depth != null && Number.isSafeInteger(opts.depth) ? opts.depth : defaultOptions.depth;\n        this._wantsDir = type ? DIR_TYPES.has(type) : false;\n        this._wantsFile = type ? FILE_TYPES.has(type) : false;\n        this._wantsEverything = type === EntryTypes.EVERYTHING_TYPE;\n        this._root = presolve(root);\n        this._isDirent = !opts.alwaysStat;\n        this._statsProp = this._isDirent ? 'dirent' : 'stats';\n        this._rdOptions = { encoding: 'utf8', withFileTypes: this._isDirent };\n        // Launch stream with one parent, the root dir.\n        this.parents = [this._exploreDir(root, 1)];\n        this.reading = false;\n        this.parent = undefined;\n    }\n    async _read(batch) {\n        if (this.reading)\n            return;\n        this.reading = true;\n        try {\n            while (!this.destroyed && batch > 0) {\n                const par = this.parent;\n                const fil = par && par.files;\n                if (fil && fil.length > 0) {\n                    const { path, depth } = par;\n                    const slice = fil.splice(0, batch).map((dirent) => this._formatEntry(dirent, path));\n                    const awaited = await Promise.all(slice);\n                    for (const entry of awaited) {\n                        if (!entry)\n                            continue;\n                        if (this.destroyed)\n                            return;\n                        const entryType = await this._getEntryType(entry);\n                        if (entryType === 'directory' && this._directoryFilter(entry)) {\n                            if (depth <= this._maxDepth) {\n                                this.parents.push(this._exploreDir(entry.fullPath, depth + 1));\n                            }\n                            if (this._wantsDir) {\n                                this.push(entry);\n                                batch--;\n                            }\n                        }\n                        else if ((entryType === 'file' || this._includeAsFile(entry)) &&\n                            this._fileFilter(entry)) {\n                            if (this._wantsFile) {\n                                this.push(entry);\n                                batch--;\n                            }\n                        }\n                    }\n                }\n                else {\n                    const parent = this.parents.pop();\n                    if (!parent) {\n                        this.push(null);\n                        break;\n                    }\n                    this.parent = await parent;\n                    if (this.destroyed)\n                        return;\n                }\n            }\n        }\n        catch (error) {\n            this.destroy(error);\n        }\n        finally {\n            this.reading = false;\n        }\n    }\n    async _exploreDir(path, depth) {\n        let files;\n        try {\n            files = await readdir(path, this._rdOptions);\n        }\n        catch (error) {\n            this._onError(error);\n        }\n        return { files, depth, path };\n    }\n    async _formatEntry(dirent, path) {\n        let entry;\n        const basename = this._isDirent ? dirent.name : dirent;\n        try {\n            const fullPath = presolve(pjoin(path, basename));\n            entry = { path: prelative(this._root, fullPath), fullPath, basename };\n            entry[this._statsProp] = this._isDirent ? dirent : await this._stat(fullPath);\n        }\n        catch (err) {\n            this._onError(err);\n            return;\n        }\n        return entry;\n    }\n    _onError(err) {\n        if (isNormalFlowError(err) && !this.destroyed) {\n            this.emit('warn', err);\n        }\n        else {\n            this.destroy(err);\n        }\n    }\n    async _getEntryType(entry) {\n        // entry may be undefined, because a warning or an error were emitted\n        // and the statsProp is undefined\n        if (!entry && this._statsProp in entry) {\n            return '';\n        }\n        const stats = entry[this._statsProp];\n        if (stats.isFile())\n            return 'file';\n        if (stats.isDirectory())\n            return 'directory';\n        if (stats && stats.isSymbolicLink()) {\n            const full = entry.fullPath;\n            try {\n                const entryRealPath = await realpath(full);\n                const entryRealPathStats = await lstat(entryRealPath);\n                if (entryRealPathStats.isFile()) {\n                    return 'file';\n                }\n                if (entryRealPathStats.isDirectory()) {\n                    const len = entryRealPath.length;\n                    if (full.startsWith(entryRealPath) && full.substr(len, 1) === psep) {\n                        const recursiveError = new Error(`Circular symlink detected: \"${full}\" points to \"${entryRealPath}\"`);\n                        // @ts-ignore\n                        recursiveError.code = RECURSIVE_ERROR_CODE;\n                        return this._onError(recursiveError);\n                    }\n                    return 'directory';\n                }\n            }\n            catch (error) {\n                this._onError(error);\n                return '';\n            }\n        }\n    }\n    _includeAsFile(entry) {\n        const stats = entry && entry[this._statsProp];\n        return stats && this._wantsEverything && !stats.isDirectory();\n    }\n}\n/**\n * Streaming version: Reads all files and directories in given root recursively.\n * Consumes ~constant small amount of RAM.\n * @param root Root directory\n * @param options Options to specify root (start directory), filters and recursion depth\n */\nexport function readdirp(root, options = {}) {\n    // @ts-ignore\n    let type = options.entryType || options.type;\n    if (type === 'both')\n        type = EntryTypes.FILE_DIR_TYPE; // backwards-compatibility\n    if (type)\n        options.type = type;\n    if (!root) {\n        throw new Error('readdirp: root argument is required. Usage: readdirp(root, options)');\n    }\n    else if (typeof root !== 'string') {\n        throw new TypeError('readdirp: root argument must be a string. Usage: readdirp(root, options)');\n    }\n    else if (type && !ALL_TYPES.includes(type)) {\n        throw new Error(`readdirp: Invalid type passed. Use one of ${ALL_TYPES.join(', ')}`);\n    }\n    options.root = root;\n    return new ReaddirpStream(options);\n}\n/**\n * Promise version: Reads all files and directories in given root recursively.\n * Compared to streaming version, will consume a lot of RAM e.g. when 1 million files are listed.\n * @returns array of paths and their entry infos\n */\nexport function readdirpPromise(root, options = {}) {\n    return new Promise((resolve, reject) => {\n        const files = [];\n        readdirp(root, options)\n            .on('data', (entry) => files.push(entry))\n            .on('end', () => resolve(files))\n            .on('error', (error) => reject(error));\n    });\n}\nexport default readdirp;\n","import { watch as fs_watch, unwatchFile, watchFile } from 'node:fs';\nimport { realpath as fsrealpath, lstat, open, stat } from 'node:fs/promises';\nimport { type as osType } from 'node:os';\nimport * as sp from 'node:path';\nexport const STR_DATA = 'data';\nexport const STR_END = 'end';\nexport const STR_CLOSE = 'close';\nexport const EMPTY_FN = () => { };\nexport const IDENTITY_FN = (val) => val;\nconst pl = process.platform;\nexport const isWindows = pl === 'win32';\nexport const isMacos = pl === 'darwin';\nexport const isLinux = pl === 'linux';\nexport const isFreeBSD = pl === 'freebsd';\nexport const isIBMi = osType() === 'OS400';\nexport const EVENTS = {\n    ALL: 'all',\n    READY: 'ready',\n    ADD: 'add',\n    CHANGE: 'change',\n    ADD_DIR: 'addDir',\n    UNLINK: 'unlink',\n    UNLINK_DIR: 'unlinkDir',\n    RAW: 'raw',\n    ERROR: 'error',\n};\nconst EV = EVENTS;\nconst THROTTLE_MODE_WATCH = 'watch';\nconst statMethods = { lstat, stat };\nconst KEY_LISTENERS = 'listeners';\nconst KEY_ERR = 'errHandlers';\nconst KEY_RAW = 'rawEmitters';\nconst HANDLER_KEYS = [KEY_LISTENERS, KEY_ERR, KEY_RAW];\n// prettier-ignore\nconst binaryExtensions = new Set([\n    '3dm', '3ds', '3g2', '3gp', '7z', 'a', 'aac', 'adp', 'afdesign', 'afphoto', 'afpub', 'ai',\n    'aif', 'aiff', 'alz', 'ape', 'apk', 'appimage', 'ar', 'arj', 'asf', 'au', 'avi',\n    'bak', 'baml', 'bh', 'bin', 'bk', 'bmp', 'btif', 'bz2', 'bzip2',\n    'cab', 'caf', 'cgm', 'class', 'cmx', 'cpio', 'cr2', 'cur', 'dat', 'dcm', 'deb', 'dex', 'djvu',\n    'dll', 'dmg', 'dng', 'doc', 'docm', 'docx', 'dot', 'dotm', 'dra', 'DS_Store', 'dsk', 'dts',\n    'dtshd', 'dvb', 'dwg', 'dxf',\n    'ecelp4800', 'ecelp7470', 'ecelp9600', 'egg', 'eol', 'eot', 'epub', 'exe',\n    'f4v', 'fbs', 'fh', 'fla', 'flac', 'flatpak', 'fli', 'flv', 'fpx', 'fst', 'fvt',\n    'g3', 'gh', 'gif', 'graffle', 'gz', 'gzip',\n    'h261', 'h263', 'h264', 'icns', 'ico', 'ief', 'img', 'ipa', 'iso',\n    'jar', 'jpeg', 'jpg', 'jpgv', 'jpm', 'jxr', 'key', 'ktx',\n    'lha', 'lib', 'lvp', 'lz', 'lzh', 'lzma', 'lzo',\n    'm3u', 'm4a', 'm4v', 'mar', 'mdi', 'mht', 'mid', 'midi', 'mj2', 'mka', 'mkv', 'mmr', 'mng',\n    'mobi', 'mov', 'movie', 'mp3',\n    'mp4', 'mp4a', 'mpeg', 'mpg', 'mpga', 'mxu',\n    'nef', 'npx', 'numbers', 'nupkg',\n    'o', 'odp', 'ods', 'odt', 'oga', 'ogg', 'ogv', 'otf', 'ott',\n    'pages', 'pbm', 'pcx', 'pdb', 'pdf', 'pea', 'pgm', 'pic', 'png', 'pnm', 'pot', 'potm',\n    'potx', 'ppa', 'ppam',\n    'ppm', 'pps', 'ppsm', 'ppsx', 'ppt', 'pptm', 'pptx', 'psd', 'pya', 'pyc', 'pyo', 'pyv',\n    'qt',\n    'rar', 'ras', 'raw', 'resources', 'rgb', 'rip', 'rlc', 'rmf', 'rmvb', 'rpm', 'rtf', 'rz',\n    's3m', 's7z', 'scpt', 'sgi', 'shar', 'snap', 'sil', 'sketch', 'slk', 'smv', 'snk', 'so',\n    'stl', 'suo', 'sub', 'swf',\n    'tar', 'tbz', 'tbz2', 'tga', 'tgz', 'thmx', 'tif', 'tiff', 'tlz', 'ttc', 'ttf', 'txz',\n    'udf', 'uvh', 'uvi', 'uvm', 'uvp', 'uvs', 'uvu',\n    'viv', 'vob',\n    'war', 'wav', 'wax', 'wbmp', 'wdp', 'weba', 'webm', 'webp', 'whl', 'wim', 'wm', 'wma',\n    'wmv', 'wmx', 'woff', 'woff2', 'wrm', 'wvx',\n    'xbm', 'xif', 'xla', 'xlam', 'xls', 'xlsb', 'xlsm', 'xlsx', 'xlt', 'xltm', 'xltx', 'xm',\n    'xmind', 'xpi', 'xpm', 'xwd', 'xz',\n    'z', 'zip', 'zipx',\n]);\nconst isBinaryPath = (filePath) => binaryExtensions.has(sp.extname(filePath).slice(1).toLowerCase());\n// TODO: emit errors properly. Example: EMFILE on Macos.\nconst foreach = (val, fn) => {\n    if (val instanceof Set) {\n        val.forEach(fn);\n    }\n    else {\n        fn(val);\n    }\n};\nconst addAndConvert = (main, prop, item) => {\n    let container = main[prop];\n    if (!(container instanceof Set)) {\n        main[prop] = container = new Set([container]);\n    }\n    container.add(item);\n};\nconst clearItem = (cont) => (key) => {\n    const set = cont[key];\n    if (set instanceof Set) {\n        set.clear();\n    }\n    else {\n        delete cont[key];\n    }\n};\nconst delFromSet = (main, prop, item) => {\n    const container = main[prop];\n    if (container instanceof Set) {\n        container.delete(item);\n    }\n    else if (container === item) {\n        delete main[prop];\n    }\n};\nconst isEmptySet = (val) => (val instanceof Set ? val.size === 0 : !val);\nconst FsWatchInstances = new Map();\n/**\n * Instantiates the fs_watch interface\n * @param path to be watched\n * @param options to be passed to fs_watch\n * @param listener main event handler\n * @param errHandler emits info about errors\n * @param emitRaw emits raw event data\n * @returns {NativeFsWatcher}\n */\nfunction createFsWatchInstance(path, options, listener, errHandler, emitRaw) {\n    const handleEvent = (rawEvent, evPath) => {\n        listener(path);\n        emitRaw(rawEvent, evPath, { watchedPath: path });\n        // emit based on events occurring for files from a directory's watcher in\n        // case the file's watcher misses it (and rely on throttling to de-dupe)\n        if (evPath && path !== evPath) {\n            fsWatchBroadcast(sp.resolve(path, evPath), KEY_LISTENERS, sp.join(path, evPath));\n        }\n    };\n    try {\n        return fs_watch(path, {\n            persistent: options.persistent,\n        }, handleEvent);\n    }\n    catch (error) {\n        errHandler(error);\n        return undefined;\n    }\n}\n/**\n * Helper for passing fs_watch event data to a collection of listeners\n * @param fullPath absolute path bound to fs_watch instance\n */\nconst fsWatchBroadcast = (fullPath, listenerType, val1, val2, val3) => {\n    const cont = FsWatchInstances.get(fullPath);\n    if (!cont)\n        return;\n    foreach(cont[listenerType], (listener) => {\n        listener(val1, val2, val3);\n    });\n};\n/**\n * Instantiates the fs_watch interface or binds listeners\n * to an existing one covering the same file system entry\n * @param path\n * @param fullPath absolute path\n * @param options to be passed to fs_watch\n * @param handlers container for event listener functions\n */\nconst setFsWatchListener = (path, fullPath, options, handlers) => {\n    const { listener, errHandler, rawEmitter } = handlers;\n    let cont = FsWatchInstances.get(fullPath);\n    let watcher;\n    if (!options.persistent) {\n        watcher = createFsWatchInstance(path, options, listener, errHandler, rawEmitter);\n        if (!watcher)\n            return;\n        return watcher.close.bind(watcher);\n    }\n    if (cont) {\n        addAndConvert(cont, KEY_LISTENERS, listener);\n        addAndConvert(cont, KEY_ERR, errHandler);\n        addAndConvert(cont, KEY_RAW, rawEmitter);\n    }\n    else {\n        watcher = createFsWatchInstance(path, options, fsWatchBroadcast.bind(null, fullPath, KEY_LISTENERS), errHandler, // no need to use broadcast here\n        fsWatchBroadcast.bind(null, fullPath, KEY_RAW));\n        if (!watcher)\n            return;\n        watcher.on(EV.ERROR, async (error) => {\n            const broadcastErr = fsWatchBroadcast.bind(null, fullPath, KEY_ERR);\n            if (cont)\n                cont.watcherUnusable = true; // documented since Node 10.4.1\n            // Workaround for https://github.com/joyent/node/issues/4337\n            if (isWindows && error.code === 'EPERM') {\n                try {\n                    const fd = await open(path, 'r');\n                    await fd.close();\n                    broadcastErr(error);\n                }\n                catch (err) {\n                    // do nothing\n                }\n            }\n            else {\n                broadcastErr(error);\n            }\n        });\n        cont = {\n            listeners: listener,\n            errHandlers: errHandler,\n            rawEmitters: rawEmitter,\n            watcher,\n        };\n        FsWatchInstances.set(fullPath, cont);\n    }\n    // const index = cont.listeners.indexOf(listener);\n    // removes this instance's listeners and closes the underlying fs_watch\n    // instance if there are no more listeners left\n    return () => {\n        delFromSet(cont, KEY_LISTENERS, listener);\n        delFromSet(cont, KEY_ERR, errHandler);\n        delFromSet(cont, KEY_RAW, rawEmitter);\n        if (isEmptySet(cont.listeners)) {\n            // Check to protect against issue gh-730.\n            // if (cont.watcherUnusable) {\n            cont.watcher.close();\n            // }\n            FsWatchInstances.delete(fullPath);\n            HANDLER_KEYS.forEach(clearItem(cont));\n            // @ts-ignore\n            cont.watcher = undefined;\n            Object.freeze(cont);\n        }\n    };\n};\n// fs_watchFile helpers\n// object to hold per-process fs_watchFile instances\n// (may be shared across chokidar FSWatcher instances)\nconst FsWatchFileInstances = new Map();\n/**\n * Instantiates the fs_watchFile interface or binds listeners\n * to an existing one covering the same file system entry\n * @param path to be watched\n * @param fullPath absolute path\n * @param options options to be passed to fs_watchFile\n * @param handlers container for event listener functions\n * @returns closer\n */\nconst setFsWatchFileListener = (path, fullPath, options, handlers) => {\n    const { listener, rawEmitter } = handlers;\n    let cont = FsWatchFileInstances.get(fullPath);\n    // let listeners = new Set();\n    // let rawEmitters = new Set();\n    const copts = cont && cont.options;\n    if (copts && (copts.persistent < options.persistent || copts.interval > options.interval)) {\n        // \"Upgrade\" the watcher to persistence or a quicker interval.\n        // This creates some unlikely edge case issues if the user mixes\n        // settings in a very weird way, but solving for those cases\n        // doesn't seem worthwhile for the added complexity.\n        // listeners = cont.listeners;\n        // rawEmitters = cont.rawEmitters;\n        unwatchFile(fullPath);\n        cont = undefined;\n    }\n    if (cont) {\n        addAndConvert(cont, KEY_LISTENERS, listener);\n        addAndConvert(cont, KEY_RAW, rawEmitter);\n    }\n    else {\n        // TODO\n        // listeners.add(listener);\n        // rawEmitters.add(rawEmitter);\n        cont = {\n            listeners: listener,\n            rawEmitters: rawEmitter,\n            options,\n            watcher: watchFile(fullPath, options, (curr, prev) => {\n                foreach(cont.rawEmitters, (rawEmitter) => {\n                    rawEmitter(EV.CHANGE, fullPath, { curr, prev });\n                });\n                const currmtime = curr.mtimeMs;\n                if (curr.size !== prev.size || currmtime > prev.mtimeMs || currmtime === 0) {\n                    foreach(cont.listeners, (listener) => listener(path, curr));\n                }\n            }),\n        };\n        FsWatchFileInstances.set(fullPath, cont);\n    }\n    // const index = cont.listeners.indexOf(listener);\n    // Removes this instance's listeners and closes the underlying fs_watchFile\n    // instance if there are no more listeners left.\n    return () => {\n        delFromSet(cont, KEY_LISTENERS, listener);\n        delFromSet(cont, KEY_RAW, rawEmitter);\n        if (isEmptySet(cont.listeners)) {\n            FsWatchFileInstances.delete(fullPath);\n            unwatchFile(fullPath);\n            cont.options = cont.watcher = undefined;\n            Object.freeze(cont);\n        }\n    };\n};\n/**\n * @mixin\n */\nexport class NodeFsHandler {\n    fsw;\n    _boundHandleError;\n    constructor(fsW) {\n        this.fsw = fsW;\n        this._boundHandleError = (error) => fsW._handleError(error);\n    }\n    /**\n     * Watch file for changes with fs_watchFile or fs_watch.\n     * @param path to file or dir\n     * @param listener on fs change\n     * @returns closer for the watcher instance\n     */\n    _watchWithNodeFs(path, listener) {\n        const opts = this.fsw.options;\n        const directory = sp.dirname(path);\n        const basename = sp.basename(path);\n        const parent = this.fsw._getWatchedDir(directory);\n        parent.add(basename);\n        const absolutePath = sp.resolve(path);\n        const options = {\n            persistent: opts.persistent,\n        };\n        if (!listener)\n            listener = EMPTY_FN;\n        let closer;\n        if (opts.usePolling) {\n            const enableBin = opts.interval !== opts.binaryInterval;\n            options.interval = enableBin && isBinaryPath(basename) ? opts.binaryInterval : opts.interval;\n            closer = setFsWatchFileListener(path, absolutePath, options, {\n                listener,\n                rawEmitter: this.fsw._emitRaw,\n            });\n        }\n        else {\n            closer = setFsWatchListener(path, absolutePath, options, {\n                listener,\n                errHandler: this._boundHandleError,\n                rawEmitter: this.fsw._emitRaw,\n            });\n        }\n        return closer;\n    }\n    /**\n     * Watch a file and emit add event if warranted.\n     * @returns closer for the watcher instance\n     */\n    _handleFile(file, stats, initialAdd) {\n        if (this.fsw.closed) {\n            return;\n        }\n        const dirname = sp.dirname(file);\n        const basename = sp.basename(file);\n        const parent = this.fsw._getWatchedDir(dirname);\n        // stats is always present\n        let prevStats = stats;\n        // if the file is already being watched, do nothing\n        if (parent.has(basename))\n            return;\n        const listener = async (path, newStats) => {\n            if (!this.fsw._throttle(THROTTLE_MODE_WATCH, file, 5))\n                return;\n            if (!newStats || newStats.mtimeMs === 0) {\n                try {\n                    const newStats = await stat(file);\n                    if (this.fsw.closed)\n                        return;\n                    // Check that change event was not fired because of changed only accessTime.\n                    const at = newStats.atimeMs;\n                    const mt = newStats.mtimeMs;\n                    if (!at || at <= mt || mt !== prevStats.mtimeMs) {\n                        this.fsw._emit(EV.CHANGE, file, newStats);\n                    }\n                    if ((isMacos || isLinux || isFreeBSD) && prevStats.ino !== newStats.ino) {\n                        this.fsw._closeFile(path);\n                        prevStats = newStats;\n                        const closer = this._watchWithNodeFs(file, listener);\n                        if (closer)\n                            this.fsw._addPathCloser(path, closer);\n                    }\n                    else {\n                        prevStats = newStats;\n                    }\n                }\n                catch (error) {\n                    // Fix issues where mtime is null but file is still present\n                    this.fsw._remove(dirname, basename);\n                }\n                // add is about to be emitted if file not already tracked in parent\n            }\n            else if (parent.has(basename)) {\n                // Check that change event was not fired because of changed only accessTime.\n                const at = newStats.atimeMs;\n                const mt = newStats.mtimeMs;\n                if (!at || at <= mt || mt !== prevStats.mtimeMs) {\n                    this.fsw._emit(EV.CHANGE, file, newStats);\n                }\n                prevStats = newStats;\n            }\n        };\n        // kick off the watcher\n        const closer = this._watchWithNodeFs(file, listener);\n        // emit an add event if we're supposed to\n        if (!(initialAdd && this.fsw.options.ignoreInitial) && this.fsw._isntIgnored(file)) {\n            if (!this.fsw._throttle(EV.ADD, file, 0))\n                return;\n            this.fsw._emit(EV.ADD, file, stats);\n        }\n        return closer;\n    }\n    /**\n     * Handle symlinks encountered while reading a dir.\n     * @param entry returned by readdirp\n     * @param directory path of dir being read\n     * @param path of this item\n     * @param item basename of this item\n     * @returns true if no more processing is needed for this entry.\n     */\n    async _handleSymlink(entry, directory, path, item) {\n        if (this.fsw.closed) {\n            return;\n        }\n        const full = entry.fullPath;\n        const dir = this.fsw._getWatchedDir(directory);\n        if (!this.fsw.options.followSymlinks) {\n            // watch symlink directly (don't follow) and detect changes\n            this.fsw._incrReadyCount();\n            let linkPath;\n            try {\n                linkPath = await fsrealpath(path);\n            }\n            catch (e) {\n                this.fsw._emitReady();\n                return true;\n            }\n            if (this.fsw.closed)\n                return;\n            if (dir.has(item)) {\n                if (this.fsw._symlinkPaths.get(full) !== linkPath) {\n                    this.fsw._symlinkPaths.set(full, linkPath);\n                    this.fsw._emit(EV.CHANGE, path, entry.stats);\n                }\n            }\n            else {\n                dir.add(item);\n                this.fsw._symlinkPaths.set(full, linkPath);\n                this.fsw._emit(EV.ADD, path, entry.stats);\n            }\n            this.fsw._emitReady();\n            return true;\n        }\n        // don't follow the same symlink more than once\n        if (this.fsw._symlinkPaths.has(full)) {\n            return true;\n        }\n        this.fsw._symlinkPaths.set(full, true);\n    }\n    _handleRead(directory, initialAdd, wh, target, dir, depth, throttler) {\n        // Normalize the directory name on Windows\n        directory = sp.join(directory, '');\n        const throttleKey = target ? `${directory}:${target}` : directory;\n        throttler = this.fsw._throttle('readdir', throttleKey, 1000);\n        if (!throttler)\n            return;\n        const previous = this.fsw._getWatchedDir(wh.path);\n        const current = new Set();\n        let stream = this.fsw._readdirp(directory, {\n            fileFilter: (entry) => wh.filterPath(entry),\n            directoryFilter: (entry) => wh.filterDir(entry),\n        });\n        if (!stream)\n            return;\n        stream\n            .on(STR_DATA, async (entry) => {\n            if (this.fsw.closed) {\n                stream = undefined;\n                return;\n            }\n            const item = entry.path;\n            let path = sp.join(directory, item);\n            current.add(item);\n            if (entry.stats.isSymbolicLink() &&\n                (await this._handleSymlink(entry, directory, path, item))) {\n                return;\n            }\n            if (this.fsw.closed) {\n                stream = undefined;\n                return;\n            }\n            // Files that present in current directory snapshot\n            // but absent in previous are added to watch list and\n            // emit `add` event.\n            if (item === target || (!target && !previous.has(item))) {\n                this.fsw._incrReadyCount();\n                // ensure relativeness of path is preserved in case of watcher reuse\n                path = sp.join(dir, sp.relative(dir, path));\n                this._addToNodeFs(path, initialAdd, wh, depth + 1);\n            }\n        })\n            .on(EV.ERROR, this._boundHandleError);\n        return new Promise((resolve, reject) => {\n            if (!stream)\n                return reject();\n            stream.once(STR_END, () => {\n                if (this.fsw.closed) {\n                    stream = undefined;\n                    return;\n                }\n                const wasThrottled = throttler ? throttler.clear() : false;\n                resolve(undefined);\n                // Files that absent in current directory snapshot\n                // but present in previous emit `remove` event\n                // and are removed from @watched[directory].\n                previous\n                    .getChildren()\n                    .filter((item) => {\n                    return item !== directory && !current.has(item);\n                })\n                    .forEach((item) => {\n                    this.fsw._remove(directory, item);\n                });\n                stream = undefined;\n                // one more time for any missed in case changes came in extremely quickly\n                if (wasThrottled)\n                    this._handleRead(directory, false, wh, target, dir, depth, throttler);\n            });\n        });\n    }\n    /**\n     * Read directory to add / remove files from `@watched` list and re-read it on change.\n     * @param dir fs path\n     * @param stats\n     * @param initialAdd\n     * @param depth relative to user-supplied path\n     * @param target child path targeted for watch\n     * @param wh Common watch helpers for this path\n     * @param realpath\n     * @returns closer for the watcher instance.\n     */\n    async _handleDir(dir, stats, initialAdd, depth, target, wh, realpath) {\n        const parentDir = this.fsw._getWatchedDir(sp.dirname(dir));\n        const tracked = parentDir.has(sp.basename(dir));\n        if (!(initialAdd && this.fsw.options.ignoreInitial) && !target && !tracked) {\n            this.fsw._emit(EV.ADD_DIR, dir, stats);\n        }\n        // ensure dir is tracked (harmless if redundant)\n        parentDir.add(sp.basename(dir));\n        this.fsw._getWatchedDir(dir);\n        let throttler;\n        let closer;\n        const oDepth = this.fsw.options.depth;\n        if ((oDepth == null || depth <= oDepth) && !this.fsw._symlinkPaths.has(realpath)) {\n            if (!target) {\n                await this._handleRead(dir, initialAdd, wh, target, dir, depth, throttler);\n                if (this.fsw.closed)\n                    return;\n            }\n            closer = this._watchWithNodeFs(dir, (dirPath, stats) => {\n                // if current directory is removed, do nothing\n                if (stats && stats.mtimeMs === 0)\n                    return;\n                this._handleRead(dirPath, false, wh, target, dir, depth, throttler);\n            });\n        }\n        return closer;\n    }\n    /**\n     * Handle added file, directory, or glob pattern.\n     * Delegates call to _handleFile / _handleDir after checks.\n     * @param path to file or ir\n     * @param initialAdd was the file added at watch instantiation?\n     * @param priorWh depth relative to user-supplied path\n     * @param depth Child path actually targeted for watch\n     * @param target Child path actually targeted for watch\n     */\n    async _addToNodeFs(path, initialAdd, priorWh, depth, target) {\n        const ready = this.fsw._emitReady;\n        if (this.fsw._isIgnored(path) || this.fsw.closed) {\n            ready();\n            return false;\n        }\n        const wh = this.fsw._getWatchHelpers(path);\n        if (priorWh) {\n            wh.filterPath = (entry) => priorWh.filterPath(entry);\n            wh.filterDir = (entry) => priorWh.filterDir(entry);\n        }\n        // evaluate what is at the path we're being asked to watch\n        try {\n            const stats = await statMethods[wh.statMethod](wh.watchPath);\n            if (this.fsw.closed)\n                return;\n            if (this.fsw._isIgnored(wh.watchPath, stats)) {\n                ready();\n                return false;\n            }\n            const follow = this.fsw.options.followSymlinks;\n            let closer;\n            if (stats.isDirectory()) {\n                const absPath = sp.resolve(path);\n                const targetPath = follow ? await fsrealpath(path) : path;\n                if (this.fsw.closed)\n                    return;\n                closer = await this._handleDir(wh.watchPath, stats, initialAdd, depth, target, wh, targetPath);\n                if (this.fsw.closed)\n                    return;\n                // preserve this symlink's target path\n                if (absPath !== targetPath && targetPath !== undefined) {\n                    this.fsw._symlinkPaths.set(absPath, targetPath);\n                }\n            }\n            else if (stats.isSymbolicLink()) {\n                const targetPath = follow ? await fsrealpath(path) : path;\n                if (this.fsw.closed)\n                    return;\n                const parent = sp.dirname(wh.watchPath);\n                this.fsw._getWatchedDir(parent).add(wh.watchPath);\n                this.fsw._emit(EV.ADD, wh.watchPath, stats);\n                closer = await this._handleDir(parent, stats, initialAdd, depth, path, wh, targetPath);\n                if (this.fsw.closed)\n                    return;\n                // preserve this symlink's target path\n                if (targetPath !== undefined) {\n                    this.fsw._symlinkPaths.set(sp.resolve(path), targetPath);\n                }\n            }\n            else {\n                closer = this._handleFile(wh.watchPath, stats, initialAdd);\n            }\n            ready();\n            if (closer)\n                this.fsw._addPathCloser(path, closer);\n            return false;\n        }\n        catch (error) {\n            if (this.fsw._handleError(error)) {\n                ready();\n                return path;\n            }\n        }\n    }\n}\n","/*! chokidar - MIT License (c) 2012 Paul Miller (paulmillr.com) */\nimport { EventEmitter } from 'node:events';\nimport { stat as statcb, Stats } from 'node:fs';\nimport { readdir, stat } from 'node:fs/promises';\nimport * as sp from 'node:path';\nimport { readdirp, ReaddirpStream } from 'readdirp';\nimport { EMPTY_FN, EVENTS as EV, isIBMi, isWindows, NodeFsHandler, STR_CLOSE, STR_END, } from './handler.js';\nconst SLASH = '/';\nconst SLASH_SLASH = '//';\nconst ONE_DOT = '.';\nconst TWO_DOTS = '..';\nconst STRING_TYPE = 'string';\nconst BACK_SLASH_RE = /\\\\/g;\nconst DOUBLE_SLASH_RE = /\\/\\//g;\nconst DOT_RE = /\\..*\\.(sw[px])$|~$|\\.subl.*\\.tmp/;\nconst REPLACER_RE = /^\\.[/\\\\]/;\nfunction arrify(item) {\n    return Array.isArray(item) ? item : [item];\n}\nconst isMatcherObject = (matcher) => typeof matcher === 'object' && matcher !== null && !(matcher instanceof RegExp);\nfunction createPattern(matcher) {\n    if (typeof matcher === 'function')\n        return matcher;\n    if (typeof matcher === 'string')\n        return (string) => matcher === string;\n    if (matcher instanceof RegExp)\n        return (string) => matcher.test(string);\n    if (typeof matcher === 'object' && matcher !== null) {\n        return (string) => {\n            if (matcher.path === string)\n                return true;\n            if (matcher.recursive) {\n                const relative = sp.relative(matcher.path, string);\n                if (!relative) {\n                    return false;\n                }\n                return !relative.startsWith('..') && !sp.isAbsolute(relative);\n            }\n            return false;\n        };\n    }\n    return () => false;\n}\nfunction normalizePath(path) {\n    if (typeof path !== 'string')\n        throw new Error('string expected');\n    path = sp.normalize(path);\n    path = path.replace(/\\\\/g, '/');\n    let prepend = false;\n    if (path.startsWith('//'))\n        prepend = true;\n    path = path.replace(DOUBLE_SLASH_RE, '/');\n    if (prepend)\n        path = '/' + path;\n    return path;\n}\nfunction matchPatterns(patterns, testString, stats) {\n    const path = normalizePath(testString);\n    for (let index = 0; index < patterns.length; index++) {\n        const pattern = patterns[index];\n        if (pattern(path, stats)) {\n            return true;\n        }\n    }\n    return false;\n}\nfunction anymatch(matchers, testString) {\n    if (matchers == null) {\n        throw new TypeError('anymatch: specify first argument');\n    }\n    // Early cache for matchers.\n    const matchersArray = arrify(matchers);\n    const patterns = matchersArray.map((matcher) => createPattern(matcher));\n    if (testString == null) {\n        return (testString, stats) => {\n            return matchPatterns(patterns, testString, stats);\n        };\n    }\n    return matchPatterns(patterns, testString);\n}\nconst unifyPaths = (paths_) => {\n    const paths = arrify(paths_).flat();\n    if (!paths.every((p) => typeof p === STRING_TYPE)) {\n        throw new TypeError(`Non-string provided as watch path: ${paths}`);\n    }\n    return paths.map(normalizePathToUnix);\n};\n// If SLASH_SLASH occurs at the beginning of path, it is not replaced\n//     because \"//StoragePC/DrivePool/Movies\" is a valid network path\nconst toUnix = (string) => {\n    let str = string.replace(BACK_SLASH_RE, SLASH);\n    let prepend = false;\n    if (str.startsWith(SLASH_SLASH)) {\n        prepend = true;\n    }\n    str = str.replace(DOUBLE_SLASH_RE, SLASH);\n    if (prepend) {\n        str = SLASH + str;\n    }\n    return str;\n};\n// Our version of upath.normalize\n// TODO: this is not equal to path-normalize module - investigate why\nconst normalizePathToUnix = (path) => toUnix(sp.normalize(toUnix(path)));\n// TODO: refactor\nconst normalizeIgnored = (cwd = '') => (path) => {\n    if (typeof path === 'string') {\n        return normalizePathToUnix(sp.isAbsolute(path) ? path : sp.join(cwd, path));\n    }\n    else {\n        return path;\n    }\n};\nconst getAbsolutePath = (path, cwd) => {\n    if (sp.isAbsolute(path)) {\n        return path;\n    }\n    return sp.join(cwd, path);\n};\nconst EMPTY_SET = Object.freeze(new Set());\n/**\n * Directory entry.\n */\nclass DirEntry {\n    path;\n    _removeWatcher;\n    items;\n    constructor(dir, removeWatcher) {\n        this.path = dir;\n        this._removeWatcher = removeWatcher;\n        this.items = new Set();\n    }\n    add(item) {\n        const { items } = this;\n        if (!items)\n            return;\n        if (item !== ONE_DOT && item !== TWO_DOTS)\n            items.add(item);\n    }\n    async remove(item) {\n        const { items } = this;\n        if (!items)\n            return;\n        items.delete(item);\n        if (items.size > 0)\n            return;\n        const dir = this.path;\n        try {\n            await readdir(dir);\n        }\n        catch (err) {\n            if (this._removeWatcher) {\n                this._removeWatcher(sp.dirname(dir), sp.basename(dir));\n            }\n        }\n    }\n    has(item) {\n        const { items } = this;\n        if (!items)\n            return;\n        return items.has(item);\n    }\n    getChildren() {\n        const { items } = this;\n        if (!items)\n            return [];\n        return [...items.values()];\n    }\n    dispose() {\n        this.items.clear();\n        this.path = '';\n        this._removeWatcher = EMPTY_FN;\n        this.items = EMPTY_SET;\n        Object.freeze(this);\n    }\n}\nconst STAT_METHOD_F = 'stat';\nconst STAT_METHOD_L = 'lstat';\nexport class WatchHelper {\n    fsw;\n    path;\n    watchPath;\n    fullWatchPath;\n    dirParts;\n    followSymlinks;\n    statMethod;\n    constructor(path, follow, fsw) {\n        this.fsw = fsw;\n        const watchPath = path;\n        this.path = path = path.replace(REPLACER_RE, '');\n        this.watchPath = watchPath;\n        this.fullWatchPath = sp.resolve(watchPath);\n        this.dirParts = [];\n        this.dirParts.forEach((parts) => {\n            if (parts.length > 1)\n                parts.pop();\n        });\n        this.followSymlinks = follow;\n        this.statMethod = follow ? STAT_METHOD_F : STAT_METHOD_L;\n    }\n    entryPath(entry) {\n        return sp.join(this.watchPath, sp.relative(this.watchPath, entry.fullPath));\n    }\n    filterPath(entry) {\n        const { stats } = entry;\n        if (stats && stats.isSymbolicLink())\n            return this.filterDir(entry);\n        const resolvedPath = this.entryPath(entry);\n        // TODO: what if stats is undefined? remove !\n        return this.fsw._isntIgnored(resolvedPath, stats) && this.fsw._hasReadPermissions(stats);\n    }\n    filterDir(entry) {\n        return this.fsw._isntIgnored(this.entryPath(entry), entry.stats);\n    }\n}\n/**\n * Watches files & directories for changes. Emitted events:\n * `add`, `addDir`, `change`, `unlink`, `unlinkDir`, `all`, `error`\n *\n *     new FSWatcher()\n *       .add(directories)\n *       .on('add', path => log('File', path, 'was added'))\n */\nexport class FSWatcher extends EventEmitter {\n    closed;\n    options;\n    _closers;\n    _ignoredPaths;\n    _throttled;\n    _streams;\n    _symlinkPaths;\n    _watched;\n    _pendingWrites;\n    _pendingUnlinks;\n    _readyCount;\n    _emitReady;\n    _closePromise;\n    _userIgnored;\n    _readyEmitted;\n    _emitRaw;\n    _boundRemove;\n    _nodeFsHandler;\n    // Not indenting methods for history sake; for now.\n    constructor(_opts = {}) {\n        super();\n        this.closed = false;\n        this._closers = new Map();\n        this._ignoredPaths = new Set();\n        this._throttled = new Map();\n        this._streams = new Set();\n        this._symlinkPaths = new Map();\n        this._watched = new Map();\n        this._pendingWrites = new Map();\n        this._pendingUnlinks = new Map();\n        this._readyCount = 0;\n        this._readyEmitted = false;\n        const awf = _opts.awaitWriteFinish;\n        const DEF_AWF = { stabilityThreshold: 2000, pollInterval: 100 };\n        const opts = {\n            // Defaults\n            persistent: true,\n            ignoreInitial: false,\n            ignorePermissionErrors: false,\n            interval: 100,\n            binaryInterval: 300,\n            followSymlinks: true,\n            usePolling: false,\n            // useAsync: false,\n            atomic: true, // NOTE: overwritten later (depends on usePolling)\n            ..._opts,\n            // Change format\n            ignored: _opts.ignored ? arrify(_opts.ignored) : arrify([]),\n            awaitWriteFinish: awf === true ? DEF_AWF : typeof awf === 'object' ? { ...DEF_AWF, ...awf } : false,\n        };\n        // Always default to polling on IBM i because fs.watch() is not available on IBM i.\n        if (isIBMi)\n            opts.usePolling = true;\n        // Editor atomic write normalization enabled by default with fs.watch\n        if (opts.atomic === undefined)\n            opts.atomic = !opts.usePolling;\n        // opts.atomic = typeof _opts.atomic === 'number' ? _opts.atomic : 100;\n        // Global override. Useful for developers, who need to force polling for all\n        // instances of chokidar, regardless of usage / dependency depth\n        const envPoll = process.env.CHOKIDAR_USEPOLLING;\n        if (envPoll !== undefined) {\n            const envLower = envPoll.toLowerCase();\n            if (envLower === 'false' || envLower === '0')\n                opts.usePolling = false;\n            else if (envLower === 'true' || envLower === '1')\n                opts.usePolling = true;\n            else\n                opts.usePolling = !!envLower;\n        }\n        const envInterval = process.env.CHOKIDAR_INTERVAL;\n        if (envInterval)\n            opts.interval = Number.parseInt(envInterval, 10);\n        // This is done to emit ready only once, but each 'add' will increase that?\n        let readyCalls = 0;\n        this._emitReady = () => {\n            readyCalls++;\n            if (readyCalls >= this._readyCount) {\n                this._emitReady = EMPTY_FN;\n                this._readyEmitted = true;\n                // use process.nextTick to allow time for listener to be bound\n                process.nextTick(() => this.emit(EV.READY));\n            }\n        };\n        this._emitRaw = (...args) => this.emit(EV.RAW, ...args);\n        this._boundRemove = this._remove.bind(this);\n        this.options = opts;\n        this._nodeFsHandler = new NodeFsHandler(this);\n        // You’re frozen when your heart’s not open.\n        Object.freeze(opts);\n    }\n    _addIgnoredPath(matcher) {\n        if (isMatcherObject(matcher)) {\n            // return early if we already have a deeply equal matcher object\n            for (const ignored of this._ignoredPaths) {\n                if (isMatcherObject(ignored) &&\n                    ignored.path === matcher.path &&\n                    ignored.recursive === matcher.recursive) {\n                    return;\n                }\n            }\n        }\n        this._ignoredPaths.add(matcher);\n    }\n    _removeIgnoredPath(matcher) {\n        this._ignoredPaths.delete(matcher);\n        // now find any matcher objects with the matcher as path\n        if (typeof matcher === 'string') {\n            for (const ignored of this._ignoredPaths) {\n                // TODO (43081j): make this more efficient.\n                // probably just make a `this._ignoredDirectories` or some\n                // such thing.\n                if (isMatcherObject(ignored) && ignored.path === matcher) {\n                    this._ignoredPaths.delete(ignored);\n                }\n            }\n        }\n    }\n    // Public methods\n    /**\n     * Adds paths to be watched on an existing FSWatcher instance.\n     * @param paths_ file or file list. Other arguments are unused\n     */\n    add(paths_, _origAdd, _internal) {\n        const { cwd } = this.options;\n        this.closed = false;\n        this._closePromise = undefined;\n        let paths = unifyPaths(paths_);\n        if (cwd) {\n            paths = paths.map((path) => {\n                const absPath = getAbsolutePath(path, cwd);\n                // Check `path` instead of `absPath` because the cwd portion can't be a glob\n                return absPath;\n            });\n        }\n        paths.forEach((path) => {\n            this._removeIgnoredPath(path);\n        });\n        this._userIgnored = undefined;\n        if (!this._readyCount)\n            this._readyCount = 0;\n        this._readyCount += paths.length;\n        Promise.all(paths.map(async (path) => {\n            const res = await this._nodeFsHandler._addToNodeFs(path, !_internal, undefined, 0, _origAdd);\n            if (res)\n                this._emitReady();\n            return res;\n        })).then((results) => {\n            if (this.closed)\n                return;\n            results.forEach((item) => {\n                if (item)\n                    this.add(sp.dirname(item), sp.basename(_origAdd || item));\n            });\n        });\n        return this;\n    }\n    /**\n     * Close watchers or start ignoring events from specified paths.\n     */\n    unwatch(paths_) {\n        if (this.closed)\n            return this;\n        const paths = unifyPaths(paths_);\n        const { cwd } = this.options;\n        paths.forEach((path) => {\n            // convert to absolute path unless relative path already matches\n            if (!sp.isAbsolute(path) && !this._closers.has(path)) {\n                if (cwd)\n                    path = sp.join(cwd, path);\n                path = sp.resolve(path);\n            }\n            this._closePath(path);\n            this._addIgnoredPath(path);\n            if (this._watched.has(path)) {\n                this._addIgnoredPath({\n                    path,\n                    recursive: true,\n                });\n            }\n            // reset the cached userIgnored anymatch fn\n            // to make ignoredPaths changes effective\n            this._userIgnored = undefined;\n        });\n        return this;\n    }\n    /**\n     * Close watchers and remove all listeners from watched paths.\n     */\n    close() {\n        if (this._closePromise) {\n            return this._closePromise;\n        }\n        this.closed = true;\n        // Memory management.\n        this.removeAllListeners();\n        const closers = [];\n        this._closers.forEach((closerList) => closerList.forEach((closer) => {\n            const promise = closer();\n            if (promise instanceof Promise)\n                closers.push(promise);\n        }));\n        this._streams.forEach((stream) => stream.destroy());\n        this._userIgnored = undefined;\n        this._readyCount = 0;\n        this._readyEmitted = false;\n        this._watched.forEach((dirent) => dirent.dispose());\n        this._closers.clear();\n        this._watched.clear();\n        this._streams.clear();\n        this._symlinkPaths.clear();\n        this._throttled.clear();\n        this._closePromise = closers.length\n            ? Promise.all(closers).then(() => undefined)\n            : Promise.resolve();\n        return this._closePromise;\n    }\n    /**\n     * Expose list of watched paths\n     * @returns for chaining\n     */\n    getWatched() {\n        const watchList = {};\n        this._watched.forEach((entry, dir) => {\n            const key = this.options.cwd ? sp.relative(this.options.cwd, dir) : dir;\n            const index = key || ONE_DOT;\n            watchList[index] = entry.getChildren().sort();\n        });\n        return watchList;\n    }\n    emitWithAll(event, args) {\n        this.emit(event, ...args);\n        if (event !== EV.ERROR)\n            this.emit(EV.ALL, event, ...args);\n    }\n    // Common helpers\n    // --------------\n    /**\n     * Normalize and emit events.\n     * Calling _emit DOES NOT MEAN emit() would be called!\n     * @param event Type of event\n     * @param path File or directory path\n     * @param stats arguments to be passed with event\n     * @returns the error if defined, otherwise the value of the FSWatcher instance's `closed` flag\n     */\n    async _emit(event, path, stats) {\n        if (this.closed)\n            return;\n        const opts = this.options;\n        if (isWindows)\n            path = sp.normalize(path);\n        if (opts.cwd)\n            path = sp.relative(opts.cwd, path);\n        const args = [path];\n        if (stats != null)\n            args.push(stats);\n        const awf = opts.awaitWriteFinish;\n        let pw;\n        if (awf && (pw = this._pendingWrites.get(path))) {\n            pw.lastChange = new Date();\n            return this;\n        }\n        if (opts.atomic) {\n            if (event === EV.UNLINK) {\n                this._pendingUnlinks.set(path, [event, ...args]);\n                setTimeout(() => {\n                    this._pendingUnlinks.forEach((entry, path) => {\n                        this.emit(...entry);\n                        this.emit(EV.ALL, ...entry);\n                        this._pendingUnlinks.delete(path);\n                    });\n                }, typeof opts.atomic === 'number' ? opts.atomic : 100);\n                return this;\n            }\n            if (event === EV.ADD && this._pendingUnlinks.has(path)) {\n                event = EV.CHANGE;\n                this._pendingUnlinks.delete(path);\n            }\n        }\n        if (awf && (event === EV.ADD || event === EV.CHANGE) && this._readyEmitted) {\n            const awfEmit = (err, stats) => {\n                if (err) {\n                    event = EV.ERROR;\n                    args[0] = err;\n                    this.emitWithAll(event, args);\n                }\n                else if (stats) {\n                    // if stats doesn't exist the file must have been deleted\n                    if (args.length > 1) {\n                        args[1] = stats;\n                    }\n                    else {\n                        args.push(stats);\n                    }\n                    this.emitWithAll(event, args);\n                }\n            };\n            this._awaitWriteFinish(path, awf.stabilityThreshold, event, awfEmit);\n            return this;\n        }\n        if (event === EV.CHANGE) {\n            const isThrottled = !this._throttle(EV.CHANGE, path, 50);\n            if (isThrottled)\n                return this;\n        }\n        if (opts.alwaysStat &&\n            stats === undefined &&\n            (event === EV.ADD || event === EV.ADD_DIR || event === EV.CHANGE)) {\n            const fullPath = opts.cwd ? sp.join(opts.cwd, path) : path;\n            let stats;\n            try {\n                stats = await stat(fullPath);\n            }\n            catch (err) {\n                // do nothing\n            }\n            // Suppress event when fs_stat fails, to avoid sending undefined 'stat'\n            if (!stats || this.closed)\n                return;\n            args.push(stats);\n        }\n        this.emitWithAll(event, args);\n        return this;\n    }\n    /**\n     * Common handler for errors\n     * @returns The error if defined, otherwise the value of the FSWatcher instance's `closed` flag\n     */\n    _handleError(error) {\n        const code = error && error.code;\n        if (error &&\n            code !== 'ENOENT' &&\n            code !== 'ENOTDIR' &&\n            (!this.options.ignorePermissionErrors || (code !== 'EPERM' && code !== 'EACCES'))) {\n            this.emit(EV.ERROR, error);\n        }\n        return error || this.closed;\n    }\n    /**\n     * Helper utility for throttling\n     * @param actionType type being throttled\n     * @param path being acted upon\n     * @param timeout duration of time to suppress duplicate actions\n     * @returns tracking object or false if action should be suppressed\n     */\n    _throttle(actionType, path, timeout) {\n        if (!this._throttled.has(actionType)) {\n            this._throttled.set(actionType, new Map());\n        }\n        const action = this._throttled.get(actionType);\n        if (!action)\n            throw new Error('invalid throttle');\n        const actionPath = action.get(path);\n        if (actionPath) {\n            actionPath.count++;\n            return false;\n        }\n        // eslint-disable-next-line prefer-const\n        let timeoutObject;\n        const clear = () => {\n            const item = action.get(path);\n            const count = item ? item.count : 0;\n            action.delete(path);\n            clearTimeout(timeoutObject);\n            if (item)\n                clearTimeout(item.timeoutObject);\n            return count;\n        };\n        timeoutObject = setTimeout(clear, timeout);\n        const thr = { timeoutObject, clear, count: 0 };\n        action.set(path, thr);\n        return thr;\n    }\n    _incrReadyCount() {\n        return this._readyCount++;\n    }\n    /**\n     * Awaits write operation to finish.\n     * Polls a newly created file for size variations. When files size does not change for 'threshold' milliseconds calls callback.\n     * @param path being acted upon\n     * @param threshold Time in milliseconds a file size must be fixed before acknowledging write OP is finished\n     * @param event\n     * @param awfEmit Callback to be called when ready for event to be emitted.\n     */\n    _awaitWriteFinish(path, threshold, event, awfEmit) {\n        const awf = this.options.awaitWriteFinish;\n        if (typeof awf !== 'object')\n            return;\n        const pollInterval = awf.pollInterval;\n        let timeoutHandler;\n        let fullPath = path;\n        if (this.options.cwd && !sp.isAbsolute(path)) {\n            fullPath = sp.join(this.options.cwd, path);\n        }\n        const now = new Date();\n        const writes = this._pendingWrites;\n        function awaitWriteFinishFn(prevStat) {\n            statcb(fullPath, (err, curStat) => {\n                if (err || !writes.has(path)) {\n                    if (err && err.code !== 'ENOENT')\n                        awfEmit(err);\n                    return;\n                }\n                const now = Number(new Date());\n                if (prevStat && curStat.size !== prevStat.size) {\n                    writes.get(path).lastChange = now;\n                }\n                const pw = writes.get(path);\n                const df = now - pw.lastChange;\n                if (df >= threshold) {\n                    writes.delete(path);\n                    awfEmit(undefined, curStat);\n                }\n                else {\n                    timeoutHandler = setTimeout(awaitWriteFinishFn, pollInterval, curStat);\n                }\n            });\n        }\n        if (!writes.has(path)) {\n            writes.set(path, {\n                lastChange: now,\n                cancelWait: () => {\n                    writes.delete(path);\n                    clearTimeout(timeoutHandler);\n                    return event;\n                },\n            });\n            timeoutHandler = setTimeout(awaitWriteFinishFn, pollInterval);\n        }\n    }\n    /**\n     * Determines whether user has asked to ignore this path.\n     */\n    _isIgnored(path, stats) {\n        if (this.options.atomic && DOT_RE.test(path))\n            return true;\n        if (!this._userIgnored) {\n            const { cwd } = this.options;\n            const ign = this.options.ignored;\n            const ignored = (ign || []).map(normalizeIgnored(cwd));\n            const ignoredPaths = [...this._ignoredPaths];\n            const list = [...ignoredPaths.map(normalizeIgnored(cwd)), ...ignored];\n            this._userIgnored = anymatch(list, undefined);\n        }\n        return this._userIgnored(path, stats);\n    }\n    _isntIgnored(path, stat) {\n        return !this._isIgnored(path, stat);\n    }\n    /**\n     * Provides a set of common helpers and properties relating to symlink handling.\n     * @param path file or directory pattern being watched\n     */\n    _getWatchHelpers(path) {\n        return new WatchHelper(path, this.options.followSymlinks, this);\n    }\n    // Directory helpers\n    // -----------------\n    /**\n     * Provides directory tracking objects\n     * @param directory path of the directory\n     */\n    _getWatchedDir(directory) {\n        const dir = sp.resolve(directory);\n        if (!this._watched.has(dir))\n            this._watched.set(dir, new DirEntry(dir, this._boundRemove));\n        return this._watched.get(dir);\n    }\n    // File helpers\n    // ------------\n    /**\n     * Check for read permissions: https://stackoverflow.com/a/11781404/1358405\n     */\n    _hasReadPermissions(stats) {\n        if (this.options.ignorePermissionErrors)\n            return true;\n        return Boolean(Number(stats.mode) & 0o400);\n    }\n    /**\n     * Handles emitting unlink events for\n     * files and directories, and via recursion, for\n     * files and directories within directories that are unlinked\n     * @param directory within which the following item is located\n     * @param item      base path of item/directory\n     */\n    _remove(directory, item, isDirectory) {\n        // if what is being deleted is a directory, get that directory's paths\n        // for recursive deleting and cleaning of watched object\n        // if it is not a directory, nestedDirectoryChildren will be empty array\n        const path = sp.join(directory, item);\n        const fullPath = sp.resolve(path);\n        isDirectory =\n            isDirectory != null ? isDirectory : this._watched.has(path) || this._watched.has(fullPath);\n        // prevent duplicate handling in case of arriving here nearly simultaneously\n        // via multiple paths (such as _handleFile and _handleDir)\n        if (!this._throttle('remove', path, 100))\n            return;\n        // if the only watched file is removed, watch for its return\n        if (!isDirectory && this._watched.size === 1) {\n            this.add(directory, item, true);\n        }\n        // This will create a new entry in the watched object in either case\n        // so we got to do the directory check beforehand\n        const wp = this._getWatchedDir(path);\n        const nestedDirectoryChildren = wp.getChildren();\n        // Recursively remove children directories / files.\n        nestedDirectoryChildren.forEach((nested) => this._remove(path, nested));\n        // Check if item was on the watched list and remove it\n        const parent = this._getWatchedDir(directory);\n        const wasTracked = parent.has(item);\n        parent.remove(item);\n        // Fixes issue #1042 -> Relative paths were detected and added as symlinks\n        // (https://github.com/paulmillr/chokidar/blob/e1753ddbc9571bdc33b4a4af172d52cb6e611c10/lib/nodefs-handler.js#L612),\n        // but never removed from the map in case the path was deleted.\n        // This leads to an incorrect state if the path was recreated:\n        // https://github.com/paulmillr/chokidar/blob/e1753ddbc9571bdc33b4a4af172d52cb6e611c10/lib/nodefs-handler.js#L553\n        if (this._symlinkPaths.has(fullPath)) {\n            this._symlinkPaths.delete(fullPath);\n        }\n        // If we wait for this file to be fully written, cancel the wait.\n        let relPath = path;\n        if (this.options.cwd)\n            relPath = sp.relative(this.options.cwd, path);\n        if (this.options.awaitWriteFinish && this._pendingWrites.has(relPath)) {\n            const event = this._pendingWrites.get(relPath).cancelWait();\n            if (event === EV.ADD)\n                return;\n        }\n        // The Entry will either be a directory that just got removed\n        // or a bogus entry to a file, in either case we have to remove it\n        this._watched.delete(path);\n        this._watched.delete(fullPath);\n        const eventName = isDirectory ? EV.UNLINK_DIR : EV.UNLINK;\n        if (wasTracked && !this._isIgnored(path))\n            this._emit(eventName, path);\n        // Avoid conflicts if we later create another file with the same name\n        this._closePath(path);\n    }\n    /**\n     * Closes all watchers for a path\n     */\n    _closePath(path) {\n        this._closeFile(path);\n        const dir = sp.dirname(path);\n        this._getWatchedDir(dir).remove(sp.basename(path));\n    }\n    /**\n     * Closes only file-specific watchers\n     */\n    _closeFile(path) {\n        const closers = this._closers.get(path);\n        if (!closers)\n            return;\n        closers.forEach((closer) => closer());\n        this._closers.delete(path);\n    }\n    _addPathCloser(path, closer) {\n        if (!closer)\n            return;\n        let list = this._closers.get(path);\n        if (!list) {\n            list = [];\n            this._closers.set(path, list);\n        }\n        list.push(closer);\n    }\n    _readdirp(root, opts) {\n        if (this.closed)\n            return;\n        const options = { type: EV.ALL, alwaysStat: true, lstat: true, ...opts, depth: 0 };\n        let stream = readdirp(root, options);\n        this._streams.add(stream);\n        stream.once(STR_CLOSE, () => {\n            stream = undefined;\n        });\n        stream.once(STR_END, () => {\n            if (stream) {\n                this._streams.delete(stream);\n                stream = undefined;\n            }\n        });\n        return stream;\n    }\n}\n/**\n * Instantiates watcher with paths to be tracked.\n * @param paths file / directory paths\n * @param options opts, such as `atomic`, `awaitWriteFinish`, `ignored`, and others\n * @returns an instance of FSWatcher for chaining.\n * @example\n * const watcher = watch('.').on('all', (event, path) => { console.log(event, path); });\n * watch('.', { atomic: true, awaitWriteFinish: true, ignored: (f, stats) => stats?.isFile() && !f.endsWith('.js') })\n */\nexport function watch(paths, options = {}) {\n    const watcher = new FSWatcher(options);\n    watcher.add(paths);\n    return watcher;\n}\nexport default { watch: watch, FSWatcher: FSWatcher };\n","import { defineCommand } from 'citty'\nimport { spawn } from 'node:child_process'\nimport { parseFileSpec, type FileSpec } from '../utils/file-spec.js'\nimport { resolveEntrypointBootstrapPath, buildEntrypointEnv } from '../utils/entrypoint-bootstrap.js'\nimport { cliError, formatError } from '../utils/error.js'\nimport { log } from '../ui/output.js'\nimport { theme } from '../ui/theme.js'\nimport { symbols } from '../ui/symbols.js'\nimport { createStartupReporter } from '../ui/startup.js'\n\n/**\n * Whether the startup reporter should animate a spinner for this run.\n *\n * The stdio transport never animates: it is the default transport (see the\n * `transport` arg below and MCP_TRANSPORT's fallback in FastMCP.run), a spawned\n * stdio child never emits any of the reporter's sniff words on stderr (they only\n * ever appear in an HTTP server's \"listening\" line), and buffering its stderr\n * behind a live spinner would hide all output for the process lifetime on a TTY.\n * `--reload` also disables animation: the reporter re-fires on every restart.\n *\n * `transport` here is always the resolved value — `spawnServer` unconditionally\n * sets the spawned child's MCP_TRANSPORT to it (see transportEnv below),\n * overriding anything already in the shell's environment — so no separate\n * MCP_TRANSPORT lookup is needed.\n */\nexport function shouldAnimateStartup(transport: string, reload: boolean): boolean {\n  return transport !== 'stdio' && !reload\n}\n\nfunction spawnServer(\n  spec: FileSpec,\n  env: NodeJS.ProcessEnv,\n): ReturnType<typeof spawn> {\n  const bootstrapPath = resolveEntrypointBootstrapPath()\n  const [cmd, args] = spec.isTypeScript\n    ? ['npx', ['tsx', bootstrapPath]]\n    : ['node', [bootstrapPath]]\n  return spawn(cmd, args, {\n    env: { ...process.env, ...buildEntrypointEnv(spec), ...env },\n    stdio: ['inherit', 'pipe', 'pipe'],\n  })\n}\n\nexport default defineCommand({\n  meta: { name: 'run', description: 'Start an MCP server from a file' },\n  args: {\n    spec: { type: 'positional', description: 'File spec (e.g. server.ts or server.ts:app)', required: true },\n    transport: { type: 'string', description: 'Transport type (stdio|http|sse)', default: 'stdio' },\n    host: { type: 'string', description: 'HTTP host to bind to (for http transport)' },\n    port: { type: 'string', description: 'HTTP port (for http/sse transports)' },\n    path: { type: 'string', description: 'HTTP path to serve on (for http transport)' },\n    reload: { type: 'boolean', description: 'Restart on file change', default: false },\n  },\n  async run({ args }) {\n    let fileSpec\n    try {\n      fileSpec = parseFileSpec(args.spec)\n    } catch (err) {\n      cliError(formatError(err))\n    }\n\n    const transportEnv: Record<string, string> = {\n      MCP_TRANSPORT: args.transport,\n    }\n    if (args.host) transportEnv['MCP_HOST'] = args.host\n    if (args.port) transportEnv['MCP_PORT'] = args.port\n    if (args.path) transportEnv['MCP_PATH'] = args.path\n\n    let child = spawnServer(fileSpec, transportEnv)\n\n    function attachHandlers(proc: ReturnType<typeof spawn>): void {\n      const reporter = createStartupReporter({ animate: shouldAnimateStartup(args.transport, args.reload) })\n\n      proc.stdout?.on('data', (chunk: Buffer) => {\n        reporter.onStdout(chunk.toString())\n      })\n\n      proc.stderr?.on('data', (chunk: Buffer) => {\n        reporter.onStderr(chunk.toString())\n      })\n\n      proc.on('exit', (code) => {\n        if (!reporter.done) reporter.fail()\n        if (code !== null && code !== 0 && !args.reload) {\n          process.exit(code)\n        }\n      })\n    }\n\n    attachHandlers(child)\n\n    if (args.reload) {\n      const { watch } = await import('chokidar')\n      const watcher = watch(fileSpec.filePath, { ignoreInitial: true })\n\n      watcher.on('change', () => {\n        process.stderr.write(`${theme.muted(symbols.reload)} Reloading…\\n`)\n        child.kill()\n        child = spawnServer(fileSpec, transportEnv)\n        attachHandlers(child)\n      })\n    }\n\n    await new Promise<void>((_, reject) => {\n      process.on('SIGINT', () => {\n        child.kill()\n        process.exit(0)\n      })\n      process.on('SIGTERM', () => {\n        child.kill()\n        process.exit(0)\n      })\n      child.on('error', reject)\n    })\n  },\n})\n","import {\n  validateClientMetadataUrl,\n  createPrivateKeyJwtAuth,\n  requestJwtAuthorizationGrant,\n  exchangeJwtAuthGrant,\n  type OAuthClientProvider,\n  type OAuthClientInformationContext,\n  type OAuthDiscoveryState,\n  type OAuthClientMetadata,\n  type StoredOAuthClientInformation,\n  type StoredOAuthTokens,\n  type AddClientAuthentication,\n  type ClientAuthMethod,\n} from \"@modelcontextprotocol/client\";\n\n// ---------------------------------------------------------------------------\n// OAuthToken — internal type used by ClientCredentials for expiry tracking.\n// Not the SDK's OAuthTokens: we track expires_at in milliseconds.\n// ---------------------------------------------------------------------------\n\nexport type OAuthToken = {\n  access_token: string\n  token_type?: string\n  refresh_token?: string\n  /** Unix timestamp in milliseconds (normalized internally). */\n  expires_at?: number\n  /** Seconds until expiry — used to compute expires_at on receipt. */\n  expires_in?: number\n  scope?: string\n}\n\n// ---------------------------------------------------------------------------\n// AsyncHeaderAuth — the shape of a token-acquiring auth provider\n// ---------------------------------------------------------------------------\n\n/**\n * An auth provider that acquires a token asynchronously and injects it as a\n * request header per request. {@link ClientCredentials}, {@link JwtBearerAuth},\n * and {@link EnterpriseManagedAuth} all implement it. The transport recognizes\n * these by their `kind` discriminant and injects `getHeaders()` on every\n * request via a custom fetch wrapper (unlike static `BearerAuth`, whose header\n * never changes, or interactive `OAuth`, which the SDK transport drives itself).\n */\nexport interface AsyncHeaderAuth {\n  readonly kind: string\n  getHeaders(): Promise<Record<string, string>>\n}\n\n// ---------------------------------------------------------------------------\n// KeyValueStore — single persistence interface for all auth state\n// ---------------------------------------------------------------------------\n\nexport type KeyValueStore = {\n  get(key: string): Promise<string | null>\n  set(key: string, value: string): Promise<void>\n  delete(key: string): Promise<void>\n}\n\n// ---------------------------------------------------------------------------\n// InMemoryStore\n// ---------------------------------------------------------------------------\n\nexport class InMemoryStore implements KeyValueStore {\n  private readonly _map = new Map<string, string>()\n\n  async get(key: string): Promise<string | null> {\n    return this._map.get(key) ?? null\n  }\n\n  async set(key: string, value: string): Promise<void> {\n    this._map.set(key, value)\n  }\n\n  async delete(key: string): Promise<void> {\n    this._map.delete(key)\n  }\n}\n\n// ---------------------------------------------------------------------------\n// FileTokenStorage\n// ---------------------------------------------------------------------------\n\nexport class FileTokenStorage implements KeyValueStore {\n  private readonly _explicitPath?: string\n  private _resolvedPath?: string\n\n  constructor(path?: string) {\n    this._explicitPath = path\n  }\n\n  private async _path(): Promise<string> {\n    if (this._resolvedPath) return this._resolvedPath\n    if (this._explicitPath) return (this._resolvedPath = this._explicitPath)\n    const { homedir } = await import('os')\n    const { join } = await import('path')\n    return (this._resolvedPath = join(homedir(), '.fastmcp', 'tokens.json'))\n  }\n\n  private async _readAll(): Promise<Record<string, string>> {\n    const fs = await import('fs/promises')\n    try {\n      const raw = await fs.readFile(await this._path(), 'utf8')\n      const parsed: unknown = JSON.parse(raw)\n      if (typeof parsed === 'object' && parsed !== null && !Array.isArray(parsed)) {\n        return parsed as Record<string, string>\n      }\n      return {}\n    } catch {\n      return {}\n    }\n  }\n\n  private async _writeAll(data: Record<string, string>): Promise<void> {\n    const fs = await import('fs/promises')\n    const { dirname } = await import('path')\n    const path = await this._path()\n    await fs.mkdir(dirname(path), { recursive: true })\n    const tmp = `${path}.tmp`\n    await fs.writeFile(tmp, JSON.stringify(data, null, 2), 'utf8')\n    await fs.rename(tmp, path)\n  }\n\n  async get(key: string): Promise<string | null> {\n    const data = await this._readAll()\n    return data[key] ?? null\n  }\n\n  async set(key: string, value: string): Promise<void> {\n    const data = await this._readAll()\n    data[key] = value\n    await this._writeAll(data)\n  }\n\n  async delete(key: string): Promise<void> {\n    const data = await this._readAll()\n    if (!(key in data)) return\n    delete data[key]\n    await this._writeAll(data)\n  }\n}\n\n// ---------------------------------------------------------------------------\n// OAuth — implements OAuthClientProvider (authorization code + PKCE flow)\n// ---------------------------------------------------------------------------\n\nexport interface OAuthOptions {\n  /** Pre-registered client ID. When set, Dynamic Client Registration is skipped. */\n  clientId?: string\n  /** Pre-registered client secret. */\n  clientSecret?: string\n  /** Requested OAuth scopes (space-separated string or array). */\n  scopes?: string | string[]\n  /** Client name used in Dynamic Client Registration. Default: \"FastMCP Client\". */\n  clientName?: string\n  /** Persistent key-value store for tokens, client info, and discovery state. Default: in-memory. */\n  store?: KeyValueStore\n  /**\n   * Port for the local OAuth callback server. Default: 8765.\n   * The port must be consistent across calls because it is registered as the\n   * redirect_uri during Dynamic Client Registration.\n   */\n  callbackPort?: number\n  /**\n   * Override how the authorization URL is opened. When not provided the\n   * system browser is launched. Inject a no-op or mock here for testing.\n   */\n  onRedirect?: (url: URL) => void | Promise<void>\n  /**\n   * Client ID Metadata Document URL (SEP-991 / CIMD) — an HTTPS URL, with a\n   * non-root path, that serves this client's metadata document. When the\n   * authorization server advertises `client_id_metadata_document_supported`,\n   * the SDK's `auth()` orchestrator uses this URL directly as the `client_id`\n   * and skips Dynamic Client Registration entirely. Falls back to normal DCR\n   * (or `clientId`, if set) when the server doesn't support CIMD. Validated\n   * eagerly in the constructor.\n   */\n  clientMetadataUrl?: string\n}\n\nexport class OAuth implements OAuthClientProvider {\n  private _serverUrl = ''\n  private readonly _clientId?: string\n  private readonly _clientSecret?: string\n  private readonly _scopes?: string\n  private readonly _clientName: string\n  private readonly _store: KeyValueStore\n  private readonly _callbackPort: number\n  private readonly _onRedirect?: (url: URL) => void | Promise<void>\n  readonly clientMetadataUrl?: string\n\n  private _codeVerifier: string | undefined\n  protected _callbackPromise: Promise<URLSearchParams> | null = null\n  protected _callbackResolve: ((params: URLSearchParams) => void) | null = null\n  protected _callbackReject: ((err: Error) => void) | null = null\n  private _callbackServer: { close(): void } | null = null\n  private _actualCallbackPort: number | null = null\n\n  constructor(options: OAuthOptions = {}) {\n    this._clientId = options.clientId\n    this._clientSecret = options.clientSecret\n    this._scopes = Array.isArray(options.scopes)\n      ? options.scopes.join(' ')\n      : options.scopes\n    this._clientName = options.clientName ?? 'FastMCP Client'\n    this._store = options.store ?? new InMemoryStore()\n    this._callbackPort = options.callbackPort ?? 8765\n    this._onRedirect = options.onRedirect\n    // SEP-991: validated eagerly so a malformed clientMetadataUrl fails fast\n    // at construction rather than deep inside the auth() flow.\n    validateClientMetadataUrl(options.clientMetadataUrl)\n    this.clientMetadataUrl = options.clientMetadataUrl\n  }\n\n  /**\n   * Binds the MCP server URL so that all storage keys are namespaced by it.\n   * Called by Client before connecting.\n   */\n  _bind(serverUrl: string): void {\n    this._serverUrl = serverUrl\n  }\n\n  // ---- OAuthClientProvider interface ----\n\n  get redirectUrl(): string | URL {\n    const port = this._actualCallbackPort ?? this._callbackPort\n    return `http://localhost:${port}/callback`\n  }\n\n  get clientMetadata(): OAuthClientMetadata {\n    const port = this._actualCallbackPort ?? this._callbackPort\n    return {\n      redirect_uris: [`http://localhost:${port}/callback`],\n      token_endpoint_auth_method: this._clientSecret ? 'client_secret_post' : 'none',\n      // grant_types is intentionally omitted: the SDK's resolveClientMetadata()\n      // defaults interactive providers (those with a redirectUrl, like this one)\n      // to ['authorization_code', 'refresh_token'] (SEP-2207) — authorization\n      // servers that gate refresh-token issuance on the registered grant types\n      // need 'refresh_token' present to ever issue one during DCR. Setting this\n      // explicitly here would suppress that default (an explicit field is never\n      // overwritten) and could silently prevent refresh tokens from being\n      // issued, even though this class fully supports using one once present.\n      response_types: ['code'],\n      client_name: this._clientName,\n      ...(this._scopes ? { scope: this._scopes } : {}),\n    }\n  }\n\n  async clientInformation(\n    ctx?: OAuthClientInformationContext,\n  ): Promise<StoredOAuthClientInformation | undefined> {\n    if (this._clientId) {\n      return {\n        client_id: this._clientId,\n        ...(this._clientSecret ? { client_secret: this._clientSecret } : {}),\n      }\n    }\n    const issuer = ctx?.issuer ?? (await this._lastIssuer())\n    const raw = await this._store.get(this._key('client_info', issuer))\n    if (!raw) return undefined\n    return JSON.parse(raw) as StoredOAuthClientInformation\n  }\n\n  async saveClientInformation(\n    info: StoredOAuthClientInformation,\n    ctx?: OAuthClientInformationContext,\n  ): Promise<void> {\n    if (this._clientId) return  // pre-registered — never overwrite with DCR response\n    if (ctx?.issuer) await this._rememberIssuer(ctx.issuer)\n    await this._store.set(this._key('client_info', ctx?.issuer), JSON.stringify(info))\n  }\n\n  async tokens(ctx?: OAuthClientInformationContext): Promise<StoredOAuthTokens | undefined> {\n    // Per SEP-2352: the per-request bearer-token read (adaptOAuthProvider's\n    // token() bridge) calls this with no ctx at all, so it must resolve the\n    // most-recently-saved token set rather than returning undefined.\n    const issuer = ctx?.issuer ?? (await this._lastIssuer())\n    const raw = await this._store.get(this._key('tokens', issuer))\n    if (!raw) return undefined\n    return JSON.parse(raw) as StoredOAuthTokens\n  }\n\n  async saveTokens(tokens: StoredOAuthTokens, ctx?: OAuthClientInformationContext): Promise<void> {\n    if (ctx?.issuer) await this._rememberIssuer(ctx.issuer)\n    await this._store.set(this._key('tokens', ctx?.issuer), JSON.stringify(tokens))\n  }\n\n  async redirectToAuthorization(authorizationUrl: URL): Promise<void> {\n    this._armCallbackPromise()\n    await this._startCallbackServer()\n    if (this._onRedirect) {\n      await this._onRedirect(authorizationUrl)\n    } else {\n      await openBrowser(authorizationUrl.toString())\n    }\n  }\n\n  /**\n   * Creates the pending-callback promise that {@link waitForCallback} awaits.\n   * Subclasses (e.g. BrowserOAuth) call this before opening their own redirect.\n   */\n  protected _armCallbackPromise(): void {\n    this._callbackPromise = new Promise<URLSearchParams>((resolve, reject) => {\n      this._callbackResolve = resolve\n      this._callbackReject = reject\n    })\n    // Suppress unhandled-rejection warnings — the promise is observed via Promise.race.\n    this._callbackPromise.catch(() => {})\n  }\n\n  /** Resolves the pending callback with the full authorization callback params. */\n  protected _resolveCallback(params: URLSearchParams): void {\n    this._callbackResolve?.(params)\n  }\n\n  /** Rejects the pending callback with an error. */\n  protected _rejectCallback(err: Error): void {\n    this._callbackReject?.(err)\n  }\n\n  /**\n   * Races the pending callback promise against a timeout and clears the\n   * promise state. Subclasses reuse this and add their own teardown.\n   */\n  protected async _awaitCallback(timeoutMs: number): Promise<URLSearchParams> {\n    if (!this._callbackPromise) {\n      throw new Error('No pending OAuth callback — call redirectToAuthorization() first')\n    }\n    const timeout = new Promise<never>((_, reject) =>\n      setTimeout(\n        () => reject(new Error('OAuth callback timed out waiting for authorization')),\n        timeoutMs,\n      ),\n    )\n    try {\n      return await Promise.race([this._callbackPromise, timeout])\n    } finally {\n      this._callbackPromise = null\n      this._callbackResolve = null\n      this._callbackReject = null\n    }\n  }\n\n  saveCodeVerifier(codeVerifier: string): void {\n    this._codeVerifier = codeVerifier\n  }\n\n  codeVerifier(): string {\n    if (this._codeVerifier === undefined) {\n      throw new Error('No PKCE code verifier has been saved')\n    }\n    return this._codeVerifier\n  }\n\n  async invalidateCredentials(\n    scope: 'all' | 'client' | 'tokens' | 'verifier' | 'discovery',\n  ): Promise<void> {\n    const issuer = await this._lastIssuer()\n    if (scope === 'all' || scope === 'tokens') {\n      await this._store.delete(this._key('tokens', issuer))\n      await this._store.delete(this._key('tokens'))  // pre-issuer-keying entries, if any\n    }\n    if (scope === 'all' || scope === 'client') {\n      await this._store.delete(this._key('client_info', issuer))\n      await this._store.delete(this._key('client_info'))\n    }\n    if (scope === 'all' || scope === 'verifier') {\n      this._codeVerifier = undefined\n    }\n    if (scope === 'all' || scope === 'discovery') {\n      await this._store.delete(this._key('discovery'))\n    }\n  }\n\n  async saveDiscoveryState(state: OAuthDiscoveryState): Promise<void> {\n    await this._store.set(this._key('discovery'), JSON.stringify(state))\n  }\n\n  async discoveryState(): Promise<OAuthDiscoveryState | undefined> {\n    const raw = await this._store.get(this._key('discovery'))\n    if (!raw) return undefined\n    return JSON.parse(raw) as OAuthDiscoveryState\n  }\n\n  // ---- Internal helpers ----\n\n  /**\n   * Returns the actual port the callback server bound to.\n   * Only populated after redirectToAuthorization() has been called.\n   */\n  get callbackServerPort(): number | null {\n    return this._actualCallbackPort\n  }\n\n  /**\n   * Waits for the OAuth authorization code to arrive via the callback server,\n   * then stops the server and resolves with the full callback `URLSearchParams`\n   * (including `code` and, when present, the RFC 9207 `iss` parameter).\n   *\n   * Must be called after the UnauthorizedError thrown by connect() is caught.\n   * Pass the result directly to the transport's `finishAuth(callbackParams)`.\n   */\n  async waitForCallback(timeoutMs = 5 * 60 * 1000): Promise<URLSearchParams> {\n    try {\n      return await this._awaitCallback(timeoutMs)\n    } finally {\n      this._stopCallbackServer()\n    }\n  }\n\n  private _key(type: string, issuer?: string): string {\n    return issuer ? `${issuer}/${type}` : `${this._serverUrl}/${type}`\n  }\n\n  /** Storage key for the \"last issuer seen for this server\" pointer (SEP-2352). */\n  private _issuerPointerKey(): string {\n    return `${this._serverUrl}/issuer`\n  }\n\n  /**\n   * Remembers the resolved authorization-server issuer for this MCP server,\n   * so later no-ctx reads (e.g. the transport's per-request bearer-token read)\n   * know which issuer-keyed credential set to return.\n   */\n  private async _rememberIssuer(issuer: string): Promise<void> {\n    await this._store.set(this._issuerPointerKey(), issuer)\n  }\n\n  private async _lastIssuer(): Promise<string | undefined> {\n    return (await this._store.get(this._issuerPointerKey())) ?? undefined\n  }\n\n  private async _startCallbackServer(): Promise<void> {\n    if (this._callbackServer) return\n    const http = await import('http')\n    await new Promise<void>((resolve, reject) => {\n      const server = http.createServer((req, res) => {\n        const url = new URL(req.url ?? '/', `http://localhost`)\n        const error = url.searchParams.get('error')\n        if (error && this._callbackReject) {\n          const description = url.searchParams.get('error_description') ?? error\n          this._callbackReject(new Error(`OAuth authorization denied: ${description}`))\n          res.writeHead(200, { 'content-type': 'text/html' })\n          res.end(\n            '<html><body><h1>Authorization denied</h1><p>You may close this tab.</p></body></html>',\n          )\n          return\n        }\n        const code = url.searchParams.get('code')\n        if (code && this._callbackResolve) {\n          this._callbackResolve(url.searchParams)\n          res.writeHead(200, { 'content-type': 'text/html' })\n          res.end(\n            '<html><body><h1>Authorization complete</h1><p>You may close this tab.</p></body></html>',\n          )\n        } else {\n          res.writeHead(400)\n          res.end('Missing code parameter')\n        }\n      })\n      server.on('error', reject)\n      server.listen(this._callbackPort, () => {\n        const addr = server.address()\n        if (addr && typeof addr !== 'string') {\n          this._actualCallbackPort = addr.port\n        }\n        this._callbackServer = server\n        resolve()\n      })\n    })\n  }\n\n  private _stopCallbackServer(): void {\n    this._callbackServer?.close()\n    this._callbackServer = null\n    this._actualCallbackPort = null\n  }\n}\n\n// ---------------------------------------------------------------------------\n// BearerAuth\n// ---------------------------------------------------------------------------\n\nexport class BearerAuth {\n  private readonly _token: string\n\n  constructor(token: string) {\n    // Strip any existing Bearer prefix to avoid double-prepending\n    this._token = token.startsWith('Bearer ') ? token.slice(7) : token\n  }\n\n  getHeaders(): Record<string, string> {\n    return { Authorization: `Bearer ${this._token}` }\n  }\n}\n\n// ---------------------------------------------------------------------------\n// ClientCredentials — OAuth 2.0 client credentials grant (machine-to-machine)\n// ---------------------------------------------------------------------------\n\n/** Token-endpoint authentication method for a shared client secret. */\nexport type ClientSecretAuthMethod = 'client_secret_post' | 'client_secret_basic'\n\n/** Fields common to every {@link ClientCredentials} configuration. */\ninterface ClientCredentialsBaseOptions {\n  tokenEndpoint: string\n  clientId: string\n  scope?: string\n  /**\n   * Persistent token store. Default: in-memory. The cache key is derived from\n   * `tokenEndpoint` alone, with no client identity in it — use one store per\n   * credential identity. Do not share a persistent `store` across two\n   * `ClientCredentials` instances that have different `clientId`/`clientSecret`/\n   * `privateKey` but the same `tokenEndpoint`; they will read and overwrite\n   * each other's cached tokens.\n   */\n  store?: KeyValueStore\n  /** How many seconds before expiry to proactively re-fetch. Default: 60. */\n  refreshBufferSeconds?: number\n}\n\n/**\n * Shared-secret configuration for {@link ClientCredentials}.\n *\n * `authMethod` selects how the secret reaches the token endpoint:\n * - `client_secret_post` (default) — `client_id` and `client_secret` in the\n *   POST body. Unchanged from earlier releases.\n * - `client_secret_basic` — an RFC 6749 §2.3.1 HTTP Basic `Authorization`\n *   header. Nothing secret goes in the body.\n */\nexport interface ClientSecretCredentialsOptions extends ClientCredentialsBaseOptions {\n  clientSecret: string\n  /** Token-endpoint authentication method. Default: `client_secret_post`. */\n  authMethod?: ClientSecretAuthMethod\n  privateKey?: never\n  algorithm?: never\n}\n\n/**\n * `private_key_jwt` configuration for {@link ClientCredentials} (RFC 7523 /\n * SEP-1046): the client proves its identity with a signed JWT `client_assertion`\n * instead of a shared secret. The assertion is signed by the SDK's own\n * `private_key_jwt` machinery — no secret is ever sent to the token endpoint.\n */\nexport interface PrivateKeyJwtCredentialsOptions extends ClientCredentialsBaseOptions {\n  /** Signing key: a PEM (PKCS#8) string, its bytes, or a JWK object. */\n  privateKey: string | Uint8Array | Record<string, unknown>\n  /** JWS signing algorithm, e.g. `ES256` or `RS256`. */\n  algorithm: string\n  /**\n   * The assertion's `aud` claim. Required — there is no safe default, because\n   * this provider does no discovery and cannot learn the authorization server's\n   * identity on its own. RFC 7523 §3 recommends the authorization server's\n   * `issuer` identifier; some servers instead verify against the token endpoint\n   * URL. Set whichever your server checks (issuer is the more common choice).\n   */\n  audience: string\n  /** Assertion lifetime in seconds. Default: 300. */\n  jwtLifetimeSeconds?: number\n  /** Extra claims merged over the standard `iss`/`sub`/`aud`/`exp`/`iat`/`jti`. */\n  claims?: Record<string, unknown>\n  clientSecret?: never\n  authMethod?: never\n}\n\n/**\n * Configuration for {@link ClientCredentials}. A discriminated union: supply\n * either a `clientSecret` (with an optional `authMethod`) or a `privateKey`\n * (with its `algorithm`) — the two are mutually exclusive and enforced at\n * compile time.\n */\nexport type ClientCredentialsOptions =\n  | ClientSecretCredentialsOptions\n  | PrivateKeyJwtCredentialsOptions\n\nconst DEFAULT_REFRESH_BUFFER_SECONDS = 60\n\n/** Internal discriminant for the selected token-endpoint auth method. */\ntype TokenEndpointAuthMethod = ClientSecretAuthMethod | 'private_key_jwt'\n\n/**\n * Builds an RFC 6749 §2.3.1 HTTP Basic `Authorization` header value. The client\n * id and secret are each percent-encoded (RFC 3986, via `encodeURIComponent` —\n * space becomes `%20`, not `+`), which a conformant §2.3.1 decoder accepts, then\n * joined with a colon and Base64-encoded.\n */\nfunction basicAuthHeader(clientId: string, clientSecret: string): string {\n  const credentials = `${encodeURIComponent(clientId)}:${encodeURIComponent(clientSecret)}`\n  return `Basic ${btoa(credentials)}`\n}\n\nfunction normalizeToken(token: OAuthToken): OAuthToken {\n  if (typeof token.expires_at === 'number' && token.expires_at > 0) {\n    if (token.expires_at < 1e10) {\n      return { ...token, expires_at: token.expires_at * 1000 }\n    }\n    return token\n  }\n  if (typeof token.expires_in === 'number' && token.expires_in > 0) {\n    return { ...token, expires_at: Date.now() + token.expires_in * 1000 }\n  }\n  return token\n}\n\nfunction isExpiring(token: OAuthToken, bufferMs: number): boolean {\n  if (token.expires_at == null) return false\n  return token.expires_at - Date.now() <= bufferMs\n}\n\n/**\n * A persisted, single-flight token cache shared by every non-interactive token\n * provider ({@link ClientCredentials}, {@link JwtBearerAuth},\n * {@link EnterpriseManagedAuth}). It reads the store, returns a still-valid\n * token, and otherwise coalesces concurrent fetches into one call of the\n * provider's `fetcher`, normalizes the result (computing `expires_at`), and\n * persists it. Providers supply only the grant-specific network call — the\n * caching, expiry, and coalescing live here once, not per provider.\n */\nclass TokenCache {\n  private _fetchPromise: Promise<OAuthToken> | null = null\n\n  constructor(\n    private readonly _store: KeyValueStore,\n    private readonly _key: string,\n    private readonly _bufferMs: number,\n  ) {}\n\n  async get(fetcher: () => Promise<OAuthToken>): Promise<OAuthToken> {\n    const raw = await this._store.get(this._key)\n    if (raw) {\n      const normalized = normalizeToken(JSON.parse(raw) as OAuthToken)\n      if (!isExpiring(normalized, this._bufferMs)) return normalized\n    }\n    this._fetchPromise ??= (async () => {\n      const token = normalizeToken(await fetcher())\n      if (!token.access_token) {\n        throw new Error('token response missing access_token')\n      }\n      await this._store.set(this._key, JSON.stringify(token))\n      return token\n    })().finally(() => {\n      this._fetchPromise = null\n    })\n    return this._fetchPromise\n  }\n}\n\nexport class ClientCredentials implements AsyncHeaderAuth {\n  readonly kind = 'client_credentials' as const\n\n  private readonly _tokenEndpoint: string\n  private readonly _clientId: string\n  private readonly _scope?: string\n  private readonly _authMethod: TokenEndpointAuthMethod\n  /** Set for `client_secret_post` / `client_secret_basic`. */\n  private readonly _clientSecret?: string\n  /**\n   * Set for `private_key_jwt`. The SDK's `createPrivateKeyJwtAuth` signs the\n   * assertion and stamps `client_assertion` / `client_assertion_type` onto the\n   * token-request params — we reuse it verbatim instead of hand-rolling JOSE.\n   */\n  private readonly _addClientAssertion?: AddClientAuthentication\n  private readonly _cache: TokenCache\n\n  constructor(options: ClientCredentialsOptions) {\n    this._tokenEndpoint = options.tokenEndpoint\n    this._clientId = options.clientId\n    this._scope = options.scope\n    const store = options.store ?? new InMemoryStore()\n    const bufferMs =\n      (options.refreshBufferSeconds ?? DEFAULT_REFRESH_BUFFER_SECONDS) * 1000\n    this._cache = new TokenCache(store, `${this._tokenEndpoint}/token`, bufferMs)\n\n    if (options.privateKey !== undefined) {\n      this._authMethod = 'private_key_jwt'\n      this._addClientAssertion = createPrivateKeyJwtAuth({\n        issuer: options.clientId,\n        subject: options.clientId,\n        privateKey: options.privateKey,\n        alg: options.algorithm,\n        audience: options.audience,\n        lifetimeSeconds: options.jwtLifetimeSeconds,\n        claims: options.claims,\n      })\n    } else {\n      this._authMethod = options.authMethod ?? 'client_secret_post'\n      this._clientSecret = options.clientSecret\n    }\n  }\n\n  async getHeaders(): Promise<Record<string, string>> {\n    const token = await this._cache.get(() => this._fetchToken())\n    const type = token.token_type?.trim() || 'Bearer'\n    return { Authorization: `${type} ${token.access_token}` }\n  }\n\n  private async _fetchToken(): Promise<OAuthToken> {\n    const params = new URLSearchParams({ grant_type: 'client_credentials' })\n    const headers: Record<string, string> = {\n      'content-type': 'application/x-www-form-urlencoded',\n    }\n\n    if (this._authMethod === 'private_key_jwt') {\n      // private_key_jwt: the SDK signs the assertion and stamps\n      // client_assertion / client_assertion_type onto the params.\n      if (this._scope) params.set('scope', this._scope)\n      await this._addClientAssertion!(new Headers(), params, this._tokenEndpoint)\n    } else if (this._authMethod === 'client_secret_basic') {\n      // client_secret_basic: credentials go in the Authorization header only.\n      if (this._scope) params.set('scope', this._scope)\n      headers.Authorization = basicAuthHeader(this._clientId, this._clientSecret!)\n    } else {\n      // client_secret_post (default): credentials in the body. Field order is\n      // kept identical to earlier releases so the request stays byte-for-byte\n      // the same for existing callers.\n      params.set('client_id', this._clientId)\n      params.set('client_secret', this._clientSecret!)\n      if (this._scope) params.set('scope', this._scope)\n    }\n\n    const response = await fetch(this._tokenEndpoint, {\n      method: 'POST',\n      headers,\n      body: params.toString(),\n    })\n\n    if (!response.ok) {\n      const detail = await response.text().catch(() => '')\n      throw new Error(\n        `ClientCredentials token fetch failed (${response.status})${detail ? `: ${detail}` : ''}`,\n      )\n    }\n\n    const data = (await response.json()) as Partial<OAuthToken>\n    if (!data.access_token) {\n      throw new Error('ClientCredentials token response missing access_token')\n    }\n    return data as OAuthToken\n  }\n}\n\n// ---------------------------------------------------------------------------\n// JwtBearerAuth — RFC 7523 §2.1 JWT-bearer grant (SEP-1933 workload identity)\n// ---------------------------------------------------------------------------\n\n/** A workload assertion: a signed JWT string, or an (async) factory for one. */\nexport type AssertionSource = string | (() => string | Promise<string>)\n\n/**\n * Configuration for {@link JwtBearerAuth}.\n *\n * The client presents a pre-issued, signed JWT (`assertion`) directly to the\n * token endpoint under `grant_type=urn:ietf:params:oauth:grant-type:jwt-bearer`\n * (RFC 7523 §2.1). No interactive authorization, no client secret by default —\n * this is the workload-identity-federation shape (SEP-1933): a workload proves\n * its identity with a JWT its runtime already minted (a Kubernetes projected\n * service-account token, a cloud instance-identity JWT, etc.).\n */\nexport interface JwtBearerOptions {\n  /** The authorization server's token endpoint. */\n  tokenEndpoint: string\n  /**\n   * The workload assertion (a signed JWT). Pass a string for a fixed assertion,\n   * or a callback to mint/read a fresh one each time a token is fetched (the\n   * usual case — workload JWTs are short-lived).\n   */\n  assertion: AssertionSource\n  /** The client identifier registered for this workload. */\n  clientId?: string\n  /**\n   * Token-endpoint client authentication. Default: `none` (public client — the\n   * assertion itself is the credential, so no separate client secret is sent).\n   */\n  authMethod?: ClientAuthMethod\n  /** Client secret, when `authMethod` is `client_secret_basic`/`_post`. */\n  clientSecret?: string\n  /** Requested scopes (space-separated). */\n  scope?: string\n  /**\n   * Persistent token store. Default: in-memory. The cache key is derived from\n   * `tokenEndpoint` alone, with no client identity in it — use one store per\n   * credential identity. Do not share a persistent `store` across two\n   * `JwtBearerAuth` instances that have different `clientId`/`assertion` but\n   * the same `tokenEndpoint`; they will read and overwrite each other's\n   * cached tokens.\n   */\n  store?: KeyValueStore\n  /** How many seconds before expiry to proactively re-fetch. Default: 60. */\n  refreshBufferSeconds?: number\n}\n\nexport class JwtBearerAuth implements AsyncHeaderAuth {\n  readonly kind = 'jwt_bearer' as const\n\n  private readonly _tokenEndpoint: string\n  private readonly _assertion: AssertionSource\n  private readonly _clientId?: string\n  private readonly _authMethod: ClientAuthMethod\n  private readonly _clientSecret?: string\n  private readonly _scope?: string\n  private readonly _cache: TokenCache\n\n  constructor(options: JwtBearerOptions) {\n    this._tokenEndpoint = options.tokenEndpoint\n    this._assertion = options.assertion\n    this._clientId = options.clientId\n    this._authMethod = options.authMethod ?? 'none'\n    this._clientSecret = options.clientSecret\n    this._scope = options.scope\n    const store = options.store ?? new InMemoryStore()\n    const bufferMs =\n      (options.refreshBufferSeconds ?? DEFAULT_REFRESH_BUFFER_SECONDS) * 1000\n    this._cache = new TokenCache(store, `${this._tokenEndpoint}/jwt-bearer`, bufferMs)\n  }\n\n  async getHeaders(): Promise<Record<string, string>> {\n    const token = await this._cache.get(() => this._fetchToken())\n    const type = token.token_type?.trim() || 'Bearer'\n    return { Authorization: `${type} ${token.access_token}` }\n  }\n\n  private async _fetchToken(): Promise<OAuthToken> {\n    const assertion =\n      typeof this._assertion === 'function' ? await this._assertion() : this._assertion\n    // Reuse the SDK's RFC 7523 wire helper: it POSTs\n    // grant_type=jwt-bearer + assertion and applies the chosen client auth.\n    // A body rewrite is needed when a scope is configured (the helper takes no\n    // scope param) or when no clientId is set (the helper's public-client path\n    // always writes client_id, so we drop the empty value it would emit).\n    const needsRewrite = this._scope !== undefined || this._clientId === undefined\n    const tokens = await exchangeJwtAuthGrant({\n      tokenEndpoint: this._tokenEndpoint,\n      jwtAuthGrant: assertion,\n      clientId: this._clientId ?? '',\n      ...(this._clientSecret ? { clientSecret: this._clientSecret } : {}),\n      authMethod: this._authMethod,\n      ...(needsRewrite ? { fetchFn: this._rewriteBody() } : {}),\n    })\n    return tokens as OAuthToken\n  }\n\n  /**\n   * Wraps fetch to fix up the token-request body the SDK helper builds:\n   * appends `scope` when configured (RFC 7523 §2.1 allows it alongside the\n   * assertion), and drops an empty `client_id` when no client identifier is set\n   * (the helper's public-client path always writes one — we send no `client_id`\n   * at all rather than `client_id=`).\n   */\n  private _rewriteBody() {\n    return async (url: string | URL, init?: RequestInit): Promise<Response> => {\n      const body = new URLSearchParams((init?.body as string) ?? '')\n      if (this._scope !== undefined && !body.has('scope')) body.set('scope', this._scope)\n      if (this._clientId === undefined && body.get('client_id') === '') {\n        body.delete('client_id')\n      }\n      return fetch(url, { ...init, body: body.toString() })\n    }\n  }\n}\n\n// ---------------------------------------------------------------------------\n// EnterpriseManagedAuth — SEP-990 token exchange + JWT-bearer grant\n// ---------------------------------------------------------------------------\n\n/**\n * Configuration for {@link EnterpriseManagedAuth} (SEP-990, Enterprise-Managed\n * Authorization / Cross-App Access).\n *\n * The flow is two hops, both stable RFCs:\n *  1. **Token exchange** (RFC 8693) at the enterprise IdP: exchange the user's\n *     OpenID Connect ID token for an *identity assertion JWT authorization\n *     grant* (ID-JAG) scoped to the target MCP server.\n *  2. **JWT-bearer grant** (RFC 7523) at the MCP server's authorization server:\n *     present the ID-JAG under `grant_type=jwt-bearer` to obtain the access\n *     token.\n */\nexport interface EnterpriseManagedOptions {\n  /** The MCP server's authorization-server token endpoint (step 2). */\n  tokenEndpoint: string\n  /** The MCP client identifier registered with the authorization server. */\n  clientId: string\n  /** The MCP client secret (default client auth is `client_secret_basic`). */\n  clientSecret?: string\n  /** Client-authentication method for step 2. Default: `client_secret_basic`. */\n  authMethod?: ClientAuthMethod\n  /**\n   * The ID-JAG audience — the target authorization server's identifier. The\n   * authorization server verifies the ID-JAG `aud` against this.\n   */\n  audience: string\n  /**\n   * The protected-resource identifier of the target MCP server (RFC 9728). The\n   * authorization server verifies the ID-JAG `resource` against this.\n   */\n  resource: string\n  /** The enterprise IdP's token endpoint (step 1). */\n  idpTokenEndpoint: string\n  /** The client identifier registered with the IdP for token exchange. */\n  idpClientId: string\n  /** The client secret for the IdP token exchange, if the IdP requires one. */\n  idpClientSecret?: string\n  /**\n   * The user's OpenID Connect ID token (the `subject_token` of the exchange).\n   * Pass a string, or a callback to read a fresh one each fetch.\n   */\n  idToken: AssertionSource\n  /** Requested scopes (space-separated). */\n  scope?: string\n  /**\n   * Persistent token store. Default: in-memory. The cache key is derived from\n   * `tokenEndpoint` alone, with no client identity in it — use one store per\n   * credential identity. Do not share a persistent `store` across two\n   * `EnterpriseManagedAuth` instances that have different `clientId`/`idToken`\n   * but the same `tokenEndpoint`; they will read and overwrite each other's\n   * cached tokens.\n   */\n  store?: KeyValueStore\n  /** How many seconds before expiry to proactively re-fetch. Default: 60. */\n  refreshBufferSeconds?: number\n}\n\nexport class EnterpriseManagedAuth implements AsyncHeaderAuth {\n  readonly kind = 'enterprise_managed' as const\n\n  private readonly _options: EnterpriseManagedOptions\n  private readonly _cache: TokenCache\n\n  constructor(options: EnterpriseManagedOptions) {\n    this._options = options\n    const store = options.store ?? new InMemoryStore()\n    const bufferMs =\n      (options.refreshBufferSeconds ?? DEFAULT_REFRESH_BUFFER_SECONDS) * 1000\n    this._cache = new TokenCache(store, `${options.tokenEndpoint}/enterprise-managed`, bufferMs)\n  }\n\n  async getHeaders(): Promise<Record<string, string>> {\n    const token = await this._cache.get(() => this._fetchToken())\n    const type = token.token_type?.trim() || 'Bearer'\n    return { Authorization: `${type} ${token.access_token}` }\n  }\n\n  private async _fetchToken(): Promise<OAuthToken> {\n    const o = this._options\n    const idToken = typeof o.idToken === 'function' ? await o.idToken() : o.idToken\n    // Step 1 — RFC 8693 token exchange at the IdP: ID token -> ID-JAG.\n    const grant = await requestJwtAuthorizationGrant({\n      tokenEndpoint: o.idpTokenEndpoint,\n      audience: o.audience,\n      resource: o.resource,\n      idToken,\n      clientId: o.idpClientId,\n      ...(o.idpClientSecret ? { clientSecret: o.idpClientSecret } : {}),\n      ...(o.scope ? { scope: o.scope } : {}),\n    })\n    // Step 2 — RFC 7523 JWT-bearer grant at the MCP authorization server:\n    // present the ID-JAG for the access token.\n    const tokens = await exchangeJwtAuthGrant({\n      tokenEndpoint: o.tokenEndpoint,\n      jwtAuthGrant: grant.jwtAuthGrant,\n      clientId: o.clientId,\n      ...(o.clientSecret ? { clientSecret: o.clientSecret } : {}),\n      authMethod: o.authMethod ?? 'client_secret_basic',\n    })\n    return tokens as OAuthToken\n  }\n}\n\n// ---------------------------------------------------------------------------\n// Internal helpers\n// ---------------------------------------------------------------------------\n\nasync function openBrowser(url: string): Promise<void> {\n  const { spawn } = await import('child_process')\n  if (process.platform === 'win32') {\n    spawn('cmd', ['/c', 'start', '', url], { detached: true, stdio: 'ignore' })\n  } else if (process.platform === 'darwin') {\n    spawn('open', [url], { detached: true, stdio: 'ignore' })\n  } else {\n    spawn('xdg-open', [url], { detached: true, stdio: 'ignore' })\n  }\n}\n","import type { ClientCapabilities } from '@modelcontextprotocol/client'\n\ninterface InferredClientCapabilities {\n  sampling: boolean\n  elicitation: boolean\n  rootsListChanged?: boolean\n}\n\nexport function buildClientCapabilities(\n  supplied: ClientCapabilities | undefined,\n  inferred: InferredClientCapabilities,\n): ClientCapabilities {\n  const capabilities: ClientCapabilities = { ...supplied }\n\n  if (inferred.sampling) {\n    capabilities.sampling = {\n      ...supplied?.sampling,\n      tools: supplied?.sampling?.tools ?? {},\n    }\n  }\n\n  if (inferred.elicitation) {\n    const elicitation = supplied?.elicitation\n    capabilities.elicitation = elicitation\n      ? { ...elicitation, form: elicitation.form ?? {} }\n      : {}\n  }\n\n  if (inferred.rootsListChanged !== undefined) {\n    capabilities.roots = {\n      ...supplied?.roots,\n      listChanged: inferred.rootsListChanged,\n    }\n  }\n\n  return capabilities\n}\n","import type { LoggingLevel, CreateMessageRequestParams, ElicitRequestParams, ElicitResult, Tool, Resource, Prompt } from \"@modelcontextprotocol/server\";\nimport type { AnySamplingResult } from './results.js'\n\nexport type LogMessage = {\n  level: LoggingLevel\n  logger?: string\n  data: unknown\n}\n\nexport type LogHandler = (message: LogMessage) => void | Promise<void>\n\nexport type ProgressHandler = (\n  progress: number,\n  total?: number,\n  message?: string,\n) => void | Promise<void>\n\nexport type SamplingHandler = (\n  params: CreateMessageRequestParams,\n) => AnySamplingResult | Promise<AnySamplingResult>\n\nexport type ElicitationHandler = (\n  params: ElicitRequestParams,\n) => ElicitResult | Promise<ElicitResult>\n\nexport type ResourceUpdateHandler = (uri: string) => void | Promise<void>\n\n/**\n * Config for receiving server-initiated list-change notifications.\n * Set debounceMs: 0 in tests for instant delivery.\n */\nexport type ListChangedHandler<T> = {\n  onChanged: (error: Error | null, items: T[] | null) => void | Promise<void>\n  /** Whether to auto-fetch the updated list before calling onChanged. Default: true. */\n  autoRefresh?: boolean\n  /** Debounce window in ms. Default: 300. Set to 0 to disable. */\n  debounceMs?: number\n}\n\nexport interface ClientHandlers {\n  log?: LogHandler\n  progress?: ProgressHandler\n  sampling?: SamplingHandler\n  elicitation?: ElicitationHandler\n  onToolsListChanged?: ListChangedHandler<Tool>\n  onResourcesListChanged?: ListChangedHandler<Resource>\n  onPromptsListChanged?: ListChangedHandler<Prompt>\n}\n\nexport function defaultLogHandler(message: LogMessage): void {\n  const prefix = message.logger ? `[${message.logger}]` : '[server]'\n  const data =\n    typeof message.data === 'string' ? message.data : JSON.stringify(message.data)\n  const text = `${prefix} ${data}`\n  const level = message.level\n  if (level === 'debug') {\n    console.debug(text)\n  } else if (level === 'warning') {\n    console.warn(text)\n  } else if (\n    level === 'error' ||\n    level === 'critical' ||\n    level === 'alert' ||\n    level === 'emergency'\n  ) {\n    console.error(text)\n  } else {\n    console.info(text)\n  }\n}\n\nexport function defaultProgressHandler(\n  progress: number,\n  total?: number,\n  message?: string,\n): void {\n  const pct = total != null ? ` (${Math.round((progress / total) * 100)}%)` : ''\n  const msg = message ? ` — ${message}` : ''\n  console.debug(\n    `progress: ${progress}${total != null ? `/${total}` : ''}${pct}${msg}`,\n  )\n}\n","{\n  \"name\": \"@prefecthq/fastmcp-ts\",\n  \"version\": \"1.9.0\",\n  \"description\": \"🏎️  The official FastMCP TypeScript library - build MCP servers and clients, fast 🏎️\",\n  \"type\": \"module\",\n  \"exports\": {\n    \"./server\": {\n      \"types\": \"./dist/server.d.ts\",\n      \"import\": \"./dist/server.js\"\n    },\n    \"./client\": {\n      \"types\": \"./dist/client.d.ts\",\n      \"import\": \"./dist/client.js\"\n    }\n  },\n  \"browser\": {\n    \"child_process\": false,\n    \"node:child_process\": false,\n    \"fs\": false,\n    \"fs/promises\": false,\n    \"node:fs\": false,\n    \"node:fs/promises\": false,\n    \"http\": false,\n    \"node:http\": false,\n    \"https\": false,\n    \"node:https\": false,\n    \"os\": false,\n    \"node:os\": false,\n    \"path\": false,\n    \"node:path\": false,\n    \"node:url\": false,\n    \"node:process\": false,\n    \"node:stream\": false,\n    \"net\": false,\n    \"node:net\": false,\n    \"tls\": false,\n    \"node:tls\": false,\n    \"@modelcontextprotocol/client/stdio\": false\n  },\n  \"sideEffects\": false,\n  \"bin\": {\n    \"fastmcp\": \"dist/cli/index.cjs\"\n  },\n  \"files\": [\n    \"dist\",\n    \"README.md\"\n  ],\n  \"engines\": {\n    \"node\": \">=22\"\n  },\n  \"scripts\": {\n    \"build\": \"tsup\",\n    \"prepublishOnly\": \"npm run build && node scripts/test-dist.mjs && npm run test:browser-bundle\",\n    \"test\": \"vitest run\",\n    \"test:browser-bundle\": \"node scripts/test-browser-bundle.mjs\",\n    \"test:e2e\": \"playwright test\",\n    \"test:watch\": \"vitest\",\n    \"test:coverage\": \"vitest run --coverage\",\n    \"typecheck\": \"tsc --noEmit\",\n    \"conformance:server\": \"node tests/conformance/run-server.mjs\",\n    \"conformance:client\": \"node tests/conformance/run-client.mjs\",\n    \"docs:dev\": \"cd docs && npx --yes mint@latest dev\",\n    \"docs:api\": \"typedoc && node scripts/generate-api-nav.mjs\",\n    \"docs:links\": \"cd docs && npx --yes mint@latest broken-links\",\n    \"changeset\": \"changeset\",\n    \"version-packages\": \"changeset version\",\n    \"release\": \"changeset publish\"\n  },\n  \"devDependencies\": {\n    \"@anthropic-ai/sdk\": \"^0.91.1\",\n    \"@changesets/cli\": \"^3.0.0\",\n    \"@google/genai\": \"^1.50.1\",\n    \"@playwright/test\": \"^1.61.1\",\n    \"@types/node\": \"^22.0.0\",\n    \"@types/url-template\": \"^2.0.31\",\n    \"@vitest/coverage-v8\": \"^4.1.8\",\n    \"arktype\": \"^2.2.0\",\n    \"esbuild\": \"^0.28.1\",\n    \"execa\": \"^9.6.1\",\n    \"fake-indexeddb\": \"^6.2.5\",\n    \"get-bin-path\": \"^11.0.1\",\n    \"jsdom\": \"^29.1.1\",\n    \"openai\": \"^6.34.0\",\n    \"tsup\": \"^8.5.1\",\n    \"tsx\": \"^4.21.0\",\n    \"typedoc\": \"^0.28.0\",\n    \"typedoc-plugin-markdown\": \"^4.12.0\",\n    \"typescript\": \"^5.0.0\",\n    \"valibot\": \"^1.3.1\",\n    \"vitest\": \"^4.1.8\",\n    \"zod\": \"^4.3.6\"\n  },\n  \"repository\": {\n    \"type\": \"git\",\n    \"url\": \"git+https://github.com/PrefectHQ/fastmcp-ts.git\"\n  },\n  \"keywords\": [\n    \"mcp\",\n    \"mcp-tools\",\n    \"fastmcp\",\n    \"mcp-clients\",\n    \"llms\",\n    \"model-context-protocol\",\n    \"mcp-servers\",\n    \"typescript\"\n  ],\n  \"author\": \"prefecthq\",\n  \"license\": \"Apache-2.0\",\n  \"bugs\": {\n    \"url\": \"https://github.com/PrefectHQ/fastmcp-ts/issues\"\n  },\n  \"homepage\": \"https://github.com/PrefectHQ/fastmcp-ts#readme\",\n  \"peerDependencies\": {\n    \"@anthropic-ai/sdk\": \">=0.39\",\n    \"@google/genai\": \">=0.7\",\n    \"openai\": \">=4\"\n  },\n  \"peerDependenciesMeta\": {\n    \"@anthropic-ai/sdk\": {\n      \"optional\": true\n    },\n    \"openai\": {\n      \"optional\": true\n    },\n    \"@google/genai\": {\n      \"optional\": true\n    }\n  },\n  \"dependencies\": {\n    \"@clack/prompts\": \"^1.2.0\",\n    \"@modelcontextprotocol/client\": \"^2.4.0\",\n    \"@modelcontextprotocol/core\": \"^2.4.0\",\n    \"@modelcontextprotocol/node\": \"^2.0.0\",\n    \"@modelcontextprotocol/server\": \"^2.4.0\",\n    \"@modelcontextprotocol/server-legacy\": \"^2.4.0\",\n    \"@standard-schema/spec\": \"^1.1.0\",\n    \"@types/express\": \"^5.0.6\",\n    \"chalk\": \"^5.6.2\",\n    \"chokidar\": \"^5.0.0\",\n    \"citty\": \"^0.2.2\",\n    \"cli-table3\": \"^0.6.5\",\n    \"express\": \"^5.2.1\",\n    \"fastest-levenshtein\": \"^1.0.16\",\n    \"jose\": \"6.2.2\",\n    \"listr2\": \"^10.2.1\",\n    \"url-template\": \"^3.1.1\",\n    \"yaml\": \"^2.8.3\"\n  }\n}\n","import type {\n  ClientCapabilities,\n  Implementation,\n  InputRequiredOptions,\n  PriorDiscovery,\n  ResponseCacheStore,\n  VersionNegotiationOptions,\n} from '@modelcontextprotocol/client'\nimport packageJson from '../../package.json' with { type: 'json' }\nimport type { AsyncHeaderAuth, BearerAuth, OAuth } from './auth.js'\nimport type { ClientHandlers } from './handlers.js'\nimport type { Root } from './results.js'\n\nexport const DEFAULT_CLIENT_INFO: Implementation = {\n  name: 'fastmcp-ts',\n  version: packageJson.version,\n}\n\nexport interface ClientDefaultOptions {\n  /** Global fallback timeout in seconds for all requests. */\n  timeout?: number\n  tool?: { timeout?: number }\n  resource?: { timeout?: number }\n  prompt?: { timeout?: number }\n}\n\n/** A single element of the roots option: a URI string or a full Root object. */\nexport type RootInput = string | Root\n\n/**\n * Static list of roots, or an async callback invoked on each roots/list request.\n * URI strings are normalised to file:// URIs automatically; relative paths are\n * resolved against process.cwd().\n */\nexport type RootsValue = RootInput[] | (() => RootInput[] | Promise<RootInput[]>)\n\nexport interface ClientOptions {\n  /**\n   * Authentication to attach to HTTP requests.\n   * A plain string is treated as a Bearer token.\n   */\n  auth?: BearerAuth | OAuth | AsyncHeaderAuth | string\n  /**\n   * Identity to advertise to the MCP server. Defaults to `fastmcp-ts` at the\n   * installed package version. Set this when FastMCP is embedded in another\n   * application.\n   */\n  clientInfo?: Implementation\n  handlers?: ClientHandlers\n  /**\n   * Additional capabilities to advertise to the server. FastMCP preserves\n   * their settings while adding capabilities inferred from handlers and roots.\n   */\n  capabilities?: ClientCapabilities\n  /**\n   * Filesystem roots to advertise to the server.\n   * Accepts a static array of strings / Root objects, or an async callback\n   * invoked on each roots/list request (useful for dynamic root sets).\n   */\n  roots?: RootsValue\n  /**\n   * When true (default), the MCP initialize handshake is performed\n   * automatically inside connect().\n   */\n  autoInitialize?: boolean\n  defaultOptions?: ClientDefaultOptions\n  /**\n   * Protocol version negotiation (protocol revision 2026-07-28 and later).\n   * The default is `{ mode: 'auto' }`: connect() probes the server once with\n   * `server/discover` and uses the modern (2026-07-28) era on definitive\n   * modern evidence, falling back to the plain legacy `initialize` handshake\n   * on anything else (a method-not-found answer, silence on a local stdio\n   * pipe, a probe child that exits). The probe is stall-safe in the SDK: on\n   * stdio it runs against a short-lived sibling process and a timeout falls\n   * back to legacy, while on HTTP — where silence means an outage — a probe\n   * timeout rejects with a typed error instead of hanging. Pass\n   * `{ mode: 'legacy' }` to opt out: no probe, the 2025 sequence\n   * byte-identical to prior behavior. Pass `{ mode: { pin: '2026-07-28' } }`\n   * to require the modern era outright — connect() throws if the server\n   * cannot speak it. See `getProtocolEra()` to read the negotiated result\n   * after connecting.\n   */\n  versionNegotiation?: VersionNegotiationOptions\n  /**\n   * A cached era verdict from a previous connection to the same server, so\n   * connect() can skip the `server/discover` probe entirely. Takes precedence\n   * over `versionNegotiation`. `{ kind: 'modern', discover }` adopts a prior\n   * `DiscoverResult` with zero round trips; `{ kind: 'legacy' }` skips the probe\n   * and runs the plain legacy `initialize` handshake. Freshness is the caller's\n   * responsibility — a stale modern verdict fails loudly at the first request; a\n   * stale legacy verdict succeeds silently forever. Reuse only within one\n   * authorization context.\n   */\n  prior?: PriorDiscovery\n  /**\n   * Multi-round-trip auto-fulfilment (protocol revision 2026-07-28). On the\n   * modern era, servers obtain client input (elicitation, sampling, roots) by\n   * answering a request with an `input_required` result instead of a\n   * server→client request. By default the client fulfils these automatically\n   * through the same `handlers.sampling`/`handlers.elicitation` callbacks,\n   * retrying up to `maxRounds` times. Set `autoFulfill: false` for manual mode.\n   * Has no effect on legacy-era connections. Passed through verbatim to the SDK\n   * client.\n   */\n  inputRequired?: InputRequiredOptions\n  /**\n   * The response-cache store backing cacheable results (SEP-2549 `ttlMs`/\n   * `cacheScope` hints on `listTools`/`listResources`/`listResourceTemplates`/\n   * `listPrompts`/`readResource`). Defaults to a fresh in-memory store per\n   * client (the SDK's own default) when omitted. Passed through verbatim.\n   */\n  responseCacheStore?: ResponseCacheStore\n  /**\n   * Opaque per-principal identifier for response-cache writes whose\n   * server-reported `cacheScope` is `'private'`. Set this to a stable identity\n   * of the authorization context (e.g. the auth subject) when one\n   * `responseCacheStore` backs several principals. Passed through verbatim.\n   */\n  cachePartition?: string\n  /**\n   * TTL (ms) applied when a cacheable result arrives without a `ttlMs` field.\n   * Default `0` (never served from cache, but still stored). Passed through\n   * verbatim.\n   */\n  defaultCacheTtlMs?: number\n  /**\n   * Allow the deprecated SSE transport when a target URL's path indicates SSE\n   * (e.g. ends in `/sse`). Default `false` — such URLs throw a clear error\n   * pointing at Streamable HTTP and this flag, rather than silently connecting\n   * over a transport the MCP SDK itself marks `@deprecated`. When enabled, a\n   * one-time deprecation warning is logged via `console.warn`.\n   */\n  legacySSE?: boolean\n}\n","import type { CallToolResult as SdkCallToolResult } from '@modelcontextprotocol/client'\nimport type { CreateMessageResult, CreateMessageResultWithTools } from \"@modelcontextprotocol/server\";\nimport type { Skill, SkillFile } from '@modelcontextprotocol/client/ext/skills'\n\nexport type {\n  Tool,\n  Resource,\n  ResourceTemplateType as ResourceTemplate,\n  ResourceContents,\n  TextResourceContents,\n  BlobResourceContents,\n  Prompt,\n  PromptArgument,\n  PromptMessage,\n  GetPromptResult,\n  SamplingMessage,\n  CreateMessageResult,\n  CreateMessageResultWithTools,\n  CreateMessageRequestParams,\n  ModelPreferences,\n  ToolUseContent,\n  ToolResultContent,\n  ToolChoice,\n  LoggingLevel,\n  ContentBlock,\n  ElicitRequestParams,\n  ElicitResult,\n  Root,\n} from '@modelcontextprotocol/server'\nexport type { Skill, SkillFile, SkillFrontmatter } from '@modelcontextprotocol/client/ext/skills'\n\n/** A skill read by `Client.readSkill()`: its entry and every file, verified against it. */\nexport interface SkillContents {\n  skill: Skill\n  files: SkillFile[]\n}\n\n/** Union of the two sampling result shapes the MCP protocol defines. */\nexport type AnySamplingResult = CreateMessageResult | CreateMessageResultWithTools\n/**\n * The SDK's CallToolResult with a typed generic for structuredContent.\n * The intersection retains its open extension fields while narrowing the two\n * values FastMCP normalizes.\n */\nexport type CallToolResult<TData = unknown> = SdkCallToolResult & {\n  structuredContent: TData | null\n  isError: boolean\n}\n\nexport function normalizeCallToolResult<TData = unknown>(\n  result: SdkCallToolResult,\n): CallToolResult<TData> {\n  return {\n    ...result,\n    structuredContent: (result.structuredContent as TData | undefined) ?? null,\n    isError: result.isError === true,\n  }\n}\n\nexport type CompletionResult = {\n  values: string[]\n  total?: number\n  hasMore?: boolean\n}\n","/**\n * Wire constants for the MCP Skills extension (SEP-2640).\n *\n * Runtime-neutral: this module imports nothing.\n */\n\n/** The identifier a server advertises in `ServerCapabilities.extensions`. */\nexport const SKILLS_EXTENSION_ID = 'io.modelcontextprotocol/skills';\n\n/** Enumerates the skills a server serves. */\nexport const SKILLS_LIST_METHOD = 'skills/list';\n\n/** Returns one skill's entry by its `SKILL.md` URI, listed or not. */\nexport const SKILLS_GET_METHOD = 'skills/get';\n\n/** Lists the direct children of a directory resource (gated by `directoryRead`). */\nexport const RESOURCES_DIRECTORY_READ_METHOD = 'resources/directory/read';\n\n/** The `mimeType` of a directory resource. */\nexport const DIRECTORY_MIME_TYPE = 'inode/directory';\n\n/**\n * Per-skill interoperability limits. Hosts MUST accept skills up to these;\n * servers SHOULD NOT publish skills over them.\n */\nexport const SKILL_LIMITS: Readonly<{ files: number; bytes: number }> = Object.freeze({ files: 512, bytes: 16_777_216 });\n\n/** `sha256:` followed by 64 lowercase hexadecimal characters. */\nexport const SKILL_DIGEST_PATTERN = /^sha256:[\\da-f]{64}$/;\n","import * as z from 'zod/v4';\n\nimport { BaseRequestParamsSchema, PaginatedRequestParamsSchema, PaginatedResultSchema, ResourceSchema, ResultSchema } from '../../schemas';\nimport { SKILL_DIGEST_PATTERN } from './constants';\n\n// Every object schema here is loose: none of the stable spec's types declare\n// `additionalProperties: false`, so unknown keys (including `_meta`) survive.\n\nexport const SkillDigestSchema = z\n    .string()\n    .regex(SKILL_DIGEST_PATTERN, 'digest must be \"sha256:\" followed by 64 lowercase hexadecimal characters');\n\nexport const SkillResourceEntrySchema = z.looseObject({\n    /** Resource URI of the file. */\n    uri: z.string(),\n    /** SHA-256 digest of the file's raw bytes. */\n    digest: SkillDigestSchema,\n    /** Length of the file's raw bytes. */\n    size: z.number().int().nonnegative()\n});\n\nexport const SkillFrontmatterSchema = z\n    .looseObject({\n        name: z.string(),\n        description: z.string()\n    })\n    // Zod copies an own `__proto__` field by assignment, which makes it the prototype: fields no key listing shows.\n    .refine(frontmatter => Object.getPrototypeOf(frontmatter) === Object.prototype, 'frontmatter must not have a \"__proto__\" field');\n\nexport const SkillResourcesSchema = z.union([z.array(SkillResourceEntrySchema), z.literal('dynamic')]);\n\nexport const SkillSchema = z.looseObject({\n    /** Resource URI of the skill's `SKILL.md`. */\n    uri: z.string(),\n    /** The `SKILL.md` frontmatter, verbatim. */\n    frontmatter: SkillFrontmatterSchema,\n    /** Every file of the skill, or `\"dynamic\"`. */\n    resources: SkillResourcesSchema,\n    _meta: z.record(z.string(), z.unknown()).optional()\n});\n\nexport const SkillCacheScopeSchema = z.enum(['public', 'private']);\n\n// Required, as the stable spec (2026-07-28) defines them; only SkillsClient reads the 2025-11-25 backport, which has none.\nconst cacheFields = {\n    ttlMs: z.number().int().nonnegative(),\n    cacheScope: SkillCacheScopeSchema\n};\n\nexport const ListSkillsResultSchema = z.looseObject({\n    ...PaginatedResultSchema.shape,\n    skills: z.array(SkillSchema),\n    ...cacheFields\n});\n\nexport const GetSkillRequestParamsSchema = BaseRequestParamsSchema.extend({\n    /** The `SKILL.md` URI of the skill to fetch. */\n    uri: z.string()\n});\n\nexport const GetSkillResultSchema = z.looseObject({\n    ...ResultSchema.shape,\n    skill: SkillSchema,\n    ...cacheFields\n});\n\nexport const DirectoryResourceSchema = z.looseObject(ResourceSchema.shape);\n\nexport const ReadResourceDirectoryRequestParamsSchema = PaginatedRequestParamsSchema.extend({\n    /** URI of the directory resource to read. */\n    uri: z.string()\n});\n\nexport const ReadResourceDirectoryResultSchema = z.looseObject({\n    ...PaginatedResultSchema.shape,\n    resources: z.array(DirectoryResourceSchema),\n    ...cacheFields\n});\n\nexport const SkillsCapabilitySchema = z.looseObject({\n    /** Whether the server serves `resources/directory/read`. */\n    directoryRead: z.boolean().optional()\n});\n\nexport { PaginatedRequestParamsSchema as ListSkillsRequestParamsSchema } from '../../schemas';\n","import { SKILLS_EXTENSION_ID } from './constants';\nimport { SkillsCapabilitySchema } from './schemas';\nimport type { SkillsCapability } from './types';\n\n/**\n * The shape this module reads capabilities out of. Declared structurally so\n * the helper stays in the runtime-neutral core package: the nominal\n * `ServerCapabilities` type lives downstream, and every value of it satisfies\n * this.\n */\nexport interface CapabilitiesWithExtensions {\n    extensions?: Record<string, unknown>;\n}\n\n/**\n * Reads the Skills extension capability out of a peer's advertised\n * capabilities, returning `undefined` when the peer does not advertise the\n * extension or advertises a malformed value.\n *\n * Shared by both roles: servers use it to check what they published, clients\n * to gate `skills/list` / `skills/get` on negotiation.\n */\nexport function skillsCapabilityOf(capabilities: CapabilitiesWithExtensions | undefined): SkillsCapability | undefined {\n    const declared = capabilities?.extensions?.[SKILLS_EXTENSION_ID];\n    if (declared === undefined) {\n        return undefined;\n    }\n    const parsed = SkillsCapabilitySchema.safeParse(declared);\n    return parsed.success ? parsed.data : undefined;\n}\n","import { SdkError, SdkErrorCode } from '@modelcontextprotocol/core-internal/public';\n\n/** Why a skill file failed verification. */\nexport type SkillVerificationReason = 'unlisted' | 'size' | 'digest' | 'frontmatter';\n\n/**\n * A skill file failed verification against its skill entry: not listed,\n * wrong size, wrong digest, or (for `SKILL.md`) frontmatter that differs from\n * the entry. Hosts must not load the file; for `SKILL.md`, not the skill.\n */\nexport class SkillVerificationError extends SdkError {\n    static {\n        Object.defineProperty(this, 'mcpBrand', { value: 'mcp.SkillVerificationError' });\n    }\n\n    readonly reason: SkillVerificationReason;\n    readonly uri: string;\n    /** For `frontmatter`: one line per differing field. */\n    readonly differences: readonly string[];\n\n    constructor(\n        reason: SkillVerificationReason,\n        uri: string,\n        message: string,\n        differences: readonly string[] = [],\n        options?: ErrorOptions\n    ) {\n        super(SdkErrorCode.InvalidResult, message, { reason, uri, differences }, options);\n        this.name = 'SkillVerificationError';\n        this.reason = reason;\n        this.uri = uri;\n        this.differences = differences;\n    }\n}\n","const encoder = new TextEncoder();\n\n/** UTF-8 bytes of `text`. */\nexport function encodeUtf8(text: string): Uint8Array {\n    return encoder.encode(text);\n}\n\n/** Decodes UTF-8 only if decoding loses nothing (a BOM is kept); otherwise `undefined`. */\nexport function decodeUtf8Lossless(bytes: Uint8Array): string | undefined {\n    try {\n        return new TextDecoder('utf-8', { fatal: true, ignoreBOM: true }).decode(bytes);\n    } catch {\n        return undefined;\n    }\n}\n\n/** Standard base64 of `bytes`. */\nexport function encodeBase64(bytes: Uint8Array): string {\n    let binary = '';\n    const chunk = 0x80_00;\n    for (let offset = 0; offset < bytes.length; offset += chunk) {\n        binary += String.fromCodePoint(...bytes.subarray(offset, offset + chunk));\n    }\n    return btoa(binary);\n}\n\n/** Bytes of a standard base64 string. */\nexport function decodeBase64(base64: string): Uint8Array {\n    const binary = atob(base64);\n    const bytes = new Uint8Array(binary.length);\n    for (let index = 0; index < binary.length; index++) bytes[index] = binary.codePointAt(index)!;\n    return bytes;\n}\n\n/** `sha256:` followed by the lowercase hex SHA-256 of `bytes` (WebCrypto, every runtime). */\nexport async function sha256Digest(bytes: Uint8Array): Promise<string> {\n    const { buffer, byteOffset, byteLength } = bytes;\n    // WebCrypto refuses views over a SharedArrayBuffer; only those are copied.\n    const view = buffer instanceof ArrayBuffer ? new Uint8Array(buffer, byteOffset, byteLength) : new Uint8Array(bytes);\n    const hash = new Uint8Array(await globalThis.crypto.subtle.digest('SHA-256', view));\n    let hex = '';\n    for (const byte of hash) hex += byte.toString(16).padStart(2, '0');\n    return `sha256:${hex}`;\n}\n","/**\n * Frontmatter reader for `SKILL.md` (SEP-2640).\n *\n * Reads the YAML subset real skills use — block mappings and sequences;\n * plain, quoted and block scalars; one-line flow collections; comments — with\n * YAML 1.2 core-schema typing. Anything outside the subset throws a\n * {@linkcode FrontmatterError} instead of being read differently from a full\n * YAML parser. Server catalogs and client verification both call it; it is\n * kept behind this module so it can be swapped for a YAML library.\n */\n\nexport class FrontmatterError extends Error {\n    readonly line: number | undefined;\n\n    constructor(message: string, line?: number) {\n        super(line === undefined ? message : `line ${line}: ${message}`);\n        this.name = 'FrontmatterError';\n        this.line = line;\n    }\n}\n\nexport interface SplitSkillMarkdown {\n    /** The YAML between the opening and closing `---` lines, with LF line endings. */\n    yaml: string;\n    /** The markdown after the closing `---` line. */\n    body: string;\n}\n\nexport interface ParsedSkillMarkdown {\n    frontmatter: Record<string, unknown>;\n    body: string;\n}\n\nconst MAX_DEPTH = 32;\n\n/** Splits `SKILL.md` into its frontmatter YAML and markdown body. */\nexport function splitFrontmatter(markdown: string): SplitSkillMarkdown {\n    let text = markdown.replaceAll('\\r\\n', '\\n');\n    if (text.codePointAt(0) === 0xfe_ff) text = text.slice(1);\n    if (!text.startsWith('---\\n')) throw new FrontmatterError('SKILL.md must begin with a \"---\" line', 1);\n    const rest = text.slice(4);\n    const close = /^---[\\t ]*$/m.exec(rest);\n    if (close === null) throw new FrontmatterError('frontmatter has no closing \"---\" line');\n    let body = rest.slice(close.index + close[0].length);\n    if (body.startsWith('\\n')) body = body.slice(1);\n    return { yaml: rest.slice(0, close.index), body };\n}\n\n/** Splits and parses `SKILL.md`. Line numbers in errors count from the file's first line. */\nexport function parseSkillMarkdown(markdown: string): ParsedSkillMarkdown {\n    const { yaml, body } = splitFrontmatter(markdown);\n    return { frontmatter: parseFrontmatterYaml(yaml, 2), body };\n}\n\n/** Parses frontmatter YAML into a JSON object. `firstLine` numbers the first YAML line in errors. */\nexport function parseFrontmatterYaml(yaml: string, firstLine = 1): Record<string, unknown> {\n    return new Parser(toLines(yaml, firstLine)).parseDocument();\n}\n\ninterface Line {\n    readonly no: number;\n    // Leading spaces only: a tab ends the indentation.\n    readonly indent: number;\n    // The line after its leading spaces and tabs.\n    readonly text: string;\n    readonly raw: string;\n}\n\nfunction toLines(yaml: string, firstLine: number): Line[] {\n    const raws = yaml.split('\\n');\n    if (raws.at(-1) === '') raws.pop();\n    return raws.map((raw, index) => ({ no: firstLine + index, indent: /^ */.exec(raw)?.[0].length ?? 0, text: trimWhiteStart(raw), raw }));\n}\n\nconst TAB_INDENT = 'tabs cannot be used for indentation';\n\nconst isSkippable = (line: Line): boolean => line.text === '' || line.text.startsWith('#');\nconst isTabIndented = (line: Line): boolean => line.raw[line.indent] === '\\t';\nconst isSequenceItem = (text: string): boolean => /^-(?:[\\t ]|$)/.test(text);\n\nclass Parser {\n    private index = 0;\n\n    constructor(private readonly lines: Line[]) {}\n\n    parseDocument(): Record<string, unknown> {\n        const first = this.peek();\n        if (first === undefined) return {};\n        // YAML drops a BOM before the first content, so reading it into the first key would differ: fail closed.\n        if (first.text.startsWith('\\uFEFF')) {\n            throw new FrontmatterError('a byte order mark inside the frontmatter is not supported', first.no);\n        }\n        if (isSequenceItem(first.text) || matchKey(first.text, first.no) === undefined) {\n            throw new FrontmatterError('frontmatter must be a mapping of keys to values', first.no);\n        }\n        const map = this.parseMapping(first.indent, 0);\n        const extra = this.peek();\n        if (extra !== undefined) throw new FrontmatterError('unexpected content', extra.no);\n        return map;\n    }\n\n    private peek(): Line | undefined {\n        while (this.index < this.lines.length && isSkippable(this.lines[this.index]!)) this.index++;\n        const line = this.lines[this.index];\n        if (line !== undefined && isTabIndented(line)) throw new FrontmatterError(TAB_INDENT, line.no);\n        return line;\n    }\n\n    private parseMapping(indent: number, depth: number): Record<string, unknown> {\n        assertDepth(depth, this.lines[this.index]?.no);\n        const map: Record<string, unknown> = {};\n        for (let line = this.peek(); line !== undefined && line.indent >= indent; line = this.peek()) {\n            if (line.indent > indent) throw new FrontmatterError('unexpected indentation', line.no);\n            if (isSequenceItem(line.text)) break;\n            const match = matchKey(line.text, line.no);\n            if (match === undefined) throw new FrontmatterError('expected \"key: value\"', line.no);\n            if (Object.hasOwn(map, match.key)) throw new FrontmatterError(`duplicate key \"${match.key}\"`, line.no);\n            this.index++;\n            map[match.key] = this.parseValue(match.rest, line, indent, depth + 1, true);\n        }\n        return map;\n    }\n\n    private parseSequence(indent: number, depth: number): unknown[] {\n        assertDepth(depth, this.lines[this.index]?.no);\n        const items: unknown[] = [];\n        for (let line = this.peek(); line !== undefined && line.indent >= indent; line = this.peek()) {\n            if (line.indent > indent) throw new FrontmatterError('unexpected indentation', line.no);\n            if (!isSequenceItem(line.text)) break;\n            const after = line.text.slice(1);\n            const rest = trimWhiteStart(after);\n            const column = line.indent + 1 + (after.length - rest.length);\n            if (rest !== '' && !rest.startsWith('#') && (isSequenceItem(rest) || matchKey(rest, line.no) !== undefined)) {\n                // `- key: value` or `- - item`: the item is a block node that starts at `column`.\n                if (/^ *\\t/.test(after)) throw new FrontmatterError(TAB_INDENT, line.no);\n                this.lines[this.index] = { ...line, indent: column, text: rest };\n                items.push(isSequenceItem(rest) ? this.parseSequence(column, depth + 1) : this.parseMapping(column, depth + 1));\n                continue;\n            }\n            this.index++;\n            items.push(this.parseValue(rest, line, indent, depth + 1, false));\n        }\n        return items;\n    }\n\n    private parseValue(rest: string, line: Line, parentIndent: number, depth: number, allowCompactSequence: boolean): unknown {\n        if (rest === '' || rest.startsWith('#')) {\n            const next = this.peek();\n            if (next !== undefined && next.indent > parentIndent) return this.parseIndented(parentIndent, depth);\n            if (allowCompactSequence && next !== undefined && next.indent === parentIndent && isSequenceItem(next.text)) {\n                return this.parseSequence(parentIndent, depth);\n            }\n            return null;\n        }\n        const first = rest[0]!;\n        if (first === '|' || first === '>') return this.parseBlockScalar(rest, line, parentIndent);\n        if (first === '\"' || first === \"'\") {\n            const { value, end } = readQuoted(rest, 0, line.no);\n            expectOnlyComment(rest.slice(end), line.no);\n            return value;\n        }\n        if (first === '[' || first === '{') {\n            const { value, end } = readFlow(rest, 0, line.no, depth);\n            expectOnlyComment(rest.slice(end), line.no);\n            return value;\n        }\n        if ('&*!'.includes(first)) throw new FrontmatterError('anchors, aliases and tags are not supported', line.no);\n        if ('%@`,]}'.includes(first)) throw new FrontmatterError(`\"${first}\" cannot start a plain value; quote it`, line.no);\n        if (isSequenceItem(rest) || /^\\?(?:[\\t ]|$)/.test(rest)) {\n            throw new FrontmatterError('a nested collection must start on its own line', line.no);\n        }\n        return this.parsePlain(rest, line, parentIndent);\n    }\n\n    private parseIndented(parentIndent: number, depth: number): unknown {\n        const line = this.peek()!;\n        if (isSequenceItem(line.text)) return this.parseSequence(line.indent, depth);\n        if (matchKey(line.text, line.no) !== undefined) return this.parseMapping(line.indent, depth);\n        this.index++;\n        return this.parseValue(line.text, line, parentIndent, depth, false);\n    }\n\n    private parsePlain(first: string, line: Line, parentIndent: number): unknown {\n        let value = stripComment(first);\n        assertPlain(value, line.no);\n        let commented = COMMENT.test(first);\n        let blanks = 0;\n        while (this.index < this.lines.length) {\n            const next = this.lines[this.index]!;\n            if (next.text === '') {\n                blanks++;\n                this.index++;\n                continue;\n            }\n            if (next.indent <= parentIndent || next.text.startsWith('#')) break;\n            if (isTabIndented(next)) throw new FrontmatterError(TAB_INDENT, next.no);\n            if (commented) throw new FrontmatterError('a comment ends a plain value; quote a value that continues past it', next.no);\n            const part = stripComment(next.text);\n            assertPlain(part, next.no);\n            commented = COMMENT.test(next.text);\n            value += blanks > 0 ? '\\n'.repeat(blanks) : ' ';\n            value += part;\n            blanks = 0;\n            this.index++;\n        }\n        return resolvePlain(value, line.no);\n    }\n\n    private parseBlockScalar(header: string, line: Line, parentIndent: number): string {\n        const match = /^([>|])([+-]?)(?:[\\t ]+#.*)?[\\t ]*$/.exec(header);\n        if (match === null) {\n            const indicator = /^[>|][+-]?\\d|^[>|]\\d/.test(header);\n            throw new FrontmatterError(\n                indicator ? 'block scalar indentation indicators are not supported' : 'invalid block scalar header',\n                line.no\n            );\n        }\n        const contents: string[] = [];\n        let contentIndent = -1;\n        let leadingWidth = 0;\n        while (this.index < this.lines.length) {\n            const next = this.lines[this.index]!;\n            const spacesOnly = next.indent === next.raw.length;\n            if (contentIndent === -1 && !spacesOnly && next.indent > parentIndent) {\n                contentIndent = next.indent;\n                if (leadingWidth > contentIndent) {\n                    throw new FrontmatterError('a leading blank line is indented more than the block scalar content', next.no);\n                }\n            }\n            if (contentIndent !== -1 && next.indent >= contentIndent) {\n                contents.push(next.raw.slice(contentIndent));\n            } else if (spacesOnly) {\n                if (contentIndent === -1) leadingWidth = Math.max(leadingWidth, next.indent);\n                contents.push('');\n            } else if (isTabIndented(next)) {\n                throw new FrontmatterError(TAB_INDENT, next.no);\n            } else {\n                break;\n            }\n            this.index++;\n        }\n        return foldBlock(contents, match[1] === '>', match[2] ?? '');\n    }\n}\n\nfunction assertDepth(depth: number, line: number | undefined): void {\n    if (depth > MAX_DEPTH) throw new FrontmatterError(`nesting deeper than ${MAX_DEPTH} levels is not supported`, line);\n}\n\ninterface KeyMatch {\n    key: string;\n    rest: string;\n}\n\nfunction matchKey(text: string, no: number): KeyMatch | undefined {\n    const first = text[0];\n    if (first === '\"' || first === \"'\") {\n        const { value, end } = readQuoted(text, 0, no);\n        const after = text.slice(end);\n        if (after === ':' || /^:[\\t ]/.test(after)) return { key: checkKey(value, no), rest: trimWhiteStart(after.slice(1)) };\n        return undefined;\n    }\n    if (first === '?') throw new FrontmatterError('complex keys (\"?\") are not supported', no);\n    if (first === undefined || '[]{}&*!|>%@`#,'.includes(first)) return undefined;\n    for (let index = 0; index < text.length; index++) {\n        const char = text[index];\n        const previous = text[index - 1];\n        if (char === '#' && (previous === ' ' || previous === '\\t')) return undefined;\n        if (char === ':') {\n            const next = text[index + 1];\n            if (next === undefined || next === ' ' || next === '\\t') {\n                const key = trimWhiteEnd(text.slice(0, index));\n                if (key === '') return undefined;\n                return { key: resolveKey(key, no), rest: trimWhiteStart(text.slice(index + 1)) };\n            }\n        }\n    }\n    return undefined;\n}\n\nfunction checkKey(key: string, no: number): string {\n    if (key === '__proto__') throw new FrontmatterError('the key \"__proto__\" is not supported', no);\n    return key;\n}\n\nfunction resolveKey(raw: string, no: number): string {\n    if (typeof resolvePlain(raw, no) !== 'string') throw new FrontmatterError(`key \"${raw}\" must be a string; quote it`, no);\n    return checkKey(raw, no);\n}\n\nfunction assertPlain(text: string, no: number): void {\n    if (/:(?:[\\t ]|$)/.test(text)) throw new FrontmatterError('a plain value cannot contain \": \"; quote the value', no);\n}\n\nconst COMMENT = /[\\t ]#/;\n\nfunction stripComment(text: string): string {\n    const match = COMMENT.exec(text);\n    return trimWhiteEnd(match === null ? text : text.slice(0, match.index));\n}\n\nfunction expectOnlyComment(after: string, no: number): void {\n    if (trimWhiteStart(after) === '' || /^[\\t ]+#/.test(after)) return;\n    throw new FrontmatterError('unexpected text after the value', no);\n}\n\n// YAML white space is only space and tab; `String.prototype.trim` would also strip Unicode spaces YAML keeps.\nfunction trimWhiteStart(text: string): string {\n    return text.slice(skipSpaces(text, 0));\n}\n\nfunction trimWhiteEnd(text: string): string {\n    let end = text.length;\n    while (end > 0 && (text[end - 1] === ' ' || text[end - 1] === '\\t')) end--;\n    return text.slice(0, end);\n}\n\nconst NULL = /^(?:~|null|Null|NULL)$/;\nconst TRUE = /^(?:true|True|TRUE)$/;\nconst FALSE = /^(?:false|False|FALSE)$/;\nconst INTEGER = /^[+-]?\\d+$/;\nconst OCTAL = /^0o[0-7]+$/;\nconst HEXADECIMAL = /^0x[\\dA-Fa-f]+$/;\nconst FLOAT = /^[+-]?(?:\\.\\d+|\\d+(?:\\.\\d*)?)(?:[Ee][+-]?\\d+)?$/;\nconst SPECIAL_FLOAT = /^(?:[+-]?\\.(?:inf|Inf|INF)|\\.(?:nan|NaN|NAN))$/;\n\nfunction resolvePlain(text: string, no: number): unknown {\n    if (text === '' || NULL.test(text)) return null;\n    if (TRUE.test(text)) return true;\n    if (FALSE.test(text)) return false;\n    let number: number | undefined;\n    if (INTEGER.test(text) || FLOAT.test(text)) number = Number(text);\n    else if (OCTAL.test(text)) number = Number.parseInt(text.slice(2), 8);\n    else if (HEXADECIMAL.test(text)) number = Number.parseInt(text.slice(2), 16);\n    else if (SPECIAL_FLOAT.test(text)) number = Number.NaN;\n    if (number === undefined) return text;\n    if (!Number.isFinite(number)) throw new FrontmatterError(`\"${text}\" cannot be represented in JSON; quote it`, no);\n    return number;\n}\n\nconst SIMPLE_ESCAPES: Readonly<Record<string, string>> = {\n    '0': '\\0',\n    a: '\\u0007',\n    b: '\\b',\n    t: '\\t',\n    '\\t': '\\t',\n    n: '\\n',\n    v: '\\v',\n    f: '\\f',\n    r: '\\r',\n    e: '\\u001B',\n    ' ': ' ',\n    '\"': '\"',\n    '/': '/',\n    '\\\\': '\\\\',\n    N: '\\u0085',\n    _: '\\u00A0',\n    L: '\\u2028',\n    P: '\\u2029'\n};\n\nconst HEX_ESCAPE_WIDTH: Readonly<Record<string, number>> = { x: 2, u: 4, U: 8 };\n\nconst UNCLOSED_QUOTE = 'a quoted value must close on the same line (multi-line quoted values are not supported)';\n\nfunction readQuoted(text: string, start: number, no: number): { value: string; end: number } {\n    const quote = text[start];\n    let value = '';\n    let index = start + 1;\n    while (index < text.length) {\n        const char = text[index]!;\n        if (quote === \"'\") {\n            if (char === \"'\") {\n                if (text[index + 1] === \"'\") {\n                    value += \"'\";\n                    index += 2;\n                    continue;\n                }\n                return { value, end: index + 1 };\n            }\n            value += char;\n            index++;\n            continue;\n        }\n        if (char === '\"') return { value, end: index + 1 };\n        if (char === '\\\\') {\n            const escape = decodeEscape(text, index, no);\n            value += escape.decoded;\n            index += escape.length;\n            continue;\n        }\n        value += char;\n        index++;\n    }\n    throw new FrontmatterError(UNCLOSED_QUOTE, no);\n}\n\nfunction decodeEscape(text: string, index: number, no: number): { decoded: string; length: number } {\n    const code = text[index + 1];\n    if (code === undefined) throw new FrontmatterError(UNCLOSED_QUOTE, no);\n    const simple = SIMPLE_ESCAPES[code];\n    if (simple !== undefined) return { decoded: simple, length: 2 };\n    const width = HEX_ESCAPE_WIDTH[code];\n    if (width === undefined) throw new FrontmatterError(`unknown escape \"\\\\${code}\"`, no);\n    const hex = text.slice(index + 2, index + 2 + width);\n    if (hex.length !== width || !/^[\\dA-Fa-f]+$/.test(hex) || Number.parseInt(hex, 16) > 0x10_ff_ff) {\n        throw new FrontmatterError(`invalid escape \"\\\\${code}${hex}\"`, no);\n    }\n    return { decoded: String.fromCodePoint(Number.parseInt(hex, 16)), length: 2 + width };\n}\n\nfunction skipSpaces(text: string, index: number): number {\n    let position = index;\n    while (text[position] === ' ' || text[position] === '\\t') position++;\n    return position;\n}\n\nconst UNCLOSED_FLOW = 'a flow collection must close on the same line';\n\nfunction readFlow(text: string, start: number, no: number, depth: number): { value: unknown; end: number } {\n    assertDepth(depth, no);\n    const open = text[start];\n    const close = open === '[' ? ']' : '}';\n    const list: unknown[] = [];\n    const map: Record<string, unknown> = {};\n    let index = skipSpaces(text, start + 1);\n    if (text[index] === close) return { value: open === '[' ? list : map, end: index + 1 };\n    for (;;) {\n        if (open === '[') {\n            const item = readFlowValue(text, index, no, depth);\n            list.push(item.value);\n            index = skipSpaces(text, item.end);\n        } else {\n            const key = readFlowKey(text, index, no);\n            const item = readFlowValue(text, key.end + 1, no, depth);\n            if (Object.hasOwn(map, key.key)) throw new FrontmatterError(`duplicate key \"${key.key}\"`, no);\n            map[key.key] = item.value;\n            index = skipSpaces(text, item.end);\n        }\n        const char = text[index];\n        if (char === ',') {\n            index = skipSpaces(text, index + 1);\n            if (text[index] === close) return { value: open === '[' ? list : map, end: index + 1 };\n            continue;\n        }\n        if (char === close) return { value: open === '[' ? list : map, end: index + 1 };\n        if (char === undefined) throw new FrontmatterError(UNCLOSED_FLOW, no);\n        throw new FrontmatterError(`unexpected \"${char}\" in a flow collection`, no);\n    }\n}\n\nfunction readFlowKey(text: string, start: number, no: number): { key: string; end: number } {\n    const index = skipSpaces(text, start);\n    const char = text[index];\n    if (char === undefined) throw new FrontmatterError(UNCLOSED_FLOW, no);\n    if (char === '\"' || char === \"'\") {\n        const quoted = readQuoted(text, index, no);\n        const colon = skipSpaces(text, quoted.end);\n        if (text[colon] !== ':') throw new FrontmatterError('expected \": \" after a key in a flow mapping', no);\n        return { key: checkKey(quoted.value, no), end: colon };\n    }\n    if (char === '[' || char === '{') throw new FrontmatterError('complex keys (flow collections as keys) are not supported', no);\n    assertFlowPlainStart(text, index, no);\n    const end = scanFlowPlain(text, index);\n    const raw = trimWhiteEnd(text.slice(index, end));\n    const after = text[end + 1];\n    if (raw === '' || text[end] !== ':' || (after !== ' ' && after !== '\\t')) {\n        throw new FrontmatterError('expected \"key: value\" in a flow mapping', no);\n    }\n    return { key: resolveKey(raw, no), end };\n}\n\n// After `-`, `?` or `:`, any of these makes it an indicator in a flow collection.\nconst FLOW_SEPARATORS = ' \\t,[]{}';\n\nfunction assertFlowPlainStart(text: string, index: number, no: number): void {\n    const char = text[index]!;\n    if ('&*!'.includes(char)) throw new FrontmatterError('anchors, aliases and tags are not supported', no);\n    if ('|>%@`#'.includes(char) || ('-?:'.includes(char) && FLOW_SEPARATORS.includes(text[index + 1] ?? ' '))) {\n        throw new FrontmatterError(`\"${char}\" cannot start a plain value in a flow collection; quote it`, no);\n    }\n}\n\n// The end of a plain flow scalar: a flow indicator, a comment or a `:` indicator.\nfunction scanFlowPlain(text: string, index: number): number {\n    let end = index;\n    while (end < text.length) {\n        const char = text[end]!;\n        if (',[]{}'.includes(char)) break;\n        if (char === '#' && (text[end - 1] === ' ' || text[end - 1] === '\\t')) break;\n        if (char === ':' && FLOW_SEPARATORS.includes(text[end + 1] ?? ' ')) break;\n        end++;\n    }\n    return end;\n}\n\nfunction readFlowValue(text: string, start: number, no: number, depth: number): { value: unknown; end: number } {\n    const index = skipSpaces(text, start);\n    const char = text[index];\n    if (char === undefined) throw new FrontmatterError(UNCLOSED_FLOW, no);\n    if (char === '[' || char === '{') return readFlow(text, index, no, depth + 1);\n    if (char === '\"' || char === \"'\") return readQuoted(text, index, no);\n    assertFlowPlainStart(text, index, no);\n    const end = scanFlowPlain(text, index);\n    if (text[end] === ':') throw new FrontmatterError('mappings inside flow collections are not supported; quote the value', no);\n    const raw = trimWhiteEnd(text.slice(index, end));\n    if (raw === '') throw new FrontmatterError('empty value in a flow collection', no);\n    return { value: resolvePlain(raw, no), end };\n}\n\n// Joins block scalar lines as YAML does (the algorithm of js-yaml's readBlockScalar).\nfunction foldBlock(contents: readonly string[], folded: boolean, chomping: string): string {\n    let result = '';\n    let emptyLines = 0;\n    let didReadContent = false;\n    let atMoreIndented = false;\n    for (const content of contents) {\n        if (content === '') {\n            emptyLines++;\n            continue;\n        }\n        if (folded) {\n            if (content.startsWith(' ') || content.startsWith('\\t')) {\n                atMoreIndented = true;\n                result += '\\n'.repeat(didReadContent ? 1 + emptyLines : emptyLines);\n            } else if (atMoreIndented) {\n                atMoreIndented = false;\n                result += '\\n'.repeat(emptyLines + 1);\n            } else if (emptyLines === 0) {\n                if (didReadContent) result += ' ';\n            } else {\n                result += '\\n'.repeat(emptyLines);\n            }\n        } else {\n            result += '\\n'.repeat(didReadContent ? 1 + emptyLines : emptyLines);\n        }\n        result += content;\n        didReadContent = true;\n        emptyLines = 0;\n    }\n    if (chomping === '+') result += '\\n'.repeat(didReadContent ? 1 + emptyLines : emptyLines);\n    else if (chomping === '' && didReadContent) result += '\\n';\n    return result;\n}\n","// WHATWG URL's path percent-encode set, `^` included on every runtime (Node 20 and 22 leave it raw), plus `%`, `/` and `\\`.\nconst ENCODED_IN_SEGMENT = /[^\\w!$&'()*+,.:;=@[\\]|~-]/gu;\n\nfunction encodePathText(text: string): string {\n    return text.replaceAll(ENCODED_IN_SEGMENT, char => encodeURIComponent(char));\n}\n\n/** Percent-encodes one path segment as WHATWG URL does, plus `%`, `/`, `\\` and the dots of `.` and `..`; throws `URIError` on a lone surrogate. */\nexport function encodeSegment(segment: string): string {\n    if (segment === '.' || segment === '..') return segment.replaceAll('.', '%2E');\n    return encodePathText(segment);\n}\n\n/** `text` without its trailing `/`s; a loop, since `/\\/+$/` backtracks polynomially on a long run of `/`. */\nexport function trimTrailingSlashes(text: string): string {\n    let end = text.length;\n    while (end > 0 && text.codePointAt(end - 1) === 0x2f) end--;\n    return text.slice(0, end);\n}\n\n/** `base` (`scheme://`, or a URI without a trailing slash) + `/`-joined encoded segments; an authority is encoded strictly. */\nexport function joinUri(base: string, segments: readonly string[]): string {\n    if (!base.endsWith('://')) return `${trimTrailingSlashes(base)}/${segments.map(segment => encodeSegment(segment)).join('/')}`;\n    const [authority, ...path] = segments;\n    if (authority === undefined) return base;\n    return [base + encodeURIComponent(authority), ...path.map(segment => encodeSegment(segment))].join('/');\n}\n\n/** WHATWG-serialised form of `uri`, or `undefined` if it does not parse. */\nexport function canonicalUri(uri: string): string | undefined {\n    try {\n        return new URL(uri).href;\n    } catch {\n        return undefined;\n    }\n}\n\n/** True when `uri` is already in canonical form. */\nexport function isRoundTripUri(uri: string): boolean {\n    return canonicalUri(uri) === uri;\n}\n\nconst MANIFEST_SUFFIX = '/SKILL.md';\n\n/** The skill's root directory URI (no trailing slash), or `undefined` if `skillMdUri` is not a `…/SKILL.md` URI in a named directory. */\nexport function skillRootUri(skillMdUri: string): string | undefined {\n    const canonical = canonicalUri(skillMdUri);\n    if (canonical === undefined || !canonical.endsWith(MANIFEST_SUFFIX)) return undefined;\n    const root = canonical.slice(0, -MANIFEST_SUFFIX.length);\n    // `scheme:/` or `scheme://` (no directory) and `…//SKILL.md` (an empty last segment) name no directory.\n    return root.endsWith('/') ? undefined : root;\n}\n\nfunction safeDecode(segment: string): string {\n    try {\n        return decodeURIComponent(segment);\n    } catch {\n        return segment;\n    }\n}\n\n/** The decoded last segment of a directory URI (the authority when the path is empty). */\nexport function lastSegmentOf(rootUri: string): string {\n    const url = new URL(rootUri);\n    const path = url.pathname;\n    return safeDecode(path === '' || path === '/' ? url.host : path.slice(path.lastIndexOf('/') + 1));\n}\n\n/** True when `uri` is strictly inside `rootUri` and no segment below it decodes to empty, `.`, `..`, or a name holding `/` or NUL. */\nexport function isWithin(rootUri: string, uri: string): boolean {\n    const canonical = canonicalUri(uri);\n    if (canonical === undefined || !canonical.startsWith(`${rootUri}/`)) return false;\n    return canonical\n        .slice(rootUri.length + 1)\n        .split('/')\n        .every(segment => {\n            const decoded = safeDecode(segment);\n            return decoded !== '' && decoded !== '.' && decoded !== '..' && !decoded.includes('/') && !decoded.includes('\\0');\n        });\n}\n\nfunction decodeOrUndefined(escapes: string): string | undefined {\n    try {\n        return decodeURIComponent(escapes);\n    } catch {\n        return undefined;\n    }\n}\n\nfunction utf8Width(lead: number): number {\n    if (lead >= 0xf0) return 4;\n    if (lead >= 0xe0) return 3;\n    if (lead >= 0xc0) return 2;\n    return 1;\n}\n\n// Each valid UTF-8 sequence is decoded and re-encoded; a `%XX` starting none is a literal `%`, as published (`10%25Dec.md`).\nfunction keyOfEscapes(run: string): string {\n    let key = '';\n    for (let at = 0; at < run.length; ) {\n        const width = 3 * utf8Width(Number.parseInt(run.slice(at + 1, at + 3), 16));\n        const decoded = decodeOrUndefined(run.slice(at, at + width));\n        if (decoded === undefined) {\n            key += `%25${run.slice(at + 1, at + 3)}`;\n            at += 3;\n        } else {\n            key += encodePathText(decoded);\n            at += width;\n        }\n    }\n    return key;\n}\n\n// Runs of `%XX` escapes; splitting on this puts them at odd indexes.\nconst ESCAPE_RUN = /((?:%[\\dA-Fa-f]{2})+)/;\n\nfunction keyOfSegment(segment: string): string {\n    return segment\n        .split(ESCAPE_RUN)\n        .map((part, index) => (index % 2 === 0 ? encodePathText(part) : keyOfEscapes(part)))\n        .join('');\n}\n\n/** The one spelling all ways of writing a file's URI below `rootUri` share (`Q&A.md`, `Q%26A.md#x`); `undefined` if it does not parse. */\nexport function skillFileKey(rootUri: string, uri: string): string | undefined {\n    let url: URL;\n    try {\n        url = new URL(uri);\n    } catch {\n        return undefined;\n    }\n    url.hash = '';\n    const canonical = url.href;\n    // A canonical path never holds a raw `?`, so one here starts a query, even an empty one.\n    if (canonical.includes('?') || !canonical.startsWith(`${rootUri}/`)) return canonical;\n    const below = canonical\n        .slice(rootUri.length + 1)\n        .split('/')\n        .map(segment => keyOfSegment(segment));\n    return `${rootUri}/${below.join('/')}`;\n}\n\n/** Resolves `ref` (default `SKILL.md`) against the skill's root, as a browser resolves a link. */\nexport function resolveSkillRef(skillMdUri: string, ref?: string): string {\n    const root = skillRootUri(skillMdUri);\n    if (root === undefined) throw new TypeError(`${skillMdUri} is not a SKILL.md URI`);\n    return new URL(ref ?? 'SKILL.md', `${root}/`).href;\n}\n\n/** Code-unit order of two URIs: the one order for entries, directory children and cursors. */\nexport function compareUris(a: string, b: string): number {\n    if (a < b) return -1;\n    if (a > b) return 1;\n    return 0;\n}\n","import type { Skill } from '@modelcontextprotocol/core/ext/skills';\nimport { SkillSchema } from '@modelcontextprotocol/core/ext/skills';\n\nimport { decodeUtf8Lossless, sha256Digest } from './bytes';\nimport { FrontmatterError, parseSkillMarkdown } from './frontmatter';\nimport { canonicalUri, compareUris, isWithin, lastSegmentOf, skillFileKey, skillRootUri } from './uri';\n\n/** Agent Skills name rule: lowercase letters, digits and single hyphens (length checked separately). */\nexport const SKILL_NAME_PATTERN = /^[\\da-z]+(?:-[\\da-z]+)*$/;\n\nconst isStringMap = (value: unknown): boolean =>\n    typeof value === 'object' &&\n    value !== null &&\n    !Array.isArray(value) &&\n    Object.values(value as Record<string, unknown>).every(item => typeof item === 'string');\n\n// Agent Skills length limits count characters (code points), not UTF-16 code units.\nfunction countCharacters(text: string): number {\n    let count = 0;\n    for (let index = 0; index < text.length; index += text.codePointAt(index)! > 0xff_ff ? 2 : 1) count++;\n    return count;\n}\n\n/** Structural rules of the stable spec and Agent Skills. Empty array = valid. */\nexport function validateSkillEntry(skill: Skill): string[] {\n    const problems: string[] = [];\n    const root = skillRootUri(skill.uri);\n    if (root === undefined) return [`uri \"${skill.uri}\" must be a URI ending in /SKILL.md inside a named directory`];\n    const frontmatter = skill.frontmatter as Record<string, unknown>;\n    const { name, description } = skill.frontmatter;\n    if (name.length === 0 || name.length > 64 || !SKILL_NAME_PATTERN.test(name)) {\n        problems.push(`frontmatter name \"${name}\" must be 1-64 lowercase letters, digits and single hyphens`);\n    } else if (lastSegmentOf(root) !== name) {\n        problems.push(`frontmatter name \"${name}\" must match the last path segment \"${lastSegmentOf(root)}\"`);\n    }\n    if (description === '' || countCharacters(description) > 1024) problems.push('frontmatter description must be 1-1024 characters');\n    const compatibility = frontmatter['compatibility'];\n    if (\n        compatibility !== undefined &&\n        (typeof compatibility !== 'string' || compatibility === '' || countCharacters(compatibility) > 500)\n    ) {\n        problems.push('frontmatter compatibility must be a string of 1-500 characters');\n    }\n    if (frontmatter['metadata'] !== undefined && !isStringMap(frontmatter['metadata'])) {\n        problems.push('frontmatter metadata must map strings to strings');\n    }\n    if (skill.resources !== 'dynamic') {\n        const self = canonicalUri(skill.uri);\n        const seen = new Set<string>();\n        let hasSelf = false;\n        for (const resource of skill.resources) {\n            const canonical = canonicalUri(resource.uri);\n            if (canonical === undefined) {\n                problems.push(`resource \"${resource.uri}\" is not a valid URI`);\n                continue;\n            }\n            // A canonical URI holds a raw `?` or `#` only as a query or fragment, even an empty one.\n            if (/[#?]/.test(canonical)) {\n                problems.push(`resource \"${resource.uri}\" must not have a query or fragment`);\n                continue;\n            }\n            const key = skillFileKey(root, canonical) ?? canonical;\n            if (seen.has(key)) problems.push(`resource \"${resource.uri}\" is listed more than once`);\n            seen.add(key);\n            if (canonical === self) hasSelf = true;\n            else if (!isWithin(root, resource.uri)) problems.push(`resource \"${resource.uri}\" is outside the skill directory ${root}`);\n        }\n        if (!hasSelf) problems.push(`resources must include ${skill.uri}`);\n    }\n    return problems;\n}\n\n/** Schema check plus {@linkcode validateSkillEntry}, for values received from elsewhere. */\nexport function skillEntryProblems(value: unknown): string[] {\n    const parsed = SkillSchema.safeParse(value);\n    if (!parsed.success) return parsed.error.issues.map(issue => `${issue.path.join('.') || '(entry)'}: ${issue.message}`);\n    return validateSkillEntry(parsed.data);\n}\n\nexport interface SkillFileInput {\n    uri: string;\n    bytes: Uint8Array;\n}\n\n/** Builds an entry from a skill's files: parses `SKILL.md`, hashes every file, sorts by URI, validates. */\nexport async function buildSkillEntry(\n    skillMdUri: string,\n    files: readonly SkillFileInput[]\n): Promise<{ skill?: Skill; problems: string[] }> {\n    const manifest = files.find(file => file.uri === skillMdUri);\n    if (manifest === undefined) return { problems: ['SKILL.md is missing'] };\n    const text = decodeUtf8Lossless(manifest.bytes);\n    if (text === undefined) return { problems: ['SKILL.md is not valid UTF-8'] };\n    let frontmatter: Record<string, unknown>;\n    try {\n        frontmatter = parseSkillMarkdown(text).frontmatter;\n    } catch (error) {\n        if (error instanceof FrontmatterError) return { problems: [`SKILL.md frontmatter: ${error.message}`] };\n        throw error;\n    }\n    if (typeof frontmatter['name'] !== 'string' || typeof frontmatter['description'] !== 'string') {\n        return { problems: ['SKILL.md frontmatter must contain string \"name\" and \"description\"'] };\n    }\n    const resources = await Promise.all(\n        files.map(async file => ({ uri: file.uri, digest: await sha256Digest(file.bytes), size: file.bytes.byteLength }))\n    );\n    resources.sort((a, b) => compareUris(a.uri, b.uri));\n    const skill = { uri: skillMdUri, frontmatter, resources } as Skill;\n    return { skill, problems: validateSkillEntry(skill) };\n}\n","import type { Skill } from '@modelcontextprotocol/core/ext/skills';\nimport { SkillSchema } from '@modelcontextprotocol/core/ext/skills';\nimport { canonicalUri, validateSkillEntry } from '@modelcontextprotocol/core-internal/ext/skills';\n\n/** A `skills/list` entry the client refused, and why. `index` counts across every page walked. */\nexport interface InvalidSkillEntry {\n    index: number;\n    uri?: string;\n    reason: string;\n}\n\nexport interface CheckedEntry {\n    skill?: Skill;\n    uri?: string;\n    problems: string[];\n}\n\n/** Schema and rule checks for one entry received from a server. */\nexport function checkEntry(value: unknown): CheckedEntry {\n    const raw = (value as { uri?: unknown } | null | undefined)?.uri;\n    const uri = typeof raw === 'string' ? raw : undefined;\n    const parsed = SkillSchema.safeParse(value);\n    if (!parsed.success) {\n        return { uri, problems: parsed.error.issues.map(issue => `${issue.path.join('.') || '(entry)'}: ${issue.message}`) };\n    }\n    return { skill: parsed.data, uri, problems: validateSkillEntry(parsed.data) };\n}\n\nfunction keyOf(entry: CheckedEntry): string | undefined {\n    return entry.uri === undefined ? undefined : (canonicalUri(entry.uri) ?? entry.uri);\n}\n\n/** Splits listing entries into valid skills and refused entries. Every copy of a repeated URI is refused. */\nexport function partitionEntries(values: readonly unknown[]): { skills: Skill[]; invalid: InvalidSkillEntry[] } {\n    const checked = values.map(value => checkEntry(value));\n    const counts = new Map<string, number>();\n    for (const entry of checked) {\n        const key = keyOf(entry);\n        if (key !== undefined) counts.set(key, (counts.get(key) ?? 0) + 1);\n    }\n    const skills: Skill[] = [];\n    const invalid: InvalidSkillEntry[] = [];\n    for (const [index, entry] of checked.entries()) {\n        const key = keyOf(entry);\n        const repeated = key !== undefined && (counts.get(key) ?? 0) > 1;\n        const problems = repeated ? [...entry.problems, 'the same uri is listed more than once'] : entry.problems;\n        if (entry.skill !== undefined && problems.length === 0) skills.push(entry.skill);\n        else invalid.push({ index, ...(entry.uri !== undefined && { uri: entry.uri }), reason: problems.join('; ') });\n    }\n    return { skills, invalid };\n}\n","import { ReadResourceDirectoryResultSchema } from '@modelcontextprotocol/core/ext/skills';\nimport * as z from 'zod/v4';\n\nconst cacheFields = {\n    ttlMs: z.number().int().nonnegative(),\n    cacheScope: z.enum(['public', 'private'])\n};\n\n/**\n * `skills/list` and `skills/get` envelopes that leave entries unchecked, so a\n * bad entry is reported on its own instead of failing the whole response.\n * Defined with this package's own `zod`, so no schema crosses package copies.\n */\nconst SkillsPageSchema = z.looseObject({\n    skills: z.array(z.unknown()),\n    nextCursor: z.string().optional(),\n    ...cacheFields\n});\n\nconst GetSkillEnvelopeSchema = z.looseObject({\n    skill: z.unknown(),\n    ...cacheFields\n});\n\n/** The 2026-07-28 result envelopes: each result extends `CacheableResult`, so both caching fields are required. */\nexport const MODERN_ENVELOPES = { list: SkillsPageSchema, get: GetSkillEnvelopeSchema, directory: ReadResourceDirectoryResultSchema };\n\nconst uncached = { ttlMs: true, cacheScope: true } as const;\n\n/** The 2025-11-25 result envelopes: the backport has no caching fields, so they are optional. */\nexport const LEGACY_ENVELOPES = {\n    list: SkillsPageSchema.partial(uncached),\n    get: GetSkillEnvelopeSchema.partial(uncached),\n    directory: ReadResourceDirectoryResultSchema.partial(uncached)\n};\n","const isPlainObject = (value: unknown): value is Record<string, unknown> =>\n    typeof value === 'object' && value !== null && !Array.isArray(value);\n\nconst show = (value: unknown): string => (value === undefined ? 'nothing' : JSON.stringify(value));\n\nconst fieldOf = (path: string, key: string): string => (path === '' ? key : `${path}.${key}`);\n\n/** Every field a reader of `object` sees, inherited ones included; Object.prototype's (`constructor`, `__proto__`) are not enumerable. */\nfunction fieldsOf(object: Record<string, unknown>): Map<string, unknown> {\n    const fields = new Map<string, unknown>();\n    for (const key in object) fields.set(key, object[key]);\n    return fields;\n}\n\n/**\n * Field-level differences between a skill entry's frontmatter and the\n * frontmatter parsed from its `SKILL.md`: every key both ways, objects in any\n * key order, arrays in order, numbers by value, no type coercion.\n */\nexport function frontmatterDifferences(entry: unknown, parsed: unknown, path = ''): string[] {\n    const label = path === '' ? '(frontmatter)' : path;\n    if (Array.isArray(entry) && Array.isArray(parsed)) {\n        if (entry.length !== parsed.length) return [`${label}: the entry has ${entry.length} items, SKILL.md has ${parsed.length}`];\n        return entry.flatMap((item, index) => frontmatterDifferences(item, parsed[index], `${path}[${index}]`));\n    }\n    if (isPlainObject(entry) && isPlainObject(parsed)) {\n        const [fromEntry, fromParsed] = [fieldsOf(entry), fieldsOf(parsed)];\n        const keys = [...new Set([...fromEntry.keys(), ...fromParsed.keys()])].toSorted();\n        return keys.flatMap(key => frontmatterDifferences(fromEntry.get(key), fromParsed.get(key), fieldOf(path, key)));\n    }\n    return entry === parsed ? [] : [`${label}: the entry has ${show(entry)}, SKILL.md has ${show(parsed)}`];\n}\n","import type { DirectoryResource, Skill, SkillCacheScope, SkillResourceEntry } from '@modelcontextprotocol/core/ext/skills';\nimport {\n    RESOURCES_DIRECTORY_READ_METHOD,\n    SKILLS_EXTENSION_ID,\n    SKILLS_GET_METHOD,\n    SKILLS_LIST_METHOD,\n    skillsCapabilityOf\n} from '@modelcontextprotocol/core/ext/skills';\nimport { isModernProtocolVersion } from '@modelcontextprotocol/core-internal';\nimport {\n    canonicalUri,\n    decodeBase64,\n    decodeUtf8Lossless,\n    encodeUtf8,\n    isWithin,\n    parseSkillMarkdown,\n    resolveSkillRef,\n    sha256Digest,\n    skillFileKey,\n    skillRootUri,\n    splitFrontmatter\n} from '@modelcontextprotocol/core-internal/ext/skills';\nimport type { ReadResourceResult, RequestOptions } from '@modelcontextprotocol/core-internal/public';\nimport { SdkError, SdkErrorCode } from '@modelcontextprotocol/core-internal/public';\nimport type * as z from 'zod/v4';\n\nimport type { CacheableRequestOptions, Client } from '../../client/client';\nimport { clientInternals } from '../../client/client';\nimport type { InvalidSkillEntry } from './entries';\nimport { checkEntry, partitionEntries } from './entries';\nimport { SkillVerificationError } from './errors';\nimport { LEGACY_ENVELOPES, MODERN_ENVELOPES } from './pageSchemas';\nimport { frontmatterDifferences } from './verify';\n\nexport interface SkillsClientOptions {\n    /**\n     * Parses the YAML between a `SKILL.md`'s `---` lines (BOM and CRLF removed) for verification, instead of the\n     * built-in parser (YAML 1.2 core-schema typing).\n     */\n    parseFrontmatter?: (yaml: string) => Record<string, unknown>;\n    /** Return invalid `skills/list` entries in `invalid` instead of throwing. Default `false`: `list()` throws on any. */\n    skipInvalid?: boolean;\n}\n\n/** What `list()` returns: the valid entries, the refused ones (only with `skipInvalid`), and the first page's caching fields. */\nexport interface SkillListing {\n    skills: Skill[];\n    invalid: InvalidSkillEntry[];\n    /** Only when `list()` was given a cursor (one page); a full walk has none. */\n    nextCursor?: string;\n    ttlMs?: number;\n    cacheScope?: SkillCacheScope;\n}\n\n/** A skill file as read and checked by {@linkcode SkillsClient.read}. */\nexport interface SkillFile {\n    /** The URI requested: the entry's spelling of the file; for `\"dynamic\"` skills, the resolved ref in its normalised form. */\n    uri: string;\n    mimeType?: string;\n    /** Exactly the bytes the entry's digest covers. */\n    bytes: Uint8Array;\n    /** When the server sent text (always, for the skill's own `SKILL.md`). */\n    text?: string;\n    /** Size and digest were checked. `false` only for `\"dynamic\"` skills. */\n    verified: boolean;\n    /** The skill's own `SKILL.md` only: its parsed frontmatter, equal to the entry's. */\n    frontmatter?: Record<string, unknown>;\n    /** The skill's own `SKILL.md` only: the markdown after the frontmatter. */\n    body?: string;\n}\n\nfunction decodeBlob(uri: string, blob: string): Uint8Array {\n    try {\n        return decodeBase64(blob);\n    } catch (error) {\n        throw new SdkError(SdkErrorCode.InvalidResult, `resources/read returned an invalid base64 blob for ${uri}`, undefined, {\n            cause: error\n        });\n    }\n}\n\n/** What `read` requests and checks: the file's URI and key, its listing, and whether it is the skill's own `SKILL.md`. */\ninterface ReadTarget {\n    /** The entry's spelling of a listed file; for a `\"dynamic\"` skill, the URI the ref resolves to. */\n    uri: string;\n    root: string;\n    /** The file's {@linkcode skillFileKey}: listings and returned contents are matched by it. */\n    key: string;\n    /** `undefined` for `\"dynamic\"` skills. */\n    listed: SkillResourceEntry | undefined;\n    manifest: boolean;\n}\n\n/**\n * Resolves `ref` against the skill root and drops its fragment. A listed file is found in the entry by\n * {@linkcode skillFileKey}, since servers percent-encode names differently (`Q&A.md`, `Q%26A.md`); a\n * `\"dynamic\"` skill's file is requested at the resolved URI, as nothing published another spelling.\n * Throws `unlisted` for a ref that does not parse or names no file of the skill.\n */\nfunction resolveTarget(skill: Skill, ref: string | undefined): ReadTarget {\n    const root = skillRootUri(skill.uri);\n    if (root === undefined) throw new TypeError(`${skill.uri} is not a SKILL.md URI`);\n    let uri: string;\n    try {\n        const resolved = new URL(resolveSkillRef(skill.uri, ref));\n        resolved.hash = '';\n        uri = resolved.href;\n    } catch (error) {\n        const given = ref ?? '';\n        throw new SkillVerificationError('unlisted', given, `${given} is not a URI reference`, [], { cause: error });\n    }\n    const key = skillFileKey(root, uri) ?? uri;\n    const manifest = key === skillFileKey(root, skill.uri);\n    const notInSkill = () => new SkillVerificationError('unlisted', uri, `${uri} is not a file of the skill ${skill.uri}`);\n    if (skill.resources === 'dynamic') {\n        if (!manifest && !isWithin(root, key)) throw notInSkill();\n        return { uri, root, key, listed: undefined, manifest };\n    }\n    const listed = skill.resources.find(resource => skillFileKey(root, resource.uri) === key);\n    if (listed === undefined) throw notInSkill();\n    return { uri: listed.uri, root, key, listed, manifest };\n}\n\n/** A result's `ttlMs` and `cacheScope`, where it has them (always, on 2026-07-28). */\nfunction cacheFieldsOf(result: { ttlMs?: number; cacheScope?: SkillCacheScope }): { ttlMs?: number; cacheScope?: SkillCacheScope } {\n    return {\n        ...(result.ttlMs !== undefined && { ttlMs: result.ttlMs }),\n        ...(result.cacheScope !== undefined && { cacheScope: result.cacheScope })\n    };\n}\n\nfunction unsupported(method: string): SdkError {\n    return new SdkError(\n        SdkErrorCode.CapabilityNotSupported,\n        `Server does not support the ${SKILLS_EXTENSION_ID} extension (required for ${method})`\n    );\n}\n\n/**\n * Host side of the MCP Skills extension (SEP-2640): lists, gets and reads a\n * server's skills, and verifies every file against the server's entry.\n * Approval, origin tagging and loading policy stay with the host.\n *\n * @example\n * ```ts\n * const skills = new SkillsClient(client);\n * const { skills: entries } = await skills.list();\n * const manifest = await skills.read(entries[0]!);\n * ```\n */\nexport class SkillsClient {\n    readonly #client: Client;\n    readonly #options: SkillsClientOptions;\n\n    constructor(client: Client, options: SkillsClientOptions = {}) {\n        this.#client = client;\n        this.#options = options;\n    }\n\n    /** The server declared the extension (and `resources`, under `enforceStrictCapabilities`). `false` before connect. */\n    get supported(): boolean {\n        const capabilities = this.#client.getServerCapabilities();\n        if (skillsCapabilityOf(capabilities) === undefined) return false;\n        return !clientInternals.enforceStrictCapabilities(this.#client) || capabilities?.resources !== undefined;\n    }\n\n    /** The server serves `resources/directory/read`. */\n    get directoryRead(): boolean {\n        return this.supported && skillsCapabilityOf(this.#client.getServerCapabilities())?.directoryRead === true;\n    }\n\n    /**\n     * Lists the server's skills, walking every page unless given a cursor\n     * (bounded by the client's `listMaxPages`). Throws an `SdkError` naming\n     * every invalid entry, and every copy of a repeated URI; with\n     * `skipInvalid`, returns them in `invalid` instead. A 2026-07-28 page\n     * without `ttlMs` and `cacheScope` throws either way. On a server without\n     * the extension: an empty listing.\n     */\n    async list(params: { cursor?: string } = {}, options?: RequestOptions): Promise<SkillListing> {\n        if (!this.supported) {\n            if (clientInternals.enforceStrictCapabilities(this.#client)) throw unsupported(SKILLS_LIST_METHOD);\n            // eslint-disable-next-line no-console\n            console.debug(`SkillsClient.list() called but the server does not declare ${SKILLS_EXTENSION_ID} - returning an empty list`);\n            return { skills: [], invalid: [] };\n        }\n        const page = await this.#pages(SKILLS_LIST_METHOD, this.#envelopes().list, {}, params.cursor, options, result => result.skills);\n        const { skills, invalid } = partitionEntries(page.skills);\n        if (invalid.length > 0 && !this.#options.skipInvalid) {\n            const detail = invalid.map(entry => `#${entry.index} ${entry.uri ?? ''}: ${entry.reason}`).join('\\n');\n            throw new SdkError(SdkErrorCode.InvalidResult, `skills/list returned invalid entries:\\n${detail}`, { invalid });\n        }\n        return {\n            skills,\n            invalid,\n            ...(params.cursor !== undefined && page.nextCursor !== undefined && { nextCursor: page.nextCursor }),\n            ...cacheFieldsOf(page)\n        };\n    }\n\n    /**\n     * One skill by its `SKILL.md` URI, listed or not, with the result's caching\n     * fields on 2026-07-28. Throws if the server returns an invalid entry or\n     * another skill.\n     */\n    async get(uri: string, options?: RequestOptions): Promise<{ skill: Skill; ttlMs?: number; cacheScope?: SkillCacheScope }> {\n        if (!this.supported) throw unsupported(SKILLS_GET_METHOD);\n        const result = await this.#client.request({ method: SKILLS_GET_METHOD, params: { uri } }, this.#envelopes().get, options);\n        const { skill, problems } = checkEntry(result.skill);\n        if (skill === undefined || problems.length > 0) {\n            throw new SdkError(SdkErrorCode.InvalidResult, `skills/get returned an invalid entry for ${uri}: ${problems.join('; ')}`);\n        }\n        if (canonicalUri(skill.uri) !== canonicalUri(uri)) {\n            throw new SdkError(SdkErrorCode.InvalidResult, `skills/get for ${uri} returned ${skill.uri}`);\n        }\n        return { skill, ...cacheFieldsOf(result) };\n    }\n\n    /**\n     * Reads one file of `skill` and verifies it. `ref` is a path relative to\n     * the skill's root (`references/FORMS.md`) or an absolute URI; the\n     * default is the skill's own `SKILL.md`; a fragment is ignored. The file\n     * must be listed in the entry (checked before any request, however either\n     * side percent-encodes the name) and is requested by the entry's URI; its\n     * size and digest must match;\n     * for the skill's own `SKILL.md` the frontmatter must also equal the\n     * entry's. A copy from the client's response cache that fails a check is\n     * fetched once more with `cacheMode: 'refresh'`. `\"dynamic\"` skills skip\n     * the listing, size and digest checks (`verified: false`) but not the\n     * frontmatter. Pass entries from {@linkcode SkillsClient.list} or\n     * {@linkcode SkillsClient.get}; an invalid entry throws a `TypeError`\n     * before any request.\n     *\n     * @throws {SkillVerificationError} when a check fails.\n     */\n    async read(skill: Skill, ref?: string, options?: CacheableRequestOptions): Promise<SkillFile> {\n        if (!this.supported) throw unsupported('resources/read');\n        const { problems } = checkEntry(skill);\n        if (problems.length > 0) throw new TypeError(`${skill.uri} is not a valid skill entry: ${problems.join('; ')}`);\n        const target = resolveTarget(skill, ref);\n        const params = { uri: target.uri };\n        const { result, cached } = await clientInternals.readResource(this.#client, params, options);\n        try {\n            return await this.#verify(skill, target, result);\n        } catch (error) {\n            if (!(error instanceof SkillVerificationError) || !cached) throw error;\n            // A cached copy that fails verification must be fetched again (SEP-2640).\n            return this.#verify(skill, target, await this.#client.readResource(params, { ...options, cacheMode: 'refresh' }));\n        }\n    }\n\n    async #verify(skill: Skill, target: ReadTarget, result: ReadResourceResult): Promise<SkillFile> {\n        const { uri, root, key, listed } = target;\n        const content = result.contents.find(item => (skillFileKey(root, item.uri) ?? item.uri) === key);\n        if (content === undefined) throw new SdkError(SdkErrorCode.InvalidResult, `resources/read returned no contents for ${uri}`);\n        const bytes = 'text' in content ? encodeUtf8(content.text) : decodeBlob(uri, content.blob);\n        if (listed !== undefined) {\n            if (bytes.byteLength !== listed.size) {\n                throw new SkillVerificationError('size', uri, `${uri} is ${bytes.byteLength} bytes; the skill entry lists ${listed.size}`);\n            }\n            const digest = await sha256Digest(bytes);\n            if (digest !== listed.digest) {\n                throw new SkillVerificationError('digest', uri, `${uri} has digest ${digest}; the skill entry lists ${listed.digest}`);\n            }\n        }\n        const file: SkillFile = {\n            uri,\n            ...(content.mimeType !== undefined && { mimeType: content.mimeType }),\n            bytes,\n            ...('text' in content && { text: content.text }),\n            verified: listed !== undefined\n        };\n        if (!target.manifest) return file;\n        const markdown = 'text' in content ? content.text : decodeUtf8Lossless(bytes);\n        if (markdown === undefined) throw new SkillVerificationError('frontmatter', uri, `${uri} is not valid UTF-8`);\n        const { frontmatter, body } = this.#parse(uri, markdown);\n        const differences = frontmatterDifferences(skill.frontmatter, frontmatter);\n        if (differences.length > 0) {\n            throw new SkillVerificationError(\n                'frontmatter',\n                uri,\n                `the frontmatter of ${uri} differs from the skill entry: ${differences.join('; ')}`,\n                differences\n            );\n        }\n        return { ...file, text: markdown, frontmatter, body };\n    }\n\n    #parse(uri: string, markdown: string): { frontmatter: Record<string, unknown>; body: string } {\n        try {\n            const parse = this.#options.parseFrontmatter;\n            if (parse === undefined) return parseSkillMarkdown(markdown);\n            const { yaml, body } = splitFrontmatter(markdown);\n            return { frontmatter: parse(yaml), body };\n        } catch (error) {\n            const reason = error instanceof Error ? error.message : String(error);\n            throw new SkillVerificationError('frontmatter', uri, `the frontmatter of ${uri} cannot be read: ${reason}`, [], {\n                cause: error\n            });\n        }\n    }\n\n    /**\n     * The direct children of a skill directory, every page walked, with the\n     * first page's caching fields on 2026-07-28. Needs `directoryRead`.\n     */\n    async readDirectory(\n        uri: string,\n        options?: RequestOptions\n    ): Promise<{ resources: DirectoryResource[]; ttlMs?: number; cacheScope?: SkillCacheScope }> {\n        if (!this.directoryRead) {\n            throw new SdkError(\n                SdkErrorCode.CapabilityNotSupported,\n                `Server does not declare directoryRead for ${SKILLS_EXTENSION_ID} (required for ${RESOURCES_DIRECTORY_READ_METHOD})`\n            );\n        }\n        const page = await this.#pages(\n            RESOURCES_DIRECTORY_READ_METHOD,\n            this.#envelopes().directory,\n            { uri },\n            undefined,\n            options,\n            result => result.resources\n        );\n        return { resources: page.resources, ...cacheFieldsOf(page) };\n    }\n\n    /** The result envelopes for the negotiated version. */\n    #envelopes(): typeof LEGACY_ENVELOPES | typeof MODERN_ENVELOPES {\n        return isModernProtocolVersion(this.#client.getNegotiatedProtocolVersion() ?? '') ? MODERN_ENVELOPES : LEGACY_ENVELOPES;\n    }\n\n    /** One page (with `cursor`), or every page in one, walked as Client walks its own list verbs. */\n    #pages<T extends { nextCursor?: string }>(\n        method: string,\n        schema: z.ZodType<T>,\n        params: Record<string, unknown>,\n        cursor: string | undefined,\n        options: RequestOptions | undefined,\n        items: (page: T) => unknown[]\n    ): Promise<T> {\n        const fetchPage = (at: string | undefined): Promise<T> =>\n            this.#client.request({ method, params: at === undefined ? params : { ...params, cursor: at } }, schema, options);\n        return cursor === undefined ? clientInternals.walkPages(this.#client, method, fetchPage, items) : fetchPage(cursor);\n    }\n}\n","module.exports = isexe\nisexe.sync = sync\n\nvar fs = require('fs')\n\nfunction checkPathExt (path, options) {\n  var pathext = options.pathExt !== undefined ?\n    options.pathExt : process.env.PATHEXT\n\n  if (!pathext) {\n    return true\n  }\n\n  pathext = pathext.split(';')\n  if (pathext.indexOf('') !== -1) {\n    return true\n  }\n  for (var i = 0; i < pathext.length; i++) {\n    var p = pathext[i].toLowerCase()\n    if (p && path.substr(-p.length).toLowerCase() === p) {\n      return true\n    }\n  }\n  return false\n}\n\nfunction checkStat (stat, path, options) {\n  if (!stat.isSymbolicLink() && !stat.isFile()) {\n    return false\n  }\n  return checkPathExt(path, options)\n}\n\nfunction isexe (path, options, cb) {\n  fs.stat(path, function (er, stat) {\n    cb(er, er ? false : checkStat(stat, path, options))\n  })\n}\n\nfunction sync (path, options) {\n  return checkStat(fs.statSync(path), path, options)\n}\n","module.exports = isexe\nisexe.sync = sync\n\nvar fs = require('fs')\n\nfunction isexe (path, options, cb) {\n  fs.stat(path, function (er, stat) {\n    cb(er, er ? false : checkStat(stat, options))\n  })\n}\n\nfunction sync (path, options) {\n  return checkStat(fs.statSync(path), options)\n}\n\nfunction checkStat (stat, options) {\n  return stat.isFile() && checkMode(stat, options)\n}\n\nfunction checkMode (stat, options) {\n  var mod = stat.mode\n  var uid = stat.uid\n  var gid = stat.gid\n\n  var myUid = options.uid !== undefined ?\n    options.uid : process.getuid && process.getuid()\n  var myGid = options.gid !== undefined ?\n    options.gid : process.getgid && process.getgid()\n\n  var u = parseInt('100', 8)\n  var g = parseInt('010', 8)\n  var o = parseInt('001', 8)\n  var ug = u | g\n\n  var ret = (mod & o) ||\n    (mod & g) && gid === myGid ||\n    (mod & u) && uid === myUid ||\n    (mod & ug) && myUid === 0\n\n  return ret\n}\n","var fs = require('fs')\nvar core\nif (process.platform === 'win32' || global.TESTING_WINDOWS) {\n  core = require('./windows.js')\n} else {\n  core = require('./mode.js')\n}\n\nmodule.exports = isexe\nisexe.sync = sync\n\nfunction isexe (path, options, cb) {\n  if (typeof options === 'function') {\n    cb = options\n    options = {}\n  }\n\n  if (!cb) {\n    if (typeof Promise !== 'function') {\n      throw new TypeError('callback not provided')\n    }\n\n    return new Promise(function (resolve, reject) {\n      isexe(path, options || {}, function (er, is) {\n        if (er) {\n          reject(er)\n        } else {\n          resolve(is)\n        }\n      })\n    })\n  }\n\n  core(path, options || {}, function (er, is) {\n    // ignore EACCES because that just means we aren't allowed to run it\n    if (er) {\n      if (er.code === 'EACCES' || options && options.ignoreErrors) {\n        er = null\n        is = false\n      }\n    }\n    cb(er, is)\n  })\n}\n\nfunction sync (path, options) {\n  // my kingdom for a filtered catch\n  try {\n    return core.sync(path, options || {})\n  } catch (er) {\n    if (options && options.ignoreErrors || er.code === 'EACCES') {\n      return false\n    } else {\n      throw er\n    }\n  }\n}\n","const isWindows = process.platform === 'win32' ||\n    process.env.OSTYPE === 'cygwin' ||\n    process.env.OSTYPE === 'msys'\n\nconst path = require('path')\nconst COLON = isWindows ? ';' : ':'\nconst isexe = require('isexe')\n\nconst getNotFoundError = (cmd) =>\n  Object.assign(new Error(`not found: ${cmd}`), { code: 'ENOENT' })\n\nconst getPathInfo = (cmd, opt) => {\n  const colon = opt.colon || COLON\n\n  // If it has a slash, then we don't bother searching the pathenv.\n  // just check the file itself, and that's it.\n  const pathEnv = cmd.match(/\\//) || isWindows && cmd.match(/\\\\/) ? ['']\n    : (\n      [\n        // windows always checks the cwd first\n        ...(isWindows ? [process.cwd()] : []),\n        ...(opt.path || process.env.PATH ||\n          /* istanbul ignore next: very unusual */ '').split(colon),\n      ]\n    )\n  const pathExtExe = isWindows\n    ? opt.pathExt || process.env.PATHEXT || '.EXE;.CMD;.BAT;.COM'\n    : ''\n  const pathExt = isWindows ? pathExtExe.split(colon) : ['']\n\n  if (isWindows) {\n    if (cmd.indexOf('.') !== -1 && pathExt[0] !== '')\n      pathExt.unshift('')\n  }\n\n  return {\n    pathEnv,\n    pathExt,\n    pathExtExe,\n  }\n}\n\nconst which = (cmd, opt, cb) => {\n  if (typeof opt === 'function') {\n    cb = opt\n    opt = {}\n  }\n  if (!opt)\n    opt = {}\n\n  const { pathEnv, pathExt, pathExtExe } = getPathInfo(cmd, opt)\n  const found = []\n\n  const step = i => new Promise((resolve, reject) => {\n    if (i === pathEnv.length)\n      return opt.all && found.length ? resolve(found)\n        : reject(getNotFoundError(cmd))\n\n    const ppRaw = pathEnv[i]\n    const pathPart = /^\".*\"$/.test(ppRaw) ? ppRaw.slice(1, -1) : ppRaw\n\n    const pCmd = path.join(pathPart, cmd)\n    const p = !pathPart && /^\\.[\\\\\\/]/.test(cmd) ? cmd.slice(0, 2) + pCmd\n      : pCmd\n\n    resolve(subStep(p, i, 0))\n  })\n\n  const subStep = (p, i, ii) => new Promise((resolve, reject) => {\n    if (ii === pathExt.length)\n      return resolve(step(i + 1))\n    const ext = pathExt[ii]\n    isexe(p + ext, { pathExt: pathExtExe }, (er, is) => {\n      if (!er && is) {\n        if (opt.all)\n          found.push(p + ext)\n        else\n          return resolve(p + ext)\n      }\n      return resolve(subStep(p, i, ii + 1))\n    })\n  })\n\n  return cb ? step(0).then(res => cb(null, res), cb) : step(0)\n}\n\nconst whichSync = (cmd, opt) => {\n  opt = opt || {}\n\n  const { pathEnv, pathExt, pathExtExe } = getPathInfo(cmd, opt)\n  const found = []\n\n  for (let i = 0; i < pathEnv.length; i ++) {\n    const ppRaw = pathEnv[i]\n    const pathPart = /^\".*\"$/.test(ppRaw) ? ppRaw.slice(1, -1) : ppRaw\n\n    const pCmd = path.join(pathPart, cmd)\n    const p = !pathPart && /^\\.[\\\\\\/]/.test(cmd) ? cmd.slice(0, 2) + pCmd\n      : pCmd\n\n    for (let j = 0; j < pathExt.length; j ++) {\n      const cur = p + pathExt[j]\n      try {\n        const is = isexe.sync(cur, { pathExt: pathExtExe })\n        if (is) {\n          if (opt.all)\n            found.push(cur)\n          else\n            return cur\n        }\n      } catch (ex) {}\n    }\n  }\n\n  if (opt.all && found.length)\n    return found\n\n  if (opt.nothrow)\n    return null\n\n  throw getNotFoundError(cmd)\n}\n\nmodule.exports = which\nwhich.sync = whichSync\n","'use strict';\n\nconst pathKey = (options = {}) => {\n\tconst environment = options.env || process.env;\n\tconst platform = options.platform || process.platform;\n\n\tif (platform !== 'win32') {\n\t\treturn 'PATH';\n\t}\n\n\treturn Object.keys(environment).reverse().find(key => key.toUpperCase() === 'PATH') || 'Path';\n};\n\nmodule.exports = pathKey;\n// TODO: Remove this for the next major release\nmodule.exports.default = pathKey;\n","'use strict';\n\nconst path = require('path');\nconst which = require('which');\nconst getPathKey = require('path-key');\n\nfunction resolveCommandAttempt(parsed, withoutPathExt) {\n    const env = parsed.options.env || process.env;\n    const cwd = process.cwd();\n    const hasCustomCwd = parsed.options.cwd != null;\n    // Worker threads do not have process.chdir()\n    const shouldSwitchCwd = hasCustomCwd && process.chdir !== undefined && !process.chdir.disabled;\n\n    // If a custom `cwd` was specified, we need to change the process cwd\n    // because `which` will do stat calls but does not support a custom cwd\n    if (shouldSwitchCwd) {\n        try {\n            process.chdir(parsed.options.cwd);\n        } catch (err) {\n            /* Empty */\n        }\n    }\n\n    let resolved;\n\n    try {\n        resolved = which.sync(parsed.command, {\n            path: env[getPathKey({ env })],\n            pathExt: withoutPathExt ? path.delimiter : undefined,\n        });\n    } catch (e) {\n        /* Empty */\n    } finally {\n        if (shouldSwitchCwd) {\n            process.chdir(cwd);\n        }\n    }\n\n    // If we successfully resolved, ensure that an absolute path is returned\n    // Note that when a custom `cwd` was used, we need to resolve to an absolute path based on it\n    if (resolved) {\n        resolved = path.resolve(hasCustomCwd ? parsed.options.cwd : '', resolved);\n    }\n\n    return resolved;\n}\n\nfunction resolveCommand(parsed) {\n    return resolveCommandAttempt(parsed) || resolveCommandAttempt(parsed, true);\n}\n\nmodule.exports = resolveCommand;\n","'use strict';\n\n// See http://www.robvanderwoude.com/escapechars.php\nconst metaCharsRegExp = /([()\\][%!^\"`<>&|;, *?])/g;\n\nfunction escapeCommand(arg) {\n    // Escape meta chars\n    arg = arg.replace(metaCharsRegExp, '^$1');\n\n    return arg;\n}\n\nfunction escapeArgument(arg, doubleEscapeMetaChars) {\n    // Convert to string\n    arg = `${arg}`;\n\n    // Algorithm below is based on https://qntm.org/cmd\n    // It's slightly altered to disable JS backtracking to avoid hanging on specially crafted input\n    // Please see https://github.com/moxystudio/node-cross-spawn/pull/160 for more information\n\n    // Sequence of backslashes followed by a double quote:\n    // double up all the backslashes and escape the double quote\n    arg = arg.replace(/(?=(\\\\+?)?)\\1\"/g, '$1$1\\\\\"');\n\n    // Sequence of backslashes followed by the end of the string\n    // (which will become a double quote later):\n    // double up all the backslashes\n    arg = arg.replace(/(?=(\\\\+?)?)\\1$/, '$1$1');\n\n    // All other backslashes occur literally\n\n    // Quote the whole thing:\n    arg = `\"${arg}\"`;\n\n    // Escape meta chars\n    arg = arg.replace(metaCharsRegExp, '^$1');\n\n    // Double escape meta chars if necessary\n    if (doubleEscapeMetaChars) {\n        arg = arg.replace(metaCharsRegExp, '^$1');\n    }\n\n    return arg;\n}\n\nmodule.exports.command = escapeCommand;\nmodule.exports.argument = escapeArgument;\n","'use strict';\nmodule.exports = /^#!(.*)/;\n","'use strict';\nconst shebangRegex = require('shebang-regex');\n\nmodule.exports = (string = '') => {\n\tconst match = string.match(shebangRegex);\n\n\tif (!match) {\n\t\treturn null;\n\t}\n\n\tconst [path, argument] = match[0].replace(/#! ?/, '').split(' ');\n\tconst binary = path.split('/').pop();\n\n\tif (binary === 'env') {\n\t\treturn argument;\n\t}\n\n\treturn argument ? `${binary} ${argument}` : binary;\n};\n","'use strict';\n\nconst fs = require('fs');\nconst shebangCommand = require('shebang-command');\n\nfunction readShebang(command) {\n    // Read the first 150 bytes from the file\n    const size = 150;\n    const buffer = Buffer.alloc(size);\n\n    let fd;\n\n    try {\n        fd = fs.openSync(command, 'r');\n        fs.readSync(fd, buffer, 0, size, 0);\n        fs.closeSync(fd);\n    } catch (e) { /* Empty */ }\n\n    // Attempt to extract shebang (null is returned if not a shebang)\n    return shebangCommand(buffer.toString());\n}\n\nmodule.exports = readShebang;\n","'use strict';\n\nconst path = require('path');\nconst resolveCommand = require('./util/resolveCommand');\nconst escape = require('./util/escape');\nconst readShebang = require('./util/readShebang');\n\nconst isWin = process.platform === 'win32';\nconst isExecutableRegExp = /\\.(?:com|exe)$/i;\nconst isCmdShimRegExp = /node_modules[\\\\/].bin[\\\\/][^\\\\/]+\\.cmd$/i;\n\nfunction detectShebang(parsed) {\n    parsed.file = resolveCommand(parsed);\n\n    const shebang = parsed.file && readShebang(parsed.file);\n\n    if (shebang) {\n        parsed.args.unshift(parsed.file);\n        parsed.command = shebang;\n\n        return resolveCommand(parsed);\n    }\n\n    return parsed.file;\n}\n\nfunction parseNonShell(parsed) {\n    if (!isWin) {\n        return parsed;\n    }\n\n    // Detect & add support for shebangs\n    const commandFile = detectShebang(parsed);\n\n    // We don't need a shell if the command filename is an executable\n    const needsShell = !isExecutableRegExp.test(commandFile);\n\n    // If a shell is required, use cmd.exe and take care of escaping everything correctly\n    // Note that `forceShell` is an hidden option used only in tests\n    if (parsed.options.forceShell || needsShell) {\n        // Need to double escape meta chars if the command is a cmd-shim located in `node_modules/.bin/`\n        // The cmd-shim simply calls execute the package bin file with NodeJS, proxying any argument\n        // Because the escape of metachars with ^ gets interpreted when the cmd.exe is first called,\n        // we need to double escape them\n        const needsDoubleEscapeMetaChars = isCmdShimRegExp.test(commandFile);\n\n        // Normalize posix paths into OS compatible paths (e.g.: foo/bar -> foo\\bar)\n        // This is necessary otherwise it will always fail with ENOENT in those cases\n        parsed.command = path.normalize(parsed.command);\n\n        // Escape command & arguments\n        parsed.command = escape.command(parsed.command);\n        parsed.args = parsed.args.map((arg) => escape.argument(arg, needsDoubleEscapeMetaChars));\n\n        const shellCommand = [parsed.command].concat(parsed.args).join(' ');\n\n        parsed.args = ['/d', '/s', '/c', `\"${shellCommand}\"`];\n        parsed.command = process.env.comspec || 'cmd.exe';\n        parsed.options.windowsVerbatimArguments = true; // Tell node's spawn that the arguments are already escaped\n    }\n\n    return parsed;\n}\n\nfunction parse(command, args, options) {\n    // Normalize arguments, similar to nodejs\n    if (args && !Array.isArray(args)) {\n        options = args;\n        args = null;\n    }\n\n    args = args ? args.slice(0) : []; // Clone array to avoid changing the original\n    options = Object.assign({}, options); // Clone object to avoid changing the original\n\n    // Build our parsed object\n    const parsed = {\n        command,\n        args,\n        options,\n        file: undefined,\n        original: {\n            command,\n            args,\n        },\n    };\n\n    // Delegate further parsing to shell or non-shell\n    return options.shell ? parsed : parseNonShell(parsed);\n}\n\nmodule.exports = parse;\n","'use strict';\n\nconst isWin = process.platform === 'win32';\n\nfunction notFoundError(original, syscall) {\n    return Object.assign(new Error(`${syscall} ${original.command} ENOENT`), {\n        code: 'ENOENT',\n        errno: 'ENOENT',\n        syscall: `${syscall} ${original.command}`,\n        path: original.command,\n        spawnargs: original.args,\n    });\n}\n\nfunction hookChildProcess(cp, parsed) {\n    if (!isWin) {\n        return;\n    }\n\n    const originalEmit = cp.emit;\n\n    cp.emit = function (name, arg1) {\n        // If emitting \"exit\" event and exit code is 1, we need to check if\n        // the command exists and emit an \"error\" instead\n        // See https://github.com/IndigoUnited/node-cross-spawn/issues/16\n        if (name === 'exit') {\n            const err = verifyENOENT(arg1, parsed);\n\n            if (err) {\n                return originalEmit.call(cp, 'error', err);\n            }\n        }\n\n        return originalEmit.apply(cp, arguments); // eslint-disable-line prefer-rest-params\n    };\n}\n\nfunction verifyENOENT(status, parsed) {\n    if (isWin && status === 1 && !parsed.file) {\n        return notFoundError(parsed.original, 'spawn');\n    }\n\n    return null;\n}\n\nfunction verifyENOENTSync(status, parsed) {\n    if (isWin && status === 1 && !parsed.file) {\n        return notFoundError(parsed.original, 'spawnSync');\n    }\n\n    return null;\n}\n\nmodule.exports = {\n    hookChildProcess,\n    verifyENOENT,\n    verifyENOENTSync,\n    notFoundError,\n};\n","'use strict';\n\nconst cp = require('child_process');\nconst parse = require('./lib/parse');\nconst enoent = require('./lib/enoent');\n\nfunction spawn(command, args, options) {\n    // Parse the arguments\n    const parsed = parse(command, args, options);\n\n    // Spawn the child process\n    const spawned = cp.spawn(parsed.command, parsed.args, parsed.options);\n\n    // Hook into child process \"exit\" event to emit an error if the command\n    // does not exists, see: https://github.com/IndigoUnited/node-cross-spawn/issues/16\n    enoent.hookChildProcess(spawned, parsed);\n\n    return spawned;\n}\n\nfunction spawnSync(command, args, options) {\n    // Parse the arguments\n    const parsed = parse(command, args, options);\n\n    // Spawn the child process\n    const result = cp.spawnSync(parsed.command, parsed.args, parsed.options);\n\n    // Analyze if the command does not exist, see: https://github.com/IndigoUnited/node-cross-spawn/issues/16\n    result.error = result.error || enoent.verifyENOENTSync(result.status, parsed);\n\n    return result;\n}\n\nmodule.exports = spawn;\nmodule.exports.spawn = spawn;\nmodule.exports.sync = spawnSync;\n\nmodule.exports._parse = parse;\nmodule.exports._enoent = enoent;\n","import type { ChildProcess, IOType } from 'node:child_process';\nimport process from 'node:process';\nimport type { Stream } from 'node:stream';\nimport { PassThrough } from 'node:stream';\n\nimport type { JSONRPCMessage, Transport } from '@modelcontextprotocol/core-internal';\nimport { ReadBuffer, SdkError, SdkErrorCode, serializeMessage } from '@modelcontextprotocol/core-internal';\nimport spawn from 'cross-spawn';\n\nexport type StdioServerParameters = {\n    /**\n     * The executable to run to start the server.\n     */\n    command: string;\n\n    /**\n     * Command line arguments to pass to the executable.\n     */\n    args?: string[];\n\n    /**\n     * The environment to use when spawning the process.\n     *\n     * If not specified, the result of {@linkcode getDefaultEnvironment} will be used.\n     */\n    env?: Record<string, string>;\n\n    /**\n     * How to handle stderr of the child process. This matches the semantics of Node's `child_process.spawn`.\n     *\n     * The default is `\"inherit\"`, meaning messages to stderr will be printed to the parent process's stderr.\n     */\n    stderr?: IOType | Stream | number;\n\n    /**\n     * The working directory to use when spawning the process.\n     *\n     * If not specified, the current working directory will be inherited.\n     */\n    cwd?: string;\n\n    /**\n     * Maximum size of the read buffer in bytes. If a single message exceeds\n     * this size the transport will emit an error and close.\n     *\n     * Defaults to 10 MB.\n     */\n    maxBufferSize?: number;\n};\n\n/**\n * Environment variables to inherit by default, if an environment is not explicitly given.\n */\nexport const DEFAULT_INHERITED_ENV_VARS =\n    process.platform === 'win32'\n        ? [\n              'APPDATA',\n              'COMSPEC',\n              'HOMEDRIVE',\n              'HOMEPATH',\n              'LOCALAPPDATA',\n              'PATH',\n              'PATHEXT',\n              'PROCESSOR_ARCHITECTURE',\n              'PROGRAMDATA',\n              'PROGRAMFILES',\n              'PROGRAMFILES(X86)',\n              'PROGRAMW6432',\n              'SYSTEMDRIVE',\n              'SYSTEMROOT',\n              'TEMP',\n              'USERNAME',\n              'USERPROFILE',\n              'WINDIR'\n          ]\n        : /* list inspired by the default env inheritance of sudo */\n          ['HOME', 'LOGNAME', 'PATH', 'SHELL', 'TERM', 'USER'];\n\n/**\n * Returns a default environment object including only environment variables deemed safe to inherit.\n */\nexport function getDefaultEnvironment(): Record<string, string> {\n    const env: Record<string, string> = {};\n\n    for (const key of DEFAULT_INHERITED_ENV_VARS) {\n        const value = process.env[key];\n        if (value === undefined) {\n            continue;\n        }\n\n        if (value.startsWith('()')) {\n            // Skip functions, which are a security risk.\n            continue;\n        }\n\n        env[key] = value;\n    }\n\n    return env;\n}\n\n/**\n * Client transport for stdio: this will connect to a server by spawning a process and communicating with it over stdin/stdout.\n *\n * This transport is only available in Node.js environments.\n */\nexport class StdioClientTransport implements Transport {\n    private _process?: ChildProcess;\n    private _readBuffer: ReadBuffer;\n    private _serverParams: StdioServerParameters;\n    private _stderrStream: PassThrough | null = null;\n\n    onclose?: () => void;\n    onerror?: (error: Error) => void;\n    onmessage?: (message: JSONRPCMessage) => void;\n\n    constructor(server: StdioServerParameters) {\n        this._serverParams = server;\n        this._readBuffer = new ReadBuffer({ maxBufferSize: server.maxBufferSize });\n        if (server.stderr === 'pipe' || server.stderr === 'overlapped') {\n            this._stderrStream = new PassThrough();\n        }\n    }\n\n    /**\n     * Starts the server process and prepares to communicate with it.\n     */\n    async start(): Promise<void> {\n        if (this._process) {\n            throw new Error(\n                'StdioClientTransport already started! If using Client class, note that connect() calls start() automatically.'\n            );\n        }\n\n        return new Promise((resolve, reject) => {\n            this._process = spawn(this._serverParams.command, this._serverParams.args ?? [], {\n                // merge default env with server env because mcp server needs some env vars\n                env: {\n                    ...getDefaultEnvironment(),\n                    ...this._serverParams.env\n                },\n                stdio: ['pipe', 'pipe', this._serverParams.stderr ?? 'inherit'],\n                shell: false,\n                windowsHide: process.platform === 'win32',\n                cwd: this._serverParams.cwd\n            });\n\n            this._process.on('error', error => {\n                reject(error);\n                this.onerror?.(error);\n            });\n\n            this._process.on('spawn', () => {\n                resolve();\n            });\n\n            this._process.on('close', _code => {\n                this._process = undefined;\n                this.onclose?.();\n            });\n\n            this._process.stdin?.on('error', error => {\n                this.onerror?.(error);\n            });\n\n            this._process.stdout?.on('data', chunk => {\n                try {\n                    this._readBuffer.append(chunk);\n                    this.processReadBuffer();\n                } catch (error) {\n                    this.onerror?.(error as Error);\n                    this.close().catch(() => {});\n                }\n            });\n\n            this._process.stdout?.on('error', error => {\n                this.onerror?.(error);\n            });\n\n            if (this._stderrStream && this._process.stderr) {\n                this._process.stderr.pipe(this._stderrStream);\n            }\n        });\n    }\n\n    /**\n     * The `stderr` stream of the child process, if {@linkcode StdioServerParameters.stderr} was set to `\"pipe\"` or `\"overlapped\"`.\n     *\n     * If `stderr` piping was requested, a `PassThrough` stream is returned _immediately_, allowing callers to\n     * attach listeners before the `start` method is invoked. This prevents loss of any early\n     * error output emitted by the child process.\n     */\n    get stderr(): Stream | null {\n        if (this._stderrStream) {\n            return this._stderrStream;\n        }\n\n        return this._process?.stderr ?? null;\n    }\n\n    /**\n     * The child process pid spawned by this transport.\n     *\n     * This is only available after the transport has been started.\n     */\n    get pid(): number | null {\n        return this._process?.pid ?? null;\n    }\n\n    private processReadBuffer() {\n        while (true) {\n            try {\n                const message = this._readBuffer.readMessage();\n                if (message === null) {\n                    break;\n                }\n\n                this.onmessage?.(message);\n            } catch (error) {\n                this.onerror?.(error as Error);\n            }\n        }\n    }\n\n    /**\n     * Reap a disposable probe sibling (see the version-negotiation sibling\n     * flow): signal-first teardown awaiting process `exit` — never the `close`\n     * event, so a helper process holding the child's stdio pipes can never\n     * block disposal. Not part of the public transport lifecycle.\n     *\n     * @internal\n     */\n    private async _dispose(): Promise<void> {\n        const proc = this._process;\n        this._process = undefined;\n        if (proc && proc.exitCode === null && proc.signalCode === null) {\n            const exited = new Promise<void>(resolve => proc.once('exit', () => resolve()));\n            try {\n                proc.stdin?.end();\n            } catch {\n                // ignore\n            }\n            try {\n                proc.kill('SIGTERM');\n            } catch {\n                // ignore\n            }\n            await Promise.race([exited, new Promise(resolve => setTimeout(resolve, 1000).unref())]);\n            if (proc.exitCode === null && proc.signalCode === null) {\n                try {\n                    proc.kill('SIGKILL');\n                } catch {\n                    // ignore\n                }\n            }\n            await exited;\n        }\n        // The child is gone — release the PARENT-side pipe handles too. A helper\n        // process holding the inherited write ends would otherwise keep them (and\n        // with them the host's event loop: stdout carries a flowing 'data'\n        // listener from start()) alive until the helper exits.\n        try {\n            proc?.stdout?.destroy();\n        } catch {\n            // ignore\n        }\n        try {\n            proc?.stdin?.destroy();\n        } catch {\n            // ignore\n        }\n        try {\n            proc?.stderr?.destroy();\n        } catch {\n            // ignore\n        }\n        this._readBuffer.clear();\n    }\n\n    async close(): Promise<void> {\n        if (this._process) {\n            const processToClose = this._process;\n            this._process = undefined;\n\n            const closePromise = new Promise<void>(resolve => {\n                processToClose.once('close', () => {\n                    resolve();\n                });\n            });\n\n            try {\n                processToClose.stdin?.end();\n            } catch {\n                // ignore\n            }\n\n            await Promise.race([closePromise, new Promise(resolve => setTimeout(resolve, 2000).unref())]);\n\n            if (processToClose.exitCode === null) {\n                try {\n                    processToClose.kill('SIGTERM');\n                } catch {\n                    // ignore\n                }\n\n                await Promise.race([closePromise, new Promise(resolve => setTimeout(resolve, 2000).unref())]);\n            }\n\n            if (processToClose.exitCode === null) {\n                try {\n                    processToClose.kill('SIGKILL');\n                } catch {\n                    // ignore\n                }\n            }\n        }\n\n        this._readBuffer.clear();\n    }\n\n    send(message: JSONRPCMessage): Promise<void> {\n        return new Promise(resolve => {\n            if (!this._process?.stdin) {\n                throw new SdkError(SdkErrorCode.NotConnected, 'Not connected');\n            }\n\n            const json = serializeMessage(message);\n            if (this._process.stdin.write(json)) {\n                resolve();\n            } else {\n                this._process.stdin.once('drain', resolve);\n            }\n        });\n    }\n}\n","import { InMemoryTransport, StreamableHTTPClientTransport, SSEClientTransport } from \"@modelcontextprotocol/client\";\nimport type { OAuthClientProvider, Transport, VersionNegotiationOptions } from \"@modelcontextprotocol/client\";\nimport { OAuth, BearerAuth, type AsyncHeaderAuth } from './auth.js'\n\n// ---------------------------------------------------------------------------\n// TransportResolutionOptions — cross-cutting knobs threaded through\n// resolveTransport / resolveEntryTransport (not just per-entry auth).\n// ---------------------------------------------------------------------------\n\nexport interface TransportResolutionOptions {\n  /** See ClientOptions.legacySSE. Default false. */\n  legacySSE?: boolean\n  /** See ClientOptions.versionNegotiation. Used only to decide, for an\n   * in-process McpServerLike input, whether a pinned-modern connection should\n   * use the server's optional `_modernFetch` hook instead of the legacy-only\n   * InMemoryTransport pair. */\n  versionNegotiation?: VersionNegotiationOptions\n}\n\n// ---------------------------------------------------------------------------\n// Stdio transport — loaded lazily. The SDK's stdio module imports Node's\n// `child_process`, so a static import would pull Node built-ins into the\n// browser bundle. Importing it on demand keeps the client graph browser-safe.\n// ---------------------------------------------------------------------------\n\nasync function createStdioTransport(opts: {\n  command: string\n  args?: string[]\n  env?: Record<string, string>\n  cwd?: string\n}): Promise<Transport> {\n  const { StdioClientTransport } = await import(\n    '@modelcontextprotocol/client/stdio'\n  )\n  return new StdioClientTransport(opts)\n}\n\n// ---------------------------------------------------------------------------\n// McpServerLike — structural interface for in-process servers.\n// Intentionally loose: avoids importing from the server module.\n// ---------------------------------------------------------------------------\n\nexport interface McpServerLike {\n  connect(transport: Transport): Promise<void>\n  /**\n   * Optional modern-era (2026-07-28) in-process fetch entrypoint, for servers\n   * built on `createMcpHandler` (e.g. `FastMCP`'s own `_modernFetch`).\n   * `InMemoryTransport` — used by `connect()` above — is 2025-era only (the\n   * legacy `Server`/session model); there is no in-process equivalent of a\n   * real HTTP round trip for the modern era's stateless-per-request dispatch.\n   * When present, and the caller pins modern era via\n   * `versionNegotiation: { mode: { pin: '2026-07-28' } }`, the client builds a\n   * `StreamableHTTPClientTransport` whose `fetch` calls this function directly\n   * — no sockets, but otherwise the same code path a real HTTP connection\n   * takes. Not used for `'auto'` or `'legacy'` modes: this server-side hook is\n   * modern-only (mirrors `createMcpHandler(..., { legacy: 'reject' })`), so\n   * auto-negotiation (which must be able to fall back to legacy) still goes\n   * through `connect()` + `InMemoryTransport`, and stays legacy-only for\n   * in-process servers until a dual-era in-process bridge exists.\n   */\n  _modernFetch?(request: Request, options?: unknown): Promise<Response>\n}\n\nfunction isMcpServerLike(value: unknown): value is McpServerLike {\n  return (\n    typeof value === 'object' &&\n    value !== null &&\n    'connect' in value &&\n    typeof (value as Record<string, unknown>).connect === 'function'\n  )\n}\n\n// ---------------------------------------------------------------------------\n// MCP config object — { mcpServers: { name: { url | command, ... } } }\n// ---------------------------------------------------------------------------\n\nexport type McpServerEntry =\n  | { url: string; headers?: Record<string, string>; auth?: BearerAuth | OAuth | AsyncHeaderAuth | string }\n  | { command: string; args?: string[]; env?: Record<string, string>; auth?: BearerAuth | OAuth | AsyncHeaderAuth | string }\n\n/** Values accepted in mcpServers: either a config object or an in-process server. */\nexport type McpServerValue = McpServerEntry | McpServerLike\n\nexport type McpConfig = {\n  mcpServers: Record<string, McpServerValue>\n}\n\nfunction isMcpConfig(value: unknown): value is McpConfig {\n  return (\n    typeof value === 'object' &&\n    value !== null &&\n    'mcpServers' in value &&\n    typeof (value as McpConfig).mcpServers === 'object' &&\n    (value as McpConfig).mcpServers !== null\n  )\n}\n\n// ---------------------------------------------------------------------------\n// StdioTransport — configuration object for stdio subprocess connections.\n// Separate from the SDK's StdioClientTransport so callers work with a plain\n// config value rather than a live transport instance.\n// ---------------------------------------------------------------------------\n\nexport class StdioTransport {\n  readonly command: string\n  readonly args: string[]\n  readonly env?: Record<string, string>\n  readonly cwd?: string\n\n  constructor(\n    command: string,\n    args: string[] = [],\n    options?: { env?: Record<string, string>; cwd?: string },\n  ) {\n    this.command = command\n    this.args = args\n    this.env = options?.env\n    this.cwd = options?.cwd\n  }\n}\n\n// ---------------------------------------------------------------------------\n// ClientTransportInput — what the Client constructor accepts\n// ---------------------------------------------------------------------------\n\nexport type ClientTransportInput =\n  | string         // HTTP/HTTPS URL → auto-detect Streamable HTTP or SSE\n  | McpServerLike  // in-process server instance\n  | McpConfig      // { mcpServers: { ... } } config object\n  | StdioTransport // explicit stdio subprocess config\n  | Transport      // pass-through — any SDK Transport (advanced)\n\n// ---------------------------------------------------------------------------\n// Resolved transport — what Client.connect() receives\n// ---------------------------------------------------------------------------\n\nexport type ResolvedTransport = {\n  transport: Transport\n  /**\n   * Called before sdkClient.connect(transport). Used for in-process servers\n   * that must be connected to their side of the InMemoryTransport first.\n   */\n  beforeConnect?: () => Promise<void>\n}\n\n// ---------------------------------------------------------------------------\n// Auth header injection helpers\n// ---------------------------------------------------------------------------\n\nfunction normalizeHeaders(headers: RequestInit['headers']): Record<string, string> {\n  if (!headers) return {}\n  if (headers instanceof Headers) return Object.fromEntries(headers.entries())\n  if (Array.isArray(headers)) return Object.fromEntries(headers as string[][])\n  return { ...(headers as Record<string, string>) }\n}\n\nfunction isAsyncAuth(\n  auth: BearerAuth | OAuth | AsyncHeaderAuth,\n): auth is AsyncHeaderAuth {\n  // ClientCredentials / JwtBearerAuth / EnterpriseManagedAuth all carry a\n  // `kind` and acquire their token asynchronously — inject per request.\n  // OAuth is now an OAuthClientProvider and is passed directly to the transport.\n  return 'kind' in auth\n}\n\ntype HttpTransportOptions = {\n  requestInit?: RequestInit\n  fetch?: (url: string | URL, init?: RequestInit) => Promise<Response>\n  eventSourceInit?: Record<string, unknown>\n  authProvider?: OAuthClientProvider\n}\n\nfunction buildHttpOptions(\n  auth: BearerAuth | OAuth | AsyncHeaderAuth | undefined,\n  extraHeaders: Record<string, string> = {},\n): HttpTransportOptions {\n  const hasExtra = Object.keys(extraHeaders).length > 0\n\n  if (!auth && !hasExtra) return {}\n\n  // OAuth implements OAuthClientProvider — hand it to the SDK transport which\n  // handles the full auth flow (discovery, DCR, PKCE, token refresh, 401 retry).\n  if (auth instanceof OAuth) {\n    const opts: HttpTransportOptions = { authProvider: auth }\n    // Extra headers are injected via requestInit (not Authorization — that's\n    // managed by the authProvider).\n    if (hasExtra) opts.requestInit = { headers: extraHeaders }\n    return opts\n  }\n\n  if (auth && isAsyncAuth(auth)) {\n    // Async token auth: inject the acquired token per-request via a custom fetch wrapper.\n    const customFetch = async (\n      url: string | URL,\n      init?: RequestInit,\n    ): Promise<Response> => {\n      const authHeaders = await auth.getHeaders()\n      return fetch(url, {\n        ...init,\n        headers: {\n          ...authHeaders,\n          ...extraHeaders,\n          ...normalizeHeaders(init?.headers),\n        },\n      })\n    }\n    return { fetch: customFetch }\n  }\n\n  // Static auth (BearerAuth) or extra headers only.\n  const staticHeaders: Record<string, string> = {\n    ...(auth ? auth.getHeaders() : {}),\n    ...extraHeaders,\n  }\n  return {\n    requestInit: { headers: staticHeaders },\n    // Also exposed for SSE's EventSource connection (eventsource npm pkg\n    // accepts headers in EventSourceInit, unlike the browser API).\n    eventSourceInit: { headers: staticHeaders },\n  }\n}\n\n// ---------------------------------------------------------------------------\n// URL string validation — URL strings must be http(s). A bare script path (or\n// any other scheme) must never be silently accepted: stdio always requires an\n// explicit StdioTransport or a { command } config entry, so a string that is\n// not an http(s) URL is a caller error and fails here with a pointer to the\n// explicit form.\n// ---------------------------------------------------------------------------\n\nconst STDIO_HINT =\n  'To run a local server script over stdio, pass an explicit StdioTransport ' +\n  \"(e.g. new StdioTransport('node', ['server.js'])) or an mcpServers entry \" +\n  'with a \"command\" key.'\n\nfunction parseHttpUrl(input: string): URL {\n  if (!URL.canParse(input)) {\n    throw new Error(\n      `\"${input}\" is not a valid URL. URL strings must be http: or https:. ${STDIO_HINT}`,\n    )\n  }\n  const url = new URL(input)\n  if (url.protocol !== 'http:' && url.protocol !== 'https:') {\n    throw new Error(\n      `\"${input}\" has unsupported scheme \"${url.protocol}\". URL strings must be ` +\n        `http: or https:. ${STDIO_HINT}`,\n    )\n  }\n  return url\n}\n\n// ---------------------------------------------------------------------------\n// URL → SDK transport\n// ---------------------------------------------------------------------------\n\nlet sseDeprecationWarned = false\n\nfunction urlToTransport(\n  url: URL,\n  auth: BearerAuth | OAuth | AsyncHeaderAuth | undefined,\n  extraHeaders: Record<string, string> = {},\n  legacySSE = false,\n): Transport {\n  const { requestInit, fetch: customFetch, eventSourceInit, authProvider } =\n    buildHttpOptions(auth, extraHeaders)\n\n  const segments = url.pathname.split('/')\n  const isSSE = segments.includes('sse') || url.pathname.endsWith('/sse')\n\n  if (isSSE) {\n    if (!legacySSE) {\n      throw new Error(\n        `The URL \"${url}\" looks like an SSE endpoint, but SSE is deprecated by the MCP SDK ` +\n          `(SSEClientTransport is marked @deprecated — prefer Streamable HTTP). Pass ` +\n          `{ legacySSE: true } to ClientOptions to connect anyway.`,\n      )\n    }\n    if (!sseDeprecationWarned) {\n      sseDeprecationWarned = true\n      console.warn(\n        '[fastmcp-ts] Connecting over the deprecated SSE transport (legacySSE: true). ' +\n          'SSEClientTransport is marked @deprecated in the MCP SDK — migrate the server to ' +\n          'Streamable HTTP when possible.',\n      )\n    }\n    return new SSEClientTransport(url, {\n      ...(authProvider ? { authProvider } : {}),\n      ...(requestInit ? { requestInit } : {}),\n      ...(eventSourceInit ? { eventSourceInit } : {}),\n      ...(customFetch ? { fetch: customFetch } : {}),\n    })\n  }\n\n  return new StreamableHTTPClientTransport(url, {\n    ...(authProvider ? { authProvider } : {}),\n    ...(requestInit ? { requestInit } : {}),\n    ...(customFetch ? { fetch: customFetch } : {}),\n  })\n}\n\n// ---------------------------------------------------------------------------\n// In-process modern-era transport — see McpServerLike._modernFetch's docs.\n// ---------------------------------------------------------------------------\n\nconst IN_PROCESS_BASE_URL = 'http://in-process.local/mcp'\n\nfunction isPinnedModern(versionNegotiation: TransportResolutionOptions['versionNegotiation']): boolean {\n  const mode = versionNegotiation?.mode\n  return typeof mode === 'object' && mode !== null && 'pin' in mode\n}\n\nfunction modernFetchTransport(entry: McpServerLike): Transport {\n  const modernFetch = entry._modernFetch!.bind(entry)\n  // Adapt the (url, init) => Response shape StreamableHTTPClientTransport calls\n  // its `fetch` option with to the (Request) => Response shape McpHttpHandler\n  // (createMcpHandler's return value) exposes.\n  const fetchAdapter = (url: string | URL, init?: RequestInit): Promise<Response> =>\n    modernFetch(new Request(url, init))\n  return new StreamableHTTPClientTransport(new URL(IN_PROCESS_BASE_URL), {\n    fetch: fetchAdapter,\n  })\n}\n\n// ---------------------------------------------------------------------------\n// resolveEntryTransport — resolves a single McpServerEntry to a transport.\n// Used by MultiServerClient to connect to each server independently.\n// ---------------------------------------------------------------------------\n\nexport async function resolveEntryTransport(\n  entry: McpServerValue,\n  auth?: BearerAuth | OAuth | AsyncHeaderAuth,\n  options?: TransportResolutionOptions,\n): Promise<ResolvedTransport> {\n  if (typeof entry !== 'object' || entry === null) {\n    throw new Error(\n      `mcpServers entry ${JSON.stringify(entry)} must be an object with a \"url\" ` +\n        `or \"command\" key. ${STDIO_HINT}`,\n    )\n  }\n\n  // In-process server (McpServerLike: has connect(transport)).\n  if (isMcpServerLike(entry)) {\n    if (isPinnedModern(options?.versionNegotiation) && entry._modernFetch) {\n      return { transport: modernFetchTransport(entry) }\n    }\n    const [serverSide, clientSide] = InMemoryTransport.createLinkedPair()\n    return {\n      transport: clientSide,\n      beforeConnect: () => entry.connect(serverSide),\n    }\n  }\n\n  const entryAuth = resolveEntryAuth(entry.auth) ?? auth\n\n  if ('url' in entry) {\n    const url = parseHttpUrl(entry.url)\n    const extraHeaders = entry.headers ?? {}\n    return { transport: urlToTransport(url, entryAuth, extraHeaders, options?.legacySSE) }\n  }\n\n  const cmd = entry as { command: string; args?: string[]; env?: Record<string, string> }\n  return {\n    transport: await createStdioTransport({\n      command: cmd.command,\n      args: cmd.args,\n      env: cmd.env,\n    }),\n  }\n}\n\nfunction resolveEntryAuth(\n  auth: BearerAuth | OAuth | AsyncHeaderAuth | string | undefined,\n): BearerAuth | OAuth | AsyncHeaderAuth | undefined {\n  if (!auth) return undefined\n  if (typeof auth === 'string') return new BearerAuth(auth)\n  return auth\n}\n\n// ---------------------------------------------------------------------------\n// resolveTransport — internal; used by Client.connect()\n// ---------------------------------------------------------------------------\n\nexport async function resolveTransport(\n  input: ClientTransportInput,\n  auth?: BearerAuth | OAuth | AsyncHeaderAuth,\n  options?: TransportResolutionOptions,\n): Promise<ResolvedTransport> {\n  // 1. Our StdioTransport config class (check before the duck-type checks below).\n  if (input instanceof StdioTransport) {\n    return {\n      transport: await createStdioTransport({\n        command: input.command,\n        args: input.args,\n        env: input.env,\n        cwd: input.cwd,\n      }),\n    }\n  }\n\n  // 2. URL string → auto-detect HTTP transport.\n  if (typeof input === 'string') {\n    const url = parseHttpUrl(input)\n    return { transport: urlToTransport(url, auth, {}, options?.legacySSE) }\n  }\n\n  // 3. Pass-through SDK Transport (has the Transport interface: start/close/send).\n  if (\n    typeof input === 'object' &&\n    input !== null &&\n    'start' in input &&\n    typeof (input as unknown as Record<string, unknown>).start === 'function'\n  ) {\n    return { transport: input as Transport }\n  }\n\n  // 4. MCP config object { mcpServers: { ... } } — use the first entry.\n  if (isMcpConfig(input)) {\n    const entries = Object.entries(input.mcpServers)\n    if (entries.length === 0) throw new Error('mcpServers config is empty')\n    const [, entry] = entries[0]!\n    return await resolveEntryTransport(entry, auth, options)\n  }\n\n  // 5. In-process server (McpServerLike: has connect(transport)).\n  if (isMcpServerLike(input)) {\n    if (isPinnedModern(options?.versionNegotiation) && input._modernFetch) {\n      return { transport: modernFetchTransport(input) }\n    }\n    const [serverSide, clientSide] = InMemoryTransport.createLinkedPair()\n    return {\n      transport: clientSide,\n      beforeConnect: () => input.connect(serverSide),\n    }\n  }\n\n  throw new Error(\n    'Unrecognized transport input: expected a URL string, FastMCP server instance, ' +\n    'mcpServers config object, StdioTransport, or SDK Transport',\n  )\n}\n","import type { LoggingLevel, RequestOptions as SdkRequestOptions } from \"@modelcontextprotocol/server\";\nimport { Client as SdkClient, LOG_LEVEL_META_KEY } from '@modelcontextprotocol/client'\nimport type {\n  ClientCapabilities,\n  Implementation,\n  McpSubscription,\n  ProtocolEra,\n  VersionNegotiationOptions,\n} from '@modelcontextprotocol/client'\nimport type { BearerAuth, OAuth, ClientCredentials } from './auth.js'\nimport { buildClientCapabilities } from './capabilities.js'\nimport type { ClientHandlers, LogHandler, ProgressHandler, ResourceUpdateHandler } from './handlers.js'\nimport { defaultLogHandler, defaultProgressHandler } from './handlers.js'\nimport type { CallToolOptions, IClient, RequestOptions } from './interfaces.js'\nimport type {\n  CallToolResult,\n  CompletionResult,\n  GetPromptResult,\n  Prompt,\n  Resource,\n  TextResourceContents,\n  BlobResourceContents,\n  ResourceTemplate,\n  Tool,\n} from './results.js'\nimport { normalizeCallToolResult } from './results.js'\nimport type { McpConfig, McpServerValue } from './transports.js'\nimport { resolveEntryTransport } from './transports.js'\nimport { DEFAULT_CLIENT_INFO, type ClientDefaultOptions } from './options.js'\nimport { ToolCallError } from './client.js'\n// ---------------------------------------------------------------------------\n// Options\n// ---------------------------------------------------------------------------\n\nexport interface MultiServerOptions {\n  /**\n   * Identity to advertise to every MCP server. Defaults to `fastmcp-ts` at the\n   * installed package version. Set this when FastMCP is embedded in another\n   * application.\n   */\n  clientInfo?: Implementation\n  handlers?: ClientHandlers\n  /**\n   * Additional capabilities to advertise to every server. FastMCP combines\n   * them with capabilities inferred from handlers and roots.\n   */\n  capabilities?: ClientCapabilities\n  /** file:// URIs to advertise to all servers as accessible roots. */\n  roots?: string[]\n  defaultOptions?: ClientDefaultOptions\n  /**\n   * Protocol version negotiation, applied identically to every server in the\n   * config (protocol revision 2026-07-28 and later). See\n   * `ClientOptions.versionNegotiation` on the single-server `Client` — same\n   * semantics, just applied per sub-client here since each connected server\n   * negotiates its own era independently. Default `{ mode: 'auto' }`: each\n   * sub-client probes its server once and falls back to legacy when the\n   * server offers no modern era; `{ mode: 'legacy' }` opts every connection\n   * out of the probe.\n   */\n  versionNegotiation?: VersionNegotiationOptions\n}\n\n// ---------------------------------------------------------------------------\n// MultiServerClient\n// ---------------------------------------------------------------------------\n\nexport class MultiServerClient implements IClient {\n  private _clients: Map<string, SdkClient> = new Map()\n  private _connectPromise: Promise<void> | null = null\n  private _connected = false\n\n  /** URI (or namespaced template URI) → server name, populated by list calls */\n  private _uriMap: Map<string, string> = new Map()\n\n  private readonly _config: McpConfig\n  private readonly _clientInfo: Implementation\n  private readonly _handlers: {\n    log: LogHandler\n    progress: ProgressHandler\n    sampling?: ClientHandlers['sampling']\n    elicitation?: ClientHandlers['elicitation']\n  }\n  private readonly _roots: string[] | undefined\n  private readonly _capabilities: ClientCapabilities\n  private readonly _defaultOptions: ClientDefaultOptions\n  private readonly _versionNegotiation: VersionNegotiationOptions\n  private _resourceSubscriptions: Map<string, ResourceUpdateHandler> = new Map()\n  /** Modern-era (2026-07-28) subscriptions/listen streams, one per server that\n   * currently has active resource subscriptions — see Client's own field of the\n   * same purpose for the full rationale. Keyed by server name since each\n   * connected server negotiates its own era independently. */\n  private _resourceListenSubscriptions: Map<string, McpSubscription> = new Map()\n  /** Per-server log level set by setLogLevel() for servers negotiated to modern\n   * era — see Client's own field of the same purpose for the full rationale.\n   * Keyed by server name since each connected server negotiates its own era\n   * independently and may therefore need (or not need) meta-threading. */\n  private _logLevels: Map<string, LoggingLevel> = new Map()\n\n  constructor(config: McpConfig, options?: MultiServerOptions) {\n    this._config = config\n    this._clientInfo = options?.clientInfo ?? DEFAULT_CLIENT_INFO\n    this._handlers = {\n      log: options?.handlers?.log ?? defaultLogHandler,\n      progress: options?.handlers?.progress ?? defaultProgressHandler,\n      sampling: options?.handlers?.sampling,\n      elicitation: options?.handlers?.elicitation,\n    }\n    this._versionNegotiation = options?.versionNegotiation ?? { mode: 'auto' }\n    this._roots = options?.roots\n    this._capabilities = buildClientCapabilities(options?.capabilities, {\n      sampling: this._handlers.sampling !== undefined,\n      elicitation: this._handlers.elicitation !== undefined,\n      rootsListChanged: this._roots === undefined ? undefined : false,\n    })\n    this._defaultOptions = options?.defaultOptions ?? {}\n  }\n\n  // -------------------------------------------------------------------------\n  // Lifecycle\n  // -------------------------------------------------------------------------\n\n  async connect(): Promise<void> {\n    if (this._connected) return\n    if (this._connectPromise) {\n      await this._connectPromise\n      return\n    }\n\n    this._connectPromise = this._doConnect().finally(() => {\n      this._connectPromise = null\n    })\n\n    await this._connectPromise\n  }\n\n  private async _doConnect(): Promise<void> {\n    const entries = Object.entries(this._config.mcpServers)\n    if (entries.length === 0) throw new Error('mcpServers config is empty')\n\n    const connected: Array<[string, SdkClient]> = []\n\n    try {\n      await Promise.all(\n        entries.map(async ([name, entry]) => {\n          const sdk = this._buildSdkClient()\n          this._registerHandlers(sdk)\n          const { transport, beforeConnect } = await resolveEntryTransport(\n            entry as McpServerValue,\n            undefined,\n            { versionNegotiation: this._versionNegotiation },\n          )\n          if (beforeConnect) await beforeConnect()\n          await sdk.connect(transport)\n          connected.push([name, sdk])\n        }),\n      )\n    } catch (err) {\n      // Roll back any connections that succeeded before the failure.\n      await Promise.allSettled(connected.map(([, sdk]) => sdk.close()))\n      throw err\n    }\n\n    for (const [name, sdk] of connected) {\n      this._clients.set(name, sdk)\n    }\n\n    this._connected = true\n  }\n\n  async close(): Promise<void> {\n    if (!this._connected) return\n    this._connected = false\n    this._uriMap.clear()\n    // Close explicitly (and first) so each closure reason is 'local', not 'remote' —\n    // see Client.close()'s equivalent ordering for the full rationale.\n    await Promise.allSettled(\n      [...this._resourceListenSubscriptions.values()].map((sub) => sub.close()),\n    )\n    this._resourceListenSubscriptions.clear()\n    await Promise.allSettled([...this._clients.values()].map((sdk) => sdk.close()))\n    this._clients.clear()\n  }\n\n  async [Symbol.asyncDispose](): Promise<void> {\n    await this.close()\n  }\n\n  isConnected(): boolean {\n    return this._connected\n  }\n\n  static async connect(\n    config: McpConfig,\n    options?: MultiServerOptions,\n  ): Promise<MultiServerClient> {\n    const client = new MultiServerClient(config, options)\n    await client.connect()\n    return client\n  }\n\n  // -------------------------------------------------------------------------\n  // Core protocol\n  // -------------------------------------------------------------------------\n\n  /**\n   * The protocol era negotiated with a specific named server: `'modern'` for\n   * 2026-07-28, `'legacy'` for 2025-11-25 and earlier, `undefined` if the\n   * server name is unknown or not yet connected. See\n   * `MultiServerOptions.versionNegotiation` — the same mode is requested of\n   * every server, but each negotiates (and may land on) its own era\n   * independently, so this is necessarily per-server rather than a single\n   * client-wide value.\n   */\n  getProtocolEra(serverName: string): ProtocolEra | undefined {\n    return this._clients.get(serverName)?.getProtocolEra()\n  }\n\n  /** See Client.ping's docs — the same era-routing applies here, per server,\n   * since each connected server negotiates its own era independently. */\n  async ping(options?: RequestOptions): Promise<boolean> {\n    this._assertConnected()\n    await Promise.all(\n      [...this._clients.values()].map((sdk) =>\n        sdk.getProtocolEra() === 'modern'\n          ? sdk.discover(this._toSdkOptions(options))\n          : sdk.ping(this._toSdkOptions(options)),\n      ),\n    )\n    return true\n  }\n\n  // -------------------------------------------------------------------------\n  // Tools\n  // -------------------------------------------------------------------------\n\n  async listTools(options?: RequestOptions): Promise<Tool[]> {\n    this._assertConnected()\n    const results = await Promise.all(\n      [...this._clients.entries()].map(async ([name, sdk]) => {\n        const r = await sdk.listTools(\n          this._metaParamsFor(name),\n          this._toSdkOptions(options, undefined, this._defaultOptions.tool?.timeout),\n        )\n        return (r.tools as Tool[]).map((t) => ({ ...t, name: `${name}_${t.name}` }))\n      }),\n    )\n    return results.flat()\n  }\n\n  async callTool<TData = unknown>(\n    name: string,\n    args?: Record<string, unknown>,\n    options?: CallToolOptions,\n  ): Promise<CallToolResult<TData>> {\n    const raw = await this.callToolRaw<TData>(name, args, options)\n    if (raw.isError) {\n      const message =\n        (raw.content as Array<{ type: string; text?: string }>)\n          .filter((c) => c.type === 'text')\n          .map((c) => c.text ?? '')\n          .join('\\n') || 'Tool returned an error'\n      throw new ToolCallError(message, raw.content)\n    }\n    return raw\n  }\n\n  async callToolRaw<TData = unknown>(\n    name: string,\n    args?: Record<string, unknown>,\n    options?: CallToolOptions,\n  ): Promise<CallToolResult<TData>> {\n    const { serverName, localName } = this._parseNamespacedName(name)\n    const sdk = this._sdkForServer(serverName)\n    const sdkOptions = this._toSdkOptions(\n      options,\n      options?.onProgress,\n      this._defaultOptions.tool?.timeout,\n    )\n    const result = await sdk.callTool(\n      { name: localName, arguments: args ?? {}, ...this._metaParamsFor(serverName) },\n      sdkOptions,\n    )\n    return normalizeCallToolResult<TData>(result)\n  }\n\n  // -------------------------------------------------------------------------\n  // Resources\n  // -------------------------------------------------------------------------\n\n  async listResources(options?: RequestOptions): Promise<Resource[]> {\n    this._assertConnected()\n    const results = await Promise.all(\n      [...this._clients.entries()].map(async ([name, sdk]) => {\n        const r = await sdk.listResources(\n          this._metaParamsFor(name),\n          this._toSdkOptions(options, undefined, this._defaultOptions.resource?.timeout),\n        )\n        const resources = r.resources as Resource[]\n        for (const res of resources) {\n          this._uriMap.set(res.uri, name)\n        }\n        return resources.map((res) => ({\n          ...res,\n          name: res.name ? `${name}_${res.name}` : res.name,\n        }))\n      }),\n    )\n    return results.flat()\n  }\n\n  async listResourceTemplates(options?: RequestOptions): Promise<ResourceTemplate[]> {\n    this._assertConnected()\n    const results = await Promise.all(\n      [...this._clients.entries()].map(async ([name, sdk]) => {\n        const r = await sdk.listResourceTemplates(\n          this._metaParamsFor(name),\n          this._toSdkOptions(options, undefined, this._defaultOptions.resource?.timeout),\n        )\n        const templates = r.resourceTemplates as ResourceTemplate[]\n        for (const tmpl of templates) {\n          this._uriMap.set(tmpl.uriTemplate, name)\n        }\n        return templates.map((tmpl) => ({\n          ...tmpl,\n          name: tmpl.name ? `${name}_${tmpl.name}` : tmpl.name,\n        }))\n      }),\n    )\n    return results.flat()\n  }\n\n  async readResource(\n    uri: string,\n    options?: RequestOptions,\n  ): Promise<Array<TextResourceContents | BlobResourceContents>> {\n    this._assertConnected()\n    const sdkOptions = this._toSdkOptions(\n      options,\n      undefined,\n      this._defaultOptions.resource?.timeout,\n    )\n\n    // Fast path: URI was seen during a previous list call.\n    const knownServer = this._uriMap.get(uri)\n    if (knownServer) {\n      const sdk = this._clients.get(knownServer)!\n      const result = await sdk.readResource({ uri, ...this._metaParamsFor(knownServer) }, sdkOptions)\n      return result.contents\n    }\n\n    // Fallback: try each server in order, return the first success.\n    const errors: unknown[] = []\n    for (const [name, sdk] of this._clients) {\n      try {\n        const result = await sdk.readResource({ uri, ...this._metaParamsFor(name) }, sdkOptions)\n        return result.contents\n      } catch (err) {\n        errors.push(err)\n      }\n    }\n    throw new Error(\n      `Resource not found on any server: ${uri}\\n` +\n        errors.map((e) => String(e)).join('\\n'),\n    )\n  }\n\n  // -------------------------------------------------------------------------\n  // Prompts\n  // -------------------------------------------------------------------------\n\n  async listPrompts(options?: RequestOptions): Promise<Prompt[]> {\n    this._assertConnected()\n    const results = await Promise.all(\n      [...this._clients.entries()].map(async ([name, sdk]) => {\n        const r = await sdk.listPrompts(\n          this._metaParamsFor(name),\n          this._toSdkOptions(options, undefined, this._defaultOptions.prompt?.timeout),\n        )\n        return (r.prompts as Prompt[]).map((p) => ({ ...p, name: `${name}_${p.name}` }))\n      }),\n    )\n    return results.flat()\n  }\n\n  async getPrompt(\n    name: string,\n    args?: Record<string, string>,\n    options?: RequestOptions,\n  ): Promise<GetPromptResult> {\n    const { serverName, localName } = this._parseNamespacedName(name)\n    const sdk = this._sdkForServer(serverName)\n    const result = await sdk.getPrompt(\n      { name: localName, arguments: args, ...this._metaParamsFor(serverName) },\n      this._toSdkOptions(options, undefined, this._defaultOptions.prompt?.timeout),\n    )\n    return result as GetPromptResult\n  }\n\n  // -------------------------------------------------------------------------\n  // Resource subscriptions\n  // -------------------------------------------------------------------------\n\n  /** See Client.subscribeResource's docs — the same era-routing applies here,\n   * per server, since each connected server negotiates its own era. */\n  async subscribeResource(\n    uri: string,\n    handler: ResourceUpdateHandler,\n    options?: RequestOptions,\n  ): Promise<void> {\n    this._assertConnected()\n    this._resourceSubscriptions.set(uri, handler)\n    const serverName = this._uriMap.get(uri)\n    if (serverName) {\n      const sdk = this._clients.get(serverName)!\n      if (sdk.getProtocolEra() === 'modern') {\n        await this._refreshResourceListenSubscriptionForServer(serverName)\n      } else {\n        await sdk.subscribeResource(\n          { uri },\n          this._toSdkOptions(options, undefined, this._defaultOptions.resource?.timeout),\n        )\n      }\n      return\n    }\n    // Fallback: the URI's owning server isn't known yet (listResources() was never\n    // called). Only legacy-era servers can be probed this way — the validating\n    // resources/subscribe RPC either succeeds (that server owns the URI) or throws;\n    // listen() has no equivalent per-URI validation, so a modern-era server can't be\n    // ruled in or out by trying it, and is skipped in this fallback.\n    const errors: unknown[] = []\n    for (const [name, sdk] of this._clients) {\n      if (sdk.getProtocolEra() === 'modern') continue\n      try {\n        await sdk.subscribeResource(\n          { uri },\n          this._toSdkOptions(options, undefined, this._defaultOptions.resource?.timeout),\n        )\n        this._uriMap.set(uri, name)\n        return\n      } catch (err) {\n        errors.push(err)\n      }\n    }\n    throw new Error(`Subscribe failed on all servers:\\n${errors.map(String).join('\\n')}`)\n  }\n\n  async unsubscribeResource(uri: string, options?: RequestOptions): Promise<void> {\n    this._assertConnected()\n    this._resourceSubscriptions.delete(uri)\n    const serverName = this._uriMap.get(uri)\n    if (serverName) {\n      const sdk = this._clients.get(serverName)!\n      if (sdk.getProtocolEra() === 'modern') {\n        await this._refreshResourceListenSubscriptionForServer(serverName)\n      } else {\n        await sdk.unsubscribeResource(\n          { uri },\n          this._toSdkOptions(options, undefined, this._defaultOptions.resource?.timeout),\n        )\n      }\n      return\n    }\n    await Promise.allSettled(\n      [...this._clients.values()]\n        .filter((sdk) => sdk.getProtocolEra() !== 'modern')\n        .map((sdk) =>\n          sdk.unsubscribeResource(\n            { uri },\n            this._toSdkOptions(options, undefined, this._defaultOptions.resource?.timeout),\n          ),\n        ),\n    )\n  }\n\n  /** Re-opens server-scoped listen stream for its currently-subscribed URIs — see\n   * Client's own private method of the same purpose for the full rationale. */\n  private async _refreshResourceListenSubscriptionForServer(serverName: string): Promise<void> {\n    const existing = this._resourceListenSubscriptions.get(serverName)\n    if (existing) {\n      await existing.close()\n      this._resourceListenSubscriptions.delete(serverName)\n    }\n    const uris = [...this._resourceSubscriptions.keys()].filter(\n      (uri) => this._uriMap.get(uri) === serverName,\n    )\n    if (uris.length === 0) return\n\n    const sdk = this._clients.get(serverName)!\n    const subscription = await sdk.listen({ resourceSubscriptions: uris })\n    this._resourceListenSubscriptions.set(serverName, subscription)\n\n    void subscription.closed.then((reason) => {\n      if (reason === 'remote' && this._resourceListenSubscriptions.get(serverName) === subscription) {\n        this._resourceListenSubscriptions.delete(serverName)\n        void this._refreshResourceListenSubscriptionForServer(serverName).catch(() => {})\n      }\n    })\n  }\n\n  // -------------------------------------------------------------------------\n  // Completion\n  // -------------------------------------------------------------------------\n\n  async complete(\n    ref: { type: 'ref/prompt'; name: string } | { type: 'ref/resource'; uri: string },\n    argument: { name: string; value: string },\n    context?: { arguments?: Record<string, string> },\n    options?: RequestOptions,\n  ): Promise<CompletionResult> {\n    this._assertConnected()\n    const sdkOptions = this._toSdkOptions(options)\n\n    if (ref.type === 'ref/prompt') {\n      const { serverName, localName } = this._parseNamespacedName(ref.name)\n      const sdk = this._sdkForServer(serverName)\n      const result = await sdk.complete(\n        {\n          ref: { type: 'ref/prompt', name: localName },\n          argument,\n          ...(context ? { context } : {}),\n          ...this._metaParamsFor(serverName),\n        },\n        sdkOptions,\n      )\n      return result.completion as CompletionResult\n    }\n\n    const serverName = this._uriMap.get(ref.uri)\n    if (serverName) {\n      const result = await this._clients.get(serverName)!.complete(\n        { ref, argument, ...(context ? { context } : {}), ...this._metaParamsFor(serverName) },\n        sdkOptions,\n      )\n      return result.completion as CompletionResult\n    }\n\n    const errors: unknown[] = []\n    for (const [name, sdk] of this._clients) {\n      try {\n        const result = await sdk.complete(\n          { ref, argument, ...(context ? { context } : {}), ...this._metaParamsFor(name) },\n          sdkOptions,\n        )\n        return result.completion as CompletionResult\n      } catch (err) {\n        errors.push(err)\n      }\n    }\n    throw new Error(`Completion failed on all servers:\\n${errors.map(String).join('\\n')}`)\n  }\n\n  // -------------------------------------------------------------------------\n  // Logging\n  // -------------------------------------------------------------------------\n\n  /** See Client.setLogLevel's docs — the same era-routing applies here, per\n   * server: legacy sends the real `logging/setLevel` RPC; modern records the\n   * level and threads it into `_meta` on that server's subsequent requests via\n   * `_metaParamsFor`, since `logging/setLevel` is absent from the modern wire\n   * registry (SEP-2577). */\n  async setLogLevel(level: LoggingLevel, options?: RequestOptions): Promise<void> {\n    this._assertConnected()\n    await Promise.all(\n      [...this._clients.entries()].map(([name, sdk]) => {\n        if (sdk.getProtocolEra() === 'modern') {\n          this._logLevels.set(name, level)\n          return undefined\n        }\n        return sdk.setLoggingLevel(level, this._toSdkOptions(options))\n      }),\n    )\n  }\n\n  // -------------------------------------------------------------------------\n  // Private helpers\n  // -------------------------------------------------------------------------\n\n  private _assertConnected(): void {\n    if (!this._connected) {\n      throw new Error('MultiServerClient is not connected. Call connect() first.')\n    }\n  }\n\n  private _parseNamespacedName(name: string): { serverName: string; localName: string } {\n    // Sort longest-first so that server names like \"my_server\" are matched\n    // before the shorter prefix \"my\".\n    const serverNames = [...this._clients.keys()].sort((a, b) => b.length - a.length)\n    for (const serverName of serverNames) {\n      const prefix = `${serverName}_`\n      if (name.startsWith(prefix)) {\n        return { serverName, localName: name.slice(prefix.length) }\n      }\n    }\n    throw new Error(\n      `Tool/prompt name \"${name}\" has no server namespace prefix. ` +\n        `Expected format: \"<serverName>_<name>\".`,\n    )\n  }\n\n  private _sdkForServer(serverName: string): SdkClient {\n    const sdk = this._clients.get(serverName)\n    if (!sdk) {\n      throw new Error(\n        `No server named \"${serverName}\" in this MultiServerClient. ` +\n          `Known servers: ${[...this._clients.keys()].join(', ')}.`,\n      )\n    }\n    return sdk\n  }\n\n  private _buildSdkClient(): SdkClient {\n    return new SdkClient(\n      this._clientInfo,\n      {\n        capabilities: this._capabilities,\n        versionNegotiation: this._versionNegotiation,\n      },\n    )\n  }\n\n  private _registerHandlers(sdk: SdkClient): void {\n    sdk.setNotificationHandler('notifications/message', (notification) => {\n      void this._handlers.log({\n        level: notification.params.level,\n        logger: notification.params.logger ?? undefined,\n        data: notification.params.data,\n      })\n    })\n\n    sdk.setNotificationHandler('notifications/resources/updated', (notification) => {\n      const handler = this._resourceSubscriptions.get(notification.params.uri)\n      if (handler) void handler(notification.params.uri)\n    })\n\n    if (this._handlers.sampling) {\n      const h = this._handlers.sampling\n      sdk.setRequestHandler('sampling/createMessage', async (req) => h(req.params))\n    }\n\n    if (this._handlers.elicitation) {\n      const h = this._handlers.elicitation\n      sdk.setRequestHandler('elicitation/create', async (req) => h(req.params))\n    }\n\n    if (this._roots) {\n      const roots = this._roots\n      sdk.setRequestHandler('roots/list', async () => ({\n        roots: roots.map((uri) => ({ uri })),\n      }))\n    }\n  }\n\n  /** See Client._metaParams's docs — the same purpose, per server name, since\n   * each connected server may be on a different era and have a different\n   * recorded log level (or none). */\n  private _metaParamsFor(serverName: string): { _meta: Record<string, unknown> } | undefined {\n    const level = this._logLevels.get(serverName)\n    if (level === undefined) return undefined\n    return { _meta: { [LOG_LEVEL_META_KEY]: level } }\n  }\n\n  private _toSdkOptions(\n    options?: RequestOptions,\n    overrideProgress?: ProgressHandler,\n    scopedTimeoutSeconds?: number,\n  ): SdkRequestOptions {\n    const timeoutSeconds =\n      options?.timeout ?? scopedTimeoutSeconds ?? this._defaultOptions.timeout\n    const progressHandler = overrideProgress ?? this._handlers.progress\n\n    const sdkOptions: SdkRequestOptions = {}\n    if (timeoutSeconds != null) sdkOptions.timeout = timeoutSeconds * 1000\n    if (options?.signal) sdkOptions.signal = options.signal\n    if (progressHandler) {\n      sdkOptions.onprogress = ({ progress, total, message }) => {\n        void progressHandler(progress, total, message)\n      }\n    }\n    return sdkOptions\n  }\n}\n","import { UnauthorizedError, Client as SdkClient, LOG_LEVEL_META_KEY } from \"@modelcontextprotocol/client\";\nimport type {\n  ClientCapabilities,\n  RequestOptions as SdkRequestOptions,\n  McpSubscription,\n  VersionNegotiationOptions,\n  ProtocolEra,\n  PriorDiscovery,\n  InputRequiredOptions,\n  ResponseCacheStore,\n  Transport,\n  Implementation,\n  ServerCapabilities,\n} from \"@modelcontextprotocol/client\";\nimport { BearerAuth, OAuth } from './auth.js'\nimport { buildClientCapabilities } from './capabilities.js'\nimport type { AsyncHeaderAuth } from './auth.js'\nimport type { ClientHandlers, ListChangedHandler, ProgressHandler, ResourceUpdateHandler } from './handlers.js'\nimport { defaultLogHandler, defaultProgressHandler } from './handlers.js'\nimport type { CallToolOptions, IClient, RequestOptions } from './interfaces.js'\nimport { DEFAULT_CLIENT_INFO } from './options.js'\nimport type { ClientDefaultOptions, ClientOptions, RootInput, RootsValue } from './options.js'\nimport type {\n  CallToolResult,\n  CompletionResult,\n  ContentBlock,\n  GetPromptResult,\n  LoggingLevel,\n  Prompt,\n  Resource,\n  TextResourceContents,\n  BlobResourceContents,\n  ResourceTemplate,\n  Root,\n  SkillContents,\n  Tool,\n} from './results.js'\nimport { normalizeCallToolResult } from './results.js'\nimport { SKILLS_EXTENSION_ID, SkillsClient } from '@modelcontextprotocol/client/ext/skills'\nimport type { Skill } from '@modelcontextprotocol/client/ext/skills'\nimport type { ClientTransportInput, McpConfig } from './transports.js'\nimport { resolveTransport } from './transports.js'\nimport type { MultiServerOptions } from './multi-server.js'\nimport { MultiServerClient } from './multi-server.js'\n\n// ---------------------------------------------------------------------------\n// Error type\n// ---------------------------------------------------------------------------\n\nexport class ToolCallError extends Error {\n  readonly content: ContentBlock[]\n\n  constructor(message: string, content: ContentBlock[]) {\n    super(message)\n    this.name = 'ToolCallError'\n    this.content = content\n  }\n}\n\n// ---------------------------------------------------------------------------\n// Client\n// ---------------------------------------------------------------------------\n\ntype OptionalHandlerKeys =\n  | 'sampling'\n  | 'elicitation'\n  | 'onToolsListChanged'\n  | 'onResourcesListChanged'\n  | 'onPromptsListChanged'\n\nexport class Client implements IClient {\n  private _sdkClient: SdkClient | null = null\n  private _refCount = 0\n  private _connectPromise: Promise<void> | null = null\n  private readonly _resourceSubscriptions = new Map<string, ResourceUpdateHandler>()\n  /** The modern-era (2026-07-28) `subscriptions/listen` stream backing all active\n   * resource subscriptions — resources/subscribe and resources/unsubscribe are\n   * 2025-only RPCs, physically absent from the modern method registry. Unused\n   * (stays undefined) on a legacy connection. */\n  private _resourceListenSubscription: McpSubscription | undefined\n  /** The live SDK transport captured at connect(). Its `finishAuth()` redeems the\n   * authorization code both during connect-time recovery and a post-connect\n   * step-up re-authorization. */\n  private _transport: Transport | undefined\n  /** Single-flight guard for a post-connect re-authorization round: concurrent\n   * interactive-OAuth 401s share one `waitForCallback`→`finishAuth` round rather\n   * than each opening its own. Cleared when the round settles. */\n  private _reauthPromise: Promise<void> | null = null\n  /** Max post-connect re-authorization rounds per request (see `_reauthRetry`):\n   * 1 for ordinary step-up, 2 to also cover SEP-2352 authorization-server\n   * migration (the AS changes mid-request). Bounded so a genuinely unauthorized\n   * request cannot loop forever. */\n  private static readonly _MAX_REAUTH_ROUNDS = 2\n\n  private readonly _input: ClientTransportInput\n  private readonly _auth: BearerAuth | OAuth | AsyncHeaderAuth | undefined\n  private readonly _clientInfo: Implementation\n  private readonly _handlers: Required<Omit<ClientHandlers, OptionalHandlerKeys>> &\n    Pick<ClientHandlers, OptionalHandlerKeys>\n  private readonly _roots: (() => Promise<Root[]>) | undefined\n  private readonly _capabilities: ClientCapabilities\n  private readonly _autoInitialize: boolean\n  private readonly _versionNegotiation: VersionNegotiationOptions\n  private readonly _prior: PriorDiscovery | undefined\n  private readonly _inputRequired: InputRequiredOptions | undefined\n  private readonly _responseCacheStore: ResponseCacheStore | undefined\n  private readonly _cachePartition: string | undefined\n  private readonly _defaultCacheTtlMs: number | undefined\n  private readonly _legacySSE: boolean\n  /** Set by setLogLevel() on a modern-era connection (where logging/setLevel is\n   * not a wire method) — threaded into `_meta[LOG_LEVEL_META_KEY]` on every\n   * subsequent request. Unused on legacy era, where setLogLevel() still sends\n   * the real `logging/setLevel` RPC. */\n  private _logLevel: LoggingLevel | undefined\n  private readonly _defaultOptions: ClientDefaultOptions\n\n  constructor(input: ClientTransportInput, options?: ClientOptions) {\n    this._input = input\n    this._auth = resolveAuth(options?.auth)\n    this._clientInfo = options?.clientInfo ?? DEFAULT_CLIENT_INFO\n    this._handlers = {\n      log: options?.handlers?.log ?? defaultLogHandler,\n      progress: options?.handlers?.progress ?? defaultProgressHandler,\n      sampling: options?.handlers?.sampling,\n      elicitation: options?.handlers?.elicitation,\n      onToolsListChanged: options?.handlers?.onToolsListChanged,\n      onResourcesListChanged: options?.handlers?.onResourcesListChanged,\n      onPromptsListChanged: options?.handlers?.onPromptsListChanged,\n    }\n    this._roots = options?.roots ? normalizeRootsOption(options.roots) : undefined\n    this._capabilities = buildClientCapabilities(options?.capabilities, {\n      sampling: this._handlers.sampling !== undefined,\n      elicitation: this._handlers.elicitation !== undefined,\n      rootsListChanged: this._roots === undefined ? undefined : true,\n    })\n    this._autoInitialize = options?.autoInitialize ?? true\n    this._versionNegotiation = options?.versionNegotiation ?? { mode: 'auto' }\n    this._prior = options?.prior\n    this._inputRequired = options?.inputRequired\n    this._responseCacheStore = options?.responseCacheStore\n    this._cachePartition = options?.cachePartition\n    this._defaultCacheTtlMs = options?.defaultCacheTtlMs\n    this._legacySSE = options?.legacySSE ?? false\n    this._defaultOptions = options?.defaultOptions ?? {}\n  }\n\n  // -------------------------------------------------------------------------\n  // Lifecycle\n  // -------------------------------------------------------------------------\n\n  async connect(): Promise<void> {\n    this._refCount++\n\n    // If another concurrent connect() is in progress, wait for it.\n    if (this._connectPromise) {\n      await this._connectPromise\n      return\n    }\n\n    // Already connected — just bump the ref count.\n    if (this._sdkClient) return\n\n    this._connectPromise = this._doConnect().finally(() => {\n      this._connectPromise = null\n    })\n\n    try {\n      await this._connectPromise\n    } catch (err) {\n      this._refCount = Math.max(0, this._refCount - 1)\n      throw err\n    }\n  }\n\n  private async _doConnect(): Promise<void> {\n    const sdkClient = new SdkClient(\n      this._clientInfo,\n      {\n        capabilities: this._capabilities,\n        listChanged: this._buildListChangedConfig(),\n        versionNegotiation: this._versionNegotiation,\n        ...(this._inputRequired ? { inputRequired: this._inputRequired } : {}),\n        ...(this._responseCacheStore ? { responseCacheStore: this._responseCacheStore } : {}),\n        ...(this._cachePartition !== undefined ? { cachePartition: this._cachePartition } : {}),\n        ...(this._defaultCacheTtlMs !== undefined\n          ? { defaultCacheTtlMs: this._defaultCacheTtlMs }\n          : {}),\n      },\n    )\n\n    this._registerHandlers(sdkClient)\n\n    const { transport, beforeConnect } = await resolveTransport(this._input, this._auth, {\n      legacySSE: this._legacySSE,\n      versionNegotiation: this._versionNegotiation,\n    })\n\n    // Bind the server URL into the OAuth provider before the SDK transport\n    // reads clientMetadata or tokens() so storage keys are properly namespaced.\n    if (this._auth instanceof OAuth) {\n      const serverUrl = this._extractServerUrl()\n      if (serverUrl) this._auth._bind(serverUrl)\n    }\n\n    if (beforeConnect) await beforeConnect()\n\n    this._transport = transport\n    try {\n      await sdkClient.connect(transport, this._prior ? { prior: this._prior } : undefined)\n    } catch (err) {\n      if (err instanceof UnauthorizedError && this._auth instanceof OAuth) {\n        // The SDK opened the browser and is waiting for the user to authorize.\n        // Wait for the callback to receive the full callback params (code +,\n        // when present, the RFC 9207 `iss` parameter), then finish auth on the\n        // original transport (it holds the discovery/PKCE context) to exchange\n        // the code for tokens. Passing URLSearchParams (rather than a bare\n        // code string) lets the SDK validate `iss` against the recorded\n        // issuer before redeeming the code.\n        const callbackParams = await this._auth.waitForCallback()\n        await this._finishAuth(transport, callbackParams)\n        // The original transport is already started and cannot be reconnected;\n        // build a fresh one for the authenticated attempt. It reads the tokens\n        // finishAuth stored in the auth provider. Pass the same resolution\n        // options as the primary attempt so the retry keeps the SSE opt-in and\n        // the era-negotiation mode.\n        const retry = await resolveTransport(this._input, this._auth, {\n          legacySSE: this._legacySSE,\n          versionNegotiation: this._versionNegotiation,\n        })\n        if (retry.beforeConnect) await retry.beforeConnect()\n        this._transport = retry.transport\n        await sdkClient.connect(retry.transport)\n      } else {\n        throw err\n      }\n    }\n\n    this._sdkClient = sdkClient\n  }\n\n  private _extractServerUrl(): string | undefined {\n    const input = this._input\n    if (typeof input === 'string') return input\n    if (\n      typeof input === 'object' &&\n      input !== null &&\n      'mcpServers' in input\n    ) {\n      const entries = Object.entries(\n        (input as { mcpServers: Record<string, { url?: string }> }).mcpServers,\n      )\n      if (entries.length > 0) {\n        const [, entry] = entries[0]!\n        if (entry && 'url' in entry && typeof entry.url === 'string') {\n          return entry.url\n        }\n      }\n    }\n    return undefined\n  }\n\n  async close(): Promise<void> {\n    this._refCount = Math.max(0, this._refCount - 1)\n    if (this._refCount > 0) return\n\n    // Close explicitly (and first) so its closure reason is 'local', not 'remote' —\n    // otherwise the resource-subscription robustness handler above would try to\n    // re-listen through a client that is already torn down.\n    if (this._resourceListenSubscription) {\n      await this._resourceListenSubscription.close().catch(() => {})\n      this._resourceListenSubscription = undefined\n    }\n\n    const sdk = this._sdkClient\n    this._sdkClient = null\n    if (sdk) await sdk.close()\n  }\n\n  async [Symbol.asyncDispose](): Promise<void> {\n    await this.close()\n  }\n\n  isConnected(): boolean {\n    return this._sdkClient !== null\n  }\n\n  /** Creates a connected MultiServerClient when given a multi-entry McpConfig. */\n  static async connect(input: McpConfig, options?: MultiServerOptions): Promise<MultiServerClient>\n  /** Creates a connected Client for a single-server transport. Use with `await using` for automatic cleanup. */\n  static async connect(input: ClientTransportInput, options?: ClientOptions): Promise<Client>\n  static async connect(\n    input: ClientTransportInput | McpConfig,\n    options?: ClientOptions | MultiServerOptions,\n  ): Promise<Client | MultiServerClient> {\n    if (\n      typeof input === 'object' &&\n      input !== null &&\n      'mcpServers' in input &&\n      Object.keys((input as McpConfig).mcpServers).length > 1\n    ) {\n      return MultiServerClient.connect(input as McpConfig, options as MultiServerOptions)\n    }\n    const client = new Client(input as ClientTransportInput, options as ClientOptions)\n    await client.connect()\n    return client\n  }\n\n  // -------------------------------------------------------------------------\n  // Core protocol\n  // -------------------------------------------------------------------------\n\n  /**\n   * Liveness check. On a legacy-era connection this sends the `ping` RPC. On a\n   * modern (2026-07-28) connection `ping` is not a wire method — the era's\n   * registry deliberately excludes it — so this sends `server/discover`\n   * instead: any successful response is equally strong liveness evidence, and\n   * `discover()` is the SDK-native modern equivalent (rather than a\n   * hand-rolled substitute). Returns `false` only on legacy `ping`'s own\n   * result; a modern-era failure throws, matching `ping()`'s existing\n   * throw-on-failure contract.\n   */\n  async ping(options?: RequestOptions): Promise<boolean> {\n    if (this.getProtocolEra() === 'modern') {\n      await this._reauthRetry(() => this._sdk().discover(this._toSdkOptions(options)))\n      return true\n    }\n    await this._reauthRetry(() => this._sdk().ping(this._toSdkOptions(options)))\n    return true\n  }\n\n  /**\n   * The protocol era negotiated at connect(): `'modern'` for 2026-07-28 (per-request\n   * envelope), `'legacy'` for 2025-11-25 and earlier (the `initialize` handshake).\n   * `undefined` before connect(). See `ClientOptions.versionNegotiation`.\n   */\n  getProtocolEra(): ProtocolEra | undefined {\n    return this._sdkClient?.getProtocolEra()\n  }\n\n  /**\n   * The connected server's self-reported identity (`serverInfo`: name, version,\n   * and optional title / websiteUrl / icons), when it identified itself. On a\n   * legacy connection it comes from the `initialize` result, where it is\n   * required. On a modern (2026-07-28) connection it comes from the\n   * `server/discover` result's metadata — FastMCP servers advertise it there,\n   * but an anonymous modern server may omit it, leaving this `undefined`.\n   * `undefined` before connect().\n   */\n  getServerInfo(): Implementation | undefined {\n    return this._sdkClient?.getServerVersion()\n  }\n\n  /**\n   * The server's `instructions` string, when the server provided one — from\n   * the legacy `initialize` result or, on a modern (2026-07-28) connection,\n   * from the `server/discover` result. `undefined` otherwise and before\n   * connect().\n   */\n  getInstructions(): string | undefined {\n    return this._sdkClient?.getInstructions()\n  }\n\n  /**\n   * The capabilities the server advertised during connection — on the legacy\n   * `initialize` result, or on the `server/discover` result for a modern\n   * (2026-07-28) connection. `undefined` before connect().\n   */\n  getServerCapabilities(): ServerCapabilities | undefined {\n    return this._sdkClient?.getServerCapabilities()\n  }\n\n  // -------------------------------------------------------------------------\n  // Tools (IToolsClient)\n  // -------------------------------------------------------------------------\n\n  async listTools(options?: RequestOptions): Promise<Tool[]> {\n    const result = await this._reauthRetry(() =>\n      this._sdk().listTools(\n        this._metaParams(),\n        this._toSdkOptions(options, undefined, this._defaultOptions.tool?.timeout),\n      ),\n    )\n    return result.tools as Tool[]\n  }\n\n  async callTool<TData = unknown>(\n    name: string,\n    args?: Record<string, unknown>,\n    options?: CallToolOptions,\n  ): Promise<CallToolResult<TData>> {\n    const raw = await this.callToolRaw<TData>(name, args, options)\n    if (raw.isError) {\n      const message =\n        (raw.content as Array<{ type: string; text?: string }>)\n          .filter((c) => c.type === 'text')\n          .map((c) => c.text ?? '')\n          .join('\\n') || 'Tool returned an error'\n      throw new ToolCallError(message, raw.content)\n    }\n    return raw\n  }\n\n  /** Returns the full result including isError without throwing. */\n  async callToolRaw<TData = unknown>(\n    name: string,\n    args?: Record<string, unknown>,\n    options?: CallToolOptions,\n  ): Promise<CallToolResult<TData>> {\n    const sdkOptions = this._toSdkOptions(\n      options,\n      options?.onProgress,\n      this._defaultOptions.tool?.timeout,\n    )\n    const result = await this._reauthRetry(() =>\n      this._sdk().callTool({ name, arguments: args ?? {}, ...this._metaParams() }, sdkOptions),\n    )\n    return normalizeCallToolResult<TData>(result)\n  }\n\n  // -------------------------------------------------------------------------\n  // Resources (IResourcesClient)\n  // -------------------------------------------------------------------------\n\n  async listResources(options?: RequestOptions): Promise<Resource[]> {\n    const result = await this._reauthRetry(() =>\n      this._sdk().listResources(\n        this._metaParams(),\n        this._toSdkOptions(options, undefined, this._defaultOptions.resource?.timeout),\n      ),\n    )\n    return result.resources as Resource[]\n  }\n\n  async listResourceTemplates(options?: RequestOptions): Promise<ResourceTemplate[]> {\n    const result = await this._reauthRetry(() =>\n      this._sdk().listResourceTemplates(\n        this._metaParams(),\n        this._toSdkOptions(options, undefined, this._defaultOptions.resource?.timeout),\n      ),\n    )\n    return result.resourceTemplates as ResourceTemplate[]\n  }\n\n  async readResource(\n    uri: string,\n    options?: RequestOptions,\n  ): Promise<Array<TextResourceContents | BlobResourceContents>> {\n    const result = await this._reauthRetry(() =>\n      this._sdk().readResource(\n        { uri, ...this._metaParams() },\n        this._toSdkOptions(options, undefined, this._defaultOptions.resource?.timeout),\n      ),\n    )\n    return result.contents\n  }\n\n  /** Returns the raw SDK ReadResourceResult without unwrapping. */\n  async readResourceRaw(uri: string, options?: RequestOptions) {\n    return this._reauthRetry(() =>\n      this._sdk().readResource(\n        { uri, ...this._metaParams() },\n        this._toSdkOptions(options, undefined, this._defaultOptions.resource?.timeout),\n      ),\n    )\n  }\n\n  /**\n   * Subscribes to change notifications for a resource URI. `handler` fires whenever\n   * the server sends a matching update, on either protocol era: on a legacy\n   * (2025-era) connection via the `resources/subscribe` RPC and unsolicited\n   * `notifications/resources/updated` push, or on a modern (2026-07-28) connection\n   * via a `subscriptions/listen` stream opted into `resourceSubscriptions` — both\n   * dispatch to the same `notifications/resources/updated` handler registered in\n   * `_registerHandlers`, so this method is the only era-aware part.\n   *\n   * On a modern connection this rejects when the server's acknowledged filter does\n   * not include the URI — that is how a server without the `resources.subscribe`\n   * capability declines per-resource subscriptions, and registering a handler that\n   * can never fire would fail silently instead.\n   */\n  async subscribeResource(\n    uri: string,\n    handler: ResourceUpdateHandler,\n    options?: RequestOptions,\n  ): Promise<void> {\n    this._resourceSubscriptions.set(uri, handler)\n    if (this._sdk().getProtocolEra() === 'modern') {\n      await this._refreshResourceListenSubscription()\n      // The listen ack reports the honored subset of the requested filter. A server\n      // that does not advertise `resources.subscribe` prunes `resourceSubscriptions`\n      // from it entirely, and updates for this URI would never be delivered — fail\n      // loudly instead of registering a dead handler (#88).\n      const honored = this._resourceListenSubscription?.honoredFilter.resourceSubscriptions ?? []\n      if (!honored.includes(uri)) {\n        this._resourceSubscriptions.delete(uri)\n        await this._refreshResourceListenSubscription()\n        throw new Error(\n          `subscribeResource(${JSON.stringify(uri)}): the server did not honor the subscription — ` +\n            `its subscriptions/acknowledged filter omits the URI, which means it does not advertise ` +\n            `the resources.subscribe capability.`,\n        )\n      }\n    } else {\n      await this._reauthRetry(() =>\n        this._sdk().subscribeResource(\n          { uri, ...this._metaParams() },\n          this._toSdkOptions(options, undefined, this._defaultOptions.resource?.timeout),\n        ),\n      )\n    }\n  }\n\n  async unsubscribeResource(uri: string, options?: RequestOptions): Promise<void> {\n    this._resourceSubscriptions.delete(uri)\n    if (this._sdk().getProtocolEra() === 'modern') {\n      await this._refreshResourceListenSubscription()\n    } else {\n      await this._reauthRetry(() =>\n        this._sdk().unsubscribeResource(\n          { uri, ...this._metaParams() },\n          this._toSdkOptions(options, undefined, this._defaultOptions.resource?.timeout),\n        ),\n      )\n    }\n  }\n\n  /**\n   * Re-opens the modern-era resource-subscription listen stream with the current\n   * set of subscribed URIs. `listen()` has no in-place filter update, so every\n   * subscribe/unsubscribe on a modern connection closes the existing stream (if\n   * any) and opens a fresh one — `subscribeResource`/`unsubscribeResource` are not\n   * expected to be called at a high frequency, so this is not a hot path.\n   */\n  private async _refreshResourceListenSubscription(): Promise<void> {\n    if (this._resourceListenSubscription) {\n      await this._resourceListenSubscription.close()\n      this._resourceListenSubscription = undefined\n    }\n    const uris = [...this._resourceSubscriptions.keys()]\n    if (uris.length === 0) return\n\n    // The modern subscribeResource/unsubscribeResource leg: opening the\n    // `subscriptions/listen` stream is a server-auth-gated request, so it steps\n    // up on a post-connect 401 like every other request method.\n    const subscription = await this._reauthRetry(() =>\n      this._sdk().listen({ resourceSubscriptions: uris }),\n    )\n    this._resourceListenSubscription = subscription\n\n    // Robustness: an unexpected disconnect ('remote') re-establishes the stream so\n    // resource-update delivery survives a dropped connection. A deliberate\n    // server-side close ('graceful') is respected — the server chose to end it, and\n    // re-listening would fight that decision. A close we triggered ourselves\n    // ('local' — e.g. this same method superseding it above) needs no action; the\n    // subscription-identity check also protects against acting on a stale handle.\n    void subscription.closed.then((reason) => {\n      if (reason === 'remote' && this._resourceListenSubscription === subscription) {\n        this._resourceListenSubscription = undefined\n        void this._refreshResourceListenSubscription().catch(() => {})\n      }\n    })\n  }\n\n  // -------------------------------------------------------------------------\n  // Prompts (IPromptsClient)\n  // -------------------------------------------------------------------------\n\n  async listPrompts(options?: RequestOptions): Promise<Prompt[]> {\n    const result = await this._reauthRetry(() =>\n      this._sdk().listPrompts(\n        this._metaParams(),\n        this._toSdkOptions(options, undefined, this._defaultOptions.prompt?.timeout),\n      ),\n    )\n    return result.prompts as Prompt[]\n  }\n\n  async getPrompt(\n    name: string,\n    args?: Record<string, string>,\n    options?: RequestOptions,\n  ): Promise<GetPromptResult> {\n    const result = await this._reauthRetry(() =>\n      this._sdk().getPrompt(\n        { name, arguments: args, ...this._metaParams() },\n        this._toSdkOptions(options, undefined, this._defaultOptions.prompt?.timeout),\n      ),\n    )\n    return result as GetPromptResult\n  }\n\n  // -------------------------------------------------------------------------\n  // Skills (SEP-2640 extension)\n  // -------------------------------------------------------------------------\n\n  /** True when the connection is modern and both sides advertise {@link SKILLS_EXTENSION_ID}. */\n  supportsSkills(): boolean {\n    return this._skillsUnavailableReason() === undefined\n  }\n\n  /** Lists every skill the server publishes. */\n  async listSkills(options?: RequestOptions): Promise<Skill[]> {\n    const skills = this._skills()\n    const listing = await this._reauthRetry(() =>\n      skills.list(undefined, this._toSdkOptions(options, undefined, this._defaultOptions.resource?.timeout)),\n    )\n    return listing.skills\n  }\n\n  /** Fetches one skill entry by the URI of its `SKILL.md` resource. */\n  async getSkill(uri: string, options?: RequestOptions): Promise<Skill> {\n    const skills = this._skills()\n    const { skill } = await this._reauthRetry(() =>\n      skills.get(uri, this._toSdkOptions(options, undefined, this._defaultOptions.resource?.timeout)),\n    )\n    return skill\n  }\n\n  /** Reads every file of a skill, each verified against the skill's entry. */\n  async readSkill(uri: string, options?: RequestOptions): Promise<SkillContents> {\n    const skill = await this.getSkill(uri, options)\n    if (skill.resources === 'dynamic') {\n      throw new Error(`Skill ${uri} has no static file list to read`)\n    }\n    const skills = this._skills()\n    const sdkOptions = this._toSdkOptions(options, undefined, this._defaultOptions.resource?.timeout)\n    const files = await Promise.all(\n      skill.resources.map((file) => this._reauthRetry(() => skills.read(skill, file.uri, sdkOptions))),\n    )\n    return { skill, files }\n  }\n\n  private _skills(): SkillsClient {\n    const reason = this._skillsUnavailableReason()\n    if (reason !== undefined) throw new Error(reason)\n    return new SkillsClient(this._sdk())\n  }\n\n  private _skillsUnavailableReason(): string | undefined {\n    const sdk = this._sdkClient\n    if (!sdk) return 'Client is not connected. Call connect() first.'\n    if (sdk.getProtocolEra() !== 'modern') {\n      return 'The Skills extension requires a modern (2026-07-28) connection'\n    }\n    if (this._capabilities.extensions?.[SKILLS_EXTENSION_ID] === undefined) {\n      return `This client did not opt into the Skills extension; add '${SKILLS_EXTENSION_ID}' to capabilities.extensions`\n    }\n    if (!new SkillsClient(sdk).supported) {\n      return 'The server does not advertise the Skills extension'\n    }\n    return undefined\n  }\n\n  // -------------------------------------------------------------------------\n  // Completion\n  // -------------------------------------------------------------------------\n\n  async complete(\n    ref: { type: 'ref/prompt'; name: string } | { type: 'ref/resource'; uri: string },\n    argument: { name: string; value: string },\n    context?: { arguments?: Record<string, string> },\n    options?: RequestOptions,\n  ): Promise<CompletionResult> {\n    const result = await this._reauthRetry(() =>\n      this._sdk().complete(\n        { ref, argument, ...(context ? { context } : {}), ...this._metaParams() },\n        this._toSdkOptions(options),\n      ),\n    )\n    return result.completion as CompletionResult\n  }\n\n  // -------------------------------------------------------------------------\n  // Logging\n  // -------------------------------------------------------------------------\n\n  /**\n   * Sets the minimum severity level for log messages sent by the server. On a\n   * legacy-era connection this sends the `logging/setLevel` RPC, unchanged. On\n   * a modern (2026-07-28) connection `logging/setLevel` is deprecated (SEP-2577)\n   * and physically absent from the era's registry — there is no RPC to send.\n   * Instead, the level is recorded and threaded into\n   * `_meta['io.modelcontextprotocol/logLevel']` on every subsequent request via\n   * `_metaParams()`, per request; user-supplied `_meta` still wins if a caller\n   * passes one explicitly (there is no such call site in this class today).\n   */\n  async setLogLevel(level: LoggingLevel, options?: RequestOptions): Promise<void> {\n    if (this.getProtocolEra() === 'modern') {\n      this._logLevel = level\n      return\n    }\n    await this._reauthRetry(() =>\n      this._sdk().setLoggingLevel(level, this._toSdkOptions(options)),\n    )\n  }\n\n  // -------------------------------------------------------------------------\n  // Private helpers\n  // -------------------------------------------------------------------------\n\n  private _sdk(): SdkClient {\n    if (!this._sdkClient) {\n      throw new Error('Client is not connected. Call connect() first.')\n    }\n    return this._sdkClient\n  }\n\n  /**\n   * Runs a post-connect SDK request and, when it rejects with the SDK's\n   * `UnauthorizedError` under an interactive {@link OAuth} provider, performs a\n   * bounded number of step-up re-authorization rounds — the same\n   * `waitForCallback`→`finishAuth` machinery `connect()` uses — retrying the\n   * request after each.\n   *\n   * This closes the post-connect gap for interactive OAuth: a request that 401s\n   * (missing/expired token) or 403s with an `insufficient_scope` challenge (a\n   * broader scope is required for that operation) drives the SDK transport to\n   * issue a fresh, scope-honoring authorization request and re-throw\n   * `UnauthorizedError` — the transport picks the challenged/union scope itself\n   * (`extractWWWAuthenticateParams` + `computeScopeUnion`); this wrapper only\n   * completes the interrupted round and retries.\n   *\n   * The bound is {@link Client._MAX_REAUTH_ROUNDS}. One round covers ordinary\n   * step-up (a single 401/403). Two rounds cover SEP-2352 authorization-server\n   * migration: the first authenticated request flips the MCP server to a new\n   * authorization server (its Protected Resource Metadata now lists a different\n   * issuer), so the very next request 401s and must re-discover, re-register, and\n   * re-authorize at the NEW server — a second round on the same wrapped request.\n   * Beyond the bound the `UnauthorizedError` propagates, so a genuinely\n   * unauthorized request never loops forever.\n   *\n   * Each round is single-flight: concurrent 401s share one `_reauthPromise`, and\n   * each caller retries its own request after it resolves — a burst never opens\n   * multiple browsers.\n   *\n   * Non-interactive auth is never re-authorized here — the original error\n   * propagates unchanged. `BearerAuth` and custom headers carry no interactive\n   * step, and a {@link ClientCredentials} scope failure is a machine-to-machine\n   * misconfiguration (no user, no browser), not a step-up flow.\n   * `MultiServerClient` configures no interactive OAuth by design, so this path\n   * stays inert there.\n   *\n   * Every outbound request method routes through this wrapper, with one\n   * exception: {@link Client.notifyRootsChanged} calls the SDK directly. It sends\n   * a notification, not a request, so there is no response to 401/403 and\n   * nothing to retry.\n   *\n   * `BrowserOAuth` (`extends OAuth`) is covered by the same guard, and its\n   * `waitForCallback` is sound for a post-connect round — `redirectToAuthorization`\n   * arms the callback promise before the transport re-throws. Two browser-only\n   * caveats apply, honestly: in **popup** mode `window.open` needs a user gesture,\n   * so a step-up fired from a request not within one is blocked and the re-auth\n   * error propagates (call from a click); **redirect** mode navigates the whole\n   * tab away (`window.location.assign`), destroying this in-flight retry — the app\n   * recovers via `resumeFromRedirect()` on the return load and a fresh request,\n   * not by this wrapper. The migration second round inherits the popup caveat: it\n   * runs outside the original user gesture, so under `BrowserOAuth` popup mode it\n   * hits the user-gesture block and surfaces as that error rather than opening a\n   * second popup.\n   */\n  private async _reauthRetry<T>(op: () => Promise<T>): Promise<T> {\n    let rounds = 0\n    for (;;) {\n      try {\n        return await op()\n      } catch (err) {\n        if (!(err instanceof UnauthorizedError) || !(this._auth instanceof OAuth)) throw err\n        // Bounded — see _MAX_REAUTH_ROUNDS. Beyond the bound the error propagates\n        // so a genuinely unauthorized request never loops forever.\n        if (rounds >= Client._MAX_REAUTH_ROUNDS) throw err\n        rounds++\n        await this._reauthorize(this._auth)\n      }\n    }\n  }\n\n  /** Single-flight wrapper around one re-authorization round. */\n  private async _reauthorize(auth: OAuth): Promise<void> {\n    this._reauthPromise ??= this._doReauthorize(auth).finally(() => {\n      this._reauthPromise = null\n    })\n    await this._reauthPromise\n  }\n\n  /**\n   * One re-authorization round: await the authorization callback the SDK\n   * transport already armed (its 401/403 handling ran discovery + opened the\n   * browser with the challenged scope), then `finishAuth()` redeems the code for\n   * the broader-scope token on the live transport. The very next request reads\n   * that token via the transport's per-request bearer-token bridge.\n   *\n   * After redeeming, the cached discovery state is invalidated so that the NEXT\n   * authorization leg re-discovers the Protected Resource Metadata from scratch.\n   * The SDK's `auth()` otherwise pins to the authorization server it first cached\n   * and re-fetches PRM only when it has none — so it never notices a SEP-2352\n   * migration (PRM `authorization_servers` changing to a new issuer). Clearing it\n   * here (after the current round's callback leg has already consumed it) makes a\n   * subsequent 401 re-run discovery, land on the new server, and register there.\n   * Re-discovery is idempotent when the server has NOT migrated, so ordinary\n   * step-up and token-refresh rounds are unaffected beyond one extra metadata\n   * fetch.\n   */\n  private async _doReauthorize(auth: OAuth): Promise<void> {\n    const callbackParams = await auth.waitForCallback()\n    // `_transport` is always set post-connect (assigned in _doConnect before\n    // `_sdkClient`), and this round only ever runs after a successful request —\n    // so the guard is theoretical. It stays only to keep the type non-null\n    // without a non-null assertion; a missing transport silently no-ops rather\n    // than throwing, which is the safer degradation if that invariant ever breaks.\n    if (this._transport) await this._finishAuth(this._transport, callbackParams)\n    await auth.invalidateCredentials('discovery')\n  }\n\n  /**\n   * Redeems the authorization callback params for tokens on `transport`, if it\n   * exposes `finishAuth` (StreamableHTTP and SSE do). Shared by connect-time\n   * recovery and post-connect step-up. Passing `URLSearchParams` (not a bare\n   * code) lets the SDK validate the RFC 9207 `iss` before redeeming.\n   */\n  private async _finishAuth(transport: Transport, params: URLSearchParams): Promise<void> {\n    if (\n      'finishAuth' in transport &&\n      typeof (transport as Record<string, unknown>).finishAuth === 'function'\n    ) {\n      await (transport as { finishAuth(p: URLSearchParams): Promise<void> }).finishAuth(params)\n    }\n  }\n\n  /**\n   * The `_meta` override to merge into an outbound request's params — carries\n   * `_logLevel` (set by setLogLevel() on a modern-era connection) so it rides\n   * along on every subsequent request. Returns `undefined` (not `{}`) when\n   * there is nothing to attach, so `{...this._metaParams()}` is a no-op and\n   * callers that pass no params at all can keep passing `undefined` unchanged.\n   */\n  private _metaParams(): { _meta: Record<string, unknown> } | undefined {\n    if (this._logLevel !== undefined && this.getProtocolEra() === 'modern') {\n      return { _meta: { [LOG_LEVEL_META_KEY]: this._logLevel } }\n    }\n    return undefined\n  }\n\n  private _toSdkOptions(\n    options?: RequestOptions,\n    overrideProgress?: ProgressHandler,\n    scopedTimeoutSeconds?: number,\n  ): SdkRequestOptions {\n    const timeoutSeconds =\n      options?.timeout ?? scopedTimeoutSeconds ?? this._defaultOptions.timeout\n    const progressHandler = overrideProgress ?? this._handlers.progress\n\n    const sdkOptions: SdkRequestOptions = {}\n    if (timeoutSeconds != null) sdkOptions.timeout = timeoutSeconds * 1000\n    if (options?.signal) sdkOptions.signal = options.signal\n    if (progressHandler) {\n      sdkOptions.onprogress = ({ progress, total, message }) => {\n        void progressHandler(progress, total, message)\n      }\n    }\n    return sdkOptions\n  }\n\n  private _buildListChangedConfig() {\n    const { onToolsListChanged, onResourcesListChanged, onPromptsListChanged } = this._handlers\n    if (!onToolsListChanged && !onResourcesListChanged && !onPromptsListChanged) return undefined\n\n    const adapt = <T>(h: ListChangedHandler<T>) => ({\n      onChanged: (err: Error | null, items: T[] | null) => { void h.onChanged(err, items) },\n      ...(h.autoRefresh !== undefined ? { autoRefresh: h.autoRefresh } : {}),\n      ...(h.debounceMs !== undefined ? { debounceMs: h.debounceMs } : {}),\n    })\n\n    return {\n      ...(onToolsListChanged ? { tools: adapt(onToolsListChanged) } : {}),\n      ...(onResourcesListChanged ? { resources: adapt(onResourcesListChanged) } : {}),\n      ...(onPromptsListChanged ? { prompts: adapt(onPromptsListChanged) } : {}),\n    }\n  }\n\n  private _registerHandlers(sdk: SdkClient): void {\n    // Log notifications from the server\n    sdk.setNotificationHandler('notifications/message', (notification) => {\n      void this._handlers.log({\n        level: notification.params.level,\n        logger: notification.params.logger ?? undefined,\n        data: notification.params.data,\n      })\n    })\n\n    // Resource update notifications (for active subscriptions)\n    sdk.setNotificationHandler('notifications/resources/updated', (notification) => {\n      const handler = this._resourceSubscriptions.get(notification.params.uri)\n      if (handler) void handler(notification.params.uri)\n    })\n\n    // Sampling: server requests an LLM completion from the client\n    if (this._handlers.sampling) {\n      const samplingHandler = this._handlers.sampling\n      sdk.setRequestHandler('sampling/createMessage', async (request) => {\n        return samplingHandler(request.params)\n      })\n    }\n\n    // Elicitation: server requests structured user input\n    if (this._handlers.elicitation) {\n      const elicitationHandler = this._handlers.elicitation\n      sdk.setRequestHandler('elicitation/create', async (request) => {\n        return elicitationHandler(request.params)\n      })\n    }\n\n    // Roots: server requests the client's accessible filesystem roots\n    if (this._roots) {\n      const getRoots = this._roots\n      sdk.setRequestHandler('roots/list', async () => ({\n        roots: await getRoots(),\n      }))\n    }\n  }\n\n  // -------------------------------------------------------------------------\n  // Roots\n  // -------------------------------------------------------------------------\n\n  /**\n   * Notify the connected server that the client's roots list has changed.\n   * The server should re-issue a roots/list request to get the updated list.\n   */\n  async notifyRootsChanged(): Promise<void> {\n    await this._sdk().sendRootsListChanged()\n  }\n}\n\n// ---------------------------------------------------------------------------\n// Helpers\n// ---------------------------------------------------------------------------\n\nfunction resolveAuth(\n  auth: BearerAuth | OAuth | AsyncHeaderAuth | string | undefined,\n): BearerAuth | OAuth | AsyncHeaderAuth | undefined {\n  if (!auth) return undefined\n  if (typeof auth === 'string') return new BearerAuth(auth)\n  return auth\n}\n\nfunction normalizeRootsOption(roots: RootsValue): () => Promise<Root[]> {\n  if (typeof roots === 'function') {\n    return async () => Promise.all((await roots()).map(normalizeRootInput))\n  }\n  return async () => Promise.all(roots.map(normalizeRootInput))\n}\n\nasync function normalizeRootInput(input: RootInput): Promise<Root> {\n  if (typeof input === 'string') return { uri: await normalizeRootUri(input) }\n  return { ...input, uri: await normalizeRootUri(input.uri) }\n}\n\nasync function normalizeRootUri(input: string): Promise<string> {\n  // Already a URI (file://, http://, ...) — pass through with no Node import.\n  if (/^[a-z][a-z0-9+.-]*:\\/\\//i.test(input)) return input\n  // A bare filesystem path requires Node to resolve against the cwd.\n  if (typeof process === 'undefined' || !process.versions?.node) {\n    throw new Error(\n      `Cannot normalize filesystem root \"${input}\" in a browser. Pass a file:// URI instead.`,\n    )\n  }\n  const { resolve } = await import('node:path')\n  const { pathToFileURL } = await import('node:url')\n  return pathToFileURL(resolve(input)).href\n}\n","import { Client } from '../../client/client.js'\nimport type { ClientOptions } from '../../client/options.js'\nimport { StdioTransport } from '../../client/transports.js'\nimport type { CliAuth } from './auth.js'\nimport type { FileSpec } from './file-spec.js'\nimport { resolveEntrypointBootstrapPath, buildEntrypointEnv } from './entrypoint-bootstrap.js'\n\nexport type TransportMode =\n  | { kind: 'url'; url: string }\n  | { kind: 'stdio'; command: string; args?: string[] }\n  | { kind: 'inprocess'; spec: FileSpec }\n\n/** CLI-level era selection (`--legacy`, `--pin`; `--modern` is a deprecated\n * no-op); resolved to a concrete `versionNegotiation` mode by\n * `resolveVersionNegotiation`. */\nexport interface EraOptions {\n  /** Deprecated no-op, kept so existing invocations do not break:\n   * auto-negotiation is the default on every transport. */\n  modern?: boolean\n  /** Force the legacy 2025 era: `{ mode: 'legacy' }`, no `server/discover`\n   * probe. */\n  legacy?: boolean\n  pin?: string\n}\n\n/**\n * One negotiation default on every transport, decided in one place so every\n * connecting command (list/call/inspect) behaves identically:\n * - The default is `{ mode: 'auto' }`: probe once with `server/discover`, use\n *   the modern (2026-07-28) era when the server offers it, fall back to the\n *   plain legacy handshake otherwise. The SDK keeps the probe stall-safe on\n *   stdio (sibling-process probe, timeout falls back to legacy).\n * - `--legacy` is the opt-out: `{ mode: 'legacy' }` skips the probe entirely.\n * - `--pin` overrides the rest on any transport — it is the strongest\n *   request, so it wins even when `--legacy` (or the deprecated no-op\n *   `--modern`) is also given, mirroring the old pin-beats-modern precedence.\n * Returns an explicit mode in every case rather than `undefined`, so the CLI\n * never leans silently on the library default.\n */\nfunction resolveVersionNegotiation(era?: EraOptions): ClientOptions['versionNegotiation'] {\n  if (era?.pin) return { mode: { pin: era.pin } }\n  if (era?.legacy) return { mode: 'legacy' }\n  return { mode: 'auto' }\n}\n\nexport async function connectClient(mode: TransportMode, auth?: CliAuth, era?: EraOptions): Promise<Client> {\n  const versionNegotiation = resolveVersionNegotiation(era)\n\n  if (mode.kind === 'url') {\n    const client = new Client(mode.url, { auth, versionNegotiation })\n    await client.connect()\n    return client\n  }\n\n  // For stdio transports the MCP protocol carries no HTTP headers, so\n  // extra.authInfo on the server is always undefined. Inject the bearer\n  // token as an environment variable so FastMCP can reconstruct the auth\n  // context server-side (see FASTMCP_CLI_AUTH_TOKEN handling in FastMCP.ts).\n  const stdioEnv = buildStdioEnv(auth)\n\n  if (mode.kind === 'stdio') {\n    const [cmd, ...rest] = mode.command.split(/\\s+/)\n    const transport = new StdioTransport(cmd!, [...rest, ...(mode.args ?? [])], { env: stdioEnv })\n    const client = new Client(transport, { auth, versionNegotiation })\n    await client.connect()\n    return client\n  }\n\n  // in-process: spawn the entrypoint bootstrap via tsx/node and connect via stdio.\n  // The bootstrap imports the user's file, resolves the server export, and\n  // calls .run() — which honors MCP_TRANSPORT=stdio set in stdioEnv below.\n  const { spec } = mode\n  const bootstrapPath = resolveEntrypointBootstrapPath()\n  const [command, cmdArgs] = spec.isTypeScript\n    ? ['npx', ['tsx', bootstrapPath]]\n    : ['node', [bootstrapPath]]\n\n  const transport = new StdioTransport(command, cmdArgs, {\n    env: { ...stdioEnv, ...buildEntrypointEnv(spec) },\n  })\n  const client = new Client(transport, { auth, versionNegotiation })\n  await client.connect()\n  return client\n}\n\nfunction buildStdioEnv(auth: CliAuth | undefined): Record<string, string> {\n  const env: Record<string, string> = { ...process.env as Record<string, string>, MCP_TRANSPORT: 'stdio' }\n  if (auth) {\n    const authHeader = auth.getHeaders().Authorization\n    const token = authHeader?.startsWith('Bearer ') ? authHeader.slice(7) : authHeader\n    if (token) env['FASTMCP_CLI_AUTH_TOKEN'] = token\n  }\n  return env\n}\n","import { BearerAuth } from '../../client/auth.js'\n\nexport type CliAuth = BearerAuth\n\nexport function resolveAuth(authFlag: string | undefined): CliAuth | undefined {\n  if (!authFlag) return undefined\n  return new BearerAuth(authFlag)\n}\n","import type { Implementation, ServerCapabilities } from '@modelcontextprotocol/client'\nimport type { Tool, Resource, ResourceTemplate, Prompt } from '../../client/results.js'\n\n/**\n * Builder for `inspect --format fastmcp`: the manifest shape the Python\n * FastMCP CLI emits for `fastmcp inspect <spec> --format fastmcp`\n * (`fastmcp.utilities.inspect.format_fastmcp_info`). Snake_case keys, the\n * Python field set, and Python's null semantics — so cross-language consumers\n * (Horizon build tooling) can read one manifest schema from both CLIs.\n *\n * The Python CLI loads the server in-process and reads server-side state; this\n * CLI inspects over an MCP client connection. Fields that never cross the wire\n * are emitted as `null`, matching Python's own client-based inspection path\n * (`inspect_fastmcp_v1`): component `tags`, template `parameters`, and — for\n * servers that do not advertise them — `instructions`, `website_url`, and\n * `icons`. Values that do cross the wire pass through in protocol shape\n * (`annotations`, `icons`, `meta` contents keep their camelCase keys, exactly\n * as Python emits them).\n */\n\n/** Python `FastMCPComponent.key` format: `{prefix}:{identifier}@{version}`.\n * Component versions are server-side state and never cross the wire, so the\n * version suffix is always empty here (`tool:echo@`). */\nfunction componentKey(prefix: string, identifier: string): string {\n  return `${prefix}:${identifier}@`\n}\n\nexport interface FastmcpManifestInput {\n  serverInfo: Implementation | undefined\n  instructions: string | undefined\n  capabilities: ServerCapabilities | undefined\n  /** Python `server_generation`: 2 for a FastMCP server loaded from a file\n   * (the only case Python's inspect supports); `null` when inspecting an\n   * arbitrary server over a URL or stdio command, where the generation is\n   * unknowable from the wire. */\n  generation: number | null\n  fastmcpVersion: string\n  mcpVersion: string\n  tools: Tool[]\n  prompts: Prompt[]\n  resources: Resource[]\n  templates: ResourceTemplate[]\n}\n\n/** JSON value type for the manifest — plain data, no undefined. */\ntype Json = null | boolean | number | string | Json[] | { [key: string]: Json }\n\nexport function buildFastmcpManifest(input: FastmcpManifestInput): Record<string, Json> {\n  const { serverInfo } = input\n  return {\n    server: {\n      name: serverInfo?.name ?? null,\n      instructions: input.instructions ?? null,\n      // Python reports an unset version as null, never ''.\n      version: serverInfo?.version || null,\n      website_url: serverInfo?.websiteUrl ?? null,\n      icons: (serverInfo?.icons as Json) ?? null,\n      generation: input.generation,\n      capabilities: (input.capabilities as Json) ?? {},\n    },\n    environment: {\n      fastmcp: input.fastmcpVersion,\n      mcp: input.mcpVersion,\n    },\n    tools: input.tools.map((t) => ({\n      key: componentKey('tool', t.name),\n      name: t.name,\n      description: t.description ?? null,\n      input_schema: (t.inputSchema as Json) ?? {},\n      output_schema: (t.outputSchema as Json) ?? null,\n      annotations: (t.annotations as Json) ?? null,\n      tags: null,\n      title: t.title ?? null,\n      icons: (t.icons as Json) ?? null,\n      meta: (t._meta as Json) ?? null,\n    })),\n    prompts: input.prompts.map((p) => ({\n      key: componentKey('prompt', p.name),\n      name: p.name,\n      description: p.description ?? null,\n      arguments: p.arguments?.length\n        ? p.arguments.map((a) => ({\n            name: a.name,\n            description: a.description ?? null,\n            required: a.required ?? null,\n          }))\n        : null,\n      tags: null,\n      title: p.title ?? null,\n      icons: (p.icons as Json) ?? null,\n      meta: (p._meta as Json) ?? null,\n    })),\n    resources: input.resources.map((r) => ({\n      key: componentKey('resource', r.uri),\n      uri: r.uri,\n      name: r.name ?? null,\n      description: r.description ?? null,\n      mime_type: r.mimeType ?? null,\n      annotations: (r.annotations as Json) ?? null,\n      tags: null,\n      title: r.title ?? null,\n      icons: (r.icons as Json) ?? null,\n      meta: (r._meta as Json) ?? null,\n    })),\n    templates: input.templates.map((t) => ({\n      key: componentKey('template', t.uriTemplate),\n      uri_template: t.uriTemplate,\n      name: t.name ?? null,\n      description: t.description ?? null,\n      mime_type: t.mimeType ?? null,\n      parameters: null,\n      annotations: (t.annotations as Json) ?? null,\n      tags: null,\n      title: t.title ?? null,\n      icons: (t.icons as Json) ?? null,\n      meta: (t._meta as Json) ?? null,\n    })),\n  }\n}\n","import { spinner as clackSpinner } from '@clack/prompts'\nimport { theme } from './theme.js'\nimport { symbols } from './symbols.js'\nimport { isQuiet } from './output.js'\n\nexport async function withSpinner<T>(label: string, fn: () => Promise<T>): Promise<T> {\n  if (isQuiet() || !process.stdout.isTTY) {\n    return fn()\n  }\n  const s = clackSpinner()\n  s.start(theme.muted(`${symbols.info} ${label}`))\n  try {\n    const result = await fn()\n    s.stop(theme.success(`${symbols.success} ${label.replace(/…$/, '')} done`))\n    return result\n  } catch (err) {\n    s.stop(theme.error(`${symbols.failure} ${label.replace(/…$/, '')} failed`))\n    throw err\n  }\n}\n","let messages = [];\nlet level = 0;\n\nconst debug = (msg, min) => {\n  if (level >= min) {\n    messages.push(msg);\n  }\n};\n\ndebug.WARN = 1;\ndebug.INFO = 2;\ndebug.DEBUG = 3;\n\ndebug.reset = () => {\n  messages = [];\n};\n\ndebug.setDebugLevel = (v) => {\n  level = v;\n};\n\ndebug.warn = (msg) => debug(msg, debug.WARN);\ndebug.info = (msg) => debug(msg, debug.INFO);\ndebug.debug = (msg) => debug(msg, debug.DEBUG);\n\ndebug.debugMessages = () => messages;\n\nmodule.exports = debug;\n","'use strict';\n\nmodule.exports = ({onlyFirst = false} = {}) => {\n\tconst pattern = [\n\t\t'[\\\\u001B\\\\u009B][[\\\\]()#;?]*(?:(?:(?:(?:;[-a-zA-Z\\\\d\\\\/#&.:=?%@~_]+)*|[a-zA-Z\\\\d]+(?:;[-a-zA-Z\\\\d\\\\/#&.:=?%@~_]*)*)?\\\\u0007)',\n\t\t'(?:(?:\\\\d{1,4}(?:;\\\\d{0,4})*)?[\\\\dA-PR-TZcf-ntqry=><~]))'\n\t].join('|');\n\n\treturn new RegExp(pattern, onlyFirst ? undefined : 'g');\n};\n","'use strict';\nconst ansiRegex = require('ansi-regex');\n\nmodule.exports = string => typeof string === 'string' ? string.replace(ansiRegex(), '') : string;\n","/* eslint-disable yoda */\n'use strict';\n\nconst isFullwidthCodePoint = codePoint => {\n\tif (Number.isNaN(codePoint)) {\n\t\treturn false;\n\t}\n\n\t// Code points are derived from:\n\t// http://www.unix.org/Public/UNIDATA/EastAsianWidth.txt\n\tif (\n\t\tcodePoint >= 0x1100 && (\n\t\t\tcodePoint <= 0x115F || // Hangul Jamo\n\t\t\tcodePoint === 0x2329 || // LEFT-POINTING ANGLE BRACKET\n\t\t\tcodePoint === 0x232A || // RIGHT-POINTING ANGLE BRACKET\n\t\t\t// CJK Radicals Supplement .. Enclosed CJK Letters and Months\n\t\t\t(0x2E80 <= codePoint && codePoint <= 0x3247 && codePoint !== 0x303F) ||\n\t\t\t// Enclosed CJK Letters and Months .. CJK Unified Ideographs Extension A\n\t\t\t(0x3250 <= codePoint && codePoint <= 0x4DBF) ||\n\t\t\t// CJK Unified Ideographs .. Yi Radicals\n\t\t\t(0x4E00 <= codePoint && codePoint <= 0xA4C6) ||\n\t\t\t// Hangul Jamo Extended-A\n\t\t\t(0xA960 <= codePoint && codePoint <= 0xA97C) ||\n\t\t\t// Hangul Syllables\n\t\t\t(0xAC00 <= codePoint && codePoint <= 0xD7A3) ||\n\t\t\t// CJK Compatibility Ideographs\n\t\t\t(0xF900 <= codePoint && codePoint <= 0xFAFF) ||\n\t\t\t// Vertical Forms\n\t\t\t(0xFE10 <= codePoint && codePoint <= 0xFE19) ||\n\t\t\t// CJK Compatibility Forms .. Small Form Variants\n\t\t\t(0xFE30 <= codePoint && codePoint <= 0xFE6B) ||\n\t\t\t// Halfwidth and Fullwidth Forms\n\t\t\t(0xFF01 <= codePoint && codePoint <= 0xFF60) ||\n\t\t\t(0xFFE0 <= codePoint && codePoint <= 0xFFE6) ||\n\t\t\t// Kana Supplement\n\t\t\t(0x1B000 <= codePoint && codePoint <= 0x1B001) ||\n\t\t\t// Enclosed Ideographic Supplement\n\t\t\t(0x1F200 <= codePoint && codePoint <= 0x1F251) ||\n\t\t\t// CJK Unified Ideographs Extension B .. Tertiary Ideographic Plane\n\t\t\t(0x20000 <= codePoint && codePoint <= 0x3FFFD)\n\t\t)\n\t) {\n\t\treturn true;\n\t}\n\n\treturn false;\n};\n\nmodule.exports = isFullwidthCodePoint;\nmodule.exports.default = isFullwidthCodePoint;\n","\"use strict\";\n\nmodule.exports = function () {\n  // https://mths.be/emoji\n  return /\\uD83C\\uDFF4\\uDB40\\uDC67\\uDB40\\uDC62(?:\\uDB40\\uDC65\\uDB40\\uDC6E\\uDB40\\uDC67|\\uDB40\\uDC73\\uDB40\\uDC63\\uDB40\\uDC74|\\uDB40\\uDC77\\uDB40\\uDC6C\\uDB40\\uDC73)\\uDB40\\uDC7F|\\uD83D\\uDC68(?:\\uD83C\\uDFFC\\u200D(?:\\uD83E\\uDD1D\\u200D\\uD83D\\uDC68\\uD83C\\uDFFB|\\uD83C[\\uDF3E\\uDF73\\uDF93\\uDFA4\\uDFA8\\uDFEB\\uDFED]|\\uD83D[\\uDCBB\\uDCBC\\uDD27\\uDD2C\\uDE80\\uDE92]|\\uD83E[\\uDDAF-\\uDDB3\\uDDBC\\uDDBD])|\\uD83C\\uDFFF\\u200D(?:\\uD83E\\uDD1D\\u200D\\uD83D\\uDC68(?:\\uD83C[\\uDFFB-\\uDFFE])|\\uD83C[\\uDF3E\\uDF73\\uDF93\\uDFA4\\uDFA8\\uDFEB\\uDFED]|\\uD83D[\\uDCBB\\uDCBC\\uDD27\\uDD2C\\uDE80\\uDE92]|\\uD83E[\\uDDAF-\\uDDB3\\uDDBC\\uDDBD])|\\uD83C\\uDFFE\\u200D(?:\\uD83E\\uDD1D\\u200D\\uD83D\\uDC68(?:\\uD83C[\\uDFFB-\\uDFFD])|\\uD83C[\\uDF3E\\uDF73\\uDF93\\uDFA4\\uDFA8\\uDFEB\\uDFED]|\\uD83D[\\uDCBB\\uDCBC\\uDD27\\uDD2C\\uDE80\\uDE92]|\\uD83E[\\uDDAF-\\uDDB3\\uDDBC\\uDDBD])|\\uD83C\\uDFFD\\u200D(?:\\uD83E\\uDD1D\\u200D\\uD83D\\uDC68(?:\\uD83C[\\uDFFB\\uDFFC])|\\uD83C[\\uDF3E\\uDF73\\uDF93\\uDFA4\\uDFA8\\uDFEB\\uDFED]|\\uD83D[\\uDCBB\\uDCBC\\uDD27\\uDD2C\\uDE80\\uDE92]|\\uD83E[\\uDDAF-\\uDDB3\\uDDBC\\uDDBD])|\\u200D(?:\\u2764\\uFE0F\\u200D(?:\\uD83D\\uDC8B\\u200D)?\\uD83D\\uDC68|(?:\\uD83D[\\uDC68\\uDC69])\\u200D(?:\\uD83D\\uDC66\\u200D\\uD83D\\uDC66|\\uD83D\\uDC67\\u200D(?:\\uD83D[\\uDC66\\uDC67]))|\\uD83D\\uDC66\\u200D\\uD83D\\uDC66|\\uD83D\\uDC67\\u200D(?:\\uD83D[\\uDC66\\uDC67])|(?:\\uD83D[\\uDC68\\uDC69])\\u200D(?:\\uD83D[\\uDC66\\uDC67])|[\\u2695\\u2696\\u2708]\\uFE0F|\\uD83D[\\uDC66\\uDC67]|\\uD83C[\\uDF3E\\uDF73\\uDF93\\uDFA4\\uDFA8\\uDFEB\\uDFED]|\\uD83D[\\uDCBB\\uDCBC\\uDD27\\uDD2C\\uDE80\\uDE92]|\\uD83E[\\uDDAF-\\uDDB3\\uDDBC\\uDDBD])|(?:\\uD83C\\uDFFB\\u200D[\\u2695\\u2696\\u2708]|\\uD83C\\uDFFF\\u200D[\\u2695\\u2696\\u2708]|\\uD83C\\uDFFE\\u200D[\\u2695\\u2696\\u2708]|\\uD83C\\uDFFD\\u200D[\\u2695\\u2696\\u2708]|\\uD83C\\uDFFC\\u200D[\\u2695\\u2696\\u2708])\\uFE0F|\\uD83C\\uDFFB\\u200D(?:\\uD83C[\\uDF3E\\uDF73\\uDF93\\uDFA4\\uDFA8\\uDFEB\\uDFED]|\\uD83D[\\uDCBB\\uDCBC\\uDD27\\uDD2C\\uDE80\\uDE92]|\\uD83E[\\uDDAF-\\uDDB3\\uDDBC\\uDDBD])|\\uD83C[\\uDFFB-\\uDFFF])|(?:\\uD83E\\uDDD1\\uD83C\\uDFFB\\u200D\\uD83E\\uDD1D\\u200D\\uD83E\\uDDD1|\\uD83D\\uDC69\\uD83C\\uDFFC\\u200D\\uD83E\\uDD1D\\u200D\\uD83D\\uDC69)\\uD83C\\uDFFB|\\uD83E\\uDDD1(?:\\uD83C\\uDFFF\\u200D\\uD83E\\uDD1D\\u200D\\uD83E\\uDDD1(?:\\uD83C[\\uDFFB-\\uDFFF])|\\u200D\\uD83E\\uDD1D\\u200D\\uD83E\\uDDD1)|(?:\\uD83E\\uDDD1\\uD83C\\uDFFE\\u200D\\uD83E\\uDD1D\\u200D\\uD83E\\uDDD1|\\uD83D\\uDC69\\uD83C\\uDFFF\\u200D\\uD83E\\uDD1D\\u200D(?:\\uD83D[\\uDC68\\uDC69]))(?:\\uD83C[\\uDFFB-\\uDFFE])|(?:\\uD83E\\uDDD1\\uD83C\\uDFFC\\u200D\\uD83E\\uDD1D\\u200D\\uD83E\\uDDD1|\\uD83D\\uDC69\\uD83C\\uDFFD\\u200D\\uD83E\\uDD1D\\u200D\\uD83D\\uDC69)(?:\\uD83C[\\uDFFB\\uDFFC])|\\uD83D\\uDC69(?:\\uD83C\\uDFFE\\u200D(?:\\uD83E\\uDD1D\\u200D\\uD83D\\uDC68(?:\\uD83C[\\uDFFB-\\uDFFD\\uDFFF])|\\uD83C[\\uDF3E\\uDF73\\uDF93\\uDFA4\\uDFA8\\uDFE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:\\uD83C[\\uDF3E\\uDF73\\uDF93\\uDFA4\\uDFA8\\uDFEB\\uDFED]|\\uD83D[\\uDCBB\\uDCBC\\uDD27\\uDD2C\\uDE80\\uDE92]|\\uD83E[\\uDDAF-\\uDDB3\\uDDBC\\uDDBD]))|\\uD83D\\uDC69\\u200D\\uD83D\\uDC69\\u200D(?:\\uD83D\\uDC66\\u200D\\uD83D\\uDC66|\\uD83D\\uDC67\\u200D(?:\\uD83D[\\uDC66\\uDC67]))|(?:\\uD83E\\uDDD1\\uD83C\\uDFFD\\u200D\\uD83E\\uDD1D\\u200D\\uD83E\\uDDD1|\\uD83D\\uDC69\\uD83C\\uDFFE\\u200D\\uD83E\\uDD1D\\u200D\\uD83D\\uDC69)(?:\\uD83C[\\uDFFB-\\uDFFD])|\\uD83D\\uDC69\\u200D\\uD83D\\uDC66\\u200D\\uD83D\\uDC66|\\uD83D\\uDC69\\u200D\\uD83D\\uDC69\\u200D(?:\\uD83D[\\uDC66\\uDC67])|(?:\\uD83D\\uDC41\\uFE0F\\u200D\\uD83D\\uDDE8|\\uD83D\\uDC69(?:\\uD83C\\uDFFF\\u200D[\\u2695\\u2696\\u2708]|\\uD83C\\uDFFE\\u200D[\\u2695\\u2696\\u2708]|\\uD83C\\uDFFC\\u200D[\\u2695\\u2696\\u2708]|\\uD83C\\uDFFB\\u200D[\\u2695\\u2696\\u2708]|\\uD83C\\uDFFD\\u200D[\\u2695\\u2696\\u2708]|\\u200D[\\u2695\\u2696\\u2708])|(?:(?:\\u26F9|\\uD83C[\\uDFCB\\uDFCC]|\\uD83D\\uDD75)\\uFE0F|\\uD83D\\uDC6F|\\uD83E[\\uDD3C\\uDDDE\\uDDDF])\\u200D[\\u2640\\u2642]|(?:\\u26F9|\\uD83C[\\uDFCB\\uDFCC]|\\uD83D\\uDD75)(?:\\uD83C[\\uDFFB-\\uDFFF])\\u200D[\\u2640\\u2642]|(?:\\uD83C[\\uDFC3\\uDFC4\\uDFCA]|\\uD83D[\\uDC6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5])(?:\\uD83C[\\uDFFB-\\uDFFF])|(?:[\\u231A\\u231B\\u23E9-\\u23EC\\u23F0\\u23F3\\u25FD\\u25FE\\u2614\\u2615\\u2648-\\u2653\\u267F\\u2693\\u26A1\\u26AA\\u26AB\\u26BD\\u26BE\\u26C4\\u26C5\\u26CE\\u26D4\\u26EA\\u26F2\\u26F3\\u26F5\\u26FA\\u26FD\\u2705\\u270A\\u270B\\u2728\\u274C\\u274E\\u2753-\\u2755\\u2757\\u2795-\\u2797\\u27B0\\u27BF\\u2B1B\\u2B1C\\u2B50\\u2B55]|\\uD83C[\\uDC04\\uDCCF\\uDD8E\\uDD91-\\uDD9A\\uDDE6-\\uDDFF\\uDE01\\uDE1A\\uDE2F\\uDE32-\\uDE36\\uDE38-\\uDE3A\\uDE50\\uDE51\\uDF00-\\uDF20\\uDF2D-\\uDF35\\uDF37-\\uDF7C\\uDF7E-\\uDF93\\uDFA0-\\uDFCA\\uDFCF-\\uDFD3\\uDFE0-\\uDFF0\\uDFF4\\uDFF8-\\uDFFF]|\\uD83D[\\uDC00-\\uDC3E\\uDC40\\uDC42-\\uDCFC\\uDCFF-\\uDD3D\\uDD4B-\\uDD4E\\uDD50-\\uDD67\\uDD7A\\uDD95\\uDD96\\uDDA4\\uDDFB-\\uDE4F\\uDE80-\\uDEC5\\uDECC\\uDED0-\\uDED2\\uDED5\\uDEEB\\uDEEC\\uDEF4-\\uDEFA\\uDFE0-\\uDFEB]|\\uD83E[\\uDD0D-\\uDD3A\\uDD3C-\\uDD45\\uDD47-\\uDD71\\uDD73-\\uDD76\\uDD7A-\\uDDA2\\uDDA5-\\uDDAA\\uDDAE-\\uDDCA\\uDDCD-\\uDDFF\\uDE70-\\uDE73\\uDE78-\\uDE7A\\uDE80-\\uDE82\\uDE90-\\uDE95])|(?:[#\\*0-9\\xA9\\xAE\\u203C\\u2049\\u2122\\u2139\\u2194-\\u2199\\u21A9\\u21AA\\u231A\\u231B\\u2328\\u23CF\\u23E9-\\u23F3\\u23F8-\\u23FA\\u24C2\\u25AA\\u25AB\\u25B6\\u25C0\\u25FB-\\u25FE\\u2600-\\u2604\\u260E\\u2611\\u2614\\u2615\\u2618\\u261D\\u2620\\u2622\\u2623\\u2626\\u262A\\u262E\\u262F\\u2638-\\u263A\\u2640\\u2642\\u2648-\\u2653\\u265F\\u2660\\u2663\\u2665\\u2666\\u2668\\u267B\\u267E\\u267F\\u2692-\\u2697\\u2699\\u269B\\u269C\\u26A0\\u26A1\\u26AA\\u26AB\\u26B0\\u26B1\\u26BD\\u26BE\\u26C4\\u26C5\\u26C8\\u26CE\\u26CF\\u26D1\\u26D3\\u26D4\\u26E9\\u26EA\\u26F0-\\u26F5\\u26F7-\\u26FA\\u26FD\\u2702\\u2705\\u2708-\\u270D\\u270F\\u2712\\u2714\\u2716\\u271D\\u2721\\u2728\\u2733\\u2734\\u2744\\u2747\\u274C\\u274E\\u2753-\\u2755\\u2757\\u2763\\u2764\\u2795-\\u2797\\u27A1\\u27B0\\u27BF\\u2934\\u2935\\u2B05-\\u2B07\\u2B1B\\u2B1C\\u2B50\\u2B55\\u3030\\u303D\\u3297\\u3299]|\\uD83C[\\uDC04\\uDCCF\\uDD70\\uDD71\\uDD7E\\uDD7F\\uDD8E\\uDD91-\\uDD9A\\uDDE6-\\uDDFF\\uDE01\\uDE02\\uDE1A\\uDE2F\\uDE32-\\uDE3A\\uDE50\\uDE51\\uDF00-\\uDF21\\uDF24-\\uDF93\\uDF96\\uDF97\\uDF99-\\uDF9B\\uDF9E-\\uDFF0\\uDFF3-\\uDFF5\\uDFF7-\\uDFFF]|\\uD83D[\\uDC00-\\uDCFD\\uDCFF-\\uDD3D\\uDD49-\\uDD4E\\uDD50-\\uDD67\\uDD6F\\uDD70\\uDD73-\\uDD7A\\uDD87\\uDD8A-\\uDD8D\\uDD90\\uDD95\\uDD96\\uDDA4\\uDDA5\\uDDA8\\uDDB1\\uDDB2\\uDDBC\\uDDC2-\\uDDC4\\uDDD1-\\uDDD3\\uDDDC-\\uDDDE\\uDDE1\\uDDE3\\uDDE8\\uDDEF\\uDDF3\\uDDFA-\\uDE4F\\uDE80-\\uDEC5\\uDECB-\\uDED2\\uDED5\\uDEE0-\\uDEE5\\uDEE9\\uDEEB\\uDEEC\\uDEF0\\uDEF3-\\uDEFA\\uDFE0-\\uDFEB]|\\uD83E[\\uDD0D-\\uDD3A\\uDD3C-\\uDD45\\uDD47-\\uDD71\\uDD73-\\uDD76\\uDD7A-\\uDDA2\\uDDA5-\\uDDAA\\uDDAE-\\uDDCA\\uDDCD-\\uDDFF\\uDE70-\\uDE73\\uDE78-\\uDE7A\\uDE80-\\uDE82\\uDE90-\\uDE95])\\uFE0F|(?:[\\u261D\\u26F9\\u270A-\\u270D]|\\uD83C[\\uDF85\\uDFC2-\\uDFC4\\uDFC7\\uDFCA-\\uDFCC]|\\uD83D[\\uDC42\\uDC43\\uDC46-\\uDC50\\uDC66-\\uDC78\\uDC7C\\uDC81-\\uDC83\\uDC85-\\uDC87\\uDC8F\\uDC91\\uDCAA\\uDD74\\uDD75\\uDD7A\\uDD90\\uDD95\\uDD96\\uDE45-\\uDE47\\uDE4B-\\uDE4F\\uDEA3\\uDEB4-\\uDEB6\\uDEC0\\uDECC]|\\uD83E[\\uDD0F\\uDD18-\\uDD1F\\uDD26\\uDD30-\\uDD39\\uDD3C-\\uDD3E\\uDDB5\\uDDB6\\uDDB8\\uDDB9\\uDDBB\\uDDCD-\\uDDCF\\uDDD1-\\uDDDD])/g;\n};\n","'use strict';\nconst stripAnsi = require('strip-ansi');\nconst isFullwidthCodePoint = require('is-fullwidth-code-point');\nconst emojiRegex = require('emoji-regex');\n\nconst stringWidth = string => {\n\tif (typeof string !== 'string' || string.length === 0) {\n\t\treturn 0;\n\t}\n\n\tstring = stripAnsi(string);\n\n\tif (string.length === 0) {\n\t\treturn 0;\n\t}\n\n\tstring = string.replace(emojiRegex(), '  ');\n\n\tlet width = 0;\n\n\tfor (let i = 0; i < string.length; i++) {\n\t\tconst code = string.codePointAt(i);\n\n\t\t// Ignore control characters\n\t\tif (code <= 0x1F || (code >= 0x7F && code <= 0x9F)) {\n\t\t\tcontinue;\n\t\t}\n\n\t\t// Ignore combining characters\n\t\tif (code >= 0x300 && code <= 0x36F) {\n\t\t\tcontinue;\n\t\t}\n\n\t\t// Surrogates\n\t\tif (code > 0xFFFF) {\n\t\t\ti++;\n\t\t}\n\n\t\twidth += isFullwidthCodePoint(code) ? 2 : 1;\n\t}\n\n\treturn width;\n};\n\nmodule.exports = stringWidth;\n// TODO: remove this in the next major version\nmodule.exports.default = stringWidth;\n","const stringWidth = require('string-width');\n\nfunction codeRegex(capture) {\n  return capture ? /\\u001b\\[((?:\\d*;){0,5}\\d*)m/g : /\\u001b\\[(?:\\d*;){0,5}\\d*m/g;\n}\n\nfunction strlen(str) {\n  let code = codeRegex();\n  let stripped = ('' + str).replace(code, '');\n  let split = stripped.split('\\n');\n  return split.reduce(function (memo, s) {\n    return stringWidth(s) > memo ? stringWidth(s) : memo;\n  }, 0);\n}\n\nfunction repeat(str, times) {\n  return Array(times + 1).join(str);\n}\n\nfunction pad(str, len, pad, dir) {\n  let length = strlen(str);\n  if (len + 1 >= length) {\n    let padlen = len - length;\n    switch (dir) {\n      case 'right': {\n        str = repeat(pad, padlen) + str;\n        break;\n      }\n      case 'center': {\n        let right = Math.ceil(padlen / 2);\n        let left = padlen - right;\n        str = repeat(pad, left) + str + repeat(pad, right);\n        break;\n      }\n      default: {\n        str = str + repeat(pad, padlen);\n        break;\n      }\n    }\n  }\n  return str;\n}\n\nlet codeCache = {};\n\nfunction addToCodeCache(name, on, off) {\n  on = '\\u001b[' + on + 'm';\n  off = '\\u001b[' + off + 'm';\n  codeCache[on] = { set: name, to: true };\n  codeCache[off] = { set: name, to: false };\n  codeCache[name] = { on: on, off: off };\n}\n\n//https://github.com/Marak/colors.js/blob/master/lib/styles.js\naddToCodeCache('bold', 1, 22);\naddToCodeCache('italics', 3, 23);\naddToCodeCache('underline', 4, 24);\naddToCodeCache('inverse', 7, 27);\naddToCodeCache('strikethrough', 9, 29);\n\nfunction updateState(state, controlChars) {\n  let controlCode = controlChars[1] ? parseInt(controlChars[1].split(';')[0]) : 0;\n  if ((controlCode >= 30 && controlCode <= 39) || (controlCode >= 90 && controlCode <= 97)) {\n    state.lastForegroundAdded = controlChars[0];\n    return;\n  }\n  if ((controlCode >= 40 && controlCode <= 49) || (controlCode >= 100 && controlCode <= 107)) {\n    state.lastBackgroundAdded = controlChars[0];\n    return;\n  }\n  if (controlCode === 0) {\n    for (let i in state) {\n      /* istanbul ignore else */\n      if (Object.prototype.hasOwnProperty.call(state, i)) {\n        delete state[i];\n      }\n    }\n    return;\n  }\n  let info = codeCache[controlChars[0]];\n  if (info) {\n    state[info.set] = info.to;\n  }\n}\n\nfunction readState(line) {\n  let code = codeRegex(true);\n  let controlChars = code.exec(line);\n  let state = {};\n  while (controlChars !== null) {\n    updateState(state, controlChars);\n    controlChars = code.exec(line);\n  }\n  return state;\n}\n\nfunction unwindState(state, ret) {\n  let lastBackgroundAdded = state.lastBackgroundAdded;\n  let lastForegroundAdded = state.lastForegroundAdded;\n\n  delete state.lastBackgroundAdded;\n  delete state.lastForegroundAdded;\n\n  Object.keys(state).forEach(function (key) {\n    if (state[key]) {\n      ret += codeCache[key].off;\n    }\n  });\n\n  if (lastBackgroundAdded && lastBackgroundAdded != '\\u001b[49m') {\n    ret += '\\u001b[49m';\n  }\n  if (lastForegroundAdded && lastForegroundAdded != '\\u001b[39m') {\n    ret += '\\u001b[39m';\n  }\n\n  return ret;\n}\n\nfunction rewindState(state, ret) {\n  let lastBackgroundAdded = state.lastBackgroundAdded;\n  let lastForegroundAdded = state.lastForegroundAdded;\n\n  delete state.lastBackgroundAdded;\n  delete state.lastForegroundAdded;\n\n  Object.keys(state).forEach(function (key) {\n    if (state[key]) {\n      ret = codeCache[key].on + ret;\n    }\n  });\n\n  if (lastBackgroundAdded && lastBackgroundAdded != '\\u001b[49m') {\n    ret = lastBackgroundAdded + ret;\n  }\n  if (lastForegroundAdded && lastForegroundAdded != '\\u001b[39m') {\n    ret = lastForegroundAdded + ret;\n  }\n\n  return ret;\n}\n\nfunction truncateWidth(str, desiredLength) {\n  if (str.length === strlen(str)) {\n    return str.substr(0, desiredLength);\n  }\n\n  while (strlen(str) > desiredLength) {\n    str = str.slice(0, -1);\n  }\n\n  return str;\n}\n\nfunction truncateWidthWithAnsi(str, desiredLength) {\n  let code = codeRegex(true);\n  let split = str.split(codeRegex());\n  let splitIndex = 0;\n  let retLen = 0;\n  let ret = '';\n  let myArray;\n  let state = {};\n\n  while (retLen < desiredLength) {\n    myArray = code.exec(str);\n    let toAdd = split[splitIndex];\n    splitIndex++;\n    if (retLen + strlen(toAdd) > desiredLength) {\n      toAdd = truncateWidth(toAdd, desiredLength - retLen);\n    }\n    ret += toAdd;\n    retLen += strlen(toAdd);\n\n    if (retLen < desiredLength) {\n      if (!myArray) {\n        break;\n      } // full-width chars may cause a whitespace which cannot be filled\n      ret += myArray[0];\n      updateState(state, myArray);\n    }\n  }\n\n  return unwindState(state, ret);\n}\n\nfunction truncate(str, desiredLength, truncateChar) {\n  truncateChar = truncateChar || '…';\n  let lengthOfStr = strlen(str);\n  if (lengthOfStr <= desiredLength) {\n    return str;\n  }\n  desiredLength -= strlen(truncateChar);\n\n  let ret = truncateWidthWithAnsi(str, desiredLength);\n\n  ret += truncateChar;\n\n  const hrefTag = '\\x1B]8;;\\x07';\n\n  if (str.includes(hrefTag) && !ret.includes(hrefTag)) {\n    ret += hrefTag;\n  }\n\n  return ret;\n}\n\nfunction defaultOptions() {\n  return {\n    chars: {\n      top: '─',\n      'top-mid': '┬',\n      'top-left': '┌',\n      'top-right': '┐',\n      bottom: '─',\n      'bottom-mid': '┴',\n      'bottom-left': '└',\n      'bottom-right': '┘',\n      left: '│',\n      'left-mid': '├',\n      mid: '─',\n      'mid-mid': '┼',\n      right: '│',\n      'right-mid': '┤',\n      middle: '│',\n    },\n    truncate: '…',\n    colWidths: [],\n    rowHeights: [],\n    colAligns: [],\n    rowAligns: [],\n    style: {\n      'padding-left': 1,\n      'padding-right': 1,\n      head: ['red'],\n      border: ['grey'],\n      compact: false,\n    },\n    head: [],\n  };\n}\n\nfunction mergeOptions(options, defaults) {\n  options = options || {};\n  defaults = defaults || defaultOptions();\n  let ret = Object.assign({}, defaults, options);\n  ret.chars = Object.assign({}, defaults.chars, options.chars);\n  ret.style = Object.assign({}, defaults.style, options.style);\n  return ret;\n}\n\n// Wrap on word boundary\nfunction wordWrap(maxLength, input) {\n  let lines = [];\n  let split = input.split(/(\\s+)/g);\n  let line = [];\n  let lineLength = 0;\n  let whitespace;\n  for (let i = 0; i < split.length; i += 2) {\n    let word = split[i];\n    let newLength = lineLength + strlen(word);\n    if (lineLength > 0 && whitespace) {\n      newLength += whitespace.length;\n    }\n    if (newLength > maxLength) {\n      if (lineLength !== 0) {\n        lines.push(line.join(''));\n      }\n      line = [word];\n      lineLength = strlen(word);\n    } else {\n      line.push(whitespace || '', word);\n      lineLength = newLength;\n    }\n    whitespace = split[i + 1];\n  }\n  if (lineLength) {\n    lines.push(line.join(''));\n  }\n  return lines;\n}\n\n// Wrap text (ignoring word boundaries)\nfunction textWrap(maxLength, input) {\n  let lines = [];\n  let line = '';\n  function pushLine(str, ws) {\n    if (line.length && ws) line += ws;\n    line += str;\n    while (line.length > maxLength) {\n      lines.push(line.slice(0, maxLength));\n      line = line.slice(maxLength);\n    }\n  }\n  let split = input.split(/(\\s+)/g);\n  for (let i = 0; i < split.length; i += 2) {\n    pushLine(split[i], i && split[i - 1]);\n  }\n  if (line.length) lines.push(line);\n  return lines;\n}\n\nfunction multiLineWordWrap(maxLength, input, wrapOnWordBoundary = true) {\n  let output = [];\n  input = input.split('\\n');\n  const handler = wrapOnWordBoundary ? wordWrap : textWrap;\n  for (let i = 0; i < input.length; i++) {\n    output.push.apply(output, handler(maxLength, input[i]));\n  }\n  return output;\n}\n\nfunction colorizeLines(input) {\n  let state = {};\n  let output = [];\n  for (let i = 0; i < input.length; i++) {\n    let line = rewindState(state, input[i]);\n    state = readState(line);\n    let temp = Object.assign({}, state);\n    output.push(unwindState(temp, line));\n  }\n  return output;\n}\n\n/**\n * Credit: Matheus Sampaio https://github.com/matheussampaio\n */\nfunction hyperlink(url, text) {\n  const OSC = '\\u001B]';\n  const BEL = '\\u0007';\n  const SEP = ';';\n\n  return [OSC, '8', SEP, SEP, url || text, BEL, text, OSC, '8', SEP, SEP, BEL].join('');\n}\n\nmodule.exports = {\n  strlen: strlen,\n  repeat: repeat,\n  pad: pad,\n  truncate: truncate,\n  mergeOptions: mergeOptions,\n  wordWrap: multiLineWordWrap,\n  colorizeLines: colorizeLines,\n  hyperlink,\n};\n","/*\nThe MIT License (MIT)\n\nCopyright (c) Sindre Sorhus <sindresorhus@gmail.com> (sindresorhus.com)\n\nPermission is hereby granted, free of charge, to any person obtaining a copy\nof this software and associated documentation files (the \"Software\"), to deal\nin the Software without restriction, including without limitation the rights\nto use, copy, modify, merge, publish, distribute, sublicense, and/or sell\ncopies of the Software, and to permit persons to whom the Software is\nfurnished to do so, subject to the following conditions:\n\nThe above copyright notice and this permission notice shall be included in\nall copies or substantial portions of the Software.\n\nTHE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\nIMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\nFITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\nAUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\nLIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\nOUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN\nTHE SOFTWARE.\n\n*/\n\nvar styles = {};\nmodule['exports'] = styles;\n\nvar codes = {\n  reset: [0, 0],\n\n  bold: [1, 22],\n  dim: [2, 22],\n  italic: [3, 23],\n  underline: [4, 24],\n  inverse: [7, 27],\n  hidden: [8, 28],\n  strikethrough: [9, 29],\n\n  black: [30, 39],\n  red: [31, 39],\n  green: [32, 39],\n  yellow: [33, 39],\n  blue: [34, 39],\n  magenta: [35, 39],\n  cyan: [36, 39],\n  white: [37, 39],\n  gray: [90, 39],\n  grey: [90, 39],\n\n  brightRed: [91, 39],\n  brightGreen: [92, 39],\n  brightYellow: [93, 39],\n  brightBlue: [94, 39],\n  brightMagenta: [95, 39],\n  brightCyan: [96, 39],\n  brightWhite: [97, 39],\n\n  bgBlack: [40, 49],\n  bgRed: [41, 49],\n  bgGreen: [42, 49],\n  bgYellow: [43, 49],\n  bgBlue: [44, 49],\n  bgMagenta: [45, 49],\n  bgCyan: [46, 49],\n  bgWhite: [47, 49],\n  bgGray: [100, 49],\n  bgGrey: [100, 49],\n\n  bgBrightRed: [101, 49],\n  bgBrightGreen: [102, 49],\n  bgBrightYellow: [103, 49],\n  bgBrightBlue: [104, 49],\n  bgBrightMagenta: [105, 49],\n  bgBrightCyan: [106, 49],\n  bgBrightWhite: [107, 49],\n\n  // legacy styles for colors pre v1.0.0\n  blackBG: [40, 49],\n  redBG: [41, 49],\n  greenBG: [42, 49],\n  yellowBG: [43, 49],\n  blueBG: [44, 49],\n  magentaBG: [45, 49],\n  cyanBG: [46, 49],\n  whiteBG: [47, 49],\n\n};\n\nObject.keys(codes).forEach(function(key) {\n  var val = codes[key];\n  var style = styles[key] = [];\n  style.open = '\\u001b[' + val[0] + 'm';\n  style.close = '\\u001b[' + val[1] + 'm';\n});\n","/*\nMIT License\n\nCopyright (c) Sindre Sorhus <sindresorhus@gmail.com> (sindresorhus.com)\n\nPermission is hereby granted, free of charge, to any person obtaining a copy of\nthis software and associated documentation files (the \"Software\"), to deal in\nthe Software without restriction, including without limitation the rights to\nuse, copy, modify, merge, publish, distribute, sublicense, and/or sell copies\nof the Software, and to permit persons to whom the Software is furnished to do\nso, subject to the following conditions:\n\nThe above copyright notice and this permission notice shall be included in all\ncopies or substantial portions of the Software.\n\nTHE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\nIMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\nFITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\nAUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\nLIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\nOUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\nSOFTWARE.\n*/\n\n'use strict';\n\nmodule.exports = function(flag, argv) {\n  argv = argv || process.argv;\n\n  var terminatorPos = argv.indexOf('--');\n  var prefix = /^-{1,2}/.test(flag) ? '' : '--';\n  var pos = argv.indexOf(prefix + flag);\n\n  return pos !== -1 && (terminatorPos === -1 ? true : pos < terminatorPos);\n};\n","/*\nThe MIT License (MIT)\n\nCopyright (c) Sindre Sorhus <sindresorhus@gmail.com> (sindresorhus.com)\n\nPermission is hereby granted, free of charge, to any person obtaining a copy\nof this software and associated documentation files (the \"Software\"), to deal\nin the Software without restriction, including without limitation the rights\nto use, copy, modify, merge, publish, distribute, sublicense, and/or sell\ncopies of the Software, and to permit persons to whom the Software is\nfurnished to do so, subject to the following conditions:\n\nThe above copyright notice and this permission notice shall be included in\nall copies or substantial portions of the Software.\n\nTHE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\nIMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\nFITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\nAUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\nLIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\nOUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN\nTHE SOFTWARE.\n\n*/\n\n'use strict';\n\nvar os = require('os');\nvar hasFlag = require('./has-flag.js');\n\nvar env = process.env;\n\nvar forceColor = void 0;\nif (hasFlag('no-color') || hasFlag('no-colors') || hasFlag('color=false')) {\n  forceColor = false;\n} else if (hasFlag('color') || hasFlag('colors') || hasFlag('color=true')\n           || hasFlag('color=always')) {\n  forceColor = true;\n}\nif ('FORCE_COLOR' in env) {\n  forceColor = env.FORCE_COLOR.length === 0\n    || parseInt(env.FORCE_COLOR, 10) !== 0;\n}\n\nfunction translateLevel(level) {\n  if (level === 0) {\n    return false;\n  }\n\n  return {\n    level: level,\n    hasBasic: true,\n    has256: level >= 2,\n    has16m: level >= 3,\n  };\n}\n\nfunction supportsColor(stream) {\n  if (forceColor === false) {\n    return 0;\n  }\n\n  if (hasFlag('color=16m') || hasFlag('color=full')\n      || hasFlag('color=truecolor')) {\n    return 3;\n  }\n\n  if (hasFlag('color=256')) {\n    return 2;\n  }\n\n  if (stream && !stream.isTTY && forceColor !== true) {\n    return 0;\n  }\n\n  var min = forceColor ? 1 : 0;\n\n  if (process.platform === 'win32') {\n    // Node.js 7.5.0 is the first version of Node.js to include a patch to\n    // libuv that enables 256 color output on Windows. Anything earlier and it\n    // won't work. However, here we target Node.js 8 at minimum as it is an LTS\n    // release, and Node.js 7 is not. Windows 10 build 10586 is the first\n    // Windows release that supports 256 colors. Windows 10 build 14931 is the\n    // first release that supports 16m/TrueColor.\n    var osRelease = os.release().split('.');\n    if (Number(process.versions.node.split('.')[0]) >= 8\n        && Number(osRelease[0]) >= 10 && Number(osRelease[2]) >= 10586) {\n      return Number(osRelease[2]) >= 14931 ? 3 : 2;\n    }\n\n    return 1;\n  }\n\n  if ('CI' in env) {\n    if (['TRAVIS', 'CIRCLECI', 'APPVEYOR', 'GITLAB_CI'].some(function(sign) {\n      return sign in env;\n    }) || env.CI_NAME === 'codeship') {\n      return 1;\n    }\n\n    return min;\n  }\n\n  if ('TEAMCITY_VERSION' in env) {\n    return (/^(9\\.(0*[1-9]\\d*)\\.|\\d{2,}\\.)/.test(env.TEAMCITY_VERSION) ? 1 : 0\n    );\n  }\n\n  if ('TERM_PROGRAM' in env) {\n    var version = parseInt((env.TERM_PROGRAM_VERSION || '').split('.')[0], 10);\n\n    switch (env.TERM_PROGRAM) {\n      case 'iTerm.app':\n        return version >= 3 ? 3 : 2;\n      case 'Hyper':\n        return 3;\n      case 'Apple_Terminal':\n        return 2;\n      // No default\n    }\n  }\n\n  if (/-256(color)?$/i.test(env.TERM)) {\n    return 2;\n  }\n\n  if (/^screen|^xterm|^vt100|^rxvt|color|ansi|cygwin|linux/i.test(env.TERM)) {\n    return 1;\n  }\n\n  if ('COLORTERM' in env) {\n    return 1;\n  }\n\n  if (env.TERM === 'dumb') {\n    return min;\n  }\n\n  return min;\n}\n\nfunction getSupportLevel(stream) {\n  var level = supportsColor(stream);\n  return translateLevel(level);\n}\n\nmodule.exports = {\n  supportsColor: getSupportLevel,\n  stdout: getSupportLevel(process.stdout),\n  stderr: getSupportLevel(process.stderr),\n};\n","module['exports'] = function runTheTrap(text, options) {\n  var result = '';\n  text = text || 'Run the trap, drop the bass';\n  text = text.split('');\n  var trap = {\n    a: ['\\u0040', '\\u0104', '\\u023a', '\\u0245', '\\u0394', '\\u039b', '\\u0414'],\n    b: ['\\u00df', '\\u0181', '\\u0243', '\\u026e', '\\u03b2', '\\u0e3f'],\n    c: ['\\u00a9', '\\u023b', '\\u03fe'],\n    d: ['\\u00d0', '\\u018a', '\\u0500', '\\u0501', '\\u0502', '\\u0503'],\n    e: ['\\u00cb', '\\u0115', '\\u018e', '\\u0258', '\\u03a3', '\\u03be', '\\u04bc',\n      '\\u0a6c'],\n    f: ['\\u04fa'],\n    g: ['\\u0262'],\n    h: ['\\u0126', '\\u0195', '\\u04a2', '\\u04ba', '\\u04c7', '\\u050a'],\n    i: ['\\u0f0f'],\n    j: ['\\u0134'],\n    k: ['\\u0138', '\\u04a0', '\\u04c3', '\\u051e'],\n    l: ['\\u0139'],\n    m: ['\\u028d', '\\u04cd', '\\u04ce', '\\u0520', '\\u0521', '\\u0d69'],\n    n: ['\\u00d1', '\\u014b', '\\u019d', '\\u0376', '\\u03a0', '\\u048a'],\n    o: ['\\u00d8', '\\u00f5', '\\u00f8', '\\u01fe', '\\u0298', '\\u047a', '\\u05dd',\n      '\\u06dd', '\\u0e4f'],\n    p: ['\\u01f7', '\\u048e'],\n    q: ['\\u09cd'],\n    r: ['\\u00ae', '\\u01a6', '\\u0210', '\\u024c', '\\u0280', '\\u042f'],\n    s: ['\\u00a7', '\\u03de', '\\u03df', '\\u03e8'],\n    t: ['\\u0141', '\\u0166', '\\u0373'],\n    u: ['\\u01b1', '\\u054d'],\n    v: ['\\u05d8'],\n    w: ['\\u0428', '\\u0460', '\\u047c', '\\u0d70'],\n    x: ['\\u04b2', '\\u04fe', '\\u04fc', '\\u04fd'],\n    y: ['\\u00a5', '\\u04b0', '\\u04cb'],\n    z: ['\\u01b5', '\\u0240'],\n  };\n  text.forEach(function(c) {\n    c = c.toLowerCase();\n    var chars = trap[c] || [' '];\n    var rand = Math.floor(Math.random() * chars.length);\n    if (typeof trap[c] !== 'undefined') {\n      result += trap[c][rand];\n    } else {\n      result += c;\n    }\n  });\n  return result;\n};\n","// please no\nmodule['exports'] = function zalgo(text, options) {\n  text = text || '   he is here   ';\n  var soul = {\n    'up': [\n      '̍', '̎', '̄', '̅',\n      '̿', '̑', '̆', '̐',\n      '͒', '͗', '͑', '̇',\n      '̈', '̊', '͂', '̓',\n      '̈', '͊', '͋', '͌',\n      '̃', '̂', '̌', '͐',\n      '̀', '́', '̋', '̏',\n      '̒', '̓', '̔', '̽',\n      '̉', 'ͣ', 'ͤ', 'ͥ',\n      'ͦ', 'ͧ', 'ͨ', 'ͩ',\n      'ͪ', 'ͫ', 'ͬ', 'ͭ',\n      'ͮ', 'ͯ', '̾', '͛',\n      '͆', '̚',\n    ],\n    'down': [\n      '̖', '̗', '̘', '̙',\n      '̜', '̝', '̞', '̟',\n      '̠', '̤', '̥', '̦',\n      '̩', '̪', '̫', '̬',\n      '̭', '̮', '̯', '̰',\n      '̱', '̲', '̳', '̹',\n      '̺', '̻', '̼', 'ͅ',\n      '͇', '͈', '͉', '͍',\n      '͎', '͓', '͔', '͕',\n      '͖', '͙', '͚', '̣',\n    ],\n    'mid': [\n      '̕', '̛', '̀', '́',\n      '͘', '̡', '̢', '̧',\n      '̨', '̴', '̵', '̶',\n      '͜', '͝', '͞',\n      '͟', '͠', '͢', '̸',\n      '̷', '͡', ' ҉',\n    ],\n  };\n  var all = [].concat(soul.up, soul.down, soul.mid);\n\n  function randomNumber(range) {\n    var r = Math.floor(Math.random() * range);\n    return r;\n  }\n\n  function isChar(character) {\n    var bool = false;\n    all.filter(function(i) {\n      bool = (i === character);\n    });\n    return bool;\n  }\n\n\n  function heComes(text, options) {\n    var result = '';\n    var counts;\n    var l;\n    options = options || {};\n    options['up'] =\n      typeof options['up'] !== 'undefined' ? options['up'] : true;\n    options['mid'] =\n      typeof options['mid'] !== 'undefined' ? options['mid'] : true;\n    options['down'] =\n      typeof options['down'] !== 'undefined' ? options['down'] : true;\n    options['size'] =\n      typeof options['size'] !== 'undefined' ? options['size'] : 'maxi';\n    text = text.split('');\n    for (l in text) {\n      if (isChar(l)) {\n        continue;\n      }\n      result = result + text[l];\n      counts = {'up': 0, 'down': 0, 'mid': 0};\n      switch (options.size) {\n        case 'mini':\n          counts.up = randomNumber(8);\n          counts.mid = randomNumber(2);\n          counts.down = randomNumber(8);\n          break;\n        case 'maxi':\n          counts.up = randomNumber(16) + 3;\n          counts.mid = randomNumber(4) + 1;\n          counts.down = randomNumber(64) + 3;\n          break;\n        default:\n          counts.up = randomNumber(8) + 1;\n          counts.mid = randomNumber(6) / 2;\n          counts.down = randomNumber(8) + 1;\n          break;\n      }\n\n      var arr = ['up', 'mid', 'down'];\n      for (var d in arr) {\n        var index = arr[d];\n        for (var i = 0; i <= counts[index]; i++) {\n          if (options[index]) {\n            result = result + soul[index][randomNumber(soul[index].length)];\n          }\n        }\n      }\n    }\n    return result;\n  }\n  // don't summon him\n  return heComes(text, options);\n};\n\n","module['exports'] = function(colors) {\n  return function(letter, i, exploded) {\n    if (letter === ' ') return letter;\n    switch (i%3) {\n      case 0: return colors.red(letter);\n      case 1: return colors.white(letter);\n      case 2: return colors.blue(letter);\n    }\n  };\n};\n","module['exports'] = function(colors) {\n  return function(letter, i, exploded) {\n    return i % 2 === 0 ? letter : colors.inverse(letter);\n  };\n};\n","module['exports'] = function(colors) {\n  // RoY G BiV\n  var rainbowColors = ['red', 'yellow', 'green', 'blue', 'magenta'];\n  return function(letter, i, exploded) {\n    if (letter === ' ') {\n      return letter;\n    } else {\n      return colors[rainbowColors[i++ % rainbowColors.length]](letter);\n    }\n  };\n};\n\n","module['exports'] = function(colors) {\n  var available = ['underline', 'inverse', 'grey', 'yellow', 'red', 'green',\n    'blue', 'white', 'cyan', 'magenta', 'brightYellow', 'brightRed',\n    'brightGreen', 'brightBlue', 'brightWhite', 'brightCyan', 'brightMagenta'];\n  return function(letter, i, exploded) {\n    return letter === ' ' ? letter :\n      colors[\n          available[Math.round(Math.random() * (available.length - 2))]\n      ](letter);\n  };\n};\n","/*\n\nThe MIT License (MIT)\n\nOriginal Library\n  - Copyright (c) Marak Squires\n\nAdditional functionality\n - Copyright (c) Sindre Sorhus <sindresorhus@gmail.com> (sindresorhus.com)\n\nPermission is hereby granted, free of charge, to any person obtaining a copy\nof this software and associated documentation files (the \"Software\"), to deal\nin the Software without restriction, including without limitation the rights\nto use, copy, modify, merge, publish, distribute, sublicense, and/or sell\ncopies of the Software, and to permit persons to whom the Software is\nfurnished to do so, subject to the following conditions:\n\nThe above copyright notice and this permission notice shall be included in\nall copies or substantial portions of the Software.\n\nTHE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\nIMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\nFITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\nAUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\nLIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\nOUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN\nTHE SOFTWARE.\n\n*/\n\nvar colors = {};\nmodule['exports'] = colors;\n\ncolors.themes = {};\n\nvar util = require('util');\nvar ansiStyles = colors.styles = require('./styles');\nvar defineProps = Object.defineProperties;\nvar newLineRegex = new RegExp(/[\\r\\n]+/g);\n\ncolors.supportsColor = require('./system/supports-colors').supportsColor;\n\nif (typeof colors.enabled === 'undefined') {\n  colors.enabled = colors.supportsColor() !== false;\n}\n\ncolors.enable = function() {\n  colors.enabled = true;\n};\n\ncolors.disable = function() {\n  colors.enabled = false;\n};\n\ncolors.stripColors = colors.strip = function(str) {\n  return ('' + str).replace(/\\x1B\\[\\d+m/g, '');\n};\n\n// eslint-disable-next-line no-unused-vars\nvar stylize = colors.stylize = function stylize(str, style) {\n  if (!colors.enabled) {\n    return str+'';\n  }\n\n  var styleMap = ansiStyles[style];\n\n  // Stylize should work for non-ANSI styles, too\n  if (!styleMap && style in colors) {\n    // Style maps like trap operate as functions on strings;\n    // they don't have properties like open or close.\n    return colors[style](str);\n  }\n\n  return styleMap.open + str + styleMap.close;\n};\n\nvar matchOperatorsRe = /[|\\\\{}()[\\]^$+*?.]/g;\nvar escapeStringRegexp = function(str) {\n  if (typeof str !== 'string') {\n    throw new TypeError('Expected a string');\n  }\n  return str.replace(matchOperatorsRe, '\\\\$&');\n};\n\nfunction build(_styles) {\n  var builder = function builder() {\n    return applyStyle.apply(builder, arguments);\n  };\n  builder._styles = _styles;\n  // __proto__ is used because we must return a function, but there is\n  // no way to create a function with a different prototype.\n  builder.__proto__ = proto;\n  return builder;\n}\n\nvar styles = (function() {\n  var ret = {};\n  ansiStyles.grey = ansiStyles.gray;\n  Object.keys(ansiStyles).forEach(function(key) {\n    ansiStyles[key].closeRe =\n      new RegExp(escapeStringRegexp(ansiStyles[key].close), 'g');\n    ret[key] = {\n      get: function() {\n        return build(this._styles.concat(key));\n      },\n    };\n  });\n  return ret;\n})();\n\nvar proto = defineProps(function colors() {}, styles);\n\nfunction applyStyle() {\n  var args = Array.prototype.slice.call(arguments);\n\n  var str = args.map(function(arg) {\n    // Use weak equality check so we can colorize null/undefined in safe mode\n    if (arg != null && arg.constructor === String) {\n      return arg;\n    } else {\n      return util.inspect(arg);\n    }\n  }).join(' ');\n\n  if (!colors.enabled || !str) {\n    return str;\n  }\n\n  var newLinesPresent = str.indexOf('\\n') != -1;\n\n  var nestedStyles = this._styles;\n\n  var i = nestedStyles.length;\n  while (i--) {\n    var code = ansiStyles[nestedStyles[i]];\n    str = code.open + str.replace(code.closeRe, code.open) + code.close;\n    if (newLinesPresent) {\n      str = str.replace(newLineRegex, function(match) {\n        return code.close + match + code.open;\n      });\n    }\n  }\n\n  return str;\n}\n\ncolors.setTheme = function(theme) {\n  if (typeof theme === 'string') {\n    console.log('colors.setTheme now only accepts an object, not a string.  ' +\n      'If you are trying to set a theme from a file, it is now your (the ' +\n      'caller\\'s) responsibility to require the file.  The old syntax ' +\n      'looked like colors.setTheme(__dirname + ' +\n      '\\'/../themes/generic-logging.js\\'); The new syntax looks like '+\n      'colors.setTheme(require(__dirname + ' +\n      '\\'/../themes/generic-logging.js\\'));');\n    return;\n  }\n  for (var style in theme) {\n    (function(style) {\n      colors[style] = function(str) {\n        if (typeof theme[style] === 'object') {\n          var out = str;\n          for (var i in theme[style]) {\n            out = colors[theme[style][i]](out);\n          }\n          return out;\n        }\n        return colors[theme[style]](str);\n      };\n    })(style);\n  }\n};\n\nfunction init() {\n  var ret = {};\n  Object.keys(styles).forEach(function(name) {\n    ret[name] = {\n      get: function() {\n        return build([name]);\n      },\n    };\n  });\n  return ret;\n}\n\nvar sequencer = function sequencer(map, str) {\n  var exploded = str.split('');\n  exploded = exploded.map(map);\n  return exploded.join('');\n};\n\n// custom formatter methods\ncolors.trap = require('./custom/trap');\ncolors.zalgo = require('./custom/zalgo');\n\n// maps\ncolors.maps = {};\ncolors.maps.america = require('./maps/america')(colors);\ncolors.maps.zebra = require('./maps/zebra')(colors);\ncolors.maps.rainbow = require('./maps/rainbow')(colors);\ncolors.maps.random = require('./maps/random')(colors);\n\nfor (var map in colors.maps) {\n  (function(map) {\n    colors[map] = function(str) {\n      return sequencer(colors.maps[map], str);\n    };\n  })(map);\n}\n\ndefineProps(colors, init());\n","//\n// Remark: Requiring this file will use the \"safe\" colors API,\n// which will not touch String.prototype.\n//\n//   var colors = require('colors/safe');\n//   colors.red(\"foo\")\n//\n//\nvar colors = require('./lib/colors');\nmodule['exports'] = colors;\n","const { info, debug } = require('./debug');\nconst utils = require('./utils');\n\nclass Cell {\n  /**\n   * A representation of a cell within the table.\n   * Implementations must have `init` and `draw` methods,\n   * as well as `colSpan`, `rowSpan`, `desiredHeight` and `desiredWidth` properties.\n   * @param options\n   * @constructor\n   */\n  constructor(options) {\n    this.setOptions(options);\n\n    /**\n     * Each cell will have it's `x` and `y` values set by the `layout-manager` prior to\n     * `init` being called;\n     * @type {Number}\n     */\n    this.x = null;\n    this.y = null;\n  }\n\n  setOptions(options) {\n    if (['boolean', 'number', 'bigint', 'string'].indexOf(typeof options) !== -1) {\n      options = { content: '' + options };\n    }\n    options = options || {};\n    this.options = options;\n    let content = options.content;\n    if (['boolean', 'number', 'bigint', 'string'].indexOf(typeof content) !== -1) {\n      this.content = String(content);\n    } else if (!content) {\n      this.content = this.options.href || '';\n    } else {\n      throw new Error('Content needs to be a primitive, got: ' + typeof content);\n    }\n    this.colSpan = options.colSpan || 1;\n    this.rowSpan = options.rowSpan || 1;\n    if (this.options.href) {\n      Object.defineProperty(this, 'href', {\n        get() {\n          return this.options.href;\n        },\n      });\n    }\n  }\n\n  mergeTableOptions(tableOptions, cells) {\n    this.cells = cells;\n\n    let optionsChars = this.options.chars || {};\n    let tableChars = tableOptions.chars;\n    let chars = (this.chars = {});\n    CHAR_NAMES.forEach(function (name) {\n      setOption(optionsChars, tableChars, name, chars);\n    });\n\n    this.truncate = this.options.truncate || tableOptions.truncate;\n\n    let style = (this.options.style = this.options.style || {});\n    let tableStyle = tableOptions.style;\n    setOption(style, tableStyle, 'padding-left', this);\n    setOption(style, tableStyle, 'padding-right', this);\n    this.head = style.head || tableStyle.head;\n    this.border = style.border || tableStyle.border;\n\n    this.fixedWidth = tableOptions.colWidths[this.x];\n    this.lines = this.computeLines(tableOptions);\n\n    this.desiredWidth = utils.strlen(this.content) + this.paddingLeft + this.paddingRight;\n    this.desiredHeight = this.lines.length;\n  }\n\n  computeLines(tableOptions) {\n    const tableWordWrap = tableOptions.wordWrap || tableOptions.textWrap;\n    const { wordWrap = tableWordWrap } = this.options;\n    if (this.fixedWidth && wordWrap) {\n      this.fixedWidth -= this.paddingLeft + this.paddingRight;\n      if (this.colSpan) {\n        let i = 1;\n        while (i < this.colSpan) {\n          this.fixedWidth += tableOptions.colWidths[this.x + i];\n          i++;\n        }\n      }\n      const { wrapOnWordBoundary: tableWrapOnWordBoundary = true } = tableOptions;\n      const { wrapOnWordBoundary = tableWrapOnWordBoundary } = this.options;\n      return this.wrapLines(utils.wordWrap(this.fixedWidth, this.content, wrapOnWordBoundary));\n    }\n    return this.wrapLines(this.content.split('\\n'));\n  }\n\n  wrapLines(computedLines) {\n    const lines = utils.colorizeLines(computedLines);\n    if (this.href) {\n      return lines.map((line) => utils.hyperlink(this.href, line));\n    }\n    return lines;\n  }\n\n  /**\n   * Initializes the Cells data structure.\n   *\n   * @param tableOptions - A fully populated set of tableOptions.\n   * In addition to the standard default values, tableOptions must have fully populated the\n   * `colWidths` and `rowWidths` arrays. Those arrays must have lengths equal to the number\n   * of columns or rows (respectively) in this table, and each array item must be a Number.\n   *\n   */\n  init(tableOptions) {\n    let x = this.x;\n    let y = this.y;\n    this.widths = tableOptions.colWidths.slice(x, x + this.colSpan);\n    this.heights = tableOptions.rowHeights.slice(y, y + this.rowSpan);\n    this.width = this.widths.reduce(sumPlusOne, -1);\n    this.height = this.heights.reduce(sumPlusOne, -1);\n\n    this.hAlign = this.options.hAlign || tableOptions.colAligns[x];\n    this.vAlign = this.options.vAlign || tableOptions.rowAligns[y];\n\n    this.drawRight = x + this.colSpan == tableOptions.colWidths.length;\n  }\n\n  /**\n   * Draws the given line of the cell.\n   * This default implementation defers to methods `drawTop`, `drawBottom`, `drawLine` and `drawEmpty`.\n   * @param lineNum - can be `top`, `bottom` or a numerical line number.\n   * @param spanningCell - will be a number if being called from a RowSpanCell, and will represent how\n   * many rows below it's being called from. Otherwise it's undefined.\n   * @returns {String} The representation of this line.\n   */\n  draw(lineNum, spanningCell) {\n    if (lineNum == 'top') return this.drawTop(this.drawRight);\n    if (lineNum == 'bottom') return this.drawBottom(this.drawRight);\n    let content = utils.truncate(this.content, 10, this.truncate);\n    if (!lineNum) {\n      info(`${this.y}-${this.x}: ${this.rowSpan - lineNum}x${this.colSpan} Cell ${content}`);\n    } else {\n      // debug(`${lineNum}-${this.x}: 1x${this.colSpan} RowSpanCell ${content}`);\n    }\n    let padLen = Math.max(this.height - this.lines.length, 0);\n    let padTop;\n    switch (this.vAlign) {\n      case 'center':\n        padTop = Math.ceil(padLen / 2);\n        break;\n      case 'bottom':\n        padTop = padLen;\n        break;\n      default:\n        padTop = 0;\n    }\n    if (lineNum < padTop || lineNum >= padTop + this.lines.length) {\n      return this.drawEmpty(this.drawRight, spanningCell);\n    }\n    let forceTruncation = this.lines.length > this.height && lineNum + 1 >= this.height;\n    return this.drawLine(lineNum - padTop, this.drawRight, forceTruncation, spanningCell);\n  }\n\n  /**\n   * Renders the top line of the cell.\n   * @param drawRight - true if this method should render the right edge of the cell.\n   * @returns {String}\n   */\n  drawTop(drawRight) {\n    let content = [];\n    if (this.cells) {\n      //TODO: cells should always exist - some tests don't fill it in though\n      this.widths.forEach(function (width, index) {\n        content.push(this._topLeftChar(index));\n        content.push(utils.repeat(this.chars[this.y == 0 ? 'top' : 'mid'], width));\n      }, this);\n    } else {\n      content.push(this._topLeftChar(0));\n      content.push(utils.repeat(this.chars[this.y == 0 ? 'top' : 'mid'], this.width));\n    }\n    if (drawRight) {\n      content.push(this.chars[this.y == 0 ? 'topRight' : 'rightMid']);\n    }\n    return this.wrapWithStyleColors('border', content.join(''));\n  }\n\n  _topLeftChar(offset) {\n    let x = this.x + offset;\n    let leftChar;\n    if (this.y == 0) {\n      leftChar = x == 0 ? 'topLeft' : offset == 0 ? 'topMid' : 'top';\n    } else {\n      if (x == 0) {\n        leftChar = 'leftMid';\n      } else {\n        leftChar = offset == 0 ? 'midMid' : 'bottomMid';\n        if (this.cells) {\n          //TODO: cells should always exist - some tests don't fill it in though\n          let spanAbove = this.cells[this.y - 1][x] instanceof Cell.ColSpanCell;\n          if (spanAbove) {\n            leftChar = offset == 0 ? 'topMid' : 'mid';\n          }\n          if (offset == 0) {\n            let i = 1;\n            while (this.cells[this.y][x - i] instanceof Cell.ColSpanCell) {\n              i++;\n            }\n            if (this.cells[this.y][x - i] instanceof Cell.RowSpanCell) {\n              leftChar = 'leftMid';\n            }\n          }\n        }\n      }\n    }\n    return this.chars[leftChar];\n  }\n\n  wrapWithStyleColors(styleProperty, content) {\n    if (this[styleProperty] && this[styleProperty].length) {\n      try {\n        let colors = require('@colors/colors/safe');\n        for (let i = this[styleProperty].length - 1; i >= 0; i--) {\n          colors = colors[this[styleProperty][i]];\n        }\n        return colors(content);\n      } catch (e) {\n        return content;\n      }\n    } else {\n      return content;\n    }\n  }\n\n  /**\n   * Renders a line of text.\n   * @param lineNum - Which line of text to render. This is not necessarily the line within the cell.\n   * There may be top-padding above the first line of text.\n   * @param drawRight - true if this method should render the right edge of the cell.\n   * @param forceTruncationSymbol - `true` if the rendered text should end with the truncation symbol even\n   * if the text fits. This is used when the cell is vertically truncated. If `false` the text should\n   * only include the truncation symbol if the text will not fit horizontally within the cell width.\n   * @param spanningCell - a number of if being called from a RowSpanCell. (how many rows below). otherwise undefined.\n   * @returns {String}\n   */\n  drawLine(lineNum, drawRight, forceTruncationSymbol, spanningCell) {\n    let left = this.chars[this.x == 0 ? 'left' : 'middle'];\n    if (this.x && spanningCell && this.cells) {\n      let cellLeft = this.cells[this.y + spanningCell][this.x - 1];\n      while (cellLeft instanceof ColSpanCell) {\n        cellLeft = this.cells[cellLeft.y][cellLeft.x - 1];\n      }\n      if (!(cellLeft instanceof RowSpanCell)) {\n        left = this.chars['rightMid'];\n      }\n    }\n    let leftPadding = utils.repeat(' ', this.paddingLeft);\n    let right = drawRight ? this.chars['right'] : '';\n    let rightPadding = utils.repeat(' ', this.paddingRight);\n    let line = this.lines[lineNum];\n    let len = this.width - (this.paddingLeft + this.paddingRight);\n    if (forceTruncationSymbol) line += this.truncate || '…';\n    let content = utils.truncate(line, len, this.truncate);\n    content = utils.pad(content, len, ' ', this.hAlign);\n    content = leftPadding + content + rightPadding;\n    return this.stylizeLine(left, content, right);\n  }\n\n  stylizeLine(left, content, right) {\n    left = this.wrapWithStyleColors('border', left);\n    right = this.wrapWithStyleColors('border', right);\n    if (this.y === 0) {\n      content = this.wrapWithStyleColors('head', content);\n    }\n    return left + content + right;\n  }\n\n  /**\n   * Renders the bottom line of the cell.\n   * @param drawRight - true if this method should render the right edge of the cell.\n   * @returns {String}\n   */\n  drawBottom(drawRight) {\n    let left = this.chars[this.x == 0 ? 'bottomLeft' : 'bottomMid'];\n    let content = utils.repeat(this.chars.bottom, this.width);\n    let right = drawRight ? this.chars['bottomRight'] : '';\n    return this.wrapWithStyleColors('border', left + content + right);\n  }\n\n  /**\n   * Renders a blank line of text within the cell. Used for top and/or bottom padding.\n   * @param drawRight - true if this method should render the right edge of the cell.\n   * @param spanningCell - a number of if being called from a RowSpanCell. (how many rows below). otherwise undefined.\n   * @returns {String}\n   */\n  drawEmpty(drawRight, spanningCell) {\n    let left = this.chars[this.x == 0 ? 'left' : 'middle'];\n    if (this.x && spanningCell && this.cells) {\n      let cellLeft = this.cells[this.y + spanningCell][this.x - 1];\n      while (cellLeft instanceof ColSpanCell) {\n        cellLeft = this.cells[cellLeft.y][cellLeft.x - 1];\n      }\n      if (!(cellLeft instanceof RowSpanCell)) {\n        left = this.chars['rightMid'];\n      }\n    }\n    let right = drawRight ? this.chars['right'] : '';\n    let content = utils.repeat(' ', this.width);\n    return this.stylizeLine(left, content, right);\n  }\n}\n\nclass ColSpanCell {\n  /**\n   * A Cell that doesn't do anything. It just draws empty lines.\n   * Used as a placeholder in column spanning.\n   * @constructor\n   */\n  constructor() {}\n\n  draw(lineNum) {\n    if (typeof lineNum === 'number') {\n      debug(`${this.y}-${this.x}: 1x1 ColSpanCell`);\n    }\n    return '';\n  }\n\n  init() {}\n\n  mergeTableOptions() {}\n}\n\nclass RowSpanCell {\n  /**\n   * A placeholder Cell for a Cell that spans multiple rows.\n   * It delegates rendering to the original cell, but adds the appropriate offset.\n   * @param originalCell\n   * @constructor\n   */\n  constructor(originalCell) {\n    this.originalCell = originalCell;\n  }\n\n  init(tableOptions) {\n    let y = this.y;\n    let originalY = this.originalCell.y;\n    this.cellOffset = y - originalY;\n    this.offset = findDimension(tableOptions.rowHeights, originalY, this.cellOffset);\n  }\n\n  draw(lineNum) {\n    if (lineNum == 'top') {\n      return this.originalCell.draw(this.offset, this.cellOffset);\n    }\n    if (lineNum == 'bottom') {\n      return this.originalCell.draw('bottom');\n    }\n    debug(`${this.y}-${this.x}: 1x${this.colSpan} RowSpanCell for ${this.originalCell.content}`);\n    return this.originalCell.draw(this.offset + 1 + lineNum);\n  }\n\n  mergeTableOptions() {}\n}\n\nfunction firstDefined(...args) {\n  return args.filter((v) => v !== undefined && v !== null).shift();\n}\n\n// HELPER FUNCTIONS\nfunction setOption(objA, objB, nameB, targetObj) {\n  let nameA = nameB.split('-');\n  if (nameA.length > 1) {\n    nameA[1] = nameA[1].charAt(0).toUpperCase() + nameA[1].substr(1);\n    nameA = nameA.join('');\n    targetObj[nameA] = firstDefined(objA[nameA], objA[nameB], objB[nameA], objB[nameB]);\n  } else {\n    targetObj[nameB] = firstDefined(objA[nameB], objB[nameB]);\n  }\n}\n\nfunction findDimension(dimensionTable, startingIndex, span) {\n  let ret = dimensionTable[startingIndex];\n  for (let i = 1; i < span; i++) {\n    ret += 1 + dimensionTable[startingIndex + i];\n  }\n  return ret;\n}\n\nfunction sumPlusOne(a, b) {\n  return a + b + 1;\n}\n\nlet CHAR_NAMES = [\n  'top',\n  'top-mid',\n  'top-left',\n  'top-right',\n  'bottom',\n  'bottom-mid',\n  'bottom-left',\n  'bottom-right',\n  'left',\n  'left-mid',\n  'mid',\n  'mid-mid',\n  'right',\n  'right-mid',\n  'middle',\n];\n\nmodule.exports = Cell;\nmodule.exports.ColSpanCell = ColSpanCell;\nmodule.exports.RowSpanCell = RowSpanCell;\n","const { warn, debug } = require('./debug');\nconst Cell = require('./cell');\nconst { ColSpanCell, RowSpanCell } = Cell;\n\n(function () {\n  function next(alloc, col) {\n    if (alloc[col] > 0) {\n      return next(alloc, col + 1);\n    }\n    return col;\n  }\n\n  function layoutTable(table) {\n    let alloc = {};\n    table.forEach(function (row, rowIndex) {\n      let col = 0;\n      row.forEach(function (cell) {\n        cell.y = rowIndex;\n        // Avoid erroneous call to next() on first row\n        cell.x = rowIndex ? next(alloc, col) : col;\n        const rowSpan = cell.rowSpan || 1;\n        const colSpan = cell.colSpan || 1;\n        if (rowSpan > 1) {\n          for (let cs = 0; cs < colSpan; cs++) {\n            alloc[cell.x + cs] = rowSpan;\n          }\n        }\n        col = cell.x + colSpan;\n      });\n      Object.keys(alloc).forEach((idx) => {\n        alloc[idx]--;\n        if (alloc[idx] < 1) delete alloc[idx];\n      });\n    });\n  }\n\n  function maxWidth(table) {\n    let mw = 0;\n    table.forEach(function (row) {\n      row.forEach(function (cell) {\n        mw = Math.max(mw, cell.x + (cell.colSpan || 1));\n      });\n    });\n    return mw;\n  }\n\n  function maxHeight(table) {\n    return table.length;\n  }\n\n  function cellsConflict(cell1, cell2) {\n    let yMin1 = cell1.y;\n    let yMax1 = cell1.y - 1 + (cell1.rowSpan || 1);\n    let yMin2 = cell2.y;\n    let yMax2 = cell2.y - 1 + (cell2.rowSpan || 1);\n    let yConflict = !(yMin1 > yMax2 || yMin2 > yMax1);\n\n    let xMin1 = cell1.x;\n    let xMax1 = cell1.x - 1 + (cell1.colSpan || 1);\n    let xMin2 = cell2.x;\n    let xMax2 = cell2.x - 1 + (cell2.colSpan || 1);\n    let xConflict = !(xMin1 > xMax2 || xMin2 > xMax1);\n\n    return yConflict && xConflict;\n  }\n\n  function conflictExists(rows, x, y) {\n    let i_max = Math.min(rows.length - 1, y);\n    let cell = { x: x, y: y };\n    for (let i = 0; i <= i_max; i++) {\n      let row = rows[i];\n      for (let j = 0; j < row.length; j++) {\n        if (cellsConflict(cell, row[j])) {\n          return true;\n        }\n      }\n    }\n    return false;\n  }\n\n  function allBlank(rows, y, xMin, xMax) {\n    for (let x = xMin; x < xMax; x++) {\n      if (conflictExists(rows, x, y)) {\n        return false;\n      }\n    }\n    return true;\n  }\n\n  function addRowSpanCells(table) {\n    table.forEach(function (row, rowIndex) {\n      row.forEach(function (cell) {\n        for (let i = 1; i < cell.rowSpan; i++) {\n          let rowSpanCell = new RowSpanCell(cell);\n          rowSpanCell.x = cell.x;\n          rowSpanCell.y = cell.y + i;\n          rowSpanCell.colSpan = cell.colSpan;\n          insertCell(rowSpanCell, table[rowIndex + i]);\n        }\n      });\n    });\n  }\n\n  function addColSpanCells(cellRows) {\n    for (let rowIndex = cellRows.length - 1; rowIndex >= 0; rowIndex--) {\n      let cellColumns = cellRows[rowIndex];\n      for (let columnIndex = 0; columnIndex < cellColumns.length; columnIndex++) {\n        let cell = cellColumns[columnIndex];\n        for (let k = 1; k < cell.colSpan; k++) {\n          let colSpanCell = new ColSpanCell();\n          colSpanCell.x = cell.x + k;\n          colSpanCell.y = cell.y;\n          cellColumns.splice(columnIndex + 1, 0, colSpanCell);\n        }\n      }\n    }\n  }\n\n  function insertCell(cell, row) {\n    let x = 0;\n    while (x < row.length && row[x].x < cell.x) {\n      x++;\n    }\n    row.splice(x, 0, cell);\n  }\n\n  function fillInTable(table) {\n    let h_max = maxHeight(table);\n    let w_max = maxWidth(table);\n    debug(`Max rows: ${h_max}; Max cols: ${w_max}`);\n    for (let y = 0; y < h_max; y++) {\n      for (let x = 0; x < w_max; x++) {\n        if (!conflictExists(table, x, y)) {\n          let opts = { x: x, y: y, colSpan: 1, rowSpan: 1 };\n          x++;\n          while (x < w_max && !conflictExists(table, x, y)) {\n            opts.colSpan++;\n            x++;\n          }\n          let y2 = y + 1;\n          while (y2 < h_max && allBlank(table, y2, opts.x, opts.x + opts.colSpan)) {\n            opts.rowSpan++;\n            y2++;\n          }\n          let cell = new Cell(opts);\n          cell.x = opts.x;\n          cell.y = opts.y;\n          warn(`Missing cell at ${cell.y}-${cell.x}.`);\n          insertCell(cell, table[y]);\n        }\n      }\n    }\n  }\n\n  function generateCells(rows) {\n    return rows.map(function (row) {\n      if (!Array.isArray(row)) {\n        let key = Object.keys(row)[0];\n        row = row[key];\n        if (Array.isArray(row)) {\n          row = row.slice();\n          row.unshift(key);\n        } else {\n          row = [key, row];\n        }\n      }\n      return row.map(function (cell) {\n        return new Cell(cell);\n      });\n    });\n  }\n\n  function makeTableLayout(rows) {\n    let cellRows = generateCells(rows);\n    layoutTable(cellRows);\n    fillInTable(cellRows);\n    addRowSpanCells(cellRows);\n    addColSpanCells(cellRows);\n    return cellRows;\n  }\n\n  module.exports = {\n    makeTableLayout: makeTableLayout,\n    layoutTable: layoutTable,\n    addRowSpanCells: addRowSpanCells,\n    maxWidth: maxWidth,\n    fillInTable: fillInTable,\n    computeWidths: makeComputeWidths('colSpan', 'desiredWidth', 'x', 1),\n    computeHeights: makeComputeWidths('rowSpan', 'desiredHeight', 'y', 1),\n  };\n})();\n\nfunction makeComputeWidths(colSpan, desiredWidth, x, forcedMin) {\n  return function (vals, table) {\n    let result = [];\n    let spanners = [];\n    let auto = {};\n    table.forEach(function (row) {\n      row.forEach(function (cell) {\n        if ((cell[colSpan] || 1) > 1) {\n          spanners.push(cell);\n        } else {\n          result[cell[x]] = Math.max(result[cell[x]] || 0, cell[desiredWidth] || 0, forcedMin);\n        }\n      });\n    });\n\n    vals.forEach(function (val, index) {\n      if (typeof val === 'number') {\n        result[index] = val;\n      }\n    });\n\n    //spanners.forEach(function(cell){\n    for (let k = spanners.length - 1; k >= 0; k--) {\n      let cell = spanners[k];\n      let span = cell[colSpan];\n      let col = cell[x];\n      let existingWidth = result[col];\n      let editableCols = typeof vals[col] === 'number' ? 0 : 1;\n      if (typeof existingWidth === 'number') {\n        for (let i = 1; i < span; i++) {\n          existingWidth += 1 + result[col + i];\n          if (typeof vals[col + i] !== 'number') {\n            editableCols++;\n          }\n        }\n      } else {\n        existingWidth = desiredWidth === 'desiredWidth' ? cell.desiredWidth - 1 : 1;\n        if (!auto[col] || auto[col] < existingWidth) {\n          auto[col] = existingWidth;\n        }\n      }\n\n      if (cell[desiredWidth] > existingWidth) {\n        let i = 0;\n        while (editableCols > 0 && cell[desiredWidth] > existingWidth) {\n          if (typeof vals[col + i] !== 'number') {\n            let dif = Math.round((cell[desiredWidth] - existingWidth) / editableCols);\n            existingWidth += dif;\n            result[col + i] += dif;\n            editableCols--;\n          }\n          i++;\n        }\n      }\n    }\n\n    Object.assign(vals, result, auto);\n    for (let j = 0; j < vals.length; j++) {\n      vals[j] = Math.max(forcedMin, vals[j] || 0);\n    }\n  };\n}\n","const debug = require('./debug');\nconst utils = require('./utils');\nconst tableLayout = require('./layout-manager');\n\nclass Table extends Array {\n  constructor(opts) {\n    super();\n\n    const options = utils.mergeOptions(opts);\n    Object.defineProperty(this, 'options', {\n      value: options,\n      enumerable: options.debug,\n    });\n\n    if (options.debug) {\n      switch (typeof options.debug) {\n        case 'boolean':\n          debug.setDebugLevel(debug.WARN);\n          break;\n        case 'number':\n          debug.setDebugLevel(options.debug);\n          break;\n        case 'string':\n          debug.setDebugLevel(parseInt(options.debug, 10));\n          break;\n        default:\n          debug.setDebugLevel(debug.WARN);\n          debug.warn(`Debug option is expected to be boolean, number, or string. Received a ${typeof options.debug}`);\n      }\n      Object.defineProperty(this, 'messages', {\n        get() {\n          return debug.debugMessages();\n        },\n      });\n    }\n  }\n\n  toString() {\n    let array = this;\n    let headersPresent = this.options.head && this.options.head.length;\n    if (headersPresent) {\n      array = [this.options.head];\n      if (this.length) {\n        array.push.apply(array, this);\n      }\n    } else {\n      this.options.style.head = [];\n    }\n\n    let cells = tableLayout.makeTableLayout(array);\n\n    cells.forEach(function (row) {\n      row.forEach(function (cell) {\n        cell.mergeTableOptions(this.options, cells);\n      }, this);\n    }, this);\n\n    tableLayout.computeWidths(this.options.colWidths, cells);\n    tableLayout.computeHeights(this.options.rowHeights, cells);\n\n    cells.forEach(function (row) {\n      row.forEach(function (cell) {\n        cell.init(this.options);\n      }, this);\n    }, this);\n\n    let result = [];\n\n    for (let rowIndex = 0; rowIndex < cells.length; rowIndex++) {\n      let row = cells[rowIndex];\n      let heightOfRow = this.options.rowHeights[rowIndex];\n\n      if (rowIndex === 0 || !this.options.style.compact || (rowIndex == 1 && headersPresent)) {\n        doDraw(row, 'top', result);\n      }\n\n      for (let lineNum = 0; lineNum < heightOfRow; lineNum++) {\n        doDraw(row, lineNum, result);\n      }\n\n      if (rowIndex + 1 == cells.length) {\n        doDraw(row, 'bottom', result);\n      }\n    }\n\n    return result.join('\\n');\n  }\n\n  get width() {\n    let str = this.toString().split('\\n');\n    return str[0].length;\n  }\n}\n\nTable.reset = () => debug.reset();\n\nfunction doDraw(row, lineNum, result) {\n  let line = [];\n  row.forEach(function (cell) {\n    line.push(cell.draw(lineNum));\n  });\n  let str = line.join('');\n  if (str.length) result.push(str);\n}\n\nmodule.exports = Table;\n","module.exports = require('./src/table');","import Table from 'cli-table3'\nimport { theme } from './theme.js'\nimport { log } from './output.js'\n\nexport function renderTable(\n  headers: string[],\n  rows: string[][],\n  opts?: { emptyMessage?: string },\n): void {\n  if (rows.length === 0) {\n    log.muted(opts?.emptyMessage ?? 'No items found.')\n    return\n  }\n\n  const table = new Table({\n    head: headers.map((h) => theme.label(h)),\n    style: { 'padding-left': 1, 'padding-right': 1, border: [], head: [] },\n  })\n\n  for (const row of rows) {\n    table.push(row)\n  }\n\n  process.stderr.write(table.toString() + '\\n')\n}\n","import { defineCommand } from 'citty'\nimport { parseFileSpec } from '../utils/file-spec.js'\nimport { connectClient } from '../utils/connect.js'\nimport { resolveAuth } from '../utils/auth.js'\nimport { buildFastmcpManifest } from '../utils/manifest.js'\nimport { withSpinner } from '../ui/spinner.js'\nimport { output, setJsonMode } from '../ui/format.js'\nimport { log } from '../ui/output.js'\nimport { renderTable } from '../ui/table.js'\nimport { cliError, formatError, EXIT } from '../utils/error.js'\n\ndeclare const __FASTMCP_VERSION__: string\ndeclare const __MCP_SDK_VERSION__: string\n\nexport default defineCommand({\n  meta: { name: 'inspect', description: 'Inspect tools, resources, and prompts from an MCP server' },\n  args: {\n    url: { type: 'string', description: 'Server URL' },\n    command: { type: 'string', description: 'stdio server command' },\n    file: { type: 'string', description: 'Server file (e.g. server.ts)' },\n    export: { type: 'string', description: 'Named export to resolve (e.g. server); overrides file:export syntax' },\n    auth: { type: 'string', description: 'Bearer token' },\n    json: { type: 'boolean', description: 'Output JSON', default: false },\n    format: { type: 'string', description: 'Output format: fastmcp (the snake_case manifest the Python FastMCP CLI emits for --format fastmcp). Implies JSON output.' },\n    modern: { type: 'boolean', description: 'Deprecated no-op: auto-negotiation is the default on every transport', default: false },\n    legacy: { type: 'boolean', description: 'Force the legacy 2025 protocol era; skips the server/discover probe', default: false },\n    pin: { type: 'string', description: 'Pin the protocol era to this revision (e.g. 2026-07-28)' },\n  },\n  async run({ args }) {\n    if (args.format !== undefined && args.format !== 'fastmcp') {\n      cliError(`Unknown format \"${args.format}\". Supported formats: fastmcp`)\n    }\n    if (args.json || args.format) setJsonMode(true)\n    if (!args.url && !args.command && !args.file) {\n      cliError('Provide a server URL, --command <cmd>, or --file <file>')\n    }\n\n    const authObj = resolveAuth(args.auth)\n\n    let fileSpec\n    if (args.file) {\n      try {\n        fileSpec = parseFileSpec(args.file, args.export)\n      } catch (err) {\n        cliError(formatError(err))\n      }\n    }\n\n    const mode = args.file\n      ? { kind: 'inprocess' as const, spec: fileSpec! }\n      : args.command\n        ? { kind: 'stdio' as const, command: args.command }\n        : { kind: 'url' as const, url: args.url! }\n\n    const era = { modern: args.modern, legacy: args.legacy, pin: args.pin }\n\n    let client\n    try {\n      client = await withSpinner('Inspecting server…', () =>\n        connectClient(mode, authObj, era),\n      )\n    } catch (err) {\n      cliError(formatError(err), { code: EXIT.CONNECTION })\n    }\n\n    try {\n      if (args.format === 'fastmcp') {\n        const [tools, resources, templates, prompts] = await Promise.all([\n          client.listTools().catch(() => [] as Awaited<ReturnType<typeof client.listTools>>),\n          client.listResources().catch(() => [] as Awaited<ReturnType<typeof client.listResources>>),\n          client.listResourceTemplates().catch(() => [] as Awaited<ReturnType<typeof client.listResourceTemplates>>),\n          client.listPrompts().catch(() => [] as Awaited<ReturnType<typeof client.listPrompts>>),\n        ])\n\n        const manifest = buildFastmcpManifest({\n          serverInfo: client.getServerInfo(),\n          instructions: client.getInstructions(),\n          capabilities: client.getServerCapabilities(),\n          // A --file entrypoint is a FastMCP server (Python generation 2, the\n          // only case Python's inspect supports); over --url/--command the\n          // generation is unknowable from the wire.\n          generation: mode.kind === 'inprocess' ? 2 : null,\n          fastmcpVersion: __FASTMCP_VERSION__,\n          mcpVersion: __MCP_SDK_VERSION__,\n          tools,\n          prompts,\n          resources,\n          templates,\n        })\n\n        output(manifest, () => {})\n        return\n      }\n\n      const [tools, resources, prompts] = await Promise.all([\n        client.listTools().catch(() => [] as Awaited<ReturnType<typeof client.listTools>>),\n        client.listResources().catch(() => [] as Awaited<ReturnType<typeof client.listResources>>),\n        client.listPrompts().catch(() => [] as Awaited<ReturnType<typeof client.listPrompts>>),\n      ])\n\n      const data = { tools, resources, prompts }\n\n      output(data, ({ tools, resources, prompts }) => {\n        log.section(`Tools (${tools.length})`)\n        renderTable(\n          ['Name', 'Description'],\n          tools.map((t) => [t.name, t.description ?? '']),\n          { emptyMessage: 'No tools registered.' },\n        )\n\n        log.section(`Resources (${resources.length})`)\n        renderTable(\n          ['URI', 'Description'],\n          resources.map((r) => [r.uri, r.description ?? '']),\n          { emptyMessage: 'No resources registered.' },\n        )\n\n        log.section(`Prompts (${prompts.length})`)\n        renderTable(\n          ['Name', 'Description'],\n          prompts.map((p) => [p.name, p.description ?? '']),\n          { emptyMessage: 'No prompts registered.' },\n        )\n      })\n    } finally {\n      await client.close().catch(() => {})\n    }\n  },\n})\n","import { theme } from './theme.js'\n\ninterface JsonSchemaProperty {\n  type?: string\n  description?: string\n  enum?: unknown[]\n  [key: string]: unknown\n}\n\ninterface JsonSchema {\n  type?: string\n  properties?: Record<string, JsonSchemaProperty>\n  required?: string[]\n  [key: string]: unknown\n}\n\nexport function renderSchema(schema: JsonSchema, json: boolean): string {\n  if (json) {\n    return JSON.stringify(schema, null, 2)\n  }\n\n  const properties = schema.properties ?? {}\n  const required = new Set(schema.required ?? [])\n  const lines: string[] = []\n\n  for (const [name, prop] of Object.entries(properties)) {\n    const type = prop.type ?? 'any'\n    const req = required.has(name) ? theme.warning('required') : theme.muted('optional')\n    const desc = prop.enum\n      ? prop.enum.map((v) => JSON.stringify(v)).join(' | ')\n      : (prop.description ?? '')\n    lines.push(\n      `  ${theme.label(name.padEnd(16))} ${theme.code(String(type).padEnd(8))} ${req.padEnd(8 + 8)}  ${theme.muted(desc)}`,\n    )\n  }\n\n  return lines.length ? lines.join('\\n') : theme.muted('  (no parameters)')\n}\n","import { defineCommand } from 'citty'\nimport { connectClient } from '../utils/connect.js'\nimport { resolveAuth } from '../utils/auth.js'\nimport { parseFileSpec } from '../utils/file-spec.js'\nimport { withSpinner } from '../ui/spinner.js'\nimport { output, setJsonMode } from '../ui/format.js'\nimport { log } from '../ui/output.js'\nimport { renderTable } from '../ui/table.js'\nimport { renderSchema } from '../ui/schema.js'\nimport { cliError, formatError, EXIT } from '../utils/error.js'\n\nexport default defineCommand({\n  meta: { name: 'list', description: 'List tools, resources, and prompts from an MCP server' },\n  args: {\n    url: { type: 'string', description: 'Server URL' },\n    command: { type: 'string', description: 'stdio server command' },\n    file: { type: 'string', description: 'Server file (e.g. server.ts)' },\n    export: { type: 'string', description: 'Named export to resolve (e.g. server); overrides file:export syntax' },\n    auth: { type: 'string', description: 'Bearer token' },\n    resources: { type: 'boolean', description: 'Also list resources', default: false },\n    prompts: { type: 'boolean', description: 'Also list prompts', default: false },\n    'input-schema': { type: 'boolean', description: 'Expand input schemas', default: false },\n    json: { type: 'boolean', description: 'Output JSON', default: false },\n    modern: { type: 'boolean', description: 'Deprecated no-op: auto-negotiation is the default on every transport', default: false },\n    legacy: { type: 'boolean', description: 'Force the legacy 2025 protocol era; skips the server/discover probe', default: false },\n    pin: { type: 'string', description: 'Pin the protocol era to this revision (e.g. 2026-07-28)' },\n  },\n  async run({ args }) {\n    if (args.json) setJsonMode(true)\n    if (!args.url && !args.command && !args.file) {\n      cliError('Provide a server URL, --command <cmd>, or --file <file>')\n    }\n\n    const authObj = resolveAuth(args.auth)\n\n    let fileSpec\n    if (args.file) {\n      try {\n        fileSpec = parseFileSpec(args.file, args.export)\n      } catch (err) {\n        cliError(formatError(err))\n      }\n    }\n\n    const mode = args.file\n      ? { kind: 'inprocess' as const, spec: fileSpec! }\n      : args.command\n        ? { kind: 'stdio' as const, command: args.command }\n        : { kind: 'url' as const, url: args.url! }\n\n    const era = { modern: args.modern, legacy: args.legacy, pin: args.pin }\n\n    let client\n    try {\n      client = await withSpinner('Connecting to server…', () =>\n        connectClient(mode, authObj, era),\n      )\n    } catch (err) {\n      cliError(formatError(err), { code: EXIT.CONNECTION })\n    }\n\n    try {\n      const tools = await withSpinner('Fetching tools…', () => client.listTools())\n      const resources = args.resources\n        ? await withSpinner('Fetching resources…', () => client.listResources())\n        : []\n      const prompts = args.prompts\n        ? await withSpinner('Fetching prompts…', () => client.listPrompts())\n        : []\n\n      const data = { tools, resources, prompts }\n\n      output(data, ({ tools, resources, prompts }) => {\n        const showInputSchema = args['input-schema']\n\n        log.section(`Tools (${tools.length})`)\n        if (showInputSchema) {\n          for (const tool of tools) {\n            log.kv(tool.name, tool.description ?? '')\n            if (tool.inputSchema) {\n              process.stderr.write(renderSchema(tool.inputSchema as Parameters<typeof renderSchema>[0], false) + '\\n')\n            }\n          }\n        } else {\n          renderTable(\n            ['Name', 'Description'],\n            tools.map((t) => [t.name, t.description ?? '']),\n            { emptyMessage: 'No tools.' },\n          )\n        }\n\n        if (resources.length > 0 || args.resources) {\n          log.section(`Resources (${resources.length})`)\n          renderTable(\n            ['URI', 'Description'],\n            resources.map((r) => [r.uri, r.description ?? '']),\n            { emptyMessage: 'No resources.' },\n          )\n        }\n\n        if (prompts.length > 0 || args.prompts) {\n          log.section(`Prompts (${prompts.length})`)\n          renderTable(\n            ['Name', 'Description'],\n            prompts.map((p) => [p.name, p.description ?? '']),\n            { emptyMessage: 'No prompts.' },\n          )\n        }\n      })\n    } finally {\n      await client.close().catch(() => {})\n    }\n  },\n})\n","const peq = new Uint32Array(0x10000);\nconst myers_32 = (a, b) => {\n    const n = a.length;\n    const m = b.length;\n    const lst = 1 << (n - 1);\n    let pv = -1;\n    let mv = 0;\n    let sc = n;\n    let i = n;\n    while (i--) {\n        peq[a.charCodeAt(i)] |= 1 << i;\n    }\n    for (i = 0; i < m; i++) {\n        let eq = peq[b.charCodeAt(i)];\n        const xv = eq | mv;\n        eq |= ((eq & pv) + pv) ^ pv;\n        mv |= ~(eq | pv);\n        pv &= eq;\n        if (mv & lst) {\n            sc++;\n        }\n        if (pv & lst) {\n            sc--;\n        }\n        mv = (mv << 1) | 1;\n        pv = (pv << 1) | ~(xv | mv);\n        mv &= xv;\n    }\n    i = n;\n    while (i--) {\n        peq[a.charCodeAt(i)] = 0;\n    }\n    return sc;\n};\nconst myers_x = (b, a) => {\n    const n = a.length;\n    const m = b.length;\n    const mhc = [];\n    const phc = [];\n    const hsize = Math.ceil(n / 32);\n    const vsize = Math.ceil(m / 32);\n    for (let i = 0; i < hsize; i++) {\n        phc[i] = -1;\n        mhc[i] = 0;\n    }\n    let j = 0;\n    for (; j < vsize - 1; j++) {\n        let mv = 0;\n        let pv = -1;\n        const start = j * 32;\n        const vlen = Math.min(32, m) + start;\n        for (let k = start; k < vlen; k++) {\n            peq[b.charCodeAt(k)] |= 1 << k;\n        }\n        for (let i = 0; i < n; i++) {\n            const eq = peq[a.charCodeAt(i)];\n            const pb = (phc[(i / 32) | 0] >>> i) & 1;\n            const mb = (mhc[(i / 32) | 0] >>> i) & 1;\n            const xv = eq | mv;\n            const xh = ((((eq | mb) & pv) + pv) ^ pv) | eq | mb;\n            let ph = mv | ~(xh | pv);\n            let mh = pv & xh;\n            if ((ph >>> 31) ^ pb) {\n                phc[(i / 32) | 0] ^= 1 << i;\n            }\n            if ((mh >>> 31) ^ mb) {\n                mhc[(i / 32) | 0] ^= 1 << i;\n            }\n            ph = (ph << 1) | pb;\n            mh = (mh << 1) | mb;\n            pv = mh | ~(xv | ph);\n            mv = ph & xv;\n        }\n        for (let k = start; k < vlen; k++) {\n            peq[b.charCodeAt(k)] = 0;\n        }\n    }\n    let mv = 0;\n    let pv = -1;\n    const start = j * 32;\n    const vlen = Math.min(32, m - start) + start;\n    for (let k = start; k < vlen; k++) {\n        peq[b.charCodeAt(k)] |= 1 << k;\n    }\n    let score = m;\n    for (let i = 0; i < n; i++) {\n        const eq = peq[a.charCodeAt(i)];\n        const pb = (phc[(i / 32) | 0] >>> i) & 1;\n        const mb = (mhc[(i / 32) | 0] >>> i) & 1;\n        const xv = eq | mv;\n        const xh = ((((eq | mb) & pv) + pv) ^ pv) | eq | mb;\n        let ph = mv | ~(xh | pv);\n        let mh = pv & xh;\n        score += (ph >>> (m - 1)) & 1;\n        score -= (mh >>> (m - 1)) & 1;\n        if ((ph >>> 31) ^ pb) {\n            phc[(i / 32) | 0] ^= 1 << i;\n        }\n        if ((mh >>> 31) ^ mb) {\n            mhc[(i / 32) | 0] ^= 1 << i;\n        }\n        ph = (ph << 1) | pb;\n        mh = (mh << 1) | mb;\n        pv = mh | ~(xv | ph);\n        mv = ph & xv;\n    }\n    for (let k = start; k < vlen; k++) {\n        peq[b.charCodeAt(k)] = 0;\n    }\n    return score;\n};\nconst distance = (a, b) => {\n    if (a.length < b.length) {\n        const tmp = b;\n        b = a;\n        a = tmp;\n    }\n    if (b.length === 0) {\n        return a.length;\n    }\n    if (a.length <= 32) {\n        return myers_32(a, b);\n    }\n    return myers_x(a, b);\n};\nconst closest = (str, arr) => {\n    let min_distance = Infinity;\n    let min_index = 0;\n    for (let i = 0; i < arr.length; i++) {\n        const dist = distance(str, arr[i]);\n        if (dist < min_distance) {\n            min_distance = dist;\n            min_index = i;\n        }\n    }\n    return arr[min_index];\n};\nexport { closest, distance };\n","import { distance } from 'fastest-levenshtein'\n\nconst SUGGESTION_THRESHOLD = 4\n\nexport function findSuggestions(query: string, candidates: string[]): string[] {\n  return candidates\n    .map((c) => ({ name: c, dist: distance(query, c) }))\n    .filter(({ dist }) => dist <= SUGGESTION_THRESHOLD)\n    .sort((a, b) => a.dist - b.dist)\n    .map(({ name }) => name)\n}\n\nexport function closestMatch(query: string, candidates: string[]): string | undefined {\n  const suggestions = findSuggestions(query, candidates)\n  return suggestions[0]\n}\n","import { defineCommand } from 'citty'\nimport { connectClient } from '../utils/connect.js'\nimport { resolveAuth } from '../utils/auth.js'\nimport { parseFileSpec } from '../utils/file-spec.js'\nimport { withSpinner } from '../ui/spinner.js'\nimport { output, setJsonMode } from '../ui/format.js'\nimport { log } from '../ui/output.js'\nimport { theme } from '../ui/theme.js'\nimport { cliError, formatError, EXIT } from '../utils/error.js'\nimport { closestMatch } from '../utils/fuzzy.js'\n\nfunction parseKvArgs(rawArgs: string[]): Record<string, unknown> {\n  const result: Record<string, unknown> = {}\n  for (const arg of rawArgs) {\n    const idx = arg.indexOf('=')\n    if (idx === -1) {\n      result[arg] = true\n      continue\n    }\n    const key = arg.slice(0, idx)\n    const raw = arg.slice(idx + 1)\n    try {\n      result[key] = JSON.parse(raw)\n    } catch {\n      result[key] = raw\n    }\n  }\n  return result\n}\n\ntype JsonSchema = { properties?: Record<string, { type?: string | string[] }>; [k: string]: unknown }\n\n// Coerce kv-parsed values to match the declared schema types.\n// JSON.parse turns bare \"1\" into a number; if the schema says string, convert it back.\nfunction coerceToSchema(input: Record<string, unknown>, schema: JsonSchema): Record<string, unknown> {\n  const props = schema.properties\n  if (!props) return input\n  const out: Record<string, unknown> = { ...input }\n  for (const [key, value] of Object.entries(out)) {\n    const prop = props[key]\n    if (!prop) continue\n    const types = ([] as string[]).concat(prop.type ?? [])\n    if (types.includes('string') && typeof value !== 'string') {\n      out[key] = String(value)\n    } else if (types.includes('number') && typeof value === 'string' && value !== '' && !isNaN(Number(value))) {\n      out[key] = Number(value)\n    } else if (types.includes('integer') && typeof value === 'string' && value !== '' && Number.isInteger(Number(value))) {\n      out[key] = Number(value)\n    }\n  }\n  return out\n}\n\nexport default defineCommand({\n  meta: { name: 'call', description: 'Call a tool, resource, or prompt on an MCP server' },\n  args: {\n    target: { type: 'positional', description: 'Tool name, resource URI, or prompt name', required: true },\n    url: { type: 'string', description: 'Server URL' },\n    command: { type: 'string', description: 'stdio server command' },\n    file: { type: 'string', description: 'Server file (e.g. server.ts)' },\n    export: { type: 'string', description: 'Named export to resolve (e.g. server); overrides file:export syntax' },\n    auth: { type: 'string', description: 'Bearer token' },\n    'input-json': { type: 'string', description: 'Raw JSON input instead of key=value args' },\n    json: { type: 'boolean', description: 'Output JSON', default: false },\n    modern: { type: 'boolean', description: 'Deprecated no-op: auto-negotiation is the default on every transport', default: false },\n    legacy: { type: 'boolean', description: 'Force the legacy 2025 protocol era; skips the server/discover probe', default: false },\n    pin: { type: 'string', description: 'Pin the protocol era to this revision (e.g. 2026-07-28)' },\n  },\n  async run({ args, rawArgs }) {\n    if (args.json) setJsonMode(true)\n    if (!args.url && !args.command && !args.file) {\n      cliError('Provide --url <url>, --command <cmd>, or --file <file>')\n    }\n\n    const authObj = resolveAuth(args.auth)\n\n    let fileSpec\n    if (args.file) {\n      try {\n        fileSpec = parseFileSpec(args.file, args.export)\n      } catch (err) {\n        cliError(formatError(err))\n      }\n    }\n\n    const mode = args.file\n      ? { kind: 'inprocess' as const, spec: fileSpec! }\n      : args.command\n        ? { kind: 'stdio' as const, command: args.command }\n        : { kind: 'url' as const, url: args.url! }\n\n    const era = { modern: args.modern, legacy: args.legacy, pin: args.pin }\n\n    let client\n    try {\n      client = await withSpinner('Connecting to server…', () =>\n        connectClient(mode, authObj, era),\n      )\n    } catch (err) {\n      cliError(formatError(err), { code: EXIT.CONNECTION })\n    }\n\n    const [tools, resources, prompts] = await Promise.all([\n      client.listTools().catch(() => [] as Awaited<ReturnType<typeof client.listTools>>),\n      client.listResources().catch(() => [] as Awaited<ReturnType<typeof client.listResources>>),\n      client.listPrompts().catch(() => [] as Awaited<ReturnType<typeof client.listPrompts>>),\n    ])\n\n    const target = args.target\n\n    const matchedTool = tools.find((t) => t.name === target)\n    const matchedResource = resources.find((r) => r.uri === target)\n    const matchedPrompt = prompts.find((p) => p.name === target)\n\n    if (!matchedTool && !matchedResource && !matchedPrompt) {\n      const allNames = [\n        ...tools.map((t) => t.name),\n        ...resources.map((r) => r.uri),\n        ...prompts.map((p) => p.name),\n      ]\n      const suggestion = closestMatch(target, allNames)\n      cliError(\n        `No tool, resource, or prompt named \"${target}\".`,\n        { hint: suggestion ? `Did you mean \"${suggestion}\"?` : undefined },\n      )\n    }\n\n    // String-valued flags only: boolean flags (--modern, --legacy, --json)\n    // carry no separate value token, so they never appear in rawArgs as a\n    // bare word to exclude from key=value parsing.\n    const flagValues = new Set([target, args.url, args.command, args.file, args.export, args.auth, args['input-json'], args.pin].filter(Boolean) as string[])\n    const kvRaw = (rawArgs as string[]).filter((a) => !a.startsWith('-') && !flagValues.has(a))\n    let input: Record<string, unknown> = args['input-json']\n      ? (JSON.parse(args['input-json']) as Record<string, unknown>)\n      : parseKvArgs(kvRaw)\n    if (matchedTool?.inputSchema) {\n      input = coerceToSchema(input, matchedTool.inputSchema as JsonSchema)\n    }\n\n    try {\n      if (matchedTool) {\n        const result = await withSpinner(`Calling ${target}…`, () =>\n          client.callTool(target, input),\n        )\n\n        output(result, (r) => {\n          for (const block of r.content) {\n            if (block.type === 'text') {\n              log.raw(block.text)\n            } else {\n              log.raw(JSON.stringify(block, null, 2))\n            }\n          }\n        })\n      } else if (matchedResource) {\n        const result = await withSpinner(`Reading resource ${target}…`, () =>\n          client.readResource(target),\n        )\n\n        output(result, (r) => {\n          for (const content of r) {\n            if ('text' in content) {\n              log.raw(content.text as string)\n            } else {\n              process.stderr.write(theme.muted(`[binary resource, ${content.mimeType ?? 'unknown mime'}]\\n`))\n            }\n          }\n        })\n      } else if (matchedPrompt) {\n        const result = await withSpinner(`Getting prompt ${target}…`, () =>\n          client.getPrompt(target, input as Record<string, string>),\n        )\n\n        output(result, (r) => {\n          for (const msg of r.messages) {\n            const role = theme.label(msg.role + ':')\n            const content = typeof msg.content === 'string'\n              ? msg.content\n              : JSON.stringify(msg.content, null, 2)\n            log.raw(`${role} ${content}`)\n          }\n        })\n      }\n    } catch (err) {\n      cliError(formatError(err), { code: EXIT.SERVER })\n    } finally {\n      await client.close().catch(() => {})\n    }\n  },\n})\n","'use strict';\n\nconst ALIAS = Symbol.for('yaml.alias');\nconst DOC = Symbol.for('yaml.document');\nconst MAP = Symbol.for('yaml.map');\nconst PAIR = Symbol.for('yaml.pair');\nconst SCALAR = Symbol.for('yaml.scalar');\nconst SEQ = Symbol.for('yaml.seq');\nconst NODE_TYPE = Symbol.for('yaml.node.type');\nconst isAlias = (node) => !!node && typeof node === 'object' && node[NODE_TYPE] === ALIAS;\nconst isDocument = (node) => !!node && typeof node === 'object' && node[NODE_TYPE] === DOC;\nconst isMap = (node) => !!node && typeof node === 'object' && node[NODE_TYPE] === MAP;\nconst isPair = (node) => !!node && typeof node === 'object' && node[NODE_TYPE] === PAIR;\nconst isScalar = (node) => !!node && typeof node === 'object' && node[NODE_TYPE] === SCALAR;\nconst isSeq = (node) => !!node && typeof node === 'object' && node[NODE_TYPE] === SEQ;\nfunction isCollection(node) {\n    if (node && typeof node === 'object')\n        switch (node[NODE_TYPE]) {\n            case MAP:\n            case SEQ:\n                return true;\n        }\n    return false;\n}\nfunction isNode(node) {\n    if (node && typeof node === 'object')\n        switch (node[NODE_TYPE]) {\n            case ALIAS:\n            case MAP:\n            case SCALAR:\n            case SEQ:\n                return true;\n        }\n    return false;\n}\nconst hasAnchor = (node) => (isScalar(node) || isCollection(node)) && !!node.anchor;\n\nexports.ALIAS = ALIAS;\nexports.DOC = DOC;\nexports.MAP = MAP;\nexports.NODE_TYPE = NODE_TYPE;\nexports.PAIR = PAIR;\nexports.SCALAR = SCALAR;\nexports.SEQ = SEQ;\nexports.hasAnchor = hasAnchor;\nexports.isAlias = isAlias;\nexports.isCollection = isCollection;\nexports.isDocument = isDocument;\nexports.isMap = isMap;\nexports.isNode = isNode;\nexports.isPair = isPair;\nexports.isScalar = isScalar;\nexports.isSeq = isSeq;\n","'use strict';\n\nvar identity = require('./nodes/identity.js');\n\nconst BREAK = Symbol('break visit');\nconst SKIP = Symbol('skip children');\nconst REMOVE = Symbol('remove node');\n/**\n * Apply a visitor to an AST node or document.\n *\n * Walks through the tree (depth-first) starting from `node`, calling a\n * `visitor` function with three arguments:\n *   - `key`: For sequence values and map `Pair`, the node's index in the\n *     collection. Within a `Pair`, `'key'` or `'value'`, correspondingly.\n *     `null` for the root node.\n *   - `node`: The current node.\n *   - `path`: The ancestry of the current node.\n *\n * The return value of the visitor may be used to control the traversal:\n *   - `undefined` (default): Do nothing and continue\n *   - `visit.SKIP`: Do not visit the children of this node, continue with next\n *     sibling\n *   - `visit.BREAK`: Terminate traversal completely\n *   - `visit.REMOVE`: Remove the current node, then continue with the next one\n *   - `Node`: Replace the current node, then continue by visiting it\n *   - `number`: While iterating the items of a sequence or map, set the index\n *     of the next step. This is useful especially if the index of the current\n *     node has changed.\n *\n * If `visitor` is a single function, it will be called with all values\n * encountered in the tree, including e.g. `null` values. Alternatively,\n * separate visitor functions may be defined for each `Map`, `Pair`, `Seq`,\n * `Alias` and `Scalar` node. To define the same visitor function for more than\n * one node type, use the `Collection` (map and seq), `Value` (map, seq & scalar)\n * and `Node` (alias, map, seq & scalar) targets. Of all these, only the most\n * specific defined one will be used for each node.\n */\nfunction visit(node, visitor) {\n    const visitor_ = initVisitor(visitor);\n    if (identity.isDocument(node)) {\n        const cd = visit_(null, node.contents, visitor_, Object.freeze([node]));\n        if (cd === REMOVE)\n            node.contents = null;\n    }\n    else\n        visit_(null, node, visitor_, Object.freeze([]));\n}\n// Without the `as symbol` casts, TS declares these in the `visit`\n// namespace using `var`, but then complains about that because\n// `unique symbol` must be `const`.\n/** Terminate visit traversal completely */\nvisit.BREAK = BREAK;\n/** Do not visit the children of the current node */\nvisit.SKIP = SKIP;\n/** Remove the current node */\nvisit.REMOVE = REMOVE;\nfunction visit_(key, node, visitor, path) {\n    const ctrl = callVisitor(key, node, visitor, path);\n    if (identity.isNode(ctrl) || identity.isPair(ctrl)) {\n        replaceNode(key, path, ctrl);\n        return visit_(key, ctrl, visitor, path);\n    }\n    if (typeof ctrl !== 'symbol') {\n        if (identity.isCollection(node)) {\n            path = Object.freeze(path.concat(node));\n            for (let i = 0; i < node.items.length; ++i) {\n                const ci = visit_(i, node.items[i], visitor, path);\n                if (typeof ci === 'number')\n                    i = ci - 1;\n                else if (ci === BREAK)\n                    return BREAK;\n                else if (ci === REMOVE) {\n                    node.items.splice(i, 1);\n                    i -= 1;\n                }\n            }\n        }\n        else if (identity.isPair(node)) {\n            path = Object.freeze(path.concat(node));\n            const ck = visit_('key', node.key, visitor, path);\n            if (ck === BREAK)\n                return BREAK;\n            else if (ck === REMOVE)\n                node.key = null;\n            const cv = visit_('value', node.value, visitor, path);\n            if (cv === BREAK)\n                return BREAK;\n            else if (cv === REMOVE)\n                node.value = null;\n        }\n    }\n    return ctrl;\n}\n/**\n * Apply an async visitor to an AST node or document.\n *\n * Walks through the tree (depth-first) starting from `node`, calling a\n * `visitor` function with three arguments:\n *   - `key`: For sequence values and map `Pair`, the node's index in the\n *     collection. Within a `Pair`, `'key'` or `'value'`, correspondingly.\n *     `null` for the root node.\n *   - `node`: The current node.\n *   - `path`: The ancestry of the current node.\n *\n * The return value of the visitor may be used to control the traversal:\n *   - `Promise`: Must resolve to one of the following values\n *   - `undefined` (default): Do nothing and continue\n *   - `visit.SKIP`: Do not visit the children of this node, continue with next\n *     sibling\n *   - `visit.BREAK`: Terminate traversal completely\n *   - `visit.REMOVE`: Remove the current node, then continue with the next one\n *   - `Node`: Replace the current node, then continue by visiting it\n *   - `number`: While iterating the items of a sequence or map, set the index\n *     of the next step. This is useful especially if the index of the current\n *     node has changed.\n *\n * If `visitor` is a single function, it will be called with all values\n * encountered in the tree, including e.g. `null` values. Alternatively,\n * separate visitor functions may be defined for each `Map`, `Pair`, `Seq`,\n * `Alias` and `Scalar` node. To define the same visitor function for more than\n * one node type, use the `Collection` (map and seq), `Value` (map, seq & scalar)\n * and `Node` (alias, map, seq & scalar) targets. Of all these, only the most\n * specific defined one will be used for each node.\n */\nasync function visitAsync(node, visitor) {\n    const visitor_ = initVisitor(visitor);\n    if (identity.isDocument(node)) {\n        const cd = await visitAsync_(null, node.contents, visitor_, Object.freeze([node]));\n        if (cd === REMOVE)\n            node.contents = null;\n    }\n    else\n        await visitAsync_(null, node, visitor_, Object.freeze([]));\n}\n// Without the `as symbol` casts, TS declares these in the `visit`\n// namespace using `var`, but then complains about that because\n// `unique symbol` must be `const`.\n/** Terminate visit traversal completely */\nvisitAsync.BREAK = BREAK;\n/** Do not visit the children of the current node */\nvisitAsync.SKIP = SKIP;\n/** Remove the current node */\nvisitAsync.REMOVE = REMOVE;\nasync function visitAsync_(key, node, visitor, path) {\n    const ctrl = await callVisitor(key, node, visitor, path);\n    if (identity.isNode(ctrl) || identity.isPair(ctrl)) {\n        replaceNode(key, path, ctrl);\n        return visitAsync_(key, ctrl, visitor, path);\n    }\n    if (typeof ctrl !== 'symbol') {\n        if (identity.isCollection(node)) {\n            path = Object.freeze(path.concat(node));\n            for (let i = 0; i < node.items.length; ++i) {\n                const ci = await visitAsync_(i, node.items[i], visitor, path);\n                if (typeof ci === 'number')\n                    i = ci - 1;\n                else if (ci === BREAK)\n                    return BREAK;\n                else if (ci === REMOVE) {\n                    node.items.splice(i, 1);\n                    i -= 1;\n                }\n            }\n        }\n        else if (identity.isPair(node)) {\n            path = Object.freeze(path.concat(node));\n            const ck = await visitAsync_('key', node.key, visitor, path);\n            if (ck === BREAK)\n                return BREAK;\n            else if (ck === REMOVE)\n                node.key = null;\n            const cv = await visitAsync_('value', node.value, visitor, path);\n            if (cv === BREAK)\n                return BREAK;\n            else if (cv === REMOVE)\n                node.value = null;\n        }\n    }\n    return ctrl;\n}\nfunction initVisitor(visitor) {\n    if (typeof visitor === 'object' &&\n        (visitor.Collection || visitor.Node || visitor.Value)) {\n        return Object.assign({\n            Alias: visitor.Node,\n            Map: visitor.Node,\n            Scalar: visitor.Node,\n            Seq: visitor.Node\n        }, visitor.Value && {\n            Map: visitor.Value,\n            Scalar: visitor.Value,\n            Seq: visitor.Value\n        }, visitor.Collection && {\n            Map: visitor.Collection,\n            Seq: visitor.Collection\n        }, visitor);\n    }\n    return visitor;\n}\nfunction callVisitor(key, node, visitor, path) {\n    if (typeof visitor === 'function')\n        return visitor(key, node, path);\n    if (identity.isMap(node))\n        return visitor.Map?.(key, node, path);\n    if (identity.isSeq(node))\n        return visitor.Seq?.(key, node, path);\n    if (identity.isPair(node))\n        return visitor.Pair?.(key, node, path);\n    if (identity.isScalar(node))\n        return visitor.Scalar?.(key, node, path);\n    if (identity.isAlias(node))\n        return visitor.Alias?.(key, node, path);\n    return undefined;\n}\nfunction replaceNode(key, path, node) {\n    const parent = path[path.length - 1];\n    if (identity.isCollection(parent)) {\n        parent.items[key] = node;\n    }\n    else if (identity.isPair(parent)) {\n        if (key === 'key')\n            parent.key = node;\n        else\n            parent.value = node;\n    }\n    else if (identity.isDocument(parent)) {\n        parent.contents = node;\n    }\n    else {\n        const pt = identity.isAlias(parent) ? 'alias' : 'scalar';\n        throw new Error(`Cannot replace node with ${pt} parent`);\n    }\n}\n\nexports.visit = visit;\nexports.visitAsync = visitAsync;\n","'use strict';\n\nvar identity = require('../nodes/identity.js');\nvar visit = require('../visit.js');\n\nconst escapeChars = {\n    '!': '%21',\n    ',': '%2C',\n    '[': '%5B',\n    ']': '%5D',\n    '{': '%7B',\n    '}': '%7D'\n};\nconst escapeTagName = (tn) => tn.replace(/[!,[\\]{}]/g, ch => escapeChars[ch]);\nclass Directives {\n    constructor(yaml, tags) {\n        /**\n         * The directives-end/doc-start marker `---`. If `null`, a marker may still be\n         * included in the document's stringified representation.\n         */\n        this.docStart = null;\n        /** The doc-end marker `...`.  */\n        this.docEnd = false;\n        this.yaml = Object.assign({}, Directives.defaultYaml, yaml);\n        this.tags = Object.assign({}, Directives.defaultTags, tags);\n    }\n    clone() {\n        const copy = new Directives(this.yaml, this.tags);\n        copy.docStart = this.docStart;\n        return copy;\n    }\n    /**\n     * During parsing, get a Directives instance for the current document and\n     * update the stream state according to the current version's spec.\n     */\n    atDocument() {\n        const res = new Directives(this.yaml, this.tags);\n        switch (this.yaml.version) {\n            case '1.1':\n                this.atNextDocument = true;\n                break;\n            case '1.2':\n                this.atNextDocument = false;\n                this.yaml = {\n                    explicit: Directives.defaultYaml.explicit,\n                    version: '1.2'\n                };\n                this.tags = Object.assign({}, Directives.defaultTags);\n                break;\n        }\n        return res;\n    }\n    /**\n     * @param onError - May be called even if the action was successful\n     * @returns `true` on success\n     */\n    add(line, onError) {\n        if (this.atNextDocument) {\n            this.yaml = { explicit: Directives.defaultYaml.explicit, version: '1.1' };\n            this.tags = Object.assign({}, Directives.defaultTags);\n            this.atNextDocument = false;\n        }\n        const parts = line.trim().split(/[ \\t]+/);\n        const name = parts.shift();\n        switch (name) {\n            case '%TAG': {\n                if (parts.length !== 2) {\n                    onError(0, '%TAG directive should contain exactly two parts');\n                    if (parts.length < 2)\n                        return false;\n                }\n                const [handle, prefix] = parts;\n                this.tags[handle] = prefix;\n                return true;\n            }\n            case '%YAML': {\n                this.yaml.explicit = true;\n                if (parts.length !== 1) {\n                    onError(0, '%YAML directive should contain exactly one part');\n                    return false;\n                }\n                const [version] = parts;\n                if (version === '1.1' || version === '1.2') {\n                    this.yaml.version = version;\n                    return true;\n                }\n                else {\n                    const isValid = /^\\d+\\.\\d+$/.test(version);\n                    onError(6, `Unsupported YAML version ${version}`, isValid);\n                    return false;\n                }\n            }\n            default:\n                onError(0, `Unknown directive ${name}`, true);\n                return false;\n        }\n    }\n    /**\n     * Resolves a tag, matching handles to those defined in %TAG directives.\n     *\n     * @returns Resolved tag, which may also be the non-specific tag `'!'` or a\n     *   `'!local'` tag, or `null` if unresolvable.\n     */\n    tagName(source, onError) {\n        if (source === '!')\n            return '!'; // non-specific tag\n        if (source[0] !== '!') {\n            onError(`Not a valid tag: ${source}`);\n            return null;\n        }\n        if (source[1] === '<') {\n            const verbatim = source.slice(2, -1);\n            if (verbatim === '!' || verbatim === '!!') {\n                onError(`Verbatim tags aren't resolved, so ${source} is invalid.`);\n                return null;\n            }\n            if (source[source.length - 1] !== '>')\n                onError('Verbatim tags must end with a >');\n            return verbatim;\n        }\n        const [, handle, suffix] = source.match(/^(.*!)([^!]*)$/s);\n        if (!suffix)\n            onError(`The ${source} tag has no suffix`);\n        const prefix = this.tags[handle];\n        if (prefix) {\n            try {\n                return prefix + decodeURIComponent(suffix);\n            }\n            catch (error) {\n                onError(String(error));\n                return null;\n            }\n        }\n        if (handle === '!')\n            return source; // local tag\n        onError(`Could not resolve tag: ${source}`);\n        return null;\n    }\n    /**\n     * Given a fully resolved tag, returns its printable string form,\n     * taking into account current tag prefixes and defaults.\n     */\n    tagString(tag) {\n        for (const [handle, prefix] of Object.entries(this.tags)) {\n            if (tag.startsWith(prefix))\n                return handle + escapeTagName(tag.substring(prefix.length));\n        }\n        return tag[0] === '!' ? tag : `!<${tag}>`;\n    }\n    toString(doc) {\n        const lines = this.yaml.explicit\n            ? [`%YAML ${this.yaml.version || '1.2'}`]\n            : [];\n        const tagEntries = Object.entries(this.tags);\n        let tagNames;\n        if (doc && tagEntries.length > 0 && identity.isNode(doc.contents)) {\n            const tags = {};\n            visit.visit(doc.contents, (_key, node) => {\n                if (identity.isNode(node) && node.tag)\n                    tags[node.tag] = true;\n            });\n            tagNames = Object.keys(tags);\n        }\n        else\n            tagNames = [];\n        for (const [handle, prefix] of tagEntries) {\n            if (handle === '!!' && prefix === 'tag:yaml.org,2002:')\n                continue;\n            if (!doc || tagNames.some(tn => tn.startsWith(prefix)))\n                lines.push(`%TAG ${handle} ${prefix}`);\n        }\n        return lines.join('\\n');\n    }\n}\nDirectives.defaultYaml = { explicit: false, version: '1.2' };\nDirectives.defaultTags = { '!!': 'tag:yaml.org,2002:' };\n\nexports.Directives = Directives;\n","'use strict';\n\nvar identity = require('../nodes/identity.js');\nvar visit = require('../visit.js');\n\n/**\n * Verify that the input string is a valid anchor.\n *\n * Will throw on errors.\n */\nfunction anchorIsValid(anchor) {\n    if (/[\\x00-\\x19\\s,[\\]{}]/.test(anchor)) {\n        const sa = JSON.stringify(anchor);\n        const msg = `Anchor must not contain whitespace or control characters: ${sa}`;\n        throw new Error(msg);\n    }\n    return true;\n}\nfunction anchorNames(root) {\n    const anchors = new Set();\n    visit.visit(root, {\n        Value(_key, node) {\n            if (node.anchor)\n                anchors.add(node.anchor);\n        }\n    });\n    return anchors;\n}\n/** Find a new anchor name with the given `prefix` and a one-indexed suffix. */\nfunction findNewAnchor(prefix, exclude) {\n    for (let i = 1; true; ++i) {\n        const name = `${prefix}${i}`;\n        if (!exclude.has(name))\n            return name;\n    }\n}\nfunction createNodeAnchors(doc, prefix) {\n    const aliasObjects = [];\n    const sourceObjects = new Map();\n    let prevAnchors = null;\n    return {\n        onAnchor: (source) => {\n            aliasObjects.push(source);\n            prevAnchors ?? (prevAnchors = anchorNames(doc));\n            const anchor = findNewAnchor(prefix, prevAnchors);\n            prevAnchors.add(anchor);\n            return anchor;\n        },\n        /**\n         * With circular references, the source node is only resolved after all\n         * of its child nodes are. This is why anchors are set only after all of\n         * the nodes have been created.\n         */\n        setAnchors: () => {\n            for (const source of aliasObjects) {\n                const ref = sourceObjects.get(source);\n                if (typeof ref === 'object' &&\n                    ref.anchor &&\n                    (identity.isScalar(ref.node) || identity.isCollection(ref.node))) {\n                    ref.node.anchor = ref.anchor;\n                }\n                else {\n                    const error = new Error('Failed to resolve repeated object (this should not happen)');\n                    error.source = source;\n                    throw error;\n                }\n            }\n        },\n        sourceObjects\n    };\n}\n\nexports.anchorIsValid = anchorIsValid;\nexports.anchorNames = anchorNames;\nexports.createNodeAnchors = createNodeAnchors;\nexports.findNewAnchor = findNewAnchor;\n","'use strict';\n\n/**\n * Applies the JSON.parse reviver algorithm as defined in the ECMA-262 spec,\n * in section 24.5.1.1 \"Runtime Semantics: InternalizeJSONProperty\" of the\n * 2021 edition: https://tc39.es/ecma262/#sec-json.parse\n *\n * Includes extensions for handling Map and Set objects.\n */\nfunction applyReviver(reviver, obj, key, val) {\n    if (val && typeof val === 'object') {\n        if (Array.isArray(val)) {\n            for (let i = 0, len = val.length; i < len; ++i) {\n                const v0 = val[i];\n                const v1 = applyReviver(reviver, val, String(i), v0);\n                // eslint-disable-next-line @typescript-eslint/no-array-delete\n                if (v1 === undefined)\n                    delete val[i];\n                else if (v1 !== v0)\n                    val[i] = v1;\n            }\n        }\n        else if (val instanceof Map) {\n            for (const k of Array.from(val.keys())) {\n                const v0 = val.get(k);\n                const v1 = applyReviver(reviver, val, k, v0);\n                if (v1 === undefined)\n                    val.delete(k);\n                else if (v1 !== v0)\n                    val.set(k, v1);\n            }\n        }\n        else if (val instanceof Set) {\n            for (const v0 of Array.from(val)) {\n                const v1 = applyReviver(reviver, val, v0, v0);\n                if (v1 === undefined)\n                    val.delete(v0);\n                else if (v1 !== v0) {\n                    val.delete(v0);\n                    val.add(v1);\n                }\n            }\n        }\n        else {\n            for (const [k, v0] of Object.entries(val)) {\n                const v1 = applyReviver(reviver, val, k, v0);\n                if (v1 === undefined)\n                    delete val[k];\n                else if (v1 !== v0)\n                    val[k] = v1;\n            }\n        }\n    }\n    return reviver.call(obj, key, val);\n}\n\nexports.applyReviver = applyReviver;\n","'use strict';\n\nvar identity = require('./identity.js');\n\n/**\n * Recursively convert any node or its contents to native JavaScript\n *\n * @param value - The input value\n * @param arg - If `value` defines a `toJSON()` method, use this\n *   as its first argument\n * @param ctx - Conversion context, originally set in Document#toJS(). If\n *   `{ keep: true }` is not set, output should be suitable for JSON\n *   stringification.\n */\nfunction toJS(value, arg, ctx) {\n    // eslint-disable-next-line @typescript-eslint/no-unsafe-return\n    if (Array.isArray(value))\n        return value.map((v, i) => toJS(v, String(i), ctx));\n    if (value && typeof value.toJSON === 'function') {\n        // eslint-disable-next-line @typescript-eslint/no-unsafe-call\n        if (!ctx || !identity.hasAnchor(value))\n            return value.toJSON(arg, ctx);\n        const data = { aliasCount: 0, count: 1, res: undefined };\n        ctx.anchors.set(value, data);\n        ctx.onCreate = res => {\n            data.res = res;\n            delete ctx.onCreate;\n        };\n        const res = value.toJSON(arg, ctx);\n        if (ctx.onCreate)\n            ctx.onCreate(res);\n        return res;\n    }\n    if (typeof value === 'bigint' && !ctx?.keep)\n        return Number(value);\n    return value;\n}\n\nexports.toJS = toJS;\n","'use strict';\n\nvar applyReviver = require('../doc/applyReviver.js');\nvar identity = require('./identity.js');\nvar toJS = require('./toJS.js');\n\nclass NodeBase {\n    constructor(type) {\n        Object.defineProperty(this, identity.NODE_TYPE, { value: type });\n    }\n    /** Create a copy of this node.  */\n    clone() {\n        const copy = Object.create(Object.getPrototypeOf(this), Object.getOwnPropertyDescriptors(this));\n        if (this.range)\n            copy.range = this.range.slice();\n        return copy;\n    }\n    /** A plain JavaScript representation of this node. */\n    toJS(doc, { mapAsMap, maxAliasCount, onAnchor, reviver } = {}) {\n        if (!identity.isDocument(doc))\n            throw new TypeError('A document argument is required');\n        const ctx = {\n            anchors: new Map(),\n            doc,\n            keep: true,\n            mapAsMap: mapAsMap === true,\n            mapKeyWarned: false,\n            maxAliasCount: typeof maxAliasCount === 'number' ? maxAliasCount : 100\n        };\n        const res = toJS.toJS(this, '', ctx);\n        if (typeof onAnchor === 'function')\n            for (const { count, res } of ctx.anchors.values())\n                onAnchor(res, count);\n        return typeof reviver === 'function'\n            ? applyReviver.applyReviver(reviver, { '': res }, '', res)\n            : res;\n    }\n}\n\nexports.NodeBase = NodeBase;\n","'use strict';\n\nvar anchors = require('../doc/anchors.js');\nvar visit = require('../visit.js');\nvar identity = require('./identity.js');\nvar Node = require('./Node.js');\nvar toJS = require('./toJS.js');\n\nclass Alias extends Node.NodeBase {\n    constructor(source) {\n        super(identity.ALIAS);\n        this.source = source;\n        Object.defineProperty(this, 'tag', {\n            set() {\n                throw new Error('Alias nodes cannot have tags');\n            }\n        });\n    }\n    /**\n     * Resolve the value of this alias within `doc`, finding the last\n     * instance of the `source` anchor before this node.\n     */\n    resolve(doc, ctx) {\n        if (ctx?.maxAliasCount === 0)\n            throw new ReferenceError('Alias resolution is disabled');\n        let nodes;\n        if (ctx?.aliasResolveCache) {\n            nodes = ctx.aliasResolveCache;\n        }\n        else {\n            nodes = [];\n            visit.visit(doc, {\n                Node: (_key, node) => {\n                    if (identity.isAlias(node) || identity.hasAnchor(node))\n                        nodes.push(node);\n                }\n            });\n            if (ctx)\n                ctx.aliasResolveCache = nodes;\n        }\n        let found = undefined;\n        for (const node of nodes) {\n            if (node === this)\n                break;\n            if (node.anchor === this.source)\n                found = node;\n        }\n        return found;\n    }\n    toJSON(_arg, ctx) {\n        if (!ctx)\n            return { source: this.source };\n        const { anchors, doc, maxAliasCount } = ctx;\n        const source = this.resolve(doc, ctx);\n        if (!source) {\n            const msg = `Unresolved alias (the anchor must be set before the alias): ${this.source}`;\n            throw new ReferenceError(msg);\n        }\n        let data = anchors.get(source);\n        if (!data) {\n            // Resolve anchors for Node.prototype.toJS()\n            toJS.toJS(source, null, ctx);\n            data = anchors.get(source);\n        }\n        /* istanbul ignore if */\n        if (data?.res === undefined) {\n            const msg = 'This should not happen: Alias anchor was not resolved?';\n            throw new ReferenceError(msg);\n        }\n        if (maxAliasCount >= 0) {\n            data.count += 1;\n            if (data.aliasCount === 0)\n                data.aliasCount = getAliasCount(doc, source, anchors);\n            if (data.count * data.aliasCount > maxAliasCount) {\n                const msg = 'Excessive alias count indicates a resource exhaustion attack';\n                throw new ReferenceError(msg);\n            }\n        }\n        return data.res;\n    }\n    toString(ctx, _onComment, _onChompKeep) {\n        const src = `*${this.source}`;\n        if (ctx) {\n            anchors.anchorIsValid(this.source);\n            if (ctx.options.verifyAliasOrder && !ctx.anchors.has(this.source)) {\n                const msg = `Unresolved alias (the anchor must be set before the alias): ${this.source}`;\n                throw new Error(msg);\n            }\n            if (ctx.implicitKey)\n                return `${src} `;\n        }\n        return src;\n    }\n}\nfunction getAliasCount(doc, node, anchors) {\n    if (identity.isAlias(node)) {\n        const source = node.resolve(doc);\n        const anchor = anchors && source && anchors.get(source);\n        return anchor ? anchor.count * anchor.aliasCount : 0;\n    }\n    else if (identity.isCollection(node)) {\n        let count = 0;\n        for (const item of node.items) {\n            const c = getAliasCount(doc, item, anchors);\n            if (c > count)\n                count = c;\n        }\n        return count;\n    }\n    else if (identity.isPair(node)) {\n        const kc = getAliasCount(doc, node.key, anchors);\n        const vc = getAliasCount(doc, node.value, anchors);\n        return Math.max(kc, vc);\n    }\n    return 1;\n}\n\nexports.Alias = Alias;\n","'use strict';\n\nvar identity = require('./identity.js');\nvar Node = require('./Node.js');\nvar toJS = require('./toJS.js');\n\nconst isScalarValue = (value) => !value || (typeof value !== 'function' && typeof value !== 'object');\nclass Scalar extends Node.NodeBase {\n    constructor(value) {\n        super(identity.SCALAR);\n        this.value = value;\n    }\n    toJSON(arg, ctx) {\n        return ctx?.keep ? this.value : toJS.toJS(this.value, arg, ctx);\n    }\n    toString() {\n        return String(this.value);\n    }\n}\nScalar.BLOCK_FOLDED = 'BLOCK_FOLDED';\nScalar.BLOCK_LITERAL = 'BLOCK_LITERAL';\nScalar.PLAIN = 'PLAIN';\nScalar.QUOTE_DOUBLE = 'QUOTE_DOUBLE';\nScalar.QUOTE_SINGLE = 'QUOTE_SINGLE';\n\nexports.Scalar = Scalar;\nexports.isScalarValue = isScalarValue;\n","'use strict';\n\nvar Alias = require('../nodes/Alias.js');\nvar identity = require('../nodes/identity.js');\nvar Scalar = require('../nodes/Scalar.js');\n\nconst defaultTagPrefix = 'tag:yaml.org,2002:';\nfunction findTagObject(value, tagName, tags) {\n    if (tagName) {\n        const match = tags.filter(t => t.tag === tagName);\n        const tagObj = match.find(t => !t.format) ?? match[0];\n        if (!tagObj)\n            throw new Error(`Tag ${tagName} not found`);\n        return tagObj;\n    }\n    return tags.find(t => t.identify?.(value) && !t.format);\n}\nfunction createNode(value, tagName, ctx) {\n    if (identity.isDocument(value))\n        value = value.contents;\n    if (identity.isNode(value))\n        return value;\n    if (identity.isPair(value)) {\n        const map = ctx.schema[identity.MAP].createNode?.(ctx.schema, null, ctx);\n        map.items.push(value);\n        return map;\n    }\n    if (value instanceof String ||\n        value instanceof Number ||\n        value instanceof Boolean ||\n        (typeof BigInt !== 'undefined' && value instanceof BigInt) // not supported everywhere\n    ) {\n        // https://tc39.es/ecma262/#sec-serializejsonproperty\n        value = value.valueOf();\n    }\n    const { aliasDuplicateObjects, onAnchor, onTagObj, schema, sourceObjects } = ctx;\n    // Detect duplicate references to the same object & use Alias nodes for all\n    // after first. The `ref` wrapper allows for circular references to resolve.\n    let ref = undefined;\n    if (aliasDuplicateObjects && value && typeof value === 'object') {\n        ref = sourceObjects.get(value);\n        if (ref) {\n            ref.anchor ?? (ref.anchor = onAnchor(value));\n            return new Alias.Alias(ref.anchor);\n        }\n        else {\n            ref = { anchor: null, node: null };\n            sourceObjects.set(value, ref);\n        }\n    }\n    if (tagName?.startsWith('!!'))\n        tagName = defaultTagPrefix + tagName.slice(2);\n    let tagObj = findTagObject(value, tagName, schema.tags);\n    if (!tagObj) {\n        if (value && typeof value.toJSON === 'function') {\n            // eslint-disable-next-line @typescript-eslint/no-unsafe-call\n            value = value.toJSON();\n        }\n        if (!value || typeof value !== 'object') {\n            const node = new Scalar.Scalar(value);\n            if (ref)\n                ref.node = node;\n            return node;\n        }\n        tagObj =\n            value instanceof Map\n                ? schema[identity.MAP]\n                : Symbol.iterator in Object(value)\n                    ? schema[identity.SEQ]\n                    : schema[identity.MAP];\n    }\n    if (onTagObj) {\n        onTagObj(tagObj);\n        delete ctx.onTagObj;\n    }\n    const node = tagObj?.createNode\n        ? tagObj.createNode(ctx.schema, value, ctx)\n        : typeof tagObj?.nodeClass?.from === 'function'\n            ? tagObj.nodeClass.from(ctx.schema, value, ctx)\n            : new Scalar.Scalar(value);\n    if (tagName)\n        node.tag = tagName;\n    else if (!tagObj.default)\n        node.tag = tagObj.tag;\n    if (ref)\n        ref.node = node;\n    return node;\n}\n\nexports.createNode = createNode;\n","'use strict';\n\nvar createNode = require('../doc/createNode.js');\nvar identity = require('./identity.js');\nvar Node = require('./Node.js');\n\nfunction collectionFromPath(schema, path, value) {\n    let v = value;\n    for (let i = path.length - 1; i >= 0; --i) {\n        const k = path[i];\n        if (typeof k === 'number' && Number.isInteger(k) && k >= 0) {\n            const a = [];\n            a[k] = v;\n            v = a;\n        }\n        else {\n            v = new Map([[k, v]]);\n        }\n    }\n    return createNode.createNode(v, undefined, {\n        aliasDuplicateObjects: false,\n        keepUndefined: false,\n        onAnchor: () => {\n            throw new Error('This should not happen, please report a bug.');\n        },\n        schema,\n        sourceObjects: new Map()\n    });\n}\n// Type guard is intentionally a little wrong so as to be more useful,\n// as it does not cover untypable empty non-string iterables (e.g. []).\nconst isEmptyPath = (path) => path == null ||\n    (typeof path === 'object' && !!path[Symbol.iterator]().next().done);\nclass Collection extends Node.NodeBase {\n    constructor(type, schema) {\n        super(type);\n        Object.defineProperty(this, 'schema', {\n            value: schema,\n            configurable: true,\n            enumerable: false,\n            writable: true\n        });\n    }\n    /**\n     * Create a copy of this collection.\n     *\n     * @param schema - If defined, overwrites the original's schema\n     */\n    clone(schema) {\n        const copy = Object.create(Object.getPrototypeOf(this), Object.getOwnPropertyDescriptors(this));\n        if (schema)\n            copy.schema = schema;\n        copy.items = copy.items.map(it => identity.isNode(it) || identity.isPair(it) ? it.clone(schema) : it);\n        if (this.range)\n            copy.range = this.range.slice();\n        return copy;\n    }\n    /**\n     * Adds a value to the collection. For `!!map` and `!!omap` the value must\n     * be a Pair instance or a `{ key, value }` object, which may not have a key\n     * that already exists in the map.\n     */\n    addIn(path, value) {\n        if (isEmptyPath(path))\n            this.add(value);\n        else {\n            const [key, ...rest] = path;\n            const node = this.get(key, true);\n            if (identity.isCollection(node))\n                node.addIn(rest, value);\n            else if (node === undefined && this.schema)\n                this.set(key, collectionFromPath(this.schema, rest, value));\n            else\n                throw new Error(`Expected YAML collection at ${key}. Remaining path: ${rest}`);\n        }\n    }\n    /**\n     * Removes a value from the collection.\n     * @returns `true` if the item was found and removed.\n     */\n    deleteIn(path) {\n        const [key, ...rest] = path;\n        if (rest.length === 0)\n            return this.delete(key);\n        const node = this.get(key, true);\n        if (identity.isCollection(node))\n            return node.deleteIn(rest);\n        else\n            throw new Error(`Expected YAML collection at ${key}. Remaining path: ${rest}`);\n    }\n    /**\n     * Returns item at `key`, or `undefined` if not found. By default unwraps\n     * scalar values from their surrounding node; to disable set `keepScalar` to\n     * `true` (collections are always returned intact).\n     */\n    getIn(path, keepScalar) {\n        const [key, ...rest] = path;\n        const node = this.get(key, true);\n        if (rest.length === 0)\n            return !keepScalar && identity.isScalar(node) ? node.value : node;\n        else\n            return identity.isCollection(node) ? node.getIn(rest, keepScalar) : undefined;\n    }\n    hasAllNullValues(allowScalar) {\n        return this.items.every(node => {\n            if (!identity.isPair(node))\n                return false;\n            const n = node.value;\n            return (n == null ||\n                (allowScalar &&\n                    identity.isScalar(n) &&\n                    n.value == null &&\n                    !n.commentBefore &&\n                    !n.comment &&\n                    !n.tag));\n        });\n    }\n    /**\n     * Checks if the collection includes a value with the key `key`.\n     */\n    hasIn(path) {\n        const [key, ...rest] = path;\n        if (rest.length === 0)\n            return this.has(key);\n        const node = this.get(key, true);\n        return identity.isCollection(node) ? node.hasIn(rest) : false;\n    }\n    /**\n     * Sets a value in this collection. For `!!set`, `value` needs to be a\n     * boolean to add/remove the item from the set.\n     */\n    setIn(path, value) {\n        const [key, ...rest] = path;\n        if (rest.length === 0) {\n            this.set(key, value);\n        }\n        else {\n            const node = this.get(key, true);\n            if (identity.isCollection(node))\n                node.setIn(rest, value);\n            else if (node === undefined && this.schema)\n                this.set(key, collectionFromPath(this.schema, rest, value));\n            else\n                throw new Error(`Expected YAML collection at ${key}. Remaining path: ${rest}`);\n        }\n    }\n}\n\nexports.Collection = Collection;\nexports.collectionFromPath = collectionFromPath;\nexports.isEmptyPath = isEmptyPath;\n","'use strict';\n\n/**\n * Stringifies a comment.\n *\n * Empty comment lines are left empty,\n * lines consisting of a single space are replaced by `#`,\n * and all other lines are prefixed with a `#`.\n */\nconst stringifyComment = (str) => str.replace(/^(?!$)(?: $)?/gm, '#');\nfunction indentComment(comment, indent) {\n    if (/^\\n+$/.test(comment))\n        return comment.substring(1);\n    return indent ? comment.replace(/^(?! *$)/gm, indent) : comment;\n}\nconst lineComment = (str, indent, comment) => str.endsWith('\\n')\n    ? indentComment(comment, indent)\n    : comment.includes('\\n')\n        ? '\\n' + indentComment(comment, indent)\n        : (str.endsWith(' ') ? '' : ' ') + comment;\n\nexports.indentComment = indentComment;\nexports.lineComment = lineComment;\nexports.stringifyComment = stringifyComment;\n","'use strict';\n\nconst FOLD_FLOW = 'flow';\nconst FOLD_BLOCK = 'block';\nconst FOLD_QUOTED = 'quoted';\n/**\n * Tries to keep input at up to `lineWidth` characters, splitting only on spaces\n * not followed by newlines or spaces unless `mode` is `'quoted'`. Lines are\n * terminated with `\\n` and started with `indent`.\n */\nfunction foldFlowLines(text, indent, mode = 'flow', { indentAtStart, lineWidth = 80, minContentWidth = 20, onFold, onOverflow } = {}) {\n    if (!lineWidth || lineWidth < 0)\n        return text;\n    if (lineWidth < minContentWidth)\n        minContentWidth = 0;\n    const endStep = Math.max(1 + minContentWidth, 1 + lineWidth - indent.length);\n    if (text.length <= endStep)\n        return text;\n    const folds = [];\n    const escapedFolds = {};\n    let end = lineWidth - indent.length;\n    if (typeof indentAtStart === 'number') {\n        if (indentAtStart > lineWidth - Math.max(2, minContentWidth))\n            folds.push(0);\n        else\n            end = lineWidth - indentAtStart;\n    }\n    let split = undefined;\n    let prev = undefined;\n    let overflow = false;\n    let i = -1;\n    let escStart = -1;\n    let escEnd = -1;\n    if (mode === FOLD_BLOCK) {\n        i = consumeMoreIndentedLines(text, i, indent.length);\n        if (i !== -1)\n            end = i + endStep;\n    }\n    for (let ch; (ch = text[(i += 1)]);) {\n        if (mode === FOLD_QUOTED && ch === '\\\\') {\n            escStart = i;\n            switch (text[i + 1]) {\n                case 'x':\n                    i += 3;\n                    break;\n                case 'u':\n                    i += 5;\n                    break;\n                case 'U':\n                    i += 9;\n                    break;\n                default:\n                    i += 1;\n            }\n            escEnd = i;\n        }\n        if (ch === '\\n') {\n            if (mode === FOLD_BLOCK)\n                i = consumeMoreIndentedLines(text, i, indent.length);\n            end = i + indent.length + endStep;\n            split = undefined;\n        }\n        else {\n            if (ch === ' ' &&\n                prev &&\n                prev !== ' ' &&\n                prev !== '\\n' &&\n                prev !== '\\t') {\n                // space surrounded by non-space can be replaced with newline + indent\n                const next = text[i + 1];\n                if (next && next !== ' ' && next !== '\\n' && next !== '\\t')\n                    split = i;\n            }\n            if (i >= end) {\n                if (split) {\n                    folds.push(split);\n                    end = split + endStep;\n                    split = undefined;\n                }\n                else if (mode === FOLD_QUOTED) {\n                    // white-space collected at end may stretch past lineWidth\n                    while (prev === ' ' || prev === '\\t') {\n                        prev = ch;\n                        ch = text[(i += 1)];\n                        overflow = true;\n                    }\n                    // Account for newline escape, but don't break preceding escape\n                    const j = i > escEnd + 1 ? i - 2 : escStart - 1;\n                    // Bail out if lineWidth & minContentWidth are shorter than an escape string\n                    if (escapedFolds[j])\n                        return text;\n                    folds.push(j);\n                    escapedFolds[j] = true;\n                    end = j + endStep;\n                    split = undefined;\n                }\n                else {\n                    overflow = true;\n                }\n            }\n        }\n        prev = ch;\n    }\n    if (overflow && onOverflow)\n        onOverflow();\n    if (folds.length === 0)\n        return text;\n    if (onFold)\n        onFold();\n    let res = text.slice(0, folds[0]);\n    for (let i = 0; i < folds.length; ++i) {\n        const fold = folds[i];\n        const end = folds[i + 1] || text.length;\n        if (fold === 0)\n            res = `\\n${indent}${text.slice(0, end)}`;\n        else {\n            if (mode === FOLD_QUOTED && escapedFolds[fold])\n                res += `${text[fold]}\\\\`;\n            res += `\\n${indent}${text.slice(fold + 1, end)}`;\n        }\n    }\n    return res;\n}\n/**\n * Presumes `i + 1` is at the start of a line\n * @returns index of last newline in more-indented block\n */\nfunction consumeMoreIndentedLines(text, i, indent) {\n    let end = i;\n    let start = i + 1;\n    let ch = text[start];\n    while (ch === ' ' || ch === '\\t') {\n        if (i < start + indent) {\n            ch = text[++i];\n        }\n        else {\n            do {\n                ch = text[++i];\n            } while (ch && ch !== '\\n');\n            end = i;\n            start = i + 1;\n            ch = text[start];\n        }\n    }\n    return end;\n}\n\nexports.FOLD_BLOCK = FOLD_BLOCK;\nexports.FOLD_FLOW = FOLD_FLOW;\nexports.FOLD_QUOTED = FOLD_QUOTED;\nexports.foldFlowLines = foldFlowLines;\n","'use strict';\n\nvar Scalar = require('../nodes/Scalar.js');\nvar foldFlowLines = require('./foldFlowLines.js');\n\nconst getFoldOptions = (ctx, isBlock) => ({\n    indentAtStart: isBlock ? ctx.indent.length : ctx.indentAtStart,\n    lineWidth: ctx.options.lineWidth,\n    minContentWidth: ctx.options.minContentWidth\n});\n// Also checks for lines starting with %, as parsing the output as YAML 1.1 will\n// presume that's starting a new document.\nconst containsDocumentMarker = (str) => /^(%|---|\\.\\.\\.)/m.test(str);\nfunction lineLengthOverLimit(str, lineWidth, indentLength) {\n    if (!lineWidth || lineWidth < 0)\n        return false;\n    const limit = lineWidth - indentLength;\n    const strLen = str.length;\n    if (strLen <= limit)\n        return false;\n    for (let i = 0, start = 0; i < strLen; ++i) {\n        if (str[i] === '\\n') {\n            if (i - start > limit)\n                return true;\n            start = i + 1;\n            if (strLen - start <= limit)\n                return false;\n        }\n    }\n    return true;\n}\nfunction doubleQuotedString(value, ctx) {\n    const json = JSON.stringify(value);\n    if (ctx.options.doubleQuotedAsJSON)\n        return json;\n    const { implicitKey } = ctx;\n    const minMultiLineLength = ctx.options.doubleQuotedMinMultiLineLength;\n    const indent = ctx.indent || (containsDocumentMarker(value) ? '  ' : '');\n    let str = '';\n    let start = 0;\n    for (let i = 0, ch = json[i]; ch; ch = json[++i]) {\n        if (ch === ' ' && json[i + 1] === '\\\\' && json[i + 2] === 'n') {\n            // space before newline needs to be escaped to not be folded\n            str += json.slice(start, i) + '\\\\ ';\n            i += 1;\n            start = i;\n            ch = '\\\\';\n        }\n        if (ch === '\\\\')\n            switch (json[i + 1]) {\n                case 'u':\n                    {\n                        str += json.slice(start, i);\n                        const code = json.substr(i + 2, 4);\n                        switch (code) {\n                            case '0000':\n                                str += '\\\\0';\n                                break;\n                            case '0007':\n                                str += '\\\\a';\n                                break;\n                            case '000b':\n                                str += '\\\\v';\n                                break;\n                            case '001b':\n                                str += '\\\\e';\n                                break;\n                            case '0085':\n                                str += '\\\\N';\n                                break;\n                            case '00a0':\n                                str += '\\\\_';\n                                break;\n                            case '2028':\n                                str += '\\\\L';\n                                break;\n                            case '2029':\n                                str += '\\\\P';\n                                break;\n                            default:\n                                if (code.substr(0, 2) === '00')\n                                    str += '\\\\x' + code.substr(2);\n                                else\n                                    str += json.substr(i, 6);\n                        }\n                        i += 5;\n                        start = i + 1;\n                    }\n                    break;\n                case 'n':\n                    if (implicitKey ||\n                        json[i + 2] === '\"' ||\n                        json.length < minMultiLineLength) {\n                        i += 1;\n                    }\n                    else {\n                        // folding will eat first newline\n                        str += json.slice(start, i) + '\\n\\n';\n                        while (json[i + 2] === '\\\\' &&\n                            json[i + 3] === 'n' &&\n                            json[i + 4] !== '\"') {\n                            str += '\\n';\n                            i += 2;\n                        }\n                        str += indent;\n                        // space after newline needs to be escaped to not be folded\n                        if (json[i + 2] === ' ')\n                            str += '\\\\';\n                        i += 1;\n                        start = i + 1;\n                    }\n                    break;\n                default:\n                    i += 1;\n            }\n    }\n    str = start ? str + json.slice(start) : json;\n    return implicitKey\n        ? str\n        : foldFlowLines.foldFlowLines(str, indent, foldFlowLines.FOLD_QUOTED, getFoldOptions(ctx, false));\n}\nfunction singleQuotedString(value, ctx) {\n    if (ctx.options.singleQuote === false ||\n        (ctx.implicitKey && value.includes('\\n')) ||\n        /[ \\t]\\n|\\n[ \\t]/.test(value) // single quoted string can't have leading or trailing whitespace around newline\n    )\n        return doubleQuotedString(value, ctx);\n    const indent = ctx.indent || (containsDocumentMarker(value) ? '  ' : '');\n    const res = \"'\" + value.replace(/'/g, \"''\").replace(/\\n+/g, `$&\\n${indent}`) + \"'\";\n    return ctx.implicitKey\n        ? res\n        : foldFlowLines.foldFlowLines(res, indent, foldFlowLines.FOLD_FLOW, getFoldOptions(ctx, false));\n}\nfunction quotedString(value, ctx) {\n    const { singleQuote } = ctx.options;\n    let qs;\n    if (singleQuote === false)\n        qs = doubleQuotedString;\n    else {\n        const hasDouble = value.includes('\"');\n        const hasSingle = value.includes(\"'\");\n        if (hasDouble && !hasSingle)\n            qs = singleQuotedString;\n        else if (hasSingle && !hasDouble)\n            qs = doubleQuotedString;\n        else\n            qs = singleQuote ? singleQuotedString : doubleQuotedString;\n    }\n    return qs(value, ctx);\n}\n// The negative lookbehind avoids a polynomial search,\n// but isn't supported yet on Safari: https://caniuse.com/js-regexp-lookbehind\nlet blockEndNewlines;\ntry {\n    blockEndNewlines = new RegExp('(^|(?<!\\n))\\n+(?!\\n|$)', 'g');\n}\ncatch {\n    blockEndNewlines = /\\n+(?!\\n|$)/g;\n}\nfunction blockString({ comment, type, value }, ctx, onComment, onChompKeep) {\n    const { blockQuote, commentString, lineWidth } = ctx.options;\n    // 1. Block can't end in whitespace unless the last line is non-empty.\n    // 2. Strings consisting of only whitespace are best rendered explicitly.\n    if (!blockQuote || /\\n[\\t ]+$/.test(value)) {\n        return quotedString(value, ctx);\n    }\n    const indent = ctx.indent ||\n        (ctx.forceBlockIndent || containsDocumentMarker(value) ? '  ' : '');\n    const literal = blockQuote === 'literal'\n        ? true\n        : blockQuote === 'folded' || type === Scalar.Scalar.BLOCK_FOLDED\n            ? false\n            : type === Scalar.Scalar.BLOCK_LITERAL\n                ? true\n                : !lineLengthOverLimit(value, lineWidth, indent.length);\n    if (!value)\n        return literal ? '|\\n' : '>\\n';\n    // determine chomping from whitespace at value end\n    let chomp;\n    let endStart;\n    for (endStart = value.length; endStart > 0; --endStart) {\n        const ch = value[endStart - 1];\n        if (ch !== '\\n' && ch !== '\\t' && ch !== ' ')\n            break;\n    }\n    let end = value.substring(endStart);\n    const endNlPos = end.indexOf('\\n');\n    if (endNlPos === -1) {\n        chomp = '-'; // strip\n    }\n    else if (value === end || endNlPos !== end.length - 1) {\n        chomp = '+'; // keep\n        if (onChompKeep)\n            onChompKeep();\n    }\n    else {\n        chomp = ''; // clip\n    }\n    if (end) {\n        value = value.slice(0, -end.length);\n        if (end[end.length - 1] === '\\n')\n            end = end.slice(0, -1);\n        end = end.replace(blockEndNewlines, `$&${indent}`);\n    }\n    // determine indent indicator from whitespace at value start\n    let startWithSpace = false;\n    let startEnd;\n    let startNlPos = -1;\n    for (startEnd = 0; startEnd < value.length; ++startEnd) {\n        const ch = value[startEnd];\n        if (ch === ' ')\n            startWithSpace = true;\n        else if (ch === '\\n')\n            startNlPos = startEnd;\n        else\n            break;\n    }\n    let start = value.substring(0, startNlPos < startEnd ? startNlPos + 1 : startEnd);\n    if (start) {\n        value = value.substring(start.length);\n        start = start.replace(/\\n+/g, `$&${indent}`);\n    }\n    const indentSize = indent ? '2' : '1'; // root is at -1\n    // Leading | or > is added later\n    let header = (startWithSpace ? indentSize : '') + chomp;\n    if (comment) {\n        header += ' ' + commentString(comment.replace(/ ?[\\r\\n]+/g, ' '));\n        if (onComment)\n            onComment();\n    }\n    if (!literal) {\n        const foldedValue = value\n            .replace(/\\n+/g, '\\n$&')\n            .replace(/(?:^|\\n)([\\t ].*)(?:([\\n\\t ]*)\\n(?![\\n\\t ]))?/g, '$1$2') // more-indented lines aren't folded\n            //                ^ more-ind. ^ empty     ^ capture next empty lines only at end of indent\n            .replace(/\\n+/g, `$&${indent}`);\n        let literalFallback = false;\n        const foldOptions = getFoldOptions(ctx, true);\n        if (blockQuote !== 'folded' && type !== Scalar.Scalar.BLOCK_FOLDED) {\n            foldOptions.onOverflow = () => {\n                literalFallback = true;\n            };\n        }\n        const body = foldFlowLines.foldFlowLines(`${start}${foldedValue}${end}`, indent, foldFlowLines.FOLD_BLOCK, foldOptions);\n        if (!literalFallback)\n            return `>${header}\\n${indent}${body}`;\n    }\n    value = value.replace(/\\n+/g, `$&${indent}`);\n    return `|${header}\\n${indent}${start}${value}${end}`;\n}\nfunction plainString(item, ctx, onComment, onChompKeep) {\n    const { type, value } = item;\n    const { actualString, implicitKey, indent, indentStep, inFlow } = ctx;\n    if ((implicitKey && value.includes('\\n')) ||\n        (inFlow && /[[\\]{},]/.test(value))) {\n        return quotedString(value, ctx);\n    }\n    if (/^[\\n\\t ,[\\]{}#&*!|>'\"%@`]|^[?-]$|^[?-][ \\t]|[\\n:][ \\t]|[ \\t]\\n|[\\n\\t ]#|[\\n\\t :]$/.test(value)) {\n        // not allowed:\n        // - '-' or '?'\n        // - start with an indicator character (except [?:-]) or /[?-] /\n        // - '\\n ', ': ' or ' \\n' anywhere\n        // - '#' not preceded by a non-space char\n        // - end with ' ' or ':'\n        return implicitKey || inFlow || !value.includes('\\n')\n            ? quotedString(value, ctx)\n            : blockString(item, ctx, onComment, onChompKeep);\n    }\n    if (!implicitKey &&\n        !inFlow &&\n        type !== Scalar.Scalar.PLAIN &&\n        value.includes('\\n')) {\n        // Where allowed & type not set explicitly, prefer block style for multiline strings\n        return blockString(item, ctx, onComment, onChompKeep);\n    }\n    if (containsDocumentMarker(value)) {\n        if (indent === '') {\n            ctx.forceBlockIndent = true;\n            return blockString(item, ctx, onComment, onChompKeep);\n        }\n        else if (implicitKey && indent === indentStep) {\n            return quotedString(value, ctx);\n        }\n    }\n    const str = value.replace(/\\n+/g, `$&\\n${indent}`);\n    // Verify that output will be parsed as a string, as e.g. plain numbers and\n    // booleans get parsed with those types in v1.2 (e.g. '42', 'true' & '0.9e-3'),\n    // and others in v1.1.\n    if (actualString) {\n        const test = (tag) => tag.default && tag.tag !== 'tag:yaml.org,2002:str' && tag.test?.test(str);\n        const { compat, tags } = ctx.doc.schema;\n        if (tags.some(test) || compat?.some(test))\n            return quotedString(value, ctx);\n    }\n    return implicitKey\n        ? str\n        : foldFlowLines.foldFlowLines(str, indent, foldFlowLines.FOLD_FLOW, getFoldOptions(ctx, false));\n}\nfunction stringifyString(item, ctx, onComment, onChompKeep) {\n    const { implicitKey, inFlow } = ctx;\n    const ss = typeof item.value === 'string'\n        ? item\n        : Object.assign({}, item, { value: String(item.value) });\n    let { type } = item;\n    if (type !== Scalar.Scalar.QUOTE_DOUBLE) {\n        // force double quotes on control characters & unpaired surrogates\n        if (/[\\x00-\\x08\\x0b-\\x1f\\x7f-\\x9f\\u{D800}-\\u{DFFF}]/u.test(ss.value))\n            type = Scalar.Scalar.QUOTE_DOUBLE;\n    }\n    const _stringify = (_type) => {\n        switch (_type) {\n            case Scalar.Scalar.BLOCK_FOLDED:\n            case Scalar.Scalar.BLOCK_LITERAL:\n                return implicitKey || inFlow\n                    ? quotedString(ss.value, ctx) // blocks are not valid inside flow containers\n                    : blockString(ss, ctx, onComment, onChompKeep);\n            case Scalar.Scalar.QUOTE_DOUBLE:\n                return doubleQuotedString(ss.value, ctx);\n            case Scalar.Scalar.QUOTE_SINGLE:\n                return singleQuotedString(ss.value, ctx);\n            case Scalar.Scalar.PLAIN:\n                return plainString(ss, ctx, onComment, onChompKeep);\n            default:\n                return null;\n        }\n    };\n    let res = _stringify(type);\n    if (res === null) {\n        const { defaultKeyType, defaultStringType } = ctx.options;\n        const t = (implicitKey && defaultKeyType) || defaultStringType;\n        res = _stringify(t);\n        if (res === null)\n            throw new Error(`Unsupported default string type ${t}`);\n    }\n    return res;\n}\n\nexports.stringifyString = stringifyString;\n","'use strict';\n\nvar anchors = require('../doc/anchors.js');\nvar identity = require('../nodes/identity.js');\nvar stringifyComment = require('./stringifyComment.js');\nvar stringifyString = require('./stringifyString.js');\n\nfunction createStringifyContext(doc, options) {\n    const opt = Object.assign({\n        blockQuote: true,\n        commentString: stringifyComment.stringifyComment,\n        defaultKeyType: null,\n        defaultStringType: 'PLAIN',\n        directives: null,\n        doubleQuotedAsJSON: false,\n        doubleQuotedMinMultiLineLength: 40,\n        falseStr: 'false',\n        flowCollectionPadding: true,\n        indentSeq: true,\n        lineWidth: 80,\n        minContentWidth: 20,\n        nullStr: 'null',\n        simpleKeys: false,\n        singleQuote: null,\n        trailingComma: false,\n        trueStr: 'true',\n        verifyAliasOrder: true\n    }, doc.schema.toStringOptions, options);\n    let inFlow;\n    switch (opt.collectionStyle) {\n        case 'block':\n            inFlow = false;\n            break;\n        case 'flow':\n            inFlow = true;\n            break;\n        default:\n            inFlow = null;\n    }\n    return {\n        anchors: new Set(),\n        doc,\n        flowCollectionPadding: opt.flowCollectionPadding ? ' ' : '',\n        indent: '',\n        indentStep: typeof opt.indent === 'number' ? ' '.repeat(opt.indent) : '  ',\n        inFlow,\n        options: opt\n    };\n}\nfunction getTagObject(tags, item) {\n    if (item.tag) {\n        const match = tags.filter(t => t.tag === item.tag);\n        if (match.length > 0)\n            return match.find(t => t.format === item.format) ?? match[0];\n    }\n    let tagObj = undefined;\n    let obj;\n    if (identity.isScalar(item)) {\n        obj = item.value;\n        let match = tags.filter(t => t.identify?.(obj));\n        if (match.length > 1) {\n            const testMatch = match.filter(t => t.test);\n            if (testMatch.length > 0)\n                match = testMatch;\n        }\n        tagObj =\n            match.find(t => t.format === item.format) ?? match.find(t => !t.format);\n    }\n    else {\n        obj = item;\n        tagObj = tags.find(t => t.nodeClass && obj instanceof t.nodeClass);\n    }\n    if (!tagObj) {\n        const name = obj?.constructor?.name ?? (obj === null ? 'null' : typeof obj);\n        throw new Error(`Tag not resolved for ${name} value`);\n    }\n    return tagObj;\n}\n// needs to be called before value stringifier to allow for circular anchor refs\nfunction stringifyProps(node, tagObj, { anchors: anchors$1, doc }) {\n    if (!doc.directives)\n        return '';\n    const props = [];\n    const anchor = (identity.isScalar(node) || identity.isCollection(node)) && node.anchor;\n    if (anchor && anchors.anchorIsValid(anchor)) {\n        anchors$1.add(anchor);\n        props.push(`&${anchor}`);\n    }\n    const tag = node.tag ?? (tagObj.default ? null : tagObj.tag);\n    if (tag)\n        props.push(doc.directives.tagString(tag));\n    return props.join(' ');\n}\nfunction stringify(item, ctx, onComment, onChompKeep) {\n    if (identity.isPair(item))\n        return item.toString(ctx, onComment, onChompKeep);\n    if (identity.isAlias(item)) {\n        if (ctx.doc.directives)\n            return item.toString(ctx);\n        if (ctx.resolvedAliases?.has(item)) {\n            throw new TypeError(`Cannot stringify circular structure without alias nodes`);\n        }\n        else {\n            if (ctx.resolvedAliases)\n                ctx.resolvedAliases.add(item);\n            else\n                ctx.resolvedAliases = new Set([item]);\n            item = item.resolve(ctx.doc);\n        }\n    }\n    let tagObj = undefined;\n    const node = identity.isNode(item)\n        ? item\n        : ctx.doc.createNode(item, { onTagObj: o => (tagObj = o) });\n    tagObj ?? (tagObj = getTagObject(ctx.doc.schema.tags, node));\n    const props = stringifyProps(node, tagObj, ctx);\n    if (props.length > 0)\n        ctx.indentAtStart = (ctx.indentAtStart ?? 0) + props.length + 1;\n    const str = typeof tagObj.stringify === 'function'\n        ? tagObj.stringify(node, ctx, onComment, onChompKeep)\n        : identity.isScalar(node)\n            ? stringifyString.stringifyString(node, ctx, onComment, onChompKeep)\n            : node.toString(ctx, onComment, onChompKeep);\n    if (!props)\n        return str;\n    return identity.isScalar(node) || str[0] === '{' || str[0] === '['\n        ? `${props} ${str}`\n        : `${props}\\n${ctx.indent}${str}`;\n}\n\nexports.createStringifyContext = createStringifyContext;\nexports.stringify = stringify;\n","'use strict';\n\nvar identity = require('../nodes/identity.js');\nvar Scalar = require('../nodes/Scalar.js');\nvar stringify = require('./stringify.js');\nvar stringifyComment = require('./stringifyComment.js');\n\nfunction stringifyPair({ key, value }, ctx, onComment, onChompKeep) {\n    const { allNullValues, doc, indent, indentStep, options: { commentString, indentSeq, simpleKeys } } = ctx;\n    let keyComment = (identity.isNode(key) && key.comment) || null;\n    if (simpleKeys) {\n        if (keyComment) {\n            throw new Error('With simple keys, key nodes cannot have comments');\n        }\n        if (identity.isCollection(key) || (!identity.isNode(key) && typeof key === 'object')) {\n            const msg = 'With simple keys, collection cannot be used as a key value';\n            throw new Error(msg);\n        }\n    }\n    let explicitKey = !simpleKeys &&\n        (!key ||\n            (keyComment && value == null && !ctx.inFlow) ||\n            identity.isCollection(key) ||\n            (identity.isScalar(key)\n                ? key.type === Scalar.Scalar.BLOCK_FOLDED || key.type === Scalar.Scalar.BLOCK_LITERAL\n                : typeof key === 'object'));\n    ctx = Object.assign({}, ctx, {\n        allNullValues: false,\n        implicitKey: !explicitKey && (simpleKeys || !allNullValues),\n        indent: indent + indentStep\n    });\n    let keyCommentDone = false;\n    let chompKeep = false;\n    let str = stringify.stringify(key, ctx, () => (keyCommentDone = true), () => (chompKeep = true));\n    if (!explicitKey && !ctx.inFlow && str.length > 1024) {\n        if (simpleKeys)\n            throw new Error('With simple keys, single line scalar must not span more than 1024 characters');\n        explicitKey = true;\n    }\n    if (ctx.inFlow) {\n        if (allNullValues || value == null) {\n            if (keyCommentDone && onComment)\n                onComment();\n            return str === '' ? '?' : explicitKey ? `? ${str}` : str;\n        }\n    }\n    else if ((allNullValues && !simpleKeys) || (value == null && explicitKey)) {\n        str = `? ${str}`;\n        if (keyComment && !keyCommentDone) {\n            str += stringifyComment.lineComment(str, ctx.indent, commentString(keyComment));\n        }\n        else if (chompKeep && onChompKeep)\n            onChompKeep();\n        return str;\n    }\n    if (keyCommentDone)\n        keyComment = null;\n    if (explicitKey) {\n        if (keyComment)\n            str += stringifyComment.lineComment(str, ctx.indent, commentString(keyComment));\n        str = `? ${str}\\n${indent}:`;\n    }\n    else {\n        str = `${str}:`;\n        if (keyComment)\n            str += stringifyComment.lineComment(str, ctx.indent, commentString(keyComment));\n    }\n    let vsb, vcb, valueComment;\n    if (identity.isNode(value)) {\n        vsb = !!value.spaceBefore;\n        vcb = value.commentBefore;\n        valueComment = value.comment;\n    }\n    else {\n        vsb = false;\n        vcb = null;\n        valueComment = null;\n        if (value && typeof value === 'object')\n            value = doc.createNode(value);\n    }\n    ctx.implicitKey = false;\n    if (!explicitKey && !keyComment && identity.isScalar(value))\n        ctx.indentAtStart = str.length + 1;\n    chompKeep = false;\n    if (!indentSeq &&\n        indentStep.length >= 2 &&\n        !ctx.inFlow &&\n        !explicitKey &&\n        identity.isSeq(value) &&\n        !value.flow &&\n        !value.tag &&\n        !value.anchor) {\n        // If indentSeq === false, consider '- ' as part of indentation where possible\n        ctx.indent = ctx.indent.substring(2);\n    }\n    let valueCommentDone = false;\n    const valueStr = stringify.stringify(value, ctx, () => (valueCommentDone = true), () => (chompKeep = true));\n    let ws = ' ';\n    if (keyComment || vsb || vcb) {\n        ws = vsb ? '\\n' : '';\n        if (vcb) {\n            const cs = commentString(vcb);\n            ws += `\\n${stringifyComment.indentComment(cs, ctx.indent)}`;\n        }\n        if (valueStr === '' && !ctx.inFlow) {\n            if (ws === '\\n' && valueComment)\n                ws = '\\n\\n';\n        }\n        else {\n            ws += `\\n${ctx.indent}`;\n        }\n    }\n    else if (!explicitKey && identity.isCollection(value)) {\n        const vs0 = valueStr[0];\n        const nl0 = valueStr.indexOf('\\n');\n        const hasNewline = nl0 !== -1;\n        const flow = ctx.inFlow ?? value.flow ?? value.items.length === 0;\n        if (hasNewline || !flow) {\n            let hasPropsLine = false;\n            if (hasNewline && (vs0 === '&' || vs0 === '!')) {\n                let sp0 = valueStr.indexOf(' ');\n                if (vs0 === '&' &&\n                    sp0 !== -1 &&\n                    sp0 < nl0 &&\n                    valueStr[sp0 + 1] === '!') {\n                    sp0 = valueStr.indexOf(' ', sp0 + 1);\n                }\n                if (sp0 === -1 || nl0 < sp0)\n                    hasPropsLine = true;\n            }\n            if (!hasPropsLine)\n                ws = `\\n${ctx.indent}`;\n        }\n    }\n    else if (valueStr === '' || valueStr[0] === '\\n') {\n        ws = '';\n    }\n    str += ws + valueStr;\n    if (ctx.inFlow) {\n        if (valueCommentDone && onComment)\n            onComment();\n    }\n    else if (valueComment && !valueCommentDone) {\n        str += stringifyComment.lineComment(str, ctx.indent, commentString(valueComment));\n    }\n    else if (chompKeep && onChompKeep) {\n        onChompKeep();\n    }\n    return str;\n}\n\nexports.stringifyPair = stringifyPair;\n","'use strict';\n\nvar node_process = require('process');\n\nfunction debug(logLevel, ...messages) {\n    if (logLevel === 'debug')\n        console.log(...messages);\n}\nfunction warn(logLevel, warning) {\n    if (logLevel === 'debug' || logLevel === 'warn') {\n        if (typeof node_process.emitWarning === 'function')\n            node_process.emitWarning(warning);\n        else\n            console.warn(warning);\n    }\n}\n\nexports.debug = debug;\nexports.warn = warn;\n","'use strict';\n\nvar identity = require('../../nodes/identity.js');\nvar Scalar = require('../../nodes/Scalar.js');\n\n// If the value associated with a merge key is a single mapping node, each of\n// its key/value pairs is inserted into the current mapping, unless the key\n// already exists in it. If the value associated with the merge key is a\n// sequence, then this sequence is expected to contain mapping nodes and each\n// of these nodes is merged in turn according to its order in the sequence.\n// Keys in mapping nodes earlier in the sequence override keys specified in\n// later mapping nodes. -- http://yaml.org/type/merge.html\nconst MERGE_KEY = '<<';\nconst merge = {\n    identify: value => value === MERGE_KEY ||\n        (typeof value === 'symbol' && value.description === MERGE_KEY),\n    default: 'key',\n    tag: 'tag:yaml.org,2002:merge',\n    test: /^<<$/,\n    resolve: () => Object.assign(new Scalar.Scalar(Symbol(MERGE_KEY)), {\n        addToJSMap: addMergeToJSMap\n    }),\n    stringify: () => MERGE_KEY\n};\nconst isMergeKey = (ctx, key) => (merge.identify(key) ||\n    (identity.isScalar(key) &&\n        (!key.type || key.type === Scalar.Scalar.PLAIN) &&\n        merge.identify(key.value))) &&\n    ctx?.doc.schema.tags.some(tag => tag.tag === merge.tag && tag.default);\nfunction addMergeToJSMap(ctx, map, value) {\n    const source = resolveAliasValue(ctx, value);\n    if (identity.isSeq(source))\n        for (const it of source.items)\n            mergeValue(ctx, map, it);\n    else if (Array.isArray(source))\n        for (const it of source)\n            mergeValue(ctx, map, it);\n    else\n        mergeValue(ctx, map, source);\n}\nfunction mergeValue(ctx, map, value) {\n    const source = resolveAliasValue(ctx, value);\n    if (!identity.isMap(source))\n        throw new Error('Merge sources must be maps or map aliases');\n    const srcMap = source.toJSON(null, ctx, Map);\n    for (const [key, value] of srcMap) {\n        if (map instanceof Map) {\n            if (!map.has(key))\n                map.set(key, value);\n        }\n        else if (map instanceof Set) {\n            map.add(key);\n        }\n        else if (!Object.prototype.hasOwnProperty.call(map, key)) {\n            Object.defineProperty(map, key, {\n                value,\n                writable: true,\n                enumerable: true,\n                configurable: true\n            });\n        }\n    }\n    return map;\n}\nfunction resolveAliasValue(ctx, value) {\n    return ctx && identity.isAlias(value) ? value.resolve(ctx.doc, ctx) : value;\n}\n\nexports.addMergeToJSMap = addMergeToJSMap;\nexports.isMergeKey = isMergeKey;\nexports.merge = merge;\n","'use strict';\n\nvar log = require('../log.js');\nvar merge = require('../schema/yaml-1.1/merge.js');\nvar stringify = require('../stringify/stringify.js');\nvar identity = require('./identity.js');\nvar toJS = require('./toJS.js');\n\nfunction addPairToJSMap(ctx, map, { key, value }) {\n    if (identity.isNode(key) && key.addToJSMap)\n        key.addToJSMap(ctx, map, value);\n    // TODO: Should drop this special case for bare << handling\n    else if (merge.isMergeKey(ctx, key))\n        merge.addMergeToJSMap(ctx, map, value);\n    else {\n        const jsKey = toJS.toJS(key, '', ctx);\n        if (map instanceof Map) {\n            map.set(jsKey, toJS.toJS(value, jsKey, ctx));\n        }\n        else if (map instanceof Set) {\n            map.add(jsKey);\n        }\n        else {\n            const stringKey = stringifyKey(key, jsKey, ctx);\n            const jsValue = toJS.toJS(value, stringKey, ctx);\n            if (stringKey in map)\n                Object.defineProperty(map, stringKey, {\n                    value: jsValue,\n                    writable: true,\n                    enumerable: true,\n                    configurable: true\n                });\n            else\n                map[stringKey] = jsValue;\n        }\n    }\n    return map;\n}\nfunction stringifyKey(key, jsKey, ctx) {\n    if (jsKey === null)\n        return '';\n    // eslint-disable-next-line @typescript-eslint/no-base-to-string\n    if (typeof jsKey !== 'object')\n        return String(jsKey);\n    if (identity.isNode(key) && ctx?.doc) {\n        const strCtx = stringify.createStringifyContext(ctx.doc, {});\n        strCtx.anchors = new Set();\n        for (const node of ctx.anchors.keys())\n            strCtx.anchors.add(node.anchor);\n        strCtx.inFlow = true;\n        strCtx.inStringifyKey = true;\n        const strKey = key.toString(strCtx);\n        if (!ctx.mapKeyWarned) {\n            let jsonStr = JSON.stringify(strKey);\n            if (jsonStr.length > 40)\n                jsonStr = jsonStr.substring(0, 36) + '...\"';\n            log.warn(ctx.doc.options.logLevel, `Keys with collection values will be stringified due to JS Object restrictions: ${jsonStr}. Set mapAsMap: true to use object keys.`);\n            ctx.mapKeyWarned = true;\n        }\n        return strKey;\n    }\n    return JSON.stringify(jsKey);\n}\n\nexports.addPairToJSMap = addPairToJSMap;\n","'use strict';\n\nvar createNode = require('../doc/createNode.js');\nvar stringifyPair = require('../stringify/stringifyPair.js');\nvar addPairToJSMap = require('./addPairToJSMap.js');\nvar identity = require('./identity.js');\n\nfunction createPair(key, value, ctx) {\n    const k = createNode.createNode(key, undefined, ctx);\n    const v = createNode.createNode(value, undefined, ctx);\n    return new Pair(k, v);\n}\nclass Pair {\n    constructor(key, value = null) {\n        Object.defineProperty(this, identity.NODE_TYPE, { value: identity.PAIR });\n        this.key = key;\n        this.value = value;\n    }\n    clone(schema) {\n        let { key, value } = this;\n        if (identity.isNode(key))\n            key = key.clone(schema);\n        if (identity.isNode(value))\n            value = value.clone(schema);\n        return new Pair(key, value);\n    }\n    toJSON(_, ctx) {\n        const pair = ctx?.mapAsMap ? new Map() : {};\n        return addPairToJSMap.addPairToJSMap(ctx, pair, this);\n    }\n    toString(ctx, onComment, onChompKeep) {\n        return ctx?.doc\n            ? stringifyPair.stringifyPair(this, ctx, onComment, onChompKeep)\n            : JSON.stringify(this);\n    }\n}\n\nexports.Pair = Pair;\nexports.createPair = createPair;\n","'use strict';\n\nvar identity = require('../nodes/identity.js');\nvar stringify = require('./stringify.js');\nvar stringifyComment = require('./stringifyComment.js');\n\nfunction stringifyCollection(collection, ctx, options) {\n    const flow = ctx.inFlow ?? collection.flow;\n    const stringify = flow ? stringifyFlowCollection : stringifyBlockCollection;\n    return stringify(collection, ctx, options);\n}\nfunction stringifyBlockCollection({ comment, items }, ctx, { blockItemPrefix, flowChars, itemIndent, onChompKeep, onComment }) {\n    const { indent, options: { commentString } } = ctx;\n    const itemCtx = Object.assign({}, ctx, { indent: itemIndent, type: null });\n    let chompKeep = false; // flag for the preceding node's status\n    const lines = [];\n    for (let i = 0; i < items.length; ++i) {\n        const item = items[i];\n        let comment = null;\n        if (identity.isNode(item)) {\n            if (!chompKeep && item.spaceBefore)\n                lines.push('');\n            addCommentBefore(ctx, lines, item.commentBefore, chompKeep);\n            if (item.comment)\n                comment = item.comment;\n        }\n        else if (identity.isPair(item)) {\n            const ik = identity.isNode(item.key) ? item.key : null;\n            if (ik) {\n                if (!chompKeep && ik.spaceBefore)\n                    lines.push('');\n                addCommentBefore(ctx, lines, ik.commentBefore, chompKeep);\n            }\n        }\n        chompKeep = false;\n        let str = stringify.stringify(item, itemCtx, () => (comment = null), () => (chompKeep = true));\n        if (comment)\n            str += stringifyComment.lineComment(str, itemIndent, commentString(comment));\n        if (chompKeep && comment)\n            chompKeep = false;\n        lines.push(blockItemPrefix + str);\n    }\n    let str;\n    if (lines.length === 0) {\n        str = flowChars.start + flowChars.end;\n    }\n    else {\n        str = lines[0];\n        for (let i = 1; i < lines.length; ++i) {\n            const line = lines[i];\n            str += line ? `\\n${indent}${line}` : '\\n';\n        }\n    }\n    if (comment) {\n        str += '\\n' + stringifyComment.indentComment(commentString(comment), indent);\n        if (onComment)\n            onComment();\n    }\n    else if (chompKeep && onChompKeep)\n        onChompKeep();\n    return str;\n}\nfunction stringifyFlowCollection({ items }, ctx, { flowChars, itemIndent }) {\n    const { indent, indentStep, flowCollectionPadding: fcPadding, options: { commentString } } = ctx;\n    itemIndent += indentStep;\n    const itemCtx = Object.assign({}, ctx, {\n        indent: itemIndent,\n        inFlow: true,\n        type: null\n    });\n    let reqNewline = false;\n    let linesAtValue = 0;\n    const lines = [];\n    for (let i = 0; i < items.length; ++i) {\n        const item = items[i];\n        let comment = null;\n        if (identity.isNode(item)) {\n            if (item.spaceBefore)\n                lines.push('');\n            addCommentBefore(ctx, lines, item.commentBefore, false);\n            if (item.comment)\n                comment = item.comment;\n        }\n        else if (identity.isPair(item)) {\n            const ik = identity.isNode(item.key) ? item.key : null;\n            if (ik) {\n                if (ik.spaceBefore)\n                    lines.push('');\n                addCommentBefore(ctx, lines, ik.commentBefore, false);\n                if (ik.comment)\n                    reqNewline = true;\n            }\n            const iv = identity.isNode(item.value) ? item.value : null;\n            if (iv) {\n                if (iv.comment)\n                    comment = iv.comment;\n                if (iv.commentBefore)\n                    reqNewline = true;\n            }\n            else if (item.value == null && ik?.comment) {\n                comment = ik.comment;\n            }\n        }\n        if (comment)\n            reqNewline = true;\n        let str = stringify.stringify(item, itemCtx, () => (comment = null));\n        reqNewline || (reqNewline = lines.length > linesAtValue || str.includes('\\n'));\n        if (i < items.length - 1) {\n            str += ',';\n        }\n        else if (ctx.options.trailingComma) {\n            if (ctx.options.lineWidth > 0) {\n                reqNewline || (reqNewline = lines.reduce((sum, line) => sum + line.length + 2, 2) +\n                    (str.length + 2) >\n                    ctx.options.lineWidth);\n            }\n            if (reqNewline) {\n                str += ',';\n            }\n        }\n        if (comment)\n            str += stringifyComment.lineComment(str, itemIndent, commentString(comment));\n        lines.push(str);\n        linesAtValue = lines.length;\n    }\n    const { start, end } = flowChars;\n    if (lines.length === 0) {\n        return start + end;\n    }\n    else {\n        if (!reqNewline) {\n            const len = lines.reduce((sum, line) => sum + line.length + 2, 2);\n            reqNewline = ctx.options.lineWidth > 0 && len > ctx.options.lineWidth;\n        }\n        if (reqNewline) {\n            let str = start;\n            for (const line of lines)\n                str += line ? `\\n${indentStep}${indent}${line}` : '\\n';\n            return `${str}\\n${indent}${end}`;\n        }\n        else {\n            return `${start}${fcPadding}${lines.join(' ')}${fcPadding}${end}`;\n        }\n    }\n}\nfunction addCommentBefore({ indent, options: { commentString } }, lines, comment, chompKeep) {\n    if (comment && chompKeep)\n        comment = comment.replace(/^\\n+/, '');\n    if (comment) {\n        const ic = stringifyComment.indentComment(commentString(comment), indent);\n        lines.push(ic.trimStart()); // Avoid double indent on first line\n    }\n}\n\nexports.stringifyCollection = stringifyCollection;\n","'use strict';\n\nvar stringifyCollection = require('../stringify/stringifyCollection.js');\nvar addPairToJSMap = require('./addPairToJSMap.js');\nvar Collection = require('./Collection.js');\nvar identity = require('./identity.js');\nvar Pair = require('./Pair.js');\nvar Scalar = require('./Scalar.js');\n\nfunction findPair(items, key) {\n    const k = identity.isScalar(key) ? key.value : key;\n    for (const it of items) {\n        if (identity.isPair(it)) {\n            if (it.key === key || it.key === k)\n                return it;\n            if (identity.isScalar(it.key) && it.key.value === k)\n                return it;\n        }\n    }\n    return undefined;\n}\nclass YAMLMap extends Collection.Collection {\n    static get tagName() {\n        return 'tag:yaml.org,2002:map';\n    }\n    constructor(schema) {\n        super(identity.MAP, schema);\n        this.items = [];\n    }\n    /**\n     * A generic collection parsing method that can be extended\n     * to other node classes that inherit from YAMLMap\n     */\n    static from(schema, obj, ctx) {\n        const { keepUndefined, replacer } = ctx;\n        const map = new this(schema);\n        const add = (key, value) => {\n            if (typeof replacer === 'function')\n                value = replacer.call(obj, key, value);\n            else if (Array.isArray(replacer) && !replacer.includes(key))\n                return;\n            if (value !== undefined || keepUndefined)\n                map.items.push(Pair.createPair(key, value, ctx));\n        };\n        if (obj instanceof Map) {\n            for (const [key, value] of obj)\n                add(key, value);\n        }\n        else if (obj && typeof obj === 'object') {\n            for (const key of Object.keys(obj))\n                add(key, obj[key]);\n        }\n        if (typeof schema.sortMapEntries === 'function') {\n            map.items.sort(schema.sortMapEntries);\n        }\n        return map;\n    }\n    /**\n     * Adds a value to the collection.\n     *\n     * @param overwrite - If not set `true`, using a key that is already in the\n     *   collection will throw. Otherwise, overwrites the previous value.\n     */\n    add(pair, overwrite) {\n        let _pair;\n        if (identity.isPair(pair))\n            _pair = pair;\n        else if (!pair || typeof pair !== 'object' || !('key' in pair)) {\n            // In TypeScript, this never happens.\n            _pair = new Pair.Pair(pair, pair?.value);\n        }\n        else\n            _pair = new Pair.Pair(pair.key, pair.value);\n        const prev = findPair(this.items, _pair.key);\n        const sortEntries = this.schema?.sortMapEntries;\n        if (prev) {\n            if (!overwrite)\n                throw new Error(`Key ${_pair.key} already set`);\n            // For scalars, keep the old node & its comments and anchors\n            if (identity.isScalar(prev.value) && Scalar.isScalarValue(_pair.value))\n                prev.value.value = _pair.value;\n            else\n                prev.value = _pair.value;\n        }\n        else if (sortEntries) {\n            const i = this.items.findIndex(item => sortEntries(_pair, item) < 0);\n            if (i === -1)\n                this.items.push(_pair);\n            else\n                this.items.splice(i, 0, _pair);\n        }\n        else {\n            this.items.push(_pair);\n        }\n    }\n    delete(key) {\n        const it = findPair(this.items, key);\n        if (!it)\n            return false;\n        const del = this.items.splice(this.items.indexOf(it), 1);\n        return del.length > 0;\n    }\n    get(key, keepScalar) {\n        const it = findPair(this.items, key);\n        const node = it?.value;\n        return (!keepScalar && identity.isScalar(node) ? node.value : node) ?? undefined;\n    }\n    has(key) {\n        return !!findPair(this.items, key);\n    }\n    set(key, value) {\n        this.add(new Pair.Pair(key, value), true);\n    }\n    /**\n     * @param ctx - Conversion context, originally set in Document#toJS()\n     * @param {Class} Type - If set, forces the returned collection type\n     * @returns Instance of Type, Map, or Object\n     */\n    toJSON(_, ctx, Type) {\n        const map = Type ? new Type() : ctx?.mapAsMap ? new Map() : {};\n        if (ctx?.onCreate)\n            ctx.onCreate(map);\n        for (const item of this.items)\n            addPairToJSMap.addPairToJSMap(ctx, map, item);\n        return map;\n    }\n    toString(ctx, onComment, onChompKeep) {\n        if (!ctx)\n            return JSON.stringify(this);\n        for (const item of this.items) {\n            if (!identity.isPair(item))\n                throw new Error(`Map items must all be pairs; found ${JSON.stringify(item)} instead`);\n        }\n        if (!ctx.allNullValues && this.hasAllNullValues(false))\n            ctx = Object.assign({}, ctx, { allNullValues: true });\n        return stringifyCollection.stringifyCollection(this, ctx, {\n            blockItemPrefix: '',\n            flowChars: { start: '{', end: '}' },\n            itemIndent: ctx.indent || '',\n            onChompKeep,\n            onComment\n        });\n    }\n}\n\nexports.YAMLMap = YAMLMap;\nexports.findPair = findPair;\n","'use strict';\n\nvar identity = require('../../nodes/identity.js');\nvar YAMLMap = require('../../nodes/YAMLMap.js');\n\nconst map = {\n    collection: 'map',\n    default: true,\n    nodeClass: YAMLMap.YAMLMap,\n    tag: 'tag:yaml.org,2002:map',\n    resolve(map, onError) {\n        if (!identity.isMap(map))\n            onError('Expected a mapping for this tag');\n        return map;\n    },\n    createNode: (schema, obj, ctx) => YAMLMap.YAMLMap.from(schema, obj, ctx)\n};\n\nexports.map = map;\n","'use strict';\n\nvar createNode = require('../doc/createNode.js');\nvar stringifyCollection = require('../stringify/stringifyCollection.js');\nvar Collection = require('./Collection.js');\nvar identity = require('./identity.js');\nvar Scalar = require('./Scalar.js');\nvar toJS = require('./toJS.js');\n\nclass YAMLSeq extends Collection.Collection {\n    static get tagName() {\n        return 'tag:yaml.org,2002:seq';\n    }\n    constructor(schema) {\n        super(identity.SEQ, schema);\n        this.items = [];\n    }\n    add(value) {\n        this.items.push(value);\n    }\n    /**\n     * Removes a value from the collection.\n     *\n     * `key` must contain a representation of an integer for this to succeed.\n     * It may be wrapped in a `Scalar`.\n     *\n     * @returns `true` if the item was found and removed.\n     */\n    delete(key) {\n        const idx = asItemIndex(key);\n        if (typeof idx !== 'number')\n            return false;\n        const del = this.items.splice(idx, 1);\n        return del.length > 0;\n    }\n    get(key, keepScalar) {\n        const idx = asItemIndex(key);\n        if (typeof idx !== 'number')\n            return undefined;\n        const it = this.items[idx];\n        return !keepScalar && identity.isScalar(it) ? it.value : it;\n    }\n    /**\n     * Checks if the collection includes a value with the key `key`.\n     *\n     * `key` must contain a representation of an integer for this to succeed.\n     * It may be wrapped in a `Scalar`.\n     */\n    has(key) {\n        const idx = asItemIndex(key);\n        return typeof idx === 'number' && idx < this.items.length;\n    }\n    /**\n     * Sets a value in this collection. For `!!set`, `value` needs to be a\n     * boolean to add/remove the item from the set.\n     *\n     * If `key` does not contain a representation of an integer, this will throw.\n     * It may be wrapped in a `Scalar`.\n     */\n    set(key, value) {\n        const idx = asItemIndex(key);\n        if (typeof idx !== 'number')\n            throw new Error(`Expected a valid index, not ${key}.`);\n        const prev = this.items[idx];\n        if (identity.isScalar(prev) && Scalar.isScalarValue(value))\n            prev.value = value;\n        else\n            this.items[idx] = value;\n    }\n    toJSON(_, ctx) {\n        const seq = [];\n        if (ctx?.onCreate)\n            ctx.onCreate(seq);\n        let i = 0;\n        for (const item of this.items)\n            seq.push(toJS.toJS(item, String(i++), ctx));\n        return seq;\n    }\n    toString(ctx, onComment, onChompKeep) {\n        if (!ctx)\n            return JSON.stringify(this);\n        return stringifyCollection.stringifyCollection(this, ctx, {\n            blockItemPrefix: '- ',\n            flowChars: { start: '[', end: ']' },\n            itemIndent: (ctx.indent || '') + '  ',\n            onChompKeep,\n            onComment\n        });\n    }\n    static from(schema, obj, ctx) {\n        const { replacer } = ctx;\n        const seq = new this(schema);\n        if (obj && Symbol.iterator in Object(obj)) {\n            let i = 0;\n            for (let it of obj) {\n                if (typeof replacer === 'function') {\n                    const key = obj instanceof Set ? it : String(i++);\n                    it = replacer.call(obj, key, it);\n                }\n                seq.items.push(createNode.createNode(it, undefined, ctx));\n            }\n        }\n        return seq;\n    }\n}\nfunction asItemIndex(key) {\n    let idx = identity.isScalar(key) ? key.value : key;\n    if (idx && typeof idx === 'string')\n        idx = Number(idx);\n    return typeof idx === 'number' && Number.isInteger(idx) && idx >= 0\n        ? idx\n        : null;\n}\n\nexports.YAMLSeq = YAMLSeq;\n","'use strict';\n\nvar identity = require('../../nodes/identity.js');\nvar YAMLSeq = require('../../nodes/YAMLSeq.js');\n\nconst seq = {\n    collection: 'seq',\n    default: true,\n    nodeClass: YAMLSeq.YAMLSeq,\n    tag: 'tag:yaml.org,2002:seq',\n    resolve(seq, onError) {\n        if (!identity.isSeq(seq))\n            onError('Expected a sequence for this tag');\n        return seq;\n    },\n    createNode: (schema, obj, ctx) => YAMLSeq.YAMLSeq.from(schema, obj, ctx)\n};\n\nexports.seq = seq;\n","'use strict';\n\nvar stringifyString = require('../../stringify/stringifyString.js');\n\nconst string = {\n    identify: value => typeof value === 'string',\n    default: true,\n    tag: 'tag:yaml.org,2002:str',\n    resolve: str => str,\n    stringify(item, ctx, onComment, onChompKeep) {\n        ctx = Object.assign({ actualString: true }, ctx);\n        return stringifyString.stringifyString(item, ctx, onComment, onChompKeep);\n    }\n};\n\nexports.string = string;\n","'use strict';\n\nvar Scalar = require('../../nodes/Scalar.js');\n\nconst nullTag = {\n    identify: value => value == null,\n    createNode: () => new Scalar.Scalar(null),\n    default: true,\n    tag: 'tag:yaml.org,2002:null',\n    test: /^(?:~|[Nn]ull|NULL)?$/,\n    resolve: () => new Scalar.Scalar(null),\n    stringify: ({ source }, ctx) => typeof source === 'string' && nullTag.test.test(source)\n        ? source\n        : ctx.options.nullStr\n};\n\nexports.nullTag = nullTag;\n","'use strict';\n\nvar Scalar = require('../../nodes/Scalar.js');\n\nconst boolTag = {\n    identify: value => typeof value === 'boolean',\n    default: true,\n    tag: 'tag:yaml.org,2002:bool',\n    test: /^(?:[Tt]rue|TRUE|[Ff]alse|FALSE)$/,\n    resolve: str => new Scalar.Scalar(str[0] === 't' || str[0] === 'T'),\n    stringify({ source, value }, ctx) {\n        if (source && boolTag.test.test(source)) {\n            const sv = source[0] === 't' || source[0] === 'T';\n            if (value === sv)\n                return source;\n        }\n        return value ? ctx.options.trueStr : ctx.options.falseStr;\n    }\n};\n\nexports.boolTag = boolTag;\n","'use strict';\n\nfunction stringifyNumber({ format, minFractionDigits, tag, value }) {\n    if (typeof value === 'bigint')\n        return String(value);\n    const num = typeof value === 'number' ? value : Number(value);\n    if (!isFinite(num))\n        return isNaN(num) ? '.nan' : num < 0 ? '-.inf' : '.inf';\n    let n = Object.is(value, -0) ? '-0' : JSON.stringify(value);\n    if (!format &&\n        minFractionDigits &&\n        (!tag || tag === 'tag:yaml.org,2002:float') &&\n        /^-?\\d/.test(n) &&\n        !n.includes('e')) {\n        let i = n.indexOf('.');\n        if (i < 0) {\n            i = n.length;\n            n += '.';\n        }\n        let d = minFractionDigits - (n.length - i - 1);\n        while (d-- > 0)\n            n += '0';\n    }\n    return n;\n}\n\nexports.stringifyNumber = stringifyNumber;\n","'use strict';\n\nvar Scalar = require('../../nodes/Scalar.js');\nvar stringifyNumber = require('../../stringify/stringifyNumber.js');\n\nconst floatNaN = {\n    identify: value => typeof value === 'number',\n    default: true,\n    tag: 'tag:yaml.org,2002:float',\n    test: /^(?:[-+]?\\.(?:inf|Inf|INF)|\\.nan|\\.NaN|\\.NAN)$/,\n    resolve: str => str.slice(-3).toLowerCase() === 'nan'\n        ? NaN\n        : str[0] === '-'\n            ? Number.NEGATIVE_INFINITY\n            : Number.POSITIVE_INFINITY,\n    stringify: stringifyNumber.stringifyNumber\n};\nconst floatExp = {\n    identify: value => typeof value === 'number',\n    default: true,\n    tag: 'tag:yaml.org,2002:float',\n    format: 'EXP',\n    test: /^[-+]?(?:\\.[0-9]+|[0-9]+(?:\\.[0-9]*)?)[eE][-+]?[0-9]+$/,\n    resolve: str => parseFloat(str),\n    stringify(node) {\n        const num = Number(node.value);\n        return isFinite(num) ? num.toExponential() : stringifyNumber.stringifyNumber(node);\n    }\n};\nconst float = {\n    identify: value => typeof value === 'number',\n    default: true,\n    tag: 'tag:yaml.org,2002:float',\n    test: /^[-+]?(?:\\.[0-9]+|[0-9]+\\.[0-9]*)$/,\n    resolve(str) {\n        const node = new Scalar.Scalar(parseFloat(str));\n        const dot = str.indexOf('.');\n        if (dot !== -1 && str[str.length - 1] === '0')\n            node.minFractionDigits = str.length - dot - 1;\n        return node;\n    },\n    stringify: stringifyNumber.stringifyNumber\n};\n\nexports.float = float;\nexports.floatExp = floatExp;\nexports.floatNaN = floatNaN;\n","'use strict';\n\nvar stringifyNumber = require('../../stringify/stringifyNumber.js');\n\nconst intIdentify = (value) => typeof value === 'bigint' || Number.isInteger(value);\nconst intResolve = (str, offset, radix, { intAsBigInt }) => (intAsBigInt ? BigInt(str) : parseInt(str.substring(offset), radix));\nfunction intStringify(node, radix, prefix) {\n    const { value } = node;\n    if (intIdentify(value) && value >= 0)\n        return prefix + value.toString(radix);\n    return stringifyNumber.stringifyNumber(node);\n}\nconst intOct = {\n    identify: value => intIdentify(value) && value >= 0,\n    default: true,\n    tag: 'tag:yaml.org,2002:int',\n    format: 'OCT',\n    test: /^0o[0-7]+$/,\n    resolve: (str, _onError, opt) => intResolve(str, 2, 8, opt),\n    stringify: node => intStringify(node, 8, '0o')\n};\nconst int = {\n    identify: intIdentify,\n    default: true,\n    tag: 'tag:yaml.org,2002:int',\n    test: /^[-+]?[0-9]+$/,\n    resolve: (str, _onError, opt) => intResolve(str, 0, 10, opt),\n    stringify: stringifyNumber.stringifyNumber\n};\nconst intHex = {\n    identify: value => intIdentify(value) && value >= 0,\n    default: true,\n    tag: 'tag:yaml.org,2002:int',\n    format: 'HEX',\n    test: /^0x[0-9a-fA-F]+$/,\n    resolve: (str, _onError, opt) => intResolve(str, 2, 16, opt),\n    stringify: node => intStringify(node, 16, '0x')\n};\n\nexports.int = int;\nexports.intHex = intHex;\nexports.intOct = intOct;\n","'use strict';\n\nvar map = require('../common/map.js');\nvar _null = require('../common/null.js');\nvar seq = require('../common/seq.js');\nvar string = require('../common/string.js');\nvar bool = require('./bool.js');\nvar float = require('./float.js');\nvar int = require('./int.js');\n\nconst schema = [\n    map.map,\n    seq.seq,\n    string.string,\n    _null.nullTag,\n    bool.boolTag,\n    int.intOct,\n    int.int,\n    int.intHex,\n    float.floatNaN,\n    float.floatExp,\n    float.float\n];\n\nexports.schema = schema;\n","'use strict';\n\nvar Scalar = require('../../nodes/Scalar.js');\nvar map = require('../common/map.js');\nvar seq = require('../common/seq.js');\n\nfunction intIdentify(value) {\n    return typeof value === 'bigint' || Number.isInteger(value);\n}\nconst stringifyJSON = ({ value }) => JSON.stringify(value);\nconst jsonScalars = [\n    {\n        identify: value => typeof value === 'string',\n        default: true,\n        tag: 'tag:yaml.org,2002:str',\n        resolve: str => str,\n        stringify: stringifyJSON\n    },\n    {\n        identify: value => value == null,\n        createNode: () => new Scalar.Scalar(null),\n        default: true,\n        tag: 'tag:yaml.org,2002:null',\n        test: /^null$/,\n        resolve: () => null,\n        stringify: stringifyJSON\n    },\n    {\n        identify: value => typeof value === 'boolean',\n        default: true,\n        tag: 'tag:yaml.org,2002:bool',\n        test: /^true$|^false$/,\n        resolve: str => str === 'true',\n        stringify: stringifyJSON\n    },\n    {\n        identify: intIdentify,\n        default: true,\n        tag: 'tag:yaml.org,2002:int',\n        test: /^-?(?:0|[1-9][0-9]*)$/,\n        resolve: (str, _onError, { intAsBigInt }) => intAsBigInt ? BigInt(str) : parseInt(str, 10),\n        stringify: ({ value }) => intIdentify(value) ? value.toString() : JSON.stringify(value)\n    },\n    {\n        identify: value => typeof value === 'number',\n        default: true,\n        tag: 'tag:yaml.org,2002:float',\n        test: /^-?(?:0|[1-9][0-9]*)(?:\\.[0-9]*)?(?:[eE][-+]?[0-9]+)?$/,\n        resolve: str => parseFloat(str),\n        stringify: stringifyJSON\n    }\n];\nconst jsonError = {\n    default: true,\n    tag: '',\n    test: /^/,\n    resolve(str, onError) {\n        onError(`Unresolved plain scalar ${JSON.stringify(str)}`);\n        return str;\n    }\n};\nconst schema = [map.map, seq.seq].concat(jsonScalars, jsonError);\n\nexports.schema = schema;\n","'use strict';\n\nvar node_buffer = require('buffer');\nvar Scalar = require('../../nodes/Scalar.js');\nvar stringifyString = require('../../stringify/stringifyString.js');\n\nconst binary = {\n    identify: value => value instanceof Uint8Array, // Buffer inherits from Uint8Array\n    default: false,\n    tag: 'tag:yaml.org,2002:binary',\n    /**\n     * Returns a Buffer in node and an Uint8Array in browsers\n     *\n     * To use the resulting buffer as an image, you'll want to do something like:\n     *\n     *   const blob = new Blob([buffer], { type: 'image/jpeg' })\n     *   document.querySelector('#photo').src = URL.createObjectURL(blob)\n     */\n    resolve(src, onError) {\n        if (typeof node_buffer.Buffer === 'function') {\n            return node_buffer.Buffer.from(src, 'base64');\n        }\n        else if (typeof atob === 'function') {\n            // On IE 11, atob() can't handle newlines\n            const str = atob(src.replace(/[\\n\\r]/g, ''));\n            const buffer = new Uint8Array(str.length);\n            for (let i = 0; i < str.length; ++i)\n                buffer[i] = str.charCodeAt(i);\n            return buffer;\n        }\n        else {\n            onError('This environment does not support reading binary tags; either Buffer or atob is required');\n            return src;\n        }\n    },\n    stringify({ comment, type, value }, ctx, onComment, onChompKeep) {\n        if (!value)\n            return '';\n        const buf = value; // checked earlier by binary.identify()\n        let str;\n        if (typeof node_buffer.Buffer === 'function') {\n            str =\n                buf instanceof node_buffer.Buffer\n                    ? buf.toString('base64')\n                    : node_buffer.Buffer.from(buf.buffer).toString('base64');\n        }\n        else if (typeof btoa === 'function') {\n            let s = '';\n            for (let i = 0; i < buf.length; ++i)\n                s += String.fromCharCode(buf[i]);\n            str = btoa(s);\n        }\n        else {\n            throw new Error('This environment does not support writing binary tags; either Buffer or btoa is required');\n        }\n        type ?? (type = Scalar.Scalar.BLOCK_LITERAL);\n        if (type !== Scalar.Scalar.QUOTE_DOUBLE) {\n            const lineWidth = Math.max(ctx.options.lineWidth - ctx.indent.length, ctx.options.minContentWidth);\n            const n = Math.ceil(str.length / lineWidth);\n            const lines = new Array(n);\n            for (let i = 0, o = 0; i < n; ++i, o += lineWidth) {\n                lines[i] = str.substr(o, lineWidth);\n            }\n            str = lines.join(type === Scalar.Scalar.BLOCK_LITERAL ? '\\n' : ' ');\n        }\n        return stringifyString.stringifyString({ comment, type, value: str }, ctx, onComment, onChompKeep);\n    }\n};\n\nexports.binary = binary;\n","'use strict';\n\nvar identity = require('../../nodes/identity.js');\nvar Pair = require('../../nodes/Pair.js');\nvar Scalar = require('../../nodes/Scalar.js');\nvar YAMLSeq = require('../../nodes/YAMLSeq.js');\n\nfunction resolvePairs(seq, onError) {\n    if (identity.isSeq(seq)) {\n        for (let i = 0; i < seq.items.length; ++i) {\n            let item = seq.items[i];\n            if (identity.isPair(item))\n                continue;\n            else if (identity.isMap(item)) {\n                if (item.items.length > 1)\n                    onError('Each pair must have its own sequence indicator');\n                const pair = item.items[0] || new Pair.Pair(new Scalar.Scalar(null));\n                if (item.commentBefore)\n                    pair.key.commentBefore = pair.key.commentBefore\n                        ? `${item.commentBefore}\\n${pair.key.commentBefore}`\n                        : item.commentBefore;\n                if (item.comment) {\n                    const cn = pair.value ?? pair.key;\n                    cn.comment = cn.comment\n                        ? `${item.comment}\\n${cn.comment}`\n                        : item.comment;\n                }\n                item = pair;\n            }\n            seq.items[i] = identity.isPair(item) ? item : new Pair.Pair(item);\n        }\n    }\n    else\n        onError('Expected a sequence for this tag');\n    return seq;\n}\nfunction createPairs(schema, iterable, ctx) {\n    const { replacer } = ctx;\n    const pairs = new YAMLSeq.YAMLSeq(schema);\n    pairs.tag = 'tag:yaml.org,2002:pairs';\n    let i = 0;\n    if (iterable && Symbol.iterator in Object(iterable))\n        for (let it of iterable) {\n            if (typeof replacer === 'function')\n                it = replacer.call(iterable, String(i++), it);\n            let key, value;\n            if (Array.isArray(it)) {\n                if (it.length === 2) {\n                    key = it[0];\n                    value = it[1];\n                }\n                else\n                    throw new TypeError(`Expected [key, value] tuple: ${it}`);\n            }\n            else if (it && it instanceof Object) {\n                const keys = Object.keys(it);\n                if (keys.length === 1) {\n                    key = keys[0];\n                    value = it[key];\n                }\n                else {\n                    throw new TypeError(`Expected tuple with one key, not ${keys.length} keys`);\n                }\n            }\n            else {\n                key = it;\n            }\n            pairs.items.push(Pair.createPair(key, value, ctx));\n        }\n    return pairs;\n}\nconst pairs = {\n    collection: 'seq',\n    default: false,\n    tag: 'tag:yaml.org,2002:pairs',\n    resolve: resolvePairs,\n    createNode: createPairs\n};\n\nexports.createPairs = createPairs;\nexports.pairs = pairs;\nexports.resolvePairs = resolvePairs;\n","'use strict';\n\nvar identity = require('../../nodes/identity.js');\nvar toJS = require('../../nodes/toJS.js');\nvar YAMLMap = require('../../nodes/YAMLMap.js');\nvar YAMLSeq = require('../../nodes/YAMLSeq.js');\nvar pairs = require('./pairs.js');\n\nclass YAMLOMap extends YAMLSeq.YAMLSeq {\n    constructor() {\n        super();\n        this.add = YAMLMap.YAMLMap.prototype.add.bind(this);\n        this.delete = YAMLMap.YAMLMap.prototype.delete.bind(this);\n        this.get = YAMLMap.YAMLMap.prototype.get.bind(this);\n        this.has = YAMLMap.YAMLMap.prototype.has.bind(this);\n        this.set = YAMLMap.YAMLMap.prototype.set.bind(this);\n        this.tag = YAMLOMap.tag;\n    }\n    /**\n     * If `ctx` is given, the return type is actually `Map<unknown, unknown>`,\n     * but TypeScript won't allow widening the signature of a child method.\n     */\n    toJSON(_, ctx) {\n        if (!ctx)\n            return super.toJSON(_);\n        const map = new Map();\n        if (ctx?.onCreate)\n            ctx.onCreate(map);\n        for (const pair of this.items) {\n            let key, value;\n            if (identity.isPair(pair)) {\n                key = toJS.toJS(pair.key, '', ctx);\n                value = toJS.toJS(pair.value, key, ctx);\n            }\n            else {\n                key = toJS.toJS(pair, '', ctx);\n            }\n            if (map.has(key))\n                throw new Error('Ordered maps must not include duplicate keys');\n            map.set(key, value);\n        }\n        return map;\n    }\n    static from(schema, iterable, ctx) {\n        const pairs$1 = pairs.createPairs(schema, iterable, ctx);\n        const omap = new this();\n        omap.items = pairs$1.items;\n        return omap;\n    }\n}\nYAMLOMap.tag = 'tag:yaml.org,2002:omap';\nconst omap = {\n    collection: 'seq',\n    identify: value => value instanceof Map,\n    nodeClass: YAMLOMap,\n    default: false,\n    tag: 'tag:yaml.org,2002:omap',\n    resolve(seq, onError) {\n        const pairs$1 = pairs.resolvePairs(seq, onError);\n        const seenKeys = [];\n        for (const { key } of pairs$1.items) {\n            if (identity.isScalar(key)) {\n                if (seenKeys.includes(key.value)) {\n                    onError(`Ordered maps must not include duplicate keys: ${key.value}`);\n                }\n                else {\n                    seenKeys.push(key.value);\n                }\n            }\n        }\n        return Object.assign(new YAMLOMap(), pairs$1);\n    },\n    createNode: (schema, iterable, ctx) => YAMLOMap.from(schema, iterable, ctx)\n};\n\nexports.YAMLOMap = YAMLOMap;\nexports.omap = omap;\n","'use strict';\n\nvar Scalar = require('../../nodes/Scalar.js');\n\nfunction boolStringify({ value, source }, ctx) {\n    const boolObj = value ? trueTag : falseTag;\n    if (source && boolObj.test.test(source))\n        return source;\n    return value ? ctx.options.trueStr : ctx.options.falseStr;\n}\nconst trueTag = {\n    identify: value => value === true,\n    default: true,\n    tag: 'tag:yaml.org,2002:bool',\n    test: /^(?:Y|y|[Yy]es|YES|[Tt]rue|TRUE|[Oo]n|ON)$/,\n    resolve: () => new Scalar.Scalar(true),\n    stringify: boolStringify\n};\nconst falseTag = {\n    identify: value => value === false,\n    default: true,\n    tag: 'tag:yaml.org,2002:bool',\n    test: /^(?:N|n|[Nn]o|NO|[Ff]alse|FALSE|[Oo]ff|OFF)$/,\n    resolve: () => new Scalar.Scalar(false),\n    stringify: boolStringify\n};\n\nexports.falseTag = falseTag;\nexports.trueTag = trueTag;\n","'use strict';\n\nvar Scalar = require('../../nodes/Scalar.js');\nvar stringifyNumber = require('../../stringify/stringifyNumber.js');\n\nconst floatNaN = {\n    identify: value => typeof value === 'number',\n    default: true,\n    tag: 'tag:yaml.org,2002:float',\n    test: /^(?:[-+]?\\.(?:inf|Inf|INF)|\\.nan|\\.NaN|\\.NAN)$/,\n    resolve: (str) => str.slice(-3).toLowerCase() === 'nan'\n        ? NaN\n        : str[0] === '-'\n            ? Number.NEGATIVE_INFINITY\n            : Number.POSITIVE_INFINITY,\n    stringify: stringifyNumber.stringifyNumber\n};\nconst floatExp = {\n    identify: value => typeof value === 'number',\n    default: true,\n    tag: 'tag:yaml.org,2002:float',\n    format: 'EXP',\n    test: /^[-+]?(?:[0-9][0-9_]*)?(?:\\.[0-9_]*)?[eE][-+]?[0-9]+$/,\n    resolve: (str) => parseFloat(str.replace(/_/g, '')),\n    stringify(node) {\n        const num = Number(node.value);\n        return isFinite(num) ? num.toExponential() : stringifyNumber.stringifyNumber(node);\n    }\n};\nconst float = {\n    identify: value => typeof value === 'number',\n    default: true,\n    tag: 'tag:yaml.org,2002:float',\n    test: /^[-+]?(?:[0-9][0-9_]*)?\\.[0-9_]*$/,\n    resolve(str) {\n        const node = new Scalar.Scalar(parseFloat(str.replace(/_/g, '')));\n        const dot = str.indexOf('.');\n        if (dot !== -1) {\n            const f = str.substring(dot + 1).replace(/_/g, '');\n            if (f[f.length - 1] === '0')\n                node.minFractionDigits = f.length;\n        }\n        return node;\n    },\n    stringify: stringifyNumber.stringifyNumber\n};\n\nexports.float = float;\nexports.floatExp = floatExp;\nexports.floatNaN = floatNaN;\n","'use strict';\n\nvar stringifyNumber = require('../../stringify/stringifyNumber.js');\n\nconst intIdentify = (value) => typeof value === 'bigint' || Number.isInteger(value);\nfunction intResolve(str, offset, radix, { intAsBigInt }) {\n    const sign = str[0];\n    if (sign === '-' || sign === '+')\n        offset += 1;\n    str = str.substring(offset).replace(/_/g, '');\n    if (intAsBigInt) {\n        switch (radix) {\n            case 2:\n                str = `0b${str}`;\n                break;\n            case 8:\n                str = `0o${str}`;\n                break;\n            case 16:\n                str = `0x${str}`;\n                break;\n        }\n        const n = BigInt(str);\n        return sign === '-' ? BigInt(-1) * n : n;\n    }\n    const n = parseInt(str, radix);\n    return sign === '-' ? -1 * n : n;\n}\nfunction intStringify(node, radix, prefix) {\n    const { value } = node;\n    if (intIdentify(value)) {\n        const str = value.toString(radix);\n        return value < 0 ? '-' + prefix + str.substr(1) : prefix + str;\n    }\n    return stringifyNumber.stringifyNumber(node);\n}\nconst intBin = {\n    identify: intIdentify,\n    default: true,\n    tag: 'tag:yaml.org,2002:int',\n    format: 'BIN',\n    test: /^[-+]?0b[0-1_]+$/,\n    resolve: (str, _onError, opt) => intResolve(str, 2, 2, opt),\n    stringify: node => intStringify(node, 2, '0b')\n};\nconst intOct = {\n    identify: intIdentify,\n    default: true,\n    tag: 'tag:yaml.org,2002:int',\n    format: 'OCT',\n    test: /^[-+]?0[0-7_]+$/,\n    resolve: (str, _onError, opt) => intResolve(str, 1, 8, opt),\n    stringify: node => intStringify(node, 8, '0')\n};\nconst int = {\n    identify: intIdentify,\n    default: true,\n    tag: 'tag:yaml.org,2002:int',\n    test: /^[-+]?[0-9][0-9_]*$/,\n    resolve: (str, _onError, opt) => intResolve(str, 0, 10, opt),\n    stringify: stringifyNumber.stringifyNumber\n};\nconst intHex = {\n    identify: intIdentify,\n    default: true,\n    tag: 'tag:yaml.org,2002:int',\n    format: 'HEX',\n    test: /^[-+]?0x[0-9a-fA-F_]+$/,\n    resolve: (str, _onError, opt) => intResolve(str, 2, 16, opt),\n    stringify: node => intStringify(node, 16, '0x')\n};\n\nexports.int = int;\nexports.intBin = intBin;\nexports.intHex = intHex;\nexports.intOct = intOct;\n","'use strict';\n\nvar identity = require('../../nodes/identity.js');\nvar Pair = require('../../nodes/Pair.js');\nvar YAMLMap = require('../../nodes/YAMLMap.js');\n\nclass YAMLSet extends YAMLMap.YAMLMap {\n    constructor(schema) {\n        super(schema);\n        this.tag = YAMLSet.tag;\n    }\n    add(key) {\n        let pair;\n        if (identity.isPair(key))\n            pair = key;\n        else if (key &&\n            typeof key === 'object' &&\n            'key' in key &&\n            'value' in key &&\n            key.value === null)\n            pair = new Pair.Pair(key.key, null);\n        else\n            pair = new Pair.Pair(key, null);\n        const prev = YAMLMap.findPair(this.items, pair.key);\n        if (!prev)\n            this.items.push(pair);\n    }\n    /**\n     * If `keepPair` is `true`, returns the Pair matching `key`.\n     * Otherwise, returns the value of that Pair's key.\n     */\n    get(key, keepPair) {\n        const pair = YAMLMap.findPair(this.items, key);\n        return !keepPair && identity.isPair(pair)\n            ? identity.isScalar(pair.key)\n                ? pair.key.value\n                : pair.key\n            : pair;\n    }\n    set(key, value) {\n        if (typeof value !== 'boolean')\n            throw new Error(`Expected boolean value for set(key, value) in a YAML set, not ${typeof value}`);\n        const prev = YAMLMap.findPair(this.items, key);\n        if (prev && !value) {\n            this.items.splice(this.items.indexOf(prev), 1);\n        }\n        else if (!prev && value) {\n            this.items.push(new Pair.Pair(key));\n        }\n    }\n    toJSON(_, ctx) {\n        return super.toJSON(_, ctx, Set);\n    }\n    toString(ctx, onComment, onChompKeep) {\n        if (!ctx)\n            return JSON.stringify(this);\n        if (this.hasAllNullValues(true))\n            return super.toString(Object.assign({}, ctx, { allNullValues: true }), onComment, onChompKeep);\n        else\n            throw new Error('Set items must all have null values');\n    }\n    static from(schema, iterable, ctx) {\n        const { replacer } = ctx;\n        const set = new this(schema);\n        if (iterable && Symbol.iterator in Object(iterable))\n            for (let value of iterable) {\n                if (typeof replacer === 'function')\n                    value = replacer.call(iterable, value, value);\n                set.items.push(Pair.createPair(value, null, ctx));\n            }\n        return set;\n    }\n}\nYAMLSet.tag = 'tag:yaml.org,2002:set';\nconst set = {\n    collection: 'map',\n    identify: value => value instanceof Set,\n    nodeClass: YAMLSet,\n    default: false,\n    tag: 'tag:yaml.org,2002:set',\n    createNode: (schema, iterable, ctx) => YAMLSet.from(schema, iterable, ctx),\n    resolve(map, onError) {\n        if (identity.isMap(map)) {\n            if (map.hasAllNullValues(true))\n                return Object.assign(new YAMLSet(), map);\n            else\n                onError('Set items must all have null values');\n        }\n        else\n            onError('Expected a mapping for this tag');\n        return map;\n    }\n};\n\nexports.YAMLSet = YAMLSet;\nexports.set = set;\n","'use strict';\n\nvar stringifyNumber = require('../../stringify/stringifyNumber.js');\n\n/** Internal types handle bigint as number, because TS can't figure it out. */\nfunction parseSexagesimal(str, asBigInt) {\n    const sign = str[0];\n    const parts = sign === '-' || sign === '+' ? str.substring(1) : str;\n    const num = (n) => asBigInt ? BigInt(n) : Number(n);\n    const res = parts\n        .replace(/_/g, '')\n        .split(':')\n        .reduce((res, p) => res * num(60) + num(p), num(0));\n    return (sign === '-' ? num(-1) * res : res);\n}\n/**\n * hhhh:mm:ss.sss\n *\n * Internal types handle bigint as number, because TS can't figure it out.\n */\nfunction stringifySexagesimal(node) {\n    let { value } = node;\n    let num = (n) => n;\n    if (typeof value === 'bigint')\n        num = n => BigInt(n);\n    else if (isNaN(value) || !isFinite(value))\n        return stringifyNumber.stringifyNumber(node);\n    let sign = '';\n    if (value < 0) {\n        sign = '-';\n        value *= num(-1);\n    }\n    const _60 = num(60);\n    const parts = [value % _60]; // seconds, including ms\n    if (value < 60) {\n        parts.unshift(0); // at least one : is required\n    }\n    else {\n        value = (value - parts[0]) / _60;\n        parts.unshift(value % _60); // minutes\n        if (value >= 60) {\n            value = (value - parts[0]) / _60;\n            parts.unshift(value); // hours\n        }\n    }\n    return (sign +\n        parts\n            .map(n => String(n).padStart(2, '0'))\n            .join(':')\n            .replace(/000000\\d*$/, '') // % 60 may introduce error\n    );\n}\nconst intTime = {\n    identify: value => typeof value === 'bigint' || Number.isInteger(value),\n    default: true,\n    tag: 'tag:yaml.org,2002:int',\n    format: 'TIME',\n    test: /^[-+]?[0-9][0-9_]*(?::[0-5]?[0-9])+$/,\n    resolve: (str, _onError, { intAsBigInt }) => parseSexagesimal(str, intAsBigInt),\n    stringify: stringifySexagesimal\n};\nconst floatTime = {\n    identify: value => typeof value === 'number',\n    default: true,\n    tag: 'tag:yaml.org,2002:float',\n    format: 'TIME',\n    test: /^[-+]?[0-9][0-9_]*(?::[0-5]?[0-9])+\\.[0-9_]*$/,\n    resolve: str => parseSexagesimal(str, false),\n    stringify: stringifySexagesimal\n};\nconst timestamp = {\n    identify: value => value instanceof Date,\n    default: true,\n    tag: 'tag:yaml.org,2002:timestamp',\n    // If the time zone is omitted, the timestamp is assumed to be specified in UTC. The time part\n    // may be omitted altogether, resulting in a date format. In such a case, the time part is\n    // assumed to be 00:00:00Z (start of day, UTC).\n    test: RegExp('^([0-9]{4})-([0-9]{1,2})-([0-9]{1,2})' + // YYYY-Mm-Dd\n        '(?:' + // time is optional\n        '(?:t|T|[ \\\\t]+)' + // t | T | whitespace\n        '([0-9]{1,2}):([0-9]{1,2}):([0-9]{1,2}(\\\\.[0-9]+)?)' + // Hh:Mm:Ss(.ss)?\n        '(?:[ \\\\t]*(Z|[-+][012]?[0-9](?::[0-9]{2})?))?' + // Z | +5 | -03:30\n        ')?$'),\n    resolve(str) {\n        const match = str.match(timestamp.test);\n        if (!match)\n            throw new Error('!!timestamp expects a date, starting with yyyy-mm-dd');\n        const [, year, month, day, hour, minute, second] = match.map(Number);\n        const millisec = match[7] ? Number((match[7] + '00').substr(1, 3)) : 0;\n        let date = Date.UTC(year, month - 1, day, hour || 0, minute || 0, second || 0, millisec);\n        const tz = match[8];\n        if (tz && tz !== 'Z') {\n            let d = parseSexagesimal(tz, false);\n            if (Math.abs(d) < 30)\n                d *= 60;\n            date -= 60000 * d;\n        }\n        return new Date(date);\n    },\n    stringify: ({ value }) => value?.toISOString().replace(/(T00:00:00)?\\.000Z$/, '') ?? ''\n};\n\nexports.floatTime = floatTime;\nexports.intTime = intTime;\nexports.timestamp = timestamp;\n","'use strict';\n\nvar map = require('../common/map.js');\nvar _null = require('../common/null.js');\nvar seq = require('../common/seq.js');\nvar string = require('../common/string.js');\nvar binary = require('./binary.js');\nvar bool = require('./bool.js');\nvar float = require('./float.js');\nvar int = require('./int.js');\nvar merge = require('./merge.js');\nvar omap = require('./omap.js');\nvar pairs = require('./pairs.js');\nvar set = require('./set.js');\nvar timestamp = require('./timestamp.js');\n\nconst schema = [\n    map.map,\n    seq.seq,\n    string.string,\n    _null.nullTag,\n    bool.trueTag,\n    bool.falseTag,\n    int.intBin,\n    int.intOct,\n    int.int,\n    int.intHex,\n    float.floatNaN,\n    float.floatExp,\n    float.float,\n    binary.binary,\n    merge.merge,\n    omap.omap,\n    pairs.pairs,\n    set.set,\n    timestamp.intTime,\n    timestamp.floatTime,\n    timestamp.timestamp\n];\n\nexports.schema = schema;\n","'use strict';\n\nvar map = require('./common/map.js');\nvar _null = require('./common/null.js');\nvar seq = require('./common/seq.js');\nvar string = require('./common/string.js');\nvar bool = require('./core/bool.js');\nvar float = require('./core/float.js');\nvar int = require('./core/int.js');\nvar schema = require('./core/schema.js');\nvar schema$1 = require('./json/schema.js');\nvar binary = require('./yaml-1.1/binary.js');\nvar merge = require('./yaml-1.1/merge.js');\nvar omap = require('./yaml-1.1/omap.js');\nvar pairs = require('./yaml-1.1/pairs.js');\nvar schema$2 = require('./yaml-1.1/schema.js');\nvar set = require('./yaml-1.1/set.js');\nvar timestamp = require('./yaml-1.1/timestamp.js');\n\nconst schemas = new Map([\n    ['core', schema.schema],\n    ['failsafe', [map.map, seq.seq, string.string]],\n    ['json', schema$1.schema],\n    ['yaml11', schema$2.schema],\n    ['yaml-1.1', schema$2.schema]\n]);\nconst tagsByName = {\n    binary: binary.binary,\n    bool: bool.boolTag,\n    float: float.float,\n    floatExp: float.floatExp,\n    floatNaN: float.floatNaN,\n    floatTime: timestamp.floatTime,\n    int: int.int,\n    intHex: int.intHex,\n    intOct: int.intOct,\n    intTime: timestamp.intTime,\n    map: map.map,\n    merge: merge.merge,\n    null: _null.nullTag,\n    omap: omap.omap,\n    pairs: pairs.pairs,\n    seq: seq.seq,\n    set: set.set,\n    timestamp: timestamp.timestamp\n};\nconst coreKnownTags = {\n    'tag:yaml.org,2002:binary': binary.binary,\n    'tag:yaml.org,2002:merge': merge.merge,\n    'tag:yaml.org,2002:omap': omap.omap,\n    'tag:yaml.org,2002:pairs': pairs.pairs,\n    'tag:yaml.org,2002:set': set.set,\n    'tag:yaml.org,2002:timestamp': timestamp.timestamp\n};\nfunction getTags(customTags, schemaName, addMergeTag) {\n    const schemaTags = schemas.get(schemaName);\n    if (schemaTags && !customTags) {\n        return addMergeTag && !schemaTags.includes(merge.merge)\n            ? schemaTags.concat(merge.merge)\n            : schemaTags.slice();\n    }\n    let tags = schemaTags;\n    if (!tags) {\n        if (Array.isArray(customTags))\n            tags = [];\n        else {\n            const keys = Array.from(schemas.keys())\n                .filter(key => key !== 'yaml11')\n                .map(key => JSON.stringify(key))\n                .join(', ');\n            throw new Error(`Unknown schema \"${schemaName}\"; use one of ${keys} or define customTags array`);\n        }\n    }\n    if (Array.isArray(customTags)) {\n        for (const tag of customTags)\n            tags = tags.concat(tag);\n    }\n    else if (typeof customTags === 'function') {\n        tags = customTags(tags.slice());\n    }\n    if (addMergeTag)\n        tags = tags.concat(merge.merge);\n    return tags.reduce((tags, tag) => {\n        const tagObj = typeof tag === 'string' ? tagsByName[tag] : tag;\n        if (!tagObj) {\n            const tagName = JSON.stringify(tag);\n            const keys = Object.keys(tagsByName)\n                .map(key => JSON.stringify(key))\n                .join(', ');\n            throw new Error(`Unknown custom tag ${tagName}; use one of ${keys}`);\n        }\n        if (!tags.includes(tagObj))\n            tags.push(tagObj);\n        return tags;\n    }, []);\n}\n\nexports.coreKnownTags = coreKnownTags;\nexports.getTags = getTags;\n","'use strict';\n\nvar identity = require('../nodes/identity.js');\nvar map = require('./common/map.js');\nvar seq = require('./common/seq.js');\nvar string = require('./common/string.js');\nvar tags = require('./tags.js');\n\nconst sortMapEntriesByKey = (a, b) => a.key < b.key ? -1 : a.key > b.key ? 1 : 0;\nclass Schema {\n    constructor({ compat, customTags, merge, resolveKnownTags, schema, sortMapEntries, toStringDefaults }) {\n        this.compat = Array.isArray(compat)\n            ? tags.getTags(compat, 'compat')\n            : compat\n                ? tags.getTags(null, compat)\n                : null;\n        this.name = (typeof schema === 'string' && schema) || 'core';\n        this.knownTags = resolveKnownTags ? tags.coreKnownTags : {};\n        this.tags = tags.getTags(customTags, this.name, merge);\n        this.toStringOptions = toStringDefaults ?? null;\n        Object.defineProperty(this, identity.MAP, { value: map.map });\n        Object.defineProperty(this, identity.SCALAR, { value: string.string });\n        Object.defineProperty(this, identity.SEQ, { value: seq.seq });\n        // Used by createMap()\n        this.sortMapEntries =\n            typeof sortMapEntries === 'function'\n                ? sortMapEntries\n                : sortMapEntries === true\n                    ? sortMapEntriesByKey\n                    : null;\n    }\n    clone() {\n        const copy = Object.create(Schema.prototype, Object.getOwnPropertyDescriptors(this));\n        copy.tags = this.tags.slice();\n        return copy;\n    }\n}\n\nexports.Schema = Schema;\n","'use strict';\n\nvar identity = require('../nodes/identity.js');\nvar stringify = require('./stringify.js');\nvar stringifyComment = require('./stringifyComment.js');\n\nfunction stringifyDocument(doc, options) {\n    const lines = [];\n    let hasDirectives = options.directives === true;\n    if (options.directives !== false && doc.directives) {\n        const dir = doc.directives.toString(doc);\n        if (dir) {\n            lines.push(dir);\n            hasDirectives = true;\n        }\n        else if (doc.directives.docStart)\n            hasDirectives = true;\n    }\n    if (hasDirectives)\n        lines.push('---');\n    const ctx = stringify.createStringifyContext(doc, options);\n    const { commentString } = ctx.options;\n    if (doc.commentBefore) {\n        if (lines.length !== 1)\n            lines.unshift('');\n        const cs = commentString(doc.commentBefore);\n        lines.unshift(stringifyComment.indentComment(cs, ''));\n    }\n    let chompKeep = false;\n    let contentComment = null;\n    if (doc.contents) {\n        if (identity.isNode(doc.contents)) {\n            if (doc.contents.spaceBefore && hasDirectives)\n                lines.push('');\n            if (doc.contents.commentBefore) {\n                const cs = commentString(doc.contents.commentBefore);\n                lines.push(stringifyComment.indentComment(cs, ''));\n            }\n            // top-level block scalars need to be indented if followed by a comment\n            ctx.forceBlockIndent = !!doc.comment;\n            contentComment = doc.contents.comment;\n        }\n        const onChompKeep = contentComment ? undefined : () => (chompKeep = true);\n        let body = stringify.stringify(doc.contents, ctx, () => (contentComment = null), onChompKeep);\n        if (contentComment)\n            body += stringifyComment.lineComment(body, '', commentString(contentComment));\n        if ((body[0] === '|' || body[0] === '>') &&\n            lines[lines.length - 1] === '---') {\n            // Top-level block scalars with a preceding doc marker ought to use the\n            // same line for their header.\n            lines[lines.length - 1] = `--- ${body}`;\n        }\n        else\n            lines.push(body);\n    }\n    else {\n        lines.push(stringify.stringify(doc.contents, ctx));\n    }\n    if (doc.directives?.docEnd) {\n        if (doc.comment) {\n            const cs = commentString(doc.comment);\n            if (cs.includes('\\n')) {\n                lines.push('...');\n                lines.push(stringifyComment.indentComment(cs, ''));\n            }\n            else {\n                lines.push(`... ${cs}`);\n            }\n        }\n        else {\n            lines.push('...');\n        }\n    }\n    else {\n        let dc = doc.comment;\n        if (dc && chompKeep)\n            dc = dc.replace(/^\\n+/, '');\n        if (dc) {\n            if ((!chompKeep || contentComment) && lines[lines.length - 1] !== '')\n                lines.push('');\n            lines.push(stringifyComment.indentComment(commentString(dc), ''));\n        }\n    }\n    return lines.join('\\n') + '\\n';\n}\n\nexports.stringifyDocument = stringifyDocument;\n","'use strict';\n\nvar Alias = require('../nodes/Alias.js');\nvar Collection = require('../nodes/Collection.js');\nvar identity = require('../nodes/identity.js');\nvar Pair = require('../nodes/Pair.js');\nvar toJS = require('../nodes/toJS.js');\nvar Schema = require('../schema/Schema.js');\nvar stringifyDocument = require('../stringify/stringifyDocument.js');\nvar anchors = require('./anchors.js');\nvar applyReviver = require('./applyReviver.js');\nvar createNode = require('./createNode.js');\nvar directives = require('./directives.js');\n\nclass Document {\n    constructor(value, replacer, options) {\n        /** A comment before this Document */\n        this.commentBefore = null;\n        /** A comment immediately after this Document */\n        this.comment = null;\n        /** Errors encountered during parsing. */\n        this.errors = [];\n        /** Warnings encountered during parsing. */\n        this.warnings = [];\n        Object.defineProperty(this, identity.NODE_TYPE, { value: identity.DOC });\n        let _replacer = null;\n        if (typeof replacer === 'function' || Array.isArray(replacer)) {\n            _replacer = replacer;\n        }\n        else if (options === undefined && replacer) {\n            options = replacer;\n            replacer = undefined;\n        }\n        const opt = Object.assign({\n            intAsBigInt: false,\n            keepSourceTokens: false,\n            logLevel: 'warn',\n            prettyErrors: true,\n            strict: true,\n            stringKeys: false,\n            uniqueKeys: true,\n            version: '1.2'\n        }, options);\n        this.options = opt;\n        let { version } = opt;\n        if (options?._directives) {\n            this.directives = options._directives.atDocument();\n            if (this.directives.yaml.explicit)\n                version = this.directives.yaml.version;\n        }\n        else\n            this.directives = new directives.Directives({ version });\n        this.setSchema(version, options);\n        // @ts-expect-error We can't really know that this matches Contents.\n        this.contents =\n            value === undefined ? null : this.createNode(value, _replacer, options);\n    }\n    /**\n     * Create a deep copy of this Document and its contents.\n     *\n     * Custom Node values that inherit from `Object` still refer to their original instances.\n     */\n    clone() {\n        const copy = Object.create(Document.prototype, {\n            [identity.NODE_TYPE]: { value: identity.DOC }\n        });\n        copy.commentBefore = this.commentBefore;\n        copy.comment = this.comment;\n        copy.errors = this.errors.slice();\n        copy.warnings = this.warnings.slice();\n        copy.options = Object.assign({}, this.options);\n        if (this.directives)\n            copy.directives = this.directives.clone();\n        copy.schema = this.schema.clone();\n        // @ts-expect-error We can't really know that this matches Contents.\n        copy.contents = identity.isNode(this.contents)\n            ? this.contents.clone(copy.schema)\n            : this.contents;\n        if (this.range)\n            copy.range = this.range.slice();\n        return copy;\n    }\n    /** Adds a value to the document. */\n    add(value) {\n        if (assertCollection(this.contents))\n            this.contents.add(value);\n    }\n    /** Adds a value to the document. */\n    addIn(path, value) {\n        if (assertCollection(this.contents))\n            this.contents.addIn(path, value);\n    }\n    /**\n     * Create a new `Alias` node, ensuring that the target `node` has the required anchor.\n     *\n     * If `node` already has an anchor, `name` is ignored.\n     * Otherwise, the `node.anchor` value will be set to `name`,\n     * or if an anchor with that name is already present in the document,\n     * `name` will be used as a prefix for a new unique anchor.\n     * If `name` is undefined, the generated anchor will use 'a' as a prefix.\n     */\n    createAlias(node, name) {\n        if (!node.anchor) {\n            const prev = anchors.anchorNames(this);\n            node.anchor =\n                // eslint-disable-next-line @typescript-eslint/prefer-nullish-coalescing\n                !name || prev.has(name) ? anchors.findNewAnchor(name || 'a', prev) : name;\n        }\n        return new Alias.Alias(node.anchor);\n    }\n    createNode(value, replacer, options) {\n        let _replacer = undefined;\n        if (typeof replacer === 'function') {\n            value = replacer.call({ '': value }, '', value);\n            _replacer = replacer;\n        }\n        else if (Array.isArray(replacer)) {\n            const keyToStr = (v) => typeof v === 'number' || v instanceof String || v instanceof Number;\n            const asStr = replacer.filter(keyToStr).map(String);\n            if (asStr.length > 0)\n                replacer = replacer.concat(asStr);\n            _replacer = replacer;\n        }\n        else if (options === undefined && replacer) {\n            options = replacer;\n            replacer = undefined;\n        }\n        const { aliasDuplicateObjects, anchorPrefix, flow, keepUndefined, onTagObj, tag } = options ?? {};\n        const { onAnchor, setAnchors, sourceObjects } = anchors.createNodeAnchors(this, \n        // eslint-disable-next-line @typescript-eslint/prefer-nullish-coalescing\n        anchorPrefix || 'a');\n        const ctx = {\n            aliasDuplicateObjects: aliasDuplicateObjects ?? true,\n            keepUndefined: keepUndefined ?? false,\n            onAnchor,\n            onTagObj,\n            replacer: _replacer,\n            schema: this.schema,\n            sourceObjects\n        };\n        const node = createNode.createNode(value, tag, ctx);\n        if (flow && identity.isCollection(node))\n            node.flow = true;\n        setAnchors();\n        return node;\n    }\n    /**\n     * Convert a key and a value into a `Pair` using the current schema,\n     * recursively wrapping all values as `Scalar` or `Collection` nodes.\n     */\n    createPair(key, value, options = {}) {\n        const k = this.createNode(key, null, options);\n        const v = this.createNode(value, null, options);\n        return new Pair.Pair(k, v);\n    }\n    /**\n     * Removes a value from the document.\n     * @returns `true` if the item was found and removed.\n     */\n    delete(key) {\n        return assertCollection(this.contents) ? this.contents.delete(key) : false;\n    }\n    /**\n     * Removes a value from the document.\n     * @returns `true` if the item was found and removed.\n     */\n    deleteIn(path) {\n        if (Collection.isEmptyPath(path)) {\n            if (this.contents == null)\n                return false;\n            // @ts-expect-error Presumed impossible if Strict extends false\n            this.contents = null;\n            return true;\n        }\n        return assertCollection(this.contents)\n            ? this.contents.deleteIn(path)\n            : false;\n    }\n    /**\n     * Returns item at `key`, or `undefined` if not found. By default unwraps\n     * scalar values from their surrounding node; to disable set `keepScalar` to\n     * `true` (collections are always returned intact).\n     */\n    get(key, keepScalar) {\n        return identity.isCollection(this.contents)\n            ? this.contents.get(key, keepScalar)\n            : undefined;\n    }\n    /**\n     * Returns item at `path`, or `undefined` if not found. By default unwraps\n     * scalar values from their surrounding node; to disable set `keepScalar` to\n     * `true` (collections are always returned intact).\n     */\n    getIn(path, keepScalar) {\n        if (Collection.isEmptyPath(path))\n            return !keepScalar && identity.isScalar(this.contents)\n                ? this.contents.value\n                : this.contents;\n        return identity.isCollection(this.contents)\n            ? this.contents.getIn(path, keepScalar)\n            : undefined;\n    }\n    /**\n     * Checks if the document includes a value with the key `key`.\n     */\n    has(key) {\n        return identity.isCollection(this.contents) ? this.contents.has(key) : false;\n    }\n    /**\n     * Checks if the document includes a value at `path`.\n     */\n    hasIn(path) {\n        if (Collection.isEmptyPath(path))\n            return this.contents !== undefined;\n        return identity.isCollection(this.contents) ? this.contents.hasIn(path) : false;\n    }\n    /**\n     * Sets a value in this document. For `!!set`, `value` needs to be a\n     * boolean to add/remove the item from the set.\n     */\n    set(key, value) {\n        if (this.contents == null) {\n            // @ts-expect-error We can't really know that this matches Contents.\n            this.contents = Collection.collectionFromPath(this.schema, [key], value);\n        }\n        else if (assertCollection(this.contents)) {\n            this.contents.set(key, value);\n        }\n    }\n    /**\n     * Sets a value in this document. For `!!set`, `value` needs to be a\n     * boolean to add/remove the item from the set.\n     */\n    setIn(path, value) {\n        if (Collection.isEmptyPath(path)) {\n            // @ts-expect-error We can't really know that this matches Contents.\n            this.contents = value;\n        }\n        else if (this.contents == null) {\n            // @ts-expect-error We can't really know that this matches Contents.\n            this.contents = Collection.collectionFromPath(this.schema, Array.from(path), value);\n        }\n        else if (assertCollection(this.contents)) {\n            this.contents.setIn(path, value);\n        }\n    }\n    /**\n     * Change the YAML version and schema used by the document.\n     * A `null` version disables support for directives, explicit tags, anchors, and aliases.\n     * It also requires the `schema` option to be given as a `Schema` instance value.\n     *\n     * Overrides all previously set schema options.\n     */\n    setSchema(version, options = {}) {\n        if (typeof version === 'number')\n            version = String(version);\n        let opt;\n        switch (version) {\n            case '1.1':\n                if (this.directives)\n                    this.directives.yaml.version = '1.1';\n                else\n                    this.directives = new directives.Directives({ version: '1.1' });\n                opt = { resolveKnownTags: false, schema: 'yaml-1.1' };\n                break;\n            case '1.2':\n            case 'next':\n                if (this.directives)\n                    this.directives.yaml.version = version;\n                else\n                    this.directives = new directives.Directives({ version });\n                opt = { resolveKnownTags: true, schema: 'core' };\n                break;\n            case null:\n                if (this.directives)\n                    delete this.directives;\n                opt = null;\n                break;\n            default: {\n                const sv = JSON.stringify(version);\n                throw new Error(`Expected '1.1', '1.2' or null as first argument, but found: ${sv}`);\n            }\n        }\n        // Not using `instanceof Schema` to allow for duck typing\n        if (options.schema instanceof Object)\n            this.schema = options.schema;\n        else if (opt)\n            this.schema = new Schema.Schema(Object.assign(opt, options));\n        else\n            throw new Error(`With a null YAML version, the { schema: Schema } option is required`);\n    }\n    // json & jsonArg are only used from toJSON()\n    toJS({ json, jsonArg, mapAsMap, maxAliasCount, onAnchor, reviver } = {}) {\n        const ctx = {\n            anchors: new Map(),\n            doc: this,\n            keep: !json,\n            mapAsMap: mapAsMap === true,\n            mapKeyWarned: false,\n            maxAliasCount: typeof maxAliasCount === 'number' ? maxAliasCount : 100\n        };\n        const res = toJS.toJS(this.contents, jsonArg ?? '', ctx);\n        if (typeof onAnchor === 'function')\n            for (const { count, res } of ctx.anchors.values())\n                onAnchor(res, count);\n        return typeof reviver === 'function'\n            ? applyReviver.applyReviver(reviver, { '': res }, '', res)\n            : res;\n    }\n    /**\n     * A JSON representation of the document `contents`.\n     *\n     * @param jsonArg Used by `JSON.stringify` to indicate the array index or\n     *   property name.\n     */\n    toJSON(jsonArg, onAnchor) {\n        return this.toJS({ json: true, jsonArg, mapAsMap: false, onAnchor });\n    }\n    /** A YAML representation of the document. */\n    toString(options = {}) {\n        if (this.errors.length > 0)\n            throw new Error('Document with errors cannot be stringified');\n        if ('indent' in options &&\n            (!Number.isInteger(options.indent) || Number(options.indent) <= 0)) {\n            const s = JSON.stringify(options.indent);\n            throw new Error(`\"indent\" option must be a positive integer, not ${s}`);\n        }\n        return stringifyDocument.stringifyDocument(this, options);\n    }\n}\nfunction assertCollection(contents) {\n    if (identity.isCollection(contents))\n        return true;\n    throw new Error('Expected a YAML collection as document contents');\n}\n\nexports.Document = Document;\n","'use strict';\n\nclass YAMLError extends Error {\n    constructor(name, pos, code, message) {\n        super();\n        this.name = name;\n        this.code = code;\n        this.message = message;\n        this.pos = pos;\n    }\n}\nclass YAMLParseError extends YAMLError {\n    constructor(pos, code, message) {\n        super('YAMLParseError', pos, code, message);\n    }\n}\nclass YAMLWarning extends YAMLError {\n    constructor(pos, code, message) {\n        super('YAMLWarning', pos, code, message);\n    }\n}\nconst prettifyError = (src, lc) => (error) => {\n    if (error.pos[0] === -1)\n        return;\n    error.linePos = error.pos.map(pos => lc.linePos(pos));\n    const { line, col } = error.linePos[0];\n    error.message += ` at line ${line}, column ${col}`;\n    let ci = col - 1;\n    let lineStr = src\n        .substring(lc.lineStarts[line - 1], lc.lineStarts[line])\n        .replace(/[\\n\\r]+$/, '');\n    // Trim to max 80 chars, keeping col position near the middle\n    if (ci >= 60 && lineStr.length > 80) {\n        const trimStart = Math.min(ci - 39, lineStr.length - 79);\n        lineStr = '…' + lineStr.substring(trimStart);\n        ci -= trimStart - 1;\n    }\n    if (lineStr.length > 80)\n        lineStr = lineStr.substring(0, 79) + '…';\n    // Include previous line in context if pointing at line start\n    if (line > 1 && /^ *$/.test(lineStr.substring(0, ci))) {\n        // Regexp won't match if start is trimmed\n        let prev = src.substring(lc.lineStarts[line - 2], lc.lineStarts[line - 1]);\n        if (prev.length > 80)\n            prev = prev.substring(0, 79) + '…\\n';\n        lineStr = prev + lineStr;\n    }\n    if (/[^ ]/.test(lineStr)) {\n        let count = 1;\n        const end = error.linePos[1];\n        if (end?.line === line && end.col > col) {\n            count = Math.max(1, Math.min(end.col - col, 80 - ci));\n        }\n        const pointer = ' '.repeat(ci) + '^'.repeat(count);\n        error.message += `:\\n\\n${lineStr}\\n${pointer}\\n`;\n    }\n};\n\nexports.YAMLError = YAMLError;\nexports.YAMLParseError = YAMLParseError;\nexports.YAMLWarning = YAMLWarning;\nexports.prettifyError = prettifyError;\n","'use strict';\n\nfunction resolveProps(tokens, { flow, indicator, next, offset, onError, parentIndent, startOnNewline }) {\n    let spaceBefore = false;\n    let atNewline = startOnNewline;\n    let hasSpace = startOnNewline;\n    let comment = '';\n    let commentSep = '';\n    let hasNewline = false;\n    let reqSpace = false;\n    let tab = null;\n    let anchor = null;\n    let tag = null;\n    let newlineAfterProp = null;\n    let comma = null;\n    let found = null;\n    let start = null;\n    for (const token of tokens) {\n        if (reqSpace) {\n            if (token.type !== 'space' &&\n                token.type !== 'newline' &&\n                token.type !== 'comma')\n                onError(token.offset, 'MISSING_CHAR', 'Tags and anchors must be separated from the next token by white space');\n            reqSpace = false;\n        }\n        if (tab) {\n            if (atNewline && token.type !== 'comment' && token.type !== 'newline') {\n                onError(tab, 'TAB_AS_INDENT', 'Tabs are not allowed as indentation');\n            }\n            tab = null;\n        }\n        switch (token.type) {\n            case 'space':\n                // At the doc level, tabs at line start may be parsed\n                // as leading white space rather than indentation.\n                // In a flow collection, only the parser handles indent.\n                if (!flow &&\n                    (indicator !== 'doc-start' || next?.type !== 'flow-collection') &&\n                    token.source.includes('\\t')) {\n                    tab = token;\n                }\n                hasSpace = true;\n                break;\n            case 'comment': {\n                if (!hasSpace)\n                    onError(token, 'MISSING_CHAR', 'Comments must be separated from other tokens by white space characters');\n                const cb = token.source.substring(1) || ' ';\n                if (!comment)\n                    comment = cb;\n                else\n                    comment += commentSep + cb;\n                commentSep = '';\n                atNewline = false;\n                break;\n            }\n            case 'newline':\n                if (atNewline) {\n                    if (comment)\n                        comment += token.source;\n                    else if (!found || indicator !== 'seq-item-ind')\n                        spaceBefore = true;\n                }\n                else\n                    commentSep += token.source;\n                atNewline = true;\n                hasNewline = true;\n                if (anchor || tag)\n                    newlineAfterProp = token;\n                hasSpace = true;\n                break;\n            case 'anchor':\n                if (anchor)\n                    onError(token, 'MULTIPLE_ANCHORS', 'A node can have at most one anchor');\n                if (token.source.endsWith(':'))\n                    onError(token.offset + token.source.length - 1, 'BAD_ALIAS', 'Anchor ending in : is ambiguous', true);\n                anchor = token;\n                start ?? (start = token.offset);\n                atNewline = false;\n                hasSpace = false;\n                reqSpace = true;\n                break;\n            case 'tag': {\n                if (tag)\n                    onError(token, 'MULTIPLE_TAGS', 'A node can have at most one tag');\n                tag = token;\n                start ?? (start = token.offset);\n                atNewline = false;\n                hasSpace = false;\n                reqSpace = true;\n                break;\n            }\n            case indicator:\n                // Could here handle preceding comments differently\n                if (anchor || tag)\n                    onError(token, 'BAD_PROP_ORDER', `Anchors and tags must be after the ${token.source} indicator`);\n                if (found)\n                    onError(token, 'UNEXPECTED_TOKEN', `Unexpected ${token.source} in ${flow ?? 'collection'}`);\n                found = token;\n                atNewline =\n                    indicator === 'seq-item-ind' || indicator === 'explicit-key-ind';\n                hasSpace = false;\n                break;\n            case 'comma':\n                if (flow) {\n                    if (comma)\n                        onError(token, 'UNEXPECTED_TOKEN', `Unexpected , in ${flow}`);\n                    comma = token;\n                    atNewline = false;\n                    hasSpace = false;\n                    break;\n                }\n            // else fallthrough\n            default:\n                onError(token, 'UNEXPECTED_TOKEN', `Unexpected ${token.type} token`);\n                atNewline = false;\n                hasSpace = false;\n        }\n    }\n    const last = tokens[tokens.length - 1];\n    const end = last ? last.offset + last.source.length : offset;\n    if (reqSpace &&\n        next &&\n        next.type !== 'space' &&\n        next.type !== 'newline' &&\n        next.type !== 'comma' &&\n        (next.type !== 'scalar' || next.source !== '')) {\n        onError(next.offset, 'MISSING_CHAR', 'Tags and anchors must be separated from the next token by white space');\n    }\n    if (tab &&\n        ((atNewline && tab.indent <= parentIndent) ||\n            next?.type === 'block-map' ||\n            next?.type === 'block-seq'))\n        onError(tab, 'TAB_AS_INDENT', 'Tabs are not allowed as indentation');\n    return {\n        comma,\n        found,\n        spaceBefore,\n        comment,\n        hasNewline,\n        anchor,\n        tag,\n        newlineAfterProp,\n        end,\n        start: start ?? end\n    };\n}\n\nexports.resolveProps = resolveProps;\n","'use strict';\n\nfunction containsNewline(key) {\n    if (!key)\n        return null;\n    switch (key.type) {\n        case 'alias':\n        case 'scalar':\n        case 'double-quoted-scalar':\n        case 'single-quoted-scalar':\n            if (key.source.includes('\\n'))\n                return true;\n            if (key.end)\n                for (const st of key.end)\n                    if (st.type === 'newline')\n                        return true;\n            return false;\n        case 'flow-collection':\n            for (const it of key.items) {\n                for (const st of it.start)\n                    if (st.type === 'newline')\n                        return true;\n                if (it.sep)\n                    for (const st of it.sep)\n                        if (st.type === 'newline')\n                            return true;\n                if (containsNewline(it.key) || containsNewline(it.value))\n                    return true;\n            }\n            return false;\n        default:\n            return true;\n    }\n}\n\nexports.containsNewline = containsNewline;\n","'use strict';\n\nvar utilContainsNewline = require('./util-contains-newline.js');\n\nfunction flowIndentCheck(indent, fc, onError) {\n    if (fc?.type === 'flow-collection') {\n        const end = fc.end[0];\n        if (end.indent === indent &&\n            (end.source === ']' || end.source === '}') &&\n            utilContainsNewline.containsNewline(fc)) {\n            const msg = 'Flow end indicator should be more indented than parent';\n            onError(end, 'BAD_INDENT', msg, true);\n        }\n    }\n}\n\nexports.flowIndentCheck = flowIndentCheck;\n","'use strict';\n\nvar identity = require('../nodes/identity.js');\n\nfunction mapIncludes(ctx, items, search) {\n    const { uniqueKeys } = ctx.options;\n    if (uniqueKeys === false)\n        return false;\n    const isEqual = typeof uniqueKeys === 'function'\n        ? uniqueKeys\n        : (a, b) => a === b || (identity.isScalar(a) && identity.isScalar(b) && a.value === b.value);\n    return items.some(pair => isEqual(pair.key, search));\n}\n\nexports.mapIncludes = mapIncludes;\n","'use strict';\n\nvar Pair = require('../nodes/Pair.js');\nvar YAMLMap = require('../nodes/YAMLMap.js');\nvar resolveProps = require('./resolve-props.js');\nvar utilContainsNewline = require('./util-contains-newline.js');\nvar utilFlowIndentCheck = require('./util-flow-indent-check.js');\nvar utilMapIncludes = require('./util-map-includes.js');\n\nconst startColMsg = 'All mapping items must start at the same column';\nfunction resolveBlockMap({ composeNode, composeEmptyNode }, ctx, bm, onError, tag) {\n    const NodeClass = tag?.nodeClass ?? YAMLMap.YAMLMap;\n    const map = new NodeClass(ctx.schema);\n    if (ctx.atRoot)\n        ctx.atRoot = false;\n    let offset = bm.offset;\n    let commentEnd = null;\n    for (const collItem of bm.items) {\n        const { start, key, sep, value } = collItem;\n        // key properties\n        const keyProps = resolveProps.resolveProps(start, {\n            indicator: 'explicit-key-ind',\n            next: key ?? sep?.[0],\n            offset,\n            onError,\n            parentIndent: bm.indent,\n            startOnNewline: true\n        });\n        const implicitKey = !keyProps.found;\n        if (implicitKey) {\n            if (key) {\n                if (key.type === 'block-seq')\n                    onError(offset, 'BLOCK_AS_IMPLICIT_KEY', 'A block sequence may not be used as an implicit map key');\n                else if ('indent' in key && key.indent !== bm.indent)\n                    onError(offset, 'BAD_INDENT', startColMsg);\n            }\n            if (!keyProps.anchor && !keyProps.tag && !sep) {\n                commentEnd = keyProps.end;\n                if (keyProps.comment) {\n                    if (map.comment)\n                        map.comment += '\\n' + keyProps.comment;\n                    else\n                        map.comment = keyProps.comment;\n                }\n                continue;\n            }\n            if (keyProps.newlineAfterProp || utilContainsNewline.containsNewline(key)) {\n                onError(key ?? start[start.length - 1], 'MULTILINE_IMPLICIT_KEY', 'Implicit keys need to be on a single line');\n            }\n        }\n        else if (keyProps.found?.indent !== bm.indent) {\n            onError(offset, 'BAD_INDENT', startColMsg);\n        }\n        // key value\n        ctx.atKey = true;\n        const keyStart = keyProps.end;\n        const keyNode = key\n            ? composeNode(ctx, key, keyProps, onError)\n            : composeEmptyNode(ctx, keyStart, start, null, keyProps, onError);\n        if (ctx.schema.compat)\n            utilFlowIndentCheck.flowIndentCheck(bm.indent, key, onError);\n        ctx.atKey = false;\n        if (utilMapIncludes.mapIncludes(ctx, map.items, keyNode))\n            onError(keyStart, 'DUPLICATE_KEY', 'Map keys must be unique');\n        // value properties\n        const valueProps = resolveProps.resolveProps(sep ?? [], {\n            indicator: 'map-value-ind',\n            next: value,\n            offset: keyNode.range[2],\n            onError,\n            parentIndent: bm.indent,\n            startOnNewline: !key || key.type === 'block-scalar'\n        });\n        offset = valueProps.end;\n        if (valueProps.found) {\n            if (implicitKey) {\n                if (value?.type === 'block-map' && !valueProps.hasNewline)\n                    onError(offset, 'BLOCK_AS_IMPLICIT_KEY', 'Nested mappings are not allowed in compact mappings');\n                if (ctx.options.strict &&\n                    keyProps.start < valueProps.found.offset - 1024)\n                    onError(keyNode.range, 'KEY_OVER_1024_CHARS', 'The : indicator must be at most 1024 chars after the start of an implicit block mapping key');\n            }\n            // value value\n            const valueNode = value\n                ? composeNode(ctx, value, valueProps, onError)\n                : composeEmptyNode(ctx, offset, sep, null, valueProps, onError);\n            if (ctx.schema.compat)\n                utilFlowIndentCheck.flowIndentCheck(bm.indent, value, onError);\n            offset = valueNode.range[2];\n            const pair = new Pair.Pair(keyNode, valueNode);\n            if (ctx.options.keepSourceTokens)\n                pair.srcToken = collItem;\n            map.items.push(pair);\n        }\n        else {\n            // key with no value\n            if (implicitKey)\n                onError(keyNode.range, 'MISSING_CHAR', 'Implicit map keys need to be followed by map values');\n            if (valueProps.comment) {\n                if (keyNode.comment)\n                    keyNode.comment += '\\n' + valueProps.comment;\n                else\n                    keyNode.comment = valueProps.comment;\n            }\n            const pair = new Pair.Pair(keyNode);\n            if (ctx.options.keepSourceTokens)\n                pair.srcToken = collItem;\n            map.items.push(pair);\n        }\n    }\n    if (commentEnd && commentEnd < offset)\n        onError(commentEnd, 'IMPOSSIBLE', 'Map comment with trailing content');\n    map.range = [bm.offset, offset, commentEnd ?? offset];\n    return map;\n}\n\nexports.resolveBlockMap = resolveBlockMap;\n","'use strict';\n\nvar YAMLSeq = require('../nodes/YAMLSeq.js');\nvar resolveProps = require('./resolve-props.js');\nvar utilFlowIndentCheck = require('./util-flow-indent-check.js');\n\nfunction resolveBlockSeq({ composeNode, composeEmptyNode }, ctx, bs, onError, tag) {\n    const NodeClass = tag?.nodeClass ?? YAMLSeq.YAMLSeq;\n    const seq = new NodeClass(ctx.schema);\n    if (ctx.atRoot)\n        ctx.atRoot = false;\n    if (ctx.atKey)\n        ctx.atKey = false;\n    let offset = bs.offset;\n    let commentEnd = null;\n    for (const { start, value } of bs.items) {\n        const props = resolveProps.resolveProps(start, {\n            indicator: 'seq-item-ind',\n            next: value,\n            offset,\n            onError,\n            parentIndent: bs.indent,\n            startOnNewline: true\n        });\n        if (!props.found) {\n            if (props.anchor || props.tag || value) {\n                if (value?.type === 'block-seq')\n                    onError(props.end, 'BAD_INDENT', 'All sequence items must start at the same column');\n                else\n                    onError(offset, 'MISSING_CHAR', 'Sequence item without - indicator');\n            }\n            else {\n                commentEnd = props.end;\n                if (props.comment)\n                    seq.comment = props.comment;\n                continue;\n            }\n        }\n        const node = value\n            ? composeNode(ctx, value, props, onError)\n            : composeEmptyNode(ctx, props.end, start, null, props, onError);\n        if (ctx.schema.compat)\n            utilFlowIndentCheck.flowIndentCheck(bs.indent, value, onError);\n        offset = node.range[2];\n        seq.items.push(node);\n    }\n    seq.range = [bs.offset, offset, commentEnd ?? offset];\n    return seq;\n}\n\nexports.resolveBlockSeq = resolveBlockSeq;\n","'use strict';\n\nfunction resolveEnd(end, offset, reqSpace, onError) {\n    let comment = '';\n    if (end) {\n        let hasSpace = false;\n        let sep = '';\n        for (const token of end) {\n            const { source, type } = token;\n            switch (type) {\n                case 'space':\n                    hasSpace = true;\n                    break;\n                case 'comment': {\n                    if (reqSpace && !hasSpace)\n                        onError(token, 'MISSING_CHAR', 'Comments must be separated from other tokens by white space characters');\n                    const cb = source.substring(1) || ' ';\n                    if (!comment)\n                        comment = cb;\n                    else\n                        comment += sep + cb;\n                    sep = '';\n                    break;\n                }\n                case 'newline':\n                    if (comment)\n                        sep += source;\n                    hasSpace = true;\n                    break;\n                default:\n                    onError(token, 'UNEXPECTED_TOKEN', `Unexpected ${type} at node end`);\n            }\n            offset += source.length;\n        }\n    }\n    return { comment, offset };\n}\n\nexports.resolveEnd = resolveEnd;\n","'use strict';\n\nvar identity = require('../nodes/identity.js');\nvar Pair = require('../nodes/Pair.js');\nvar YAMLMap = require('../nodes/YAMLMap.js');\nvar YAMLSeq = require('../nodes/YAMLSeq.js');\nvar resolveEnd = require('./resolve-end.js');\nvar resolveProps = require('./resolve-props.js');\nvar utilContainsNewline = require('./util-contains-newline.js');\nvar utilMapIncludes = require('./util-map-includes.js');\n\nconst blockMsg = 'Block collections are not allowed within flow collections';\nconst isBlock = (token) => token && (token.type === 'block-map' || token.type === 'block-seq');\nfunction resolveFlowCollection({ composeNode, composeEmptyNode }, ctx, fc, onError, tag) {\n    const isMap = fc.start.source === '{';\n    const fcName = isMap ? 'flow map' : 'flow sequence';\n    const NodeClass = (tag?.nodeClass ?? (isMap ? YAMLMap.YAMLMap : YAMLSeq.YAMLSeq));\n    const coll = new NodeClass(ctx.schema);\n    coll.flow = true;\n    const atRoot = ctx.atRoot;\n    if (atRoot)\n        ctx.atRoot = false;\n    if (ctx.atKey)\n        ctx.atKey = false;\n    let offset = fc.offset + fc.start.source.length;\n    for (let i = 0; i < fc.items.length; ++i) {\n        const collItem = fc.items[i];\n        const { start, key, sep, value } = collItem;\n        const props = resolveProps.resolveProps(start, {\n            flow: fcName,\n            indicator: 'explicit-key-ind',\n            next: key ?? sep?.[0],\n            offset,\n            onError,\n            parentIndent: fc.indent,\n            startOnNewline: false\n        });\n        if (!props.found) {\n            if (!props.anchor && !props.tag && !sep && !value) {\n                if (i === 0 && props.comma)\n                    onError(props.comma, 'UNEXPECTED_TOKEN', `Unexpected , in ${fcName}`);\n                else if (i < fc.items.length - 1)\n                    onError(props.start, 'UNEXPECTED_TOKEN', `Unexpected empty item in ${fcName}`);\n                if (props.comment) {\n                    if (coll.comment)\n                        coll.comment += '\\n' + props.comment;\n                    else\n                        coll.comment = props.comment;\n                }\n                offset = props.end;\n                continue;\n            }\n            if (!isMap && ctx.options.strict && utilContainsNewline.containsNewline(key))\n                onError(key, // checked by containsNewline()\n                'MULTILINE_IMPLICIT_KEY', 'Implicit keys of flow sequence pairs need to be on a single line');\n        }\n        if (i === 0) {\n            if (props.comma)\n                onError(props.comma, 'UNEXPECTED_TOKEN', `Unexpected , in ${fcName}`);\n        }\n        else {\n            if (!props.comma)\n                onError(props.start, 'MISSING_CHAR', `Missing , between ${fcName} items`);\n            if (props.comment) {\n                let prevItemComment = '';\n                loop: for (const st of start) {\n                    switch (st.type) {\n                        case 'comma':\n                        case 'space':\n                            break;\n                        case 'comment':\n                            prevItemComment = st.source.substring(1);\n                            break loop;\n                        default:\n                            break loop;\n                    }\n                }\n                if (prevItemComment) {\n                    let prev = coll.items[coll.items.length - 1];\n                    if (identity.isPair(prev))\n                        prev = prev.value ?? prev.key;\n                    if (prev.comment)\n                        prev.comment += '\\n' + prevItemComment;\n                    else\n                        prev.comment = prevItemComment;\n                    props.comment = props.comment.substring(prevItemComment.length + 1);\n                }\n            }\n        }\n        if (!isMap && !sep && !props.found) {\n            // item is a value in a seq\n            // → key & sep are empty, start does not include ? or :\n            const valueNode = value\n                ? composeNode(ctx, value, props, onError)\n                : composeEmptyNode(ctx, props.end, sep, null, props, onError);\n            coll.items.push(valueNode);\n            offset = valueNode.range[2];\n            if (isBlock(value))\n                onError(valueNode.range, 'BLOCK_IN_FLOW', blockMsg);\n        }\n        else {\n            // item is a key+value pair\n            // key value\n            ctx.atKey = true;\n            const keyStart = props.end;\n            const keyNode = key\n                ? composeNode(ctx, key, props, onError)\n                : composeEmptyNode(ctx, keyStart, start, null, props, onError);\n            if (isBlock(key))\n                onError(keyNode.range, 'BLOCK_IN_FLOW', blockMsg);\n            ctx.atKey = false;\n            // value properties\n            const valueProps = resolveProps.resolveProps(sep ?? [], {\n                flow: fcName,\n                indicator: 'map-value-ind',\n                next: value,\n                offset: keyNode.range[2],\n                onError,\n                parentIndent: fc.indent,\n                startOnNewline: false\n            });\n            if (valueProps.found) {\n                if (!isMap && !props.found && ctx.options.strict) {\n                    if (sep)\n                        for (const st of sep) {\n                            if (st === valueProps.found)\n                                break;\n                            if (st.type === 'newline') {\n                                onError(st, 'MULTILINE_IMPLICIT_KEY', 'Implicit keys of flow sequence pairs need to be on a single line');\n                                break;\n                            }\n                        }\n                    if (props.start < valueProps.found.offset - 1024)\n                        onError(valueProps.found, 'KEY_OVER_1024_CHARS', 'The : indicator must be at most 1024 chars after the start of an implicit flow sequence key');\n                }\n            }\n            else if (value) {\n                if ('source' in value && value.source?.[0] === ':')\n                    onError(value, 'MISSING_CHAR', `Missing space after : in ${fcName}`);\n                else\n                    onError(valueProps.start, 'MISSING_CHAR', `Missing , or : between ${fcName} items`);\n            }\n            // value value\n            const valueNode = value\n                ? composeNode(ctx, value, valueProps, onError)\n                : valueProps.found\n                    ? composeEmptyNode(ctx, valueProps.end, sep, null, valueProps, onError)\n                    : null;\n            if (valueNode) {\n                if (isBlock(value))\n                    onError(valueNode.range, 'BLOCK_IN_FLOW', blockMsg);\n            }\n            else if (valueProps.comment) {\n                if (keyNode.comment)\n                    keyNode.comment += '\\n' + valueProps.comment;\n                else\n                    keyNode.comment = valueProps.comment;\n            }\n            const pair = new Pair.Pair(keyNode, valueNode);\n            if (ctx.options.keepSourceTokens)\n                pair.srcToken = collItem;\n            if (isMap) {\n                const map = coll;\n                if (utilMapIncludes.mapIncludes(ctx, map.items, keyNode))\n                    onError(keyStart, 'DUPLICATE_KEY', 'Map keys must be unique');\n                map.items.push(pair);\n            }\n            else {\n                const map = new YAMLMap.YAMLMap(ctx.schema);\n                map.flow = true;\n                map.items.push(pair);\n                const endRange = (valueNode ?? keyNode).range;\n                map.range = [keyNode.range[0], endRange[1], endRange[2]];\n                coll.items.push(map);\n            }\n            offset = valueNode ? valueNode.range[2] : valueProps.end;\n        }\n    }\n    const expectedEnd = isMap ? '}' : ']';\n    const [ce, ...ee] = fc.end;\n    let cePos = offset;\n    if (ce?.source === expectedEnd)\n        cePos = ce.offset + ce.source.length;\n    else {\n        const name = fcName[0].toUpperCase() + fcName.substring(1);\n        const msg = atRoot\n            ? `${name} must end with a ${expectedEnd}`\n            : `${name} in block collection must be sufficiently indented and end with a ${expectedEnd}`;\n        onError(offset, atRoot ? 'MISSING_CHAR' : 'BAD_INDENT', msg);\n        if (ce && ce.source.length !== 1)\n            ee.unshift(ce);\n    }\n    if (ee.length > 0) {\n        const end = resolveEnd.resolveEnd(ee, cePos, ctx.options.strict, onError);\n        if (end.comment) {\n            if (coll.comment)\n                coll.comment += '\\n' + end.comment;\n            else\n                coll.comment = end.comment;\n        }\n        coll.range = [fc.offset, cePos, end.offset];\n    }\n    else {\n        coll.range = [fc.offset, cePos, cePos];\n    }\n    return coll;\n}\n\nexports.resolveFlowCollection = resolveFlowCollection;\n","'use strict';\n\nvar identity = require('../nodes/identity.js');\nvar Scalar = require('../nodes/Scalar.js');\nvar YAMLMap = require('../nodes/YAMLMap.js');\nvar YAMLSeq = require('../nodes/YAMLSeq.js');\nvar resolveBlockMap = require('./resolve-block-map.js');\nvar resolveBlockSeq = require('./resolve-block-seq.js');\nvar resolveFlowCollection = require('./resolve-flow-collection.js');\n\nfunction resolveCollection(CN, ctx, token, onError, tagName, tag) {\n    const coll = token.type === 'block-map'\n        ? resolveBlockMap.resolveBlockMap(CN, ctx, token, onError, tag)\n        : token.type === 'block-seq'\n            ? resolveBlockSeq.resolveBlockSeq(CN, ctx, token, onError, tag)\n            : resolveFlowCollection.resolveFlowCollection(CN, ctx, token, onError, tag);\n    const Coll = coll.constructor;\n    // If we got a tagName matching the class, or the tag name is '!',\n    // then use the tagName from the node class used to create it.\n    if (tagName === '!' || tagName === Coll.tagName) {\n        coll.tag = Coll.tagName;\n        return coll;\n    }\n    if (tagName)\n        coll.tag = tagName;\n    return coll;\n}\nfunction composeCollection(CN, ctx, token, props, onError) {\n    const tagToken = props.tag;\n    const tagName = !tagToken\n        ? null\n        : ctx.directives.tagName(tagToken.source, msg => onError(tagToken, 'TAG_RESOLVE_FAILED', msg));\n    if (token.type === 'block-seq') {\n        const { anchor, newlineAfterProp: nl } = props;\n        const lastProp = anchor && tagToken\n            ? anchor.offset > tagToken.offset\n                ? anchor\n                : tagToken\n            : (anchor ?? tagToken);\n        if (lastProp && (!nl || nl.offset < lastProp.offset)) {\n            const message = 'Missing newline after block sequence props';\n            onError(lastProp, 'MISSING_CHAR', message);\n        }\n    }\n    const expType = token.type === 'block-map'\n        ? 'map'\n        : token.type === 'block-seq'\n            ? 'seq'\n            : token.start.source === '{'\n                ? 'map'\n                : 'seq';\n    // shortcut: check if it's a generic YAMLMap or YAMLSeq\n    // before jumping into the custom tag logic.\n    if (!tagToken ||\n        !tagName ||\n        tagName === '!' ||\n        (tagName === YAMLMap.YAMLMap.tagName && expType === 'map') ||\n        (tagName === YAMLSeq.YAMLSeq.tagName && expType === 'seq')) {\n        return resolveCollection(CN, ctx, token, onError, tagName);\n    }\n    let tag = ctx.schema.tags.find(t => t.tag === tagName && t.collection === expType);\n    if (!tag) {\n        const kt = ctx.schema.knownTags[tagName];\n        if (kt?.collection === expType) {\n            ctx.schema.tags.push(Object.assign({}, kt, { default: false }));\n            tag = kt;\n        }\n        else {\n            if (kt) {\n                onError(tagToken, 'BAD_COLLECTION_TYPE', `${kt.tag} used for ${expType} collection, but expects ${kt.collection ?? 'scalar'}`, true);\n            }\n            else {\n                onError(tagToken, 'TAG_RESOLVE_FAILED', `Unresolved tag: ${tagName}`, true);\n            }\n            return resolveCollection(CN, ctx, token, onError, tagName);\n        }\n    }\n    const coll = resolveCollection(CN, ctx, token, onError, tagName, tag);\n    const res = tag.resolve?.(coll, msg => onError(tagToken, 'TAG_RESOLVE_FAILED', msg), ctx.options) ?? coll;\n    const node = identity.isNode(res)\n        ? res\n        : new Scalar.Scalar(res);\n    node.range = coll.range;\n    node.tag = tagName;\n    if (tag?.format)\n        node.format = tag.format;\n    return node;\n}\n\nexports.composeCollection = composeCollection;\n","'use strict';\n\nvar Scalar = require('../nodes/Scalar.js');\n\nfunction resolveBlockScalar(ctx, scalar, onError) {\n    const start = scalar.offset;\n    const header = parseBlockScalarHeader(scalar, ctx.options.strict, onError);\n    if (!header)\n        return { value: '', type: null, comment: '', range: [start, start, start] };\n    const type = header.mode === '>' ? Scalar.Scalar.BLOCK_FOLDED : Scalar.Scalar.BLOCK_LITERAL;\n    const lines = scalar.source ? splitLines(scalar.source) : [];\n    // determine the end of content & start of chomping\n    let chompStart = lines.length;\n    for (let i = lines.length - 1; i >= 0; --i) {\n        const content = lines[i][1];\n        if (content === '' || content === '\\r')\n            chompStart = i;\n        else\n            break;\n    }\n    // shortcut for empty contents\n    if (chompStart === 0) {\n        const value = header.chomp === '+' && lines.length > 0\n            ? '\\n'.repeat(Math.max(1, lines.length - 1))\n            : '';\n        let end = start + header.length;\n        if (scalar.source)\n            end += scalar.source.length;\n        return { value, type, comment: header.comment, range: [start, end, end] };\n    }\n    // find the indentation level to trim from start\n    let trimIndent = scalar.indent + header.indent;\n    let offset = scalar.offset + header.length;\n    let contentStart = 0;\n    for (let i = 0; i < chompStart; ++i) {\n        const [indent, content] = lines[i];\n        if (content === '' || content === '\\r') {\n            if (header.indent === 0 && indent.length > trimIndent)\n                trimIndent = indent.length;\n        }\n        else {\n            if (indent.length < trimIndent) {\n                const message = 'Block scalars with more-indented leading empty lines must use an explicit indentation indicator';\n                onError(offset + indent.length, 'MISSING_CHAR', message);\n            }\n            if (header.indent === 0)\n                trimIndent = indent.length;\n            contentStart = i;\n            if (trimIndent === 0 && !ctx.atRoot) {\n                const message = 'Block scalar values in collections must be indented';\n                onError(offset, 'BAD_INDENT', message);\n            }\n            break;\n        }\n        offset += indent.length + content.length + 1;\n    }\n    // include trailing more-indented empty lines in content\n    for (let i = lines.length - 1; i >= chompStart; --i) {\n        if (lines[i][0].length > trimIndent)\n            chompStart = i + 1;\n    }\n    let value = '';\n    let sep = '';\n    let prevMoreIndented = false;\n    // leading whitespace is kept intact\n    for (let i = 0; i < contentStart; ++i)\n        value += lines[i][0].slice(trimIndent) + '\\n';\n    for (let i = contentStart; i < chompStart; ++i) {\n        let [indent, content] = lines[i];\n        offset += indent.length + content.length + 1;\n        const crlf = content[content.length - 1] === '\\r';\n        if (crlf)\n            content = content.slice(0, -1);\n        /* istanbul ignore if already caught in lexer */\n        if (content && indent.length < trimIndent) {\n            const src = header.indent\n                ? 'explicit indentation indicator'\n                : 'first line';\n            const message = `Block scalar lines must not be less indented than their ${src}`;\n            onError(offset - content.length - (crlf ? 2 : 1), 'BAD_INDENT', message);\n            indent = '';\n        }\n        if (type === Scalar.Scalar.BLOCK_LITERAL) {\n            value += sep + indent.slice(trimIndent) + content;\n            sep = '\\n';\n        }\n        else if (indent.length > trimIndent || content[0] === '\\t') {\n            // more-indented content within a folded block\n            if (sep === ' ')\n                sep = '\\n';\n            else if (!prevMoreIndented && sep === '\\n')\n                sep = '\\n\\n';\n            value += sep + indent.slice(trimIndent) + content;\n            sep = '\\n';\n            prevMoreIndented = true;\n        }\n        else if (content === '') {\n            // empty line\n            if (sep === '\\n')\n                value += '\\n';\n            else\n                sep = '\\n';\n        }\n        else {\n            value += sep + content;\n            sep = ' ';\n            prevMoreIndented = false;\n        }\n    }\n    switch (header.chomp) {\n        case '-':\n            break;\n        case '+':\n            for (let i = chompStart; i < lines.length; ++i)\n                value += '\\n' + lines[i][0].slice(trimIndent);\n            if (value[value.length - 1] !== '\\n')\n                value += '\\n';\n            break;\n        default:\n            value += '\\n';\n    }\n    const end = start + header.length + scalar.source.length;\n    return { value, type, comment: header.comment, range: [start, end, end] };\n}\nfunction parseBlockScalarHeader({ offset, props }, strict, onError) {\n    /* istanbul ignore if should not happen */\n    if (props[0].type !== 'block-scalar-header') {\n        onError(props[0], 'IMPOSSIBLE', 'Block scalar header not found');\n        return null;\n    }\n    const { source } = props[0];\n    const mode = source[0];\n    let indent = 0;\n    let chomp = '';\n    let error = -1;\n    for (let i = 1; i < source.length; ++i) {\n        const ch = source[i];\n        if (!chomp && (ch === '-' || ch === '+'))\n            chomp = ch;\n        else {\n            const n = Number(ch);\n            if (!indent && n)\n                indent = n;\n            else if (error === -1)\n                error = offset + i;\n        }\n    }\n    if (error !== -1)\n        onError(error, 'UNEXPECTED_TOKEN', `Block scalar header includes extra characters: ${source}`);\n    let hasSpace = false;\n    let comment = '';\n    let length = source.length;\n    for (let i = 1; i < props.length; ++i) {\n        const token = props[i];\n        switch (token.type) {\n            case 'space':\n                hasSpace = true;\n            // fallthrough\n            case 'newline':\n                length += token.source.length;\n                break;\n            case 'comment':\n                if (strict && !hasSpace) {\n                    const message = 'Comments must be separated from other tokens by white space characters';\n                    onError(token, 'MISSING_CHAR', message);\n                }\n                length += token.source.length;\n                comment = token.source.substring(1);\n                break;\n            case 'error':\n                onError(token, 'UNEXPECTED_TOKEN', token.message);\n                length += token.source.length;\n                break;\n            /* istanbul ignore next should not happen */\n            default: {\n                const message = `Unexpected token in block scalar header: ${token.type}`;\n                onError(token, 'UNEXPECTED_TOKEN', message);\n                const ts = token.source;\n                if (ts && typeof ts === 'string')\n                    length += ts.length;\n            }\n        }\n    }\n    return { mode, indent, chomp, comment, length };\n}\n/** @returns Array of lines split up as `[indent, content]` */\nfunction splitLines(source) {\n    const split = source.split(/\\n( *)/);\n    const first = split[0];\n    const m = first.match(/^( *)/);\n    const line0 = m?.[1]\n        ? [m[1], first.slice(m[1].length)]\n        : ['', first];\n    const lines = [line0];\n    for (let i = 1; i < split.length; i += 2)\n        lines.push([split[i], split[i + 1]]);\n    return lines;\n}\n\nexports.resolveBlockScalar = resolveBlockScalar;\n","'use strict';\n\nvar Scalar = require('../nodes/Scalar.js');\nvar resolveEnd = require('./resolve-end.js');\n\nfunction resolveFlowScalar(scalar, strict, onError) {\n    const { offset, type, source, end } = scalar;\n    let _type;\n    let value;\n    const _onError = (rel, code, msg) => onError(offset + rel, code, msg);\n    switch (type) {\n        case 'scalar':\n            _type = Scalar.Scalar.PLAIN;\n            value = plainValue(source, _onError);\n            break;\n        case 'single-quoted-scalar':\n            _type = Scalar.Scalar.QUOTE_SINGLE;\n            value = singleQuotedValue(source, _onError);\n            break;\n        case 'double-quoted-scalar':\n            _type = Scalar.Scalar.QUOTE_DOUBLE;\n            value = doubleQuotedValue(source, _onError);\n            break;\n        /* istanbul ignore next should not happen */\n        default:\n            onError(scalar, 'UNEXPECTED_TOKEN', `Expected a flow scalar value, but found: ${type}`);\n            return {\n                value: '',\n                type: null,\n                comment: '',\n                range: [offset, offset + source.length, offset + source.length]\n            };\n    }\n    const valueEnd = offset + source.length;\n    const re = resolveEnd.resolveEnd(end, valueEnd, strict, onError);\n    return {\n        value,\n        type: _type,\n        comment: re.comment,\n        range: [offset, valueEnd, re.offset]\n    };\n}\nfunction plainValue(source, onError) {\n    let badChar = '';\n    switch (source[0]) {\n        /* istanbul ignore next should not happen */\n        case '\\t':\n            badChar = 'a tab character';\n            break;\n        case ',':\n            badChar = 'flow indicator character ,';\n            break;\n        case '%':\n            badChar = 'directive indicator character %';\n            break;\n        case '|':\n        case '>': {\n            badChar = `block scalar indicator ${source[0]}`;\n            break;\n        }\n        case '@':\n        case '`': {\n            badChar = `reserved character ${source[0]}`;\n            break;\n        }\n    }\n    if (badChar)\n        onError(0, 'BAD_SCALAR_START', `Plain value cannot start with ${badChar}`);\n    return foldLines(source);\n}\nfunction singleQuotedValue(source, onError) {\n    if (source[source.length - 1] !== \"'\" || source.length === 1)\n        onError(source.length, 'MISSING_CHAR', \"Missing closing 'quote\");\n    return foldLines(source.slice(1, -1)).replace(/''/g, \"'\");\n}\nfunction foldLines(source) {\n    /**\n     * The negative lookbehind here and in the `re` RegExp is to\n     * prevent causing a polynomial search time in certain cases.\n     *\n     * The try-catch is for Safari, which doesn't support this yet:\n     * https://caniuse.com/js-regexp-lookbehind\n     */\n    let first, line;\n    try {\n        first = new RegExp('(.*?)(?<![ \\t])[ \\t]*\\r?\\n', 'sy');\n        line = new RegExp('[ \\t]*(.*?)(?:(?<![ \\t])[ \\t]*)?\\r?\\n', 'sy');\n    }\n    catch {\n        first = /(.*?)[ \\t]*\\r?\\n/sy;\n        line = /[ \\t]*(.*?)[ \\t]*\\r?\\n/sy;\n    }\n    let match = first.exec(source);\n    if (!match)\n        return source;\n    let res = match[1];\n    let sep = ' ';\n    let pos = first.lastIndex;\n    line.lastIndex = pos;\n    while ((match = line.exec(source))) {\n        if (match[1] === '') {\n            if (sep === '\\n')\n                res += sep;\n            else\n                sep = '\\n';\n        }\n        else {\n            res += sep + match[1];\n            sep = ' ';\n        }\n        pos = line.lastIndex;\n    }\n    const last = /[ \\t]*(.*)/sy;\n    last.lastIndex = pos;\n    match = last.exec(source);\n    return res + sep + (match?.[1] ?? '');\n}\nfunction doubleQuotedValue(source, onError) {\n    let res = '';\n    for (let i = 1; i < source.length - 1; ++i) {\n        const ch = source[i];\n        if (ch === '\\r' && source[i + 1] === '\\n')\n            continue;\n        if (ch === '\\n') {\n            const { fold, offset } = foldNewline(source, i);\n            res += fold;\n            i = offset;\n        }\n        else if (ch === '\\\\') {\n            let next = source[++i];\n            const cc = escapeCodes[next];\n            if (cc)\n                res += cc;\n            else if (next === '\\n') {\n                // skip escaped newlines, but still trim the following line\n                next = source[i + 1];\n                while (next === ' ' || next === '\\t')\n                    next = source[++i + 1];\n            }\n            else if (next === '\\r' && source[i + 1] === '\\n') {\n                // skip escaped CRLF newlines, but still trim the following line\n                next = source[++i + 1];\n                while (next === ' ' || next === '\\t')\n                    next = source[++i + 1];\n            }\n            else if (next === 'x' || next === 'u' || next === 'U') {\n                const length = next === 'x' ? 2 : next === 'u' ? 4 : 8;\n                res += parseCharCode(source, i + 1, length, onError);\n                i += length;\n            }\n            else {\n                const raw = source.substr(i - 1, 2);\n                onError(i - 1, 'BAD_DQ_ESCAPE', `Invalid escape sequence ${raw}`);\n                res += raw;\n            }\n        }\n        else if (ch === ' ' || ch === '\\t') {\n            // trim trailing whitespace\n            const wsStart = i;\n            let next = source[i + 1];\n            while (next === ' ' || next === '\\t')\n                next = source[++i + 1];\n            if (next !== '\\n' && !(next === '\\r' && source[i + 2] === '\\n'))\n                res += i > wsStart ? source.slice(wsStart, i + 1) : ch;\n        }\n        else {\n            res += ch;\n        }\n    }\n    if (source[source.length - 1] !== '\"' || source.length === 1)\n        onError(source.length, 'MISSING_CHAR', 'Missing closing \"quote');\n    return res;\n}\n/**\n * Fold a single newline into a space, multiple newlines to N - 1 newlines.\n * Presumes `source[offset] === '\\n'`\n */\nfunction foldNewline(source, offset) {\n    let fold = '';\n    let ch = source[offset + 1];\n    while (ch === ' ' || ch === '\\t' || ch === '\\n' || ch === '\\r') {\n        if (ch === '\\r' && source[offset + 2] !== '\\n')\n            break;\n        if (ch === '\\n')\n            fold += '\\n';\n        offset += 1;\n        ch = source[offset + 1];\n    }\n    if (!fold)\n        fold = ' ';\n    return { fold, offset };\n}\nconst escapeCodes = {\n    '0': '\\0', // null character\n    a: '\\x07', // bell character\n    b: '\\b', // backspace\n    e: '\\x1b', // escape character\n    f: '\\f', // form feed\n    n: '\\n', // line feed\n    r: '\\r', // carriage return\n    t: '\\t', // horizontal tab\n    v: '\\v', // vertical tab\n    N: '\\u0085', // Unicode next line\n    _: '\\u00a0', // Unicode non-breaking space\n    L: '\\u2028', // Unicode line separator\n    P: '\\u2029', // Unicode paragraph separator\n    ' ': ' ',\n    '\"': '\"',\n    '/': '/',\n    '\\\\': '\\\\',\n    '\\t': '\\t'\n};\nfunction parseCharCode(source, offset, length, onError) {\n    const cc = source.substr(offset, length);\n    const ok = cc.length === length && /^[0-9a-fA-F]+$/.test(cc);\n    const code = ok ? parseInt(cc, 16) : NaN;\n    try {\n        return String.fromCodePoint(code);\n    }\n    catch {\n        const raw = source.substr(offset - 2, length + 2);\n        onError(offset - 2, 'BAD_DQ_ESCAPE', `Invalid escape sequence ${raw}`);\n        return raw;\n    }\n}\n\nexports.resolveFlowScalar = resolveFlowScalar;\n","'use strict';\n\nvar identity = require('../nodes/identity.js');\nvar Scalar = require('../nodes/Scalar.js');\nvar resolveBlockScalar = require('./resolve-block-scalar.js');\nvar resolveFlowScalar = require('./resolve-flow-scalar.js');\n\nfunction composeScalar(ctx, token, tagToken, onError) {\n    const { value, type, comment, range } = token.type === 'block-scalar'\n        ? resolveBlockScalar.resolveBlockScalar(ctx, token, onError)\n        : resolveFlowScalar.resolveFlowScalar(token, ctx.options.strict, onError);\n    const tagName = tagToken\n        ? ctx.directives.tagName(tagToken.source, msg => onError(tagToken, 'TAG_RESOLVE_FAILED', msg))\n        : null;\n    let tag;\n    if (ctx.options.stringKeys && ctx.atKey) {\n        tag = ctx.schema[identity.SCALAR];\n    }\n    else if (tagName)\n        tag = findScalarTagByName(ctx.schema, value, tagName, tagToken, onError);\n    else if (token.type === 'scalar')\n        tag = findScalarTagByTest(ctx, value, token, onError);\n    else\n        tag = ctx.schema[identity.SCALAR];\n    let scalar;\n    try {\n        const res = tag.resolve(value, msg => onError(tagToken ?? token, 'TAG_RESOLVE_FAILED', msg), ctx.options);\n        scalar = identity.isScalar(res) ? res : new Scalar.Scalar(res);\n    }\n    catch (error) {\n        const msg = error instanceof Error ? error.message : String(error);\n        onError(tagToken ?? token, 'TAG_RESOLVE_FAILED', msg);\n        scalar = new Scalar.Scalar(value);\n    }\n    scalar.range = range;\n    scalar.source = value;\n    if (type)\n        scalar.type = type;\n    if (tagName)\n        scalar.tag = tagName;\n    if (tag.format)\n        scalar.format = tag.format;\n    if (comment)\n        scalar.comment = comment;\n    return scalar;\n}\nfunction findScalarTagByName(schema, value, tagName, tagToken, onError) {\n    if (tagName === '!')\n        return schema[identity.SCALAR]; // non-specific tag\n    const matchWithTest = [];\n    for (const tag of schema.tags) {\n        if (!tag.collection && tag.tag === tagName) {\n            if (tag.default && tag.test)\n                matchWithTest.push(tag);\n            else\n                return tag;\n        }\n    }\n    for (const tag of matchWithTest)\n        if (tag.test?.test(value))\n            return tag;\n    const kt = schema.knownTags[tagName];\n    if (kt && !kt.collection) {\n        // Ensure that the known tag is available for stringifying,\n        // but does not get used by default.\n        schema.tags.push(Object.assign({}, kt, { default: false, test: undefined }));\n        return kt;\n    }\n    onError(tagToken, 'TAG_RESOLVE_FAILED', `Unresolved tag: ${tagName}`, tagName !== 'tag:yaml.org,2002:str');\n    return schema[identity.SCALAR];\n}\nfunction findScalarTagByTest({ atKey, directives, schema }, value, token, onError) {\n    const tag = schema.tags.find(tag => (tag.default === true || (atKey && tag.default === 'key')) &&\n        tag.test?.test(value)) || schema[identity.SCALAR];\n    if (schema.compat) {\n        const compat = schema.compat.find(tag => tag.default && tag.test?.test(value)) ??\n            schema[identity.SCALAR];\n        if (tag.tag !== compat.tag) {\n            const ts = directives.tagString(tag.tag);\n            const cs = directives.tagString(compat.tag);\n            const msg = `Value may be parsed as either ${ts} or ${cs}`;\n            onError(token, 'TAG_RESOLVE_FAILED', msg, true);\n        }\n    }\n    return tag;\n}\n\nexports.composeScalar = composeScalar;\n","'use strict';\n\nfunction emptyScalarPosition(offset, before, pos) {\n    if (before) {\n        pos ?? (pos = before.length);\n        for (let i = pos - 1; i >= 0; --i) {\n            let st = before[i];\n            switch (st.type) {\n                case 'space':\n                case 'comment':\n                case 'newline':\n                    offset -= st.source.length;\n                    continue;\n            }\n            // Technically, an empty scalar is immediately after the last non-empty\n            // node, but it's more useful to place it after any whitespace.\n            st = before[++i];\n            while (st?.type === 'space') {\n                offset += st.source.length;\n                st = before[++i];\n            }\n            break;\n        }\n    }\n    return offset;\n}\n\nexports.emptyScalarPosition = emptyScalarPosition;\n","'use strict';\n\nvar Alias = require('../nodes/Alias.js');\nvar identity = require('../nodes/identity.js');\nvar composeCollection = require('./compose-collection.js');\nvar composeScalar = require('./compose-scalar.js');\nvar resolveEnd = require('./resolve-end.js');\nvar utilEmptyScalarPosition = require('./util-empty-scalar-position.js');\n\nconst CN = { composeNode, composeEmptyNode };\nfunction composeNode(ctx, token, props, onError) {\n    const atKey = ctx.atKey;\n    const { spaceBefore, comment, anchor, tag } = props;\n    let node;\n    let isSrcToken = true;\n    switch (token.type) {\n        case 'alias':\n            node = composeAlias(ctx, token, onError);\n            if (anchor || tag)\n                onError(token, 'ALIAS_PROPS', 'An alias node must not specify any properties');\n            break;\n        case 'scalar':\n        case 'single-quoted-scalar':\n        case 'double-quoted-scalar':\n        case 'block-scalar':\n            node = composeScalar.composeScalar(ctx, token, tag, onError);\n            if (anchor)\n                node.anchor = anchor.source.substring(1);\n            break;\n        case 'block-map':\n        case 'block-seq':\n        case 'flow-collection':\n            try {\n                node = composeCollection.composeCollection(CN, ctx, token, props, onError);\n                if (anchor)\n                    node.anchor = anchor.source.substring(1);\n            }\n            catch (error) {\n                // Almost certainly here due to a stack overflow\n                const message = error instanceof Error ? error.message : String(error);\n                onError(token, 'RESOURCE_EXHAUSTION', message);\n            }\n            break;\n        default: {\n            const message = token.type === 'error'\n                ? token.message\n                : `Unsupported token (type: ${token.type})`;\n            onError(token, 'UNEXPECTED_TOKEN', message);\n            isSrcToken = false;\n        }\n    }\n    node ?? (node = composeEmptyNode(ctx, token.offset, undefined, null, props, onError));\n    if (anchor && node.anchor === '')\n        onError(anchor, 'BAD_ALIAS', 'Anchor cannot be an empty string');\n    if (atKey &&\n        ctx.options.stringKeys &&\n        (!identity.isScalar(node) ||\n            typeof node.value !== 'string' ||\n            (node.tag && node.tag !== 'tag:yaml.org,2002:str'))) {\n        const msg = 'With stringKeys, all keys must be strings';\n        onError(tag ?? token, 'NON_STRING_KEY', msg);\n    }\n    if (spaceBefore)\n        node.spaceBefore = true;\n    if (comment) {\n        if (token.type === 'scalar' && token.source === '')\n            node.comment = comment;\n        else\n            node.commentBefore = comment;\n    }\n    // @ts-expect-error Type checking misses meaning of isSrcToken\n    if (ctx.options.keepSourceTokens && isSrcToken)\n        node.srcToken = token;\n    return node;\n}\nfunction composeEmptyNode(ctx, offset, before, pos, { spaceBefore, comment, anchor, tag, end }, onError) {\n    const token = {\n        type: 'scalar',\n        offset: utilEmptyScalarPosition.emptyScalarPosition(offset, before, pos),\n        indent: -1,\n        source: ''\n    };\n    const node = composeScalar.composeScalar(ctx, token, tag, onError);\n    if (anchor) {\n        node.anchor = anchor.source.substring(1);\n        if (node.anchor === '')\n            onError(anchor, 'BAD_ALIAS', 'Anchor cannot be an empty string');\n    }\n    if (spaceBefore)\n        node.spaceBefore = true;\n    if (comment) {\n        node.comment = comment;\n        node.range[2] = end;\n    }\n    return node;\n}\nfunction composeAlias({ options }, { offset, source, end }, onError) {\n    const alias = new Alias.Alias(source.substring(1));\n    if (alias.source === '')\n        onError(offset, 'BAD_ALIAS', 'Alias cannot be an empty string');\n    if (alias.source.endsWith(':'))\n        onError(offset + source.length - 1, 'BAD_ALIAS', 'Alias ending in : is ambiguous', true);\n    const valueEnd = offset + source.length;\n    const re = resolveEnd.resolveEnd(end, valueEnd, options.strict, onError);\n    alias.range = [offset, valueEnd, re.offset];\n    if (re.comment)\n        alias.comment = re.comment;\n    return alias;\n}\n\nexports.composeEmptyNode = composeEmptyNode;\nexports.composeNode = composeNode;\n","'use strict';\n\nvar Document = require('../doc/Document.js');\nvar composeNode = require('./compose-node.js');\nvar resolveEnd = require('./resolve-end.js');\nvar resolveProps = require('./resolve-props.js');\n\nfunction composeDoc(options, directives, { offset, start, value, end }, onError) {\n    const opts = Object.assign({ _directives: directives }, options);\n    const doc = new Document.Document(undefined, opts);\n    const ctx = {\n        atKey: false,\n        atRoot: true,\n        directives: doc.directives,\n        options: doc.options,\n        schema: doc.schema\n    };\n    const props = resolveProps.resolveProps(start, {\n        indicator: 'doc-start',\n        next: value ?? end?.[0],\n        offset,\n        onError,\n        parentIndent: 0,\n        startOnNewline: true\n    });\n    if (props.found) {\n        doc.directives.docStart = true;\n        if (value &&\n            (value.type === 'block-map' || value.type === 'block-seq') &&\n            !props.hasNewline)\n            onError(props.end, 'MISSING_CHAR', 'Block collection cannot start on same line with directives-end marker');\n    }\n    // @ts-expect-error If Contents is set, let's trust the user\n    doc.contents = value\n        ? composeNode.composeNode(ctx, value, props, onError)\n        : composeNode.composeEmptyNode(ctx, props.end, start, null, props, onError);\n    const contentEnd = doc.contents.range[2];\n    const re = resolveEnd.resolveEnd(end, contentEnd, false, onError);\n    if (re.comment)\n        doc.comment = re.comment;\n    doc.range = [offset, contentEnd, re.offset];\n    return doc;\n}\n\nexports.composeDoc = composeDoc;\n","'use strict';\n\nvar node_process = require('process');\nvar directives = require('../doc/directives.js');\nvar Document = require('../doc/Document.js');\nvar errors = require('../errors.js');\nvar identity = require('../nodes/identity.js');\nvar composeDoc = require('./compose-doc.js');\nvar resolveEnd = require('./resolve-end.js');\n\nfunction getErrorPos(src) {\n    if (typeof src === 'number')\n        return [src, src + 1];\n    if (Array.isArray(src))\n        return src.length === 2 ? src : [src[0], src[1]];\n    const { offset, source } = src;\n    return [offset, offset + (typeof source === 'string' ? source.length : 1)];\n}\nfunction parsePrelude(prelude) {\n    let comment = '';\n    let atComment = false;\n    let afterEmptyLine = false;\n    for (let i = 0; i < prelude.length; ++i) {\n        const source = prelude[i];\n        switch (source[0]) {\n            case '#':\n                comment +=\n                    (comment === '' ? '' : afterEmptyLine ? '\\n\\n' : '\\n') +\n                        (source.substring(1) || ' ');\n                atComment = true;\n                afterEmptyLine = false;\n                break;\n            case '%':\n                if (prelude[i + 1]?.[0] !== '#')\n                    i += 1;\n                atComment = false;\n                break;\n            default:\n                // This may be wrong after doc-end, but in that case it doesn't matter\n                if (!atComment)\n                    afterEmptyLine = true;\n                atComment = false;\n        }\n    }\n    return { comment, afterEmptyLine };\n}\n/**\n * Compose a stream of CST nodes into a stream of YAML Documents.\n *\n * ```ts\n * import { Composer, Parser } from 'yaml'\n *\n * const src: string = ...\n * const tokens = new Parser().parse(src)\n * const docs = new Composer().compose(tokens)\n * ```\n */\nclass Composer {\n    constructor(options = {}) {\n        this.doc = null;\n        this.atDirectives = false;\n        this.prelude = [];\n        this.errors = [];\n        this.warnings = [];\n        this.onError = (source, code, message, warning) => {\n            const pos = getErrorPos(source);\n            if (warning)\n                this.warnings.push(new errors.YAMLWarning(pos, code, message));\n            else\n                this.errors.push(new errors.YAMLParseError(pos, code, message));\n        };\n        // eslint-disable-next-line @typescript-eslint/prefer-nullish-coalescing\n        this.directives = new directives.Directives({ version: options.version || '1.2' });\n        this.options = options;\n    }\n    decorate(doc, afterDoc) {\n        const { comment, afterEmptyLine } = parsePrelude(this.prelude);\n        //console.log({ dc: doc.comment, prelude, comment })\n        if (comment) {\n            const dc = doc.contents;\n            if (afterDoc) {\n                doc.comment = doc.comment ? `${doc.comment}\\n${comment}` : comment;\n            }\n            else if (afterEmptyLine || doc.directives.docStart || !dc) {\n                doc.commentBefore = comment;\n            }\n            else if (identity.isCollection(dc) && !dc.flow && dc.items.length > 0) {\n                let it = dc.items[0];\n                if (identity.isPair(it))\n                    it = it.key;\n                const cb = it.commentBefore;\n                it.commentBefore = cb ? `${comment}\\n${cb}` : comment;\n            }\n            else {\n                const cb = dc.commentBefore;\n                dc.commentBefore = cb ? `${comment}\\n${cb}` : comment;\n            }\n        }\n        if (afterDoc) {\n            for (let i = 0; i < this.errors.length; ++i)\n                doc.errors.push(this.errors[i]);\n            for (let i = 0; i < this.warnings.length; ++i)\n                doc.warnings.push(this.warnings[i]);\n        }\n        else {\n            doc.errors = this.errors;\n            doc.warnings = this.warnings;\n        }\n        this.prelude = [];\n        this.errors = [];\n        this.warnings = [];\n    }\n    /**\n     * Current stream status information.\n     *\n     * Mostly useful at the end of input for an empty stream.\n     */\n    streamInfo() {\n        return {\n            comment: parsePrelude(this.prelude).comment,\n            directives: this.directives,\n            errors: this.errors,\n            warnings: this.warnings\n        };\n    }\n    /**\n     * Compose tokens into documents.\n     *\n     * @param forceDoc - If the stream contains no document, still emit a final document including any comments and directives that would be applied to a subsequent document.\n     * @param endOffset - Should be set if `forceDoc` is also set, to set the document range end and to indicate errors correctly.\n     */\n    *compose(tokens, forceDoc = false, endOffset = -1) {\n        for (const token of tokens)\n            yield* this.next(token);\n        yield* this.end(forceDoc, endOffset);\n    }\n    /** Advance the composer by one CST token. */\n    *next(token) {\n        if (node_process.env.LOG_STREAM)\n            console.dir(token, { depth: null });\n        switch (token.type) {\n            case 'directive':\n                this.directives.add(token.source, (offset, message, warning) => {\n                    const pos = getErrorPos(token);\n                    pos[0] += offset;\n                    this.onError(pos, 'BAD_DIRECTIVE', message, warning);\n                });\n                this.prelude.push(token.source);\n                this.atDirectives = true;\n                break;\n            case 'document': {\n                const doc = composeDoc.composeDoc(this.options, this.directives, token, this.onError);\n                if (this.atDirectives && !doc.directives.docStart)\n                    this.onError(token, 'MISSING_CHAR', 'Missing directives-end/doc-start indicator line');\n                this.decorate(doc, false);\n                if (this.doc)\n                    yield this.doc;\n                this.doc = doc;\n                this.atDirectives = false;\n                break;\n            }\n            case 'byte-order-mark':\n            case 'space':\n                break;\n            case 'comment':\n            case 'newline':\n                this.prelude.push(token.source);\n                break;\n            case 'error': {\n                const msg = token.source\n                    ? `${token.message}: ${JSON.stringify(token.source)}`\n                    : token.message;\n                const error = new errors.YAMLParseError(getErrorPos(token), 'UNEXPECTED_TOKEN', msg);\n                if (this.atDirectives || !this.doc)\n                    this.errors.push(error);\n                else\n                    this.doc.errors.push(error);\n                break;\n            }\n            case 'doc-end': {\n                if (!this.doc) {\n                    const msg = 'Unexpected doc-end without preceding document';\n                    this.errors.push(new errors.YAMLParseError(getErrorPos(token), 'UNEXPECTED_TOKEN', msg));\n                    break;\n                }\n                this.doc.directives.docEnd = true;\n                const end = resolveEnd.resolveEnd(token.end, token.offset + token.source.length, this.doc.options.strict, this.onError);\n                this.decorate(this.doc, true);\n                if (end.comment) {\n                    const dc = this.doc.comment;\n                    this.doc.comment = dc ? `${dc}\\n${end.comment}` : end.comment;\n                }\n                this.doc.range[2] = end.offset;\n                break;\n            }\n            default:\n                this.errors.push(new errors.YAMLParseError(getErrorPos(token), 'UNEXPECTED_TOKEN', `Unsupported token ${token.type}`));\n        }\n    }\n    /**\n     * Call at end of input to yield any remaining document.\n     *\n     * @param forceDoc - If the stream contains no document, still emit a final document including any comments and directives that would be applied to a subsequent document.\n     * @param endOffset - Should be set if `forceDoc` is also set, to set the document range end and to indicate errors correctly.\n     */\n    *end(forceDoc = false, endOffset = -1) {\n        if (this.doc) {\n            this.decorate(this.doc, true);\n            yield this.doc;\n            this.doc = null;\n        }\n        else if (forceDoc) {\n            const opts = Object.assign({ _directives: this.directives }, this.options);\n            const doc = new Document.Document(undefined, opts);\n            if (this.atDirectives)\n                this.onError(endOffset, 'MISSING_CHAR', 'Missing directives-end indicator line');\n            doc.range = [0, endOffset, endOffset];\n            this.decorate(doc, false);\n            yield doc;\n        }\n    }\n}\n\nexports.Composer = Composer;\n","'use strict';\n\nvar resolveBlockScalar = require('../compose/resolve-block-scalar.js');\nvar resolveFlowScalar = require('../compose/resolve-flow-scalar.js');\nvar errors = require('../errors.js');\nvar stringifyString = require('../stringify/stringifyString.js');\n\nfunction resolveAsScalar(token, strict = true, onError) {\n    if (token) {\n        const _onError = (pos, code, message) => {\n            const offset = typeof pos === 'number' ? pos : Array.isArray(pos) ? pos[0] : pos.offset;\n            if (onError)\n                onError(offset, code, message);\n            else\n                throw new errors.YAMLParseError([offset, offset + 1], code, message);\n        };\n        switch (token.type) {\n            case 'scalar':\n            case 'single-quoted-scalar':\n            case 'double-quoted-scalar':\n                return resolveFlowScalar.resolveFlowScalar(token, strict, _onError);\n            case 'block-scalar':\n                return resolveBlockScalar.resolveBlockScalar({ options: { strict } }, token, _onError);\n        }\n    }\n    return null;\n}\n/**\n * Create a new scalar token with `value`\n *\n * Values that represent an actual string but may be parsed as a different type should use a `type` other than `'PLAIN'`,\n * as this function does not support any schema operations and won't check for such conflicts.\n *\n * @param value The string representation of the value, which will have its content properly indented.\n * @param context.end Comments and whitespace after the end of the value, or after the block scalar header. If undefined, a newline will be added.\n * @param context.implicitKey Being within an implicit key may affect the resolved type of the token's value.\n * @param context.indent The indent level of the token.\n * @param context.inFlow Is this scalar within a flow collection? This may affect the resolved type of the token's value.\n * @param context.offset The offset position of the token.\n * @param context.type The preferred type of the scalar token. If undefined, the previous type of the `token` will be used, defaulting to `'PLAIN'`.\n */\nfunction createScalarToken(value, context) {\n    const { implicitKey = false, indent, inFlow = false, offset = -1, type = 'PLAIN' } = context;\n    const source = stringifyString.stringifyString({ type, value }, {\n        implicitKey,\n        indent: indent > 0 ? ' '.repeat(indent) : '',\n        inFlow,\n        options: { blockQuote: true, lineWidth: -1 }\n    });\n    const end = context.end ?? [\n        { type: 'newline', offset: -1, indent, source: '\\n' }\n    ];\n    switch (source[0]) {\n        case '|':\n        case '>': {\n            const he = source.indexOf('\\n');\n            const head = source.substring(0, he);\n            const body = source.substring(he + 1) + '\\n';\n            const props = [\n                { type: 'block-scalar-header', offset, indent, source: head }\n            ];\n            if (!addEndtoBlockProps(props, end))\n                props.push({ type: 'newline', offset: -1, indent, source: '\\n' });\n            return { type: 'block-scalar', offset, indent, props, source: body };\n        }\n        case '\"':\n            return { type: 'double-quoted-scalar', offset, indent, source, end };\n        case \"'\":\n            return { type: 'single-quoted-scalar', offset, indent, source, end };\n        default:\n            return { type: 'scalar', offset, indent, source, end };\n    }\n}\n/**\n * Set the value of `token` to the given string `value`, overwriting any previous contents and type that it may have.\n *\n * Best efforts are made to retain any comments previously associated with the `token`,\n * though all contents within a collection's `items` will be overwritten.\n *\n * Values that represent an actual string but may be parsed as a different type should use a `type` other than `'PLAIN'`,\n * as this function does not support any schema operations and won't check for such conflicts.\n *\n * @param token Any token. If it does not include an `indent` value, the value will be stringified as if it were an implicit key.\n * @param value The string representation of the value, which will have its content properly indented.\n * @param context.afterKey In most cases, values after a key should have an additional level of indentation.\n * @param context.implicitKey Being within an implicit key may affect the resolved type of the token's value.\n * @param context.inFlow Being within a flow collection may affect the resolved type of the token's value.\n * @param context.type The preferred type of the scalar token. If undefined, the previous type of the `token` will be used, defaulting to `'PLAIN'`.\n */\nfunction setScalarValue(token, value, context = {}) {\n    let { afterKey = false, implicitKey = false, inFlow = false, type } = context;\n    let indent = 'indent' in token ? token.indent : null;\n    if (afterKey && typeof indent === 'number')\n        indent += 2;\n    if (!type)\n        switch (token.type) {\n            case 'single-quoted-scalar':\n                type = 'QUOTE_SINGLE';\n                break;\n            case 'double-quoted-scalar':\n                type = 'QUOTE_DOUBLE';\n                break;\n            case 'block-scalar': {\n                const header = token.props[0];\n                if (header.type !== 'block-scalar-header')\n                    throw new Error('Invalid block scalar header');\n                type = header.source[0] === '>' ? 'BLOCK_FOLDED' : 'BLOCK_LITERAL';\n                break;\n            }\n            default:\n                type = 'PLAIN';\n        }\n    const source = stringifyString.stringifyString({ type, value }, {\n        implicitKey: implicitKey || indent === null,\n        indent: indent !== null && indent > 0 ? ' '.repeat(indent) : '',\n        inFlow,\n        options: { blockQuote: true, lineWidth: -1 }\n    });\n    switch (source[0]) {\n        case '|':\n        case '>':\n            setBlockScalarValue(token, source);\n            break;\n        case '\"':\n            setFlowScalarValue(token, source, 'double-quoted-scalar');\n            break;\n        case \"'\":\n            setFlowScalarValue(token, source, 'single-quoted-scalar');\n            break;\n        default:\n            setFlowScalarValue(token, source, 'scalar');\n    }\n}\nfunction setBlockScalarValue(token, source) {\n    const he = source.indexOf('\\n');\n    const head = source.substring(0, he);\n    const body = source.substring(he + 1) + '\\n';\n    if (token.type === 'block-scalar') {\n        const header = token.props[0];\n        if (header.type !== 'block-scalar-header')\n            throw new Error('Invalid block scalar header');\n        header.source = head;\n        token.source = body;\n    }\n    else {\n        const { offset } = token;\n        const indent = 'indent' in token ? token.indent : -1;\n        const props = [\n            { type: 'block-scalar-header', offset, indent, source: head }\n        ];\n        if (!addEndtoBlockProps(props, 'end' in token ? token.end : undefined))\n            props.push({ type: 'newline', offset: -1, indent, source: '\\n' });\n        for (const key of Object.keys(token))\n            if (key !== 'type' && key !== 'offset')\n                delete token[key];\n        Object.assign(token, { type: 'block-scalar', indent, props, source: body });\n    }\n}\n/** @returns `true` if last token is a newline */\nfunction addEndtoBlockProps(props, end) {\n    if (end)\n        for (const st of end)\n            switch (st.type) {\n                case 'space':\n                case 'comment':\n                    props.push(st);\n                    break;\n                case 'newline':\n                    props.push(st);\n                    return true;\n            }\n    return false;\n}\nfunction setFlowScalarValue(token, source, type) {\n    switch (token.type) {\n        case 'scalar':\n        case 'double-quoted-scalar':\n        case 'single-quoted-scalar':\n            token.type = type;\n            token.source = source;\n            break;\n        case 'block-scalar': {\n            const end = token.props.slice(1);\n            let oa = source.length;\n            if (token.props[0].type === 'block-scalar-header')\n                oa -= token.props[0].source.length;\n            for (const tok of end)\n                tok.offset += oa;\n            delete token.props;\n            Object.assign(token, { type, source, end });\n            break;\n        }\n        case 'block-map':\n        case 'block-seq': {\n            const offset = token.offset + source.length;\n            const nl = { type: 'newline', offset, indent: token.indent, source: '\\n' };\n            delete token.items;\n            Object.assign(token, { type, source, end: [nl] });\n            break;\n        }\n        default: {\n            const indent = 'indent' in token ? token.indent : -1;\n            const end = 'end' in token && Array.isArray(token.end)\n                ? token.end.filter(st => st.type === 'space' ||\n                    st.type === 'comment' ||\n                    st.type === 'newline')\n                : [];\n            for (const key of Object.keys(token))\n                if (key !== 'type' && key !== 'offset')\n                    delete token[key];\n            Object.assign(token, { type, indent, source, end });\n        }\n    }\n}\n\nexports.createScalarToken = createScalarToken;\nexports.resolveAsScalar = resolveAsScalar;\nexports.setScalarValue = setScalarValue;\n","'use strict';\n\n/**\n * Stringify a CST document, token, or collection item\n *\n * Fair warning: This applies no validation whatsoever, and\n * simply concatenates the sources in their logical order.\n */\nconst stringify = (cst) => 'type' in cst ? stringifyToken(cst) : stringifyItem(cst);\nfunction stringifyToken(token) {\n    switch (token.type) {\n        case 'block-scalar': {\n            let res = '';\n            for (const tok of token.props)\n                res += stringifyToken(tok);\n            return res + token.source;\n        }\n        case 'block-map':\n        case 'block-seq': {\n            let res = '';\n            for (const item of token.items)\n                res += stringifyItem(item);\n            return res;\n        }\n        case 'flow-collection': {\n            let res = token.start.source;\n            for (const item of token.items)\n                res += stringifyItem(item);\n            for (const st of token.end)\n                res += st.source;\n            return res;\n        }\n        case 'document': {\n            let res = stringifyItem(token);\n            if (token.end)\n                for (const st of token.end)\n                    res += st.source;\n            return res;\n        }\n        default: {\n            let res = token.source;\n            if ('end' in token && token.end)\n                for (const st of token.end)\n                    res += st.source;\n            return res;\n        }\n    }\n}\nfunction stringifyItem({ start, key, sep, value }) {\n    let res = '';\n    for (const st of start)\n        res += st.source;\n    if (key)\n        res += stringifyToken(key);\n    if (sep)\n        for (const st of sep)\n            res += st.source;\n    if (value)\n        res += stringifyToken(value);\n    return res;\n}\n\nexports.stringify = stringify;\n","'use strict';\n\nconst BREAK = Symbol('break visit');\nconst SKIP = Symbol('skip children');\nconst REMOVE = Symbol('remove item');\n/**\n * Apply a visitor to a CST document or item.\n *\n * Walks through the tree (depth-first) starting from the root, calling a\n * `visitor` function with two arguments when entering each item:\n *   - `item`: The current item, which included the following members:\n *     - `start: SourceToken[]` – Source tokens before the key or value,\n *       possibly including its anchor or tag.\n *     - `key?: Token | null` – Set for pair values. May then be `null`, if\n *       the key before the `:` separator is empty.\n *     - `sep?: SourceToken[]` – Source tokens between the key and the value,\n *       which should include the `:` map value indicator if `value` is set.\n *     - `value?: Token` – The value of a sequence item, or of a map pair.\n *   - `path`: The steps from the root to the current node, as an array of\n *     `['key' | 'value', number]` tuples.\n *\n * The return value of the visitor may be used to control the traversal:\n *   - `undefined` (default): Do nothing and continue\n *   - `visit.SKIP`: Do not visit the children of this token, continue with\n *      next sibling\n *   - `visit.BREAK`: Terminate traversal completely\n *   - `visit.REMOVE`: Remove the current item, then continue with the next one\n *   - `number`: Set the index of the next step. This is useful especially if\n *     the index of the current token has changed.\n *   - `function`: Define the next visitor for this item. After the original\n *     visitor is called on item entry, next visitors are called after handling\n *     a non-empty `key` and when exiting the item.\n */\nfunction visit(cst, visitor) {\n    if ('type' in cst && cst.type === 'document')\n        cst = { start: cst.start, value: cst.value };\n    _visit(Object.freeze([]), cst, visitor);\n}\n// Without the `as symbol` casts, TS declares these in the `visit`\n// namespace using `var`, but then complains about that because\n// `unique symbol` must be `const`.\n/** Terminate visit traversal completely */\nvisit.BREAK = BREAK;\n/** Do not visit the children of the current item */\nvisit.SKIP = SKIP;\n/** Remove the current item */\nvisit.REMOVE = REMOVE;\n/** Find the item at `path` from `cst` as the root */\nvisit.itemAtPath = (cst, path) => {\n    let item = cst;\n    for (const [field, index] of path) {\n        const tok = item?.[field];\n        if (tok && 'items' in tok) {\n            item = tok.items[index];\n        }\n        else\n            return undefined;\n    }\n    return item;\n};\n/**\n * Get the immediate parent collection of the item at `path` from `cst` as the root.\n *\n * Throws an error if the collection is not found, which should never happen if the item itself exists.\n */\nvisit.parentCollection = (cst, path) => {\n    const parent = visit.itemAtPath(cst, path.slice(0, -1));\n    const field = path[path.length - 1][0];\n    const coll = parent?.[field];\n    if (coll && 'items' in coll)\n        return coll;\n    throw new Error('Parent collection not found');\n};\nfunction _visit(path, item, visitor) {\n    let ctrl = visitor(item, path);\n    if (typeof ctrl === 'symbol')\n        return ctrl;\n    for (const field of ['key', 'value']) {\n        const token = item[field];\n        if (token && 'items' in token) {\n            for (let i = 0; i < token.items.length; ++i) {\n                const ci = _visit(Object.freeze(path.concat([[field, i]])), token.items[i], visitor);\n                if (typeof ci === 'number')\n                    i = ci - 1;\n                else if (ci === BREAK)\n                    return BREAK;\n                else if (ci === REMOVE) {\n                    token.items.splice(i, 1);\n                    i -= 1;\n                }\n            }\n            if (typeof ctrl === 'function' && field === 'key')\n                ctrl = ctrl(item, path);\n        }\n    }\n    return typeof ctrl === 'function' ? ctrl(item, path) : ctrl;\n}\n\nexports.visit = visit;\n","'use strict';\n\nvar cstScalar = require('./cst-scalar.js');\nvar cstStringify = require('./cst-stringify.js');\nvar cstVisit = require('./cst-visit.js');\n\n/** The byte order mark */\nconst BOM = '\\u{FEFF}';\n/** Start of doc-mode */\nconst DOCUMENT = '\\x02'; // C0: Start of Text\n/** Unexpected end of flow-mode */\nconst FLOW_END = '\\x18'; // C0: Cancel\n/** Next token is a scalar value */\nconst SCALAR = '\\x1f'; // C0: Unit Separator\n/** @returns `true` if `token` is a flow or block collection */\nconst isCollection = (token) => !!token && 'items' in token;\n/** @returns `true` if `token` is a flow or block scalar; not an alias */\nconst isScalar = (token) => !!token &&\n    (token.type === 'scalar' ||\n        token.type === 'single-quoted-scalar' ||\n        token.type === 'double-quoted-scalar' ||\n        token.type === 'block-scalar');\n/* istanbul ignore next */\n/** Get a printable representation of a lexer token */\nfunction prettyToken(token) {\n    switch (token) {\n        case BOM:\n            return '<BOM>';\n        case DOCUMENT:\n            return '<DOC>';\n        case FLOW_END:\n            return '<FLOW_END>';\n        case SCALAR:\n            return '<SCALAR>';\n        default:\n            return JSON.stringify(token);\n    }\n}\n/** Identify the type of a lexer token. May return `null` for unknown tokens. */\nfunction tokenType(source) {\n    switch (source) {\n        case BOM:\n            return 'byte-order-mark';\n        case DOCUMENT:\n            return 'doc-mode';\n        case FLOW_END:\n            return 'flow-error-end';\n        case SCALAR:\n            return 'scalar';\n        case '---':\n            return 'doc-start';\n        case '...':\n            return 'doc-end';\n        case '':\n        case '\\n':\n        case '\\r\\n':\n            return 'newline';\n        case '-':\n            return 'seq-item-ind';\n        case '?':\n            return 'explicit-key-ind';\n        case ':':\n            return 'map-value-ind';\n        case '{':\n            return 'flow-map-start';\n        case '}':\n            return 'flow-map-end';\n        case '[':\n            return 'flow-seq-start';\n        case ']':\n            return 'flow-seq-end';\n        case ',':\n            return 'comma';\n    }\n    switch (source[0]) {\n        case ' ':\n        case '\\t':\n            return 'space';\n        case '#':\n            return 'comment';\n        case '%':\n            return 'directive-line';\n        case '*':\n            return 'alias';\n        case '&':\n            return 'anchor';\n        case '!':\n            return 'tag';\n        case \"'\":\n            return 'single-quoted-scalar';\n        case '\"':\n            return 'double-quoted-scalar';\n        case '|':\n        case '>':\n            return 'block-scalar-header';\n    }\n    return null;\n}\n\nexports.createScalarToken = cstScalar.createScalarToken;\nexports.resolveAsScalar = cstScalar.resolveAsScalar;\nexports.setScalarValue = cstScalar.setScalarValue;\nexports.stringify = cstStringify.stringify;\nexports.visit = cstVisit.visit;\nexports.BOM = BOM;\nexports.DOCUMENT = DOCUMENT;\nexports.FLOW_END = FLOW_END;\nexports.SCALAR = SCALAR;\nexports.isCollection = isCollection;\nexports.isScalar = isScalar;\nexports.prettyToken = prettyToken;\nexports.tokenType = tokenType;\n","'use strict';\n\nvar cst = require('./cst.js');\n\n/*\nSTART -> stream\n\nstream\n  directive -> line-end -> stream\n  indent + line-end -> stream\n  [else] -> line-start\n\nline-end\n  comment -> line-end\n  newline -> .\n  input-end -> END\n\nline-start\n  doc-start -> doc\n  doc-end -> stream\n  [else] -> indent -> block-start\n\nblock-start\n  seq-item-start -> block-start\n  explicit-key-start -> block-start\n  map-value-start -> block-start\n  [else] -> doc\n\ndoc\n  line-end -> line-start\n  spaces -> doc\n  anchor -> doc\n  tag -> doc\n  flow-start -> flow -> doc\n  flow-end -> error -> doc\n  seq-item-start -> error -> doc\n  explicit-key-start -> error -> doc\n  map-value-start -> doc\n  alias -> doc\n  quote-start -> quoted-scalar -> doc\n  block-scalar-header -> line-end -> block-scalar(min) -> line-start\n  [else] -> plain-scalar(false, min) -> doc\n\nflow\n  line-end -> flow\n  spaces -> flow\n  anchor -> flow\n  tag -> flow\n  flow-start -> flow -> flow\n  flow-end -> .\n  seq-item-start -> error -> flow\n  explicit-key-start -> flow\n  map-value-start -> flow\n  alias -> flow\n  quote-start -> quoted-scalar -> flow\n  comma -> flow\n  [else] -> plain-scalar(true, 0) -> flow\n\nquoted-scalar\n  quote-end -> .\n  [else] -> quoted-scalar\n\nblock-scalar(min)\n  newline + peek(indent < min) -> .\n  [else] -> block-scalar(min)\n\nplain-scalar(is-flow, min)\n  scalar-end(is-flow) -> .\n  peek(newline + (indent < min)) -> .\n  [else] -> plain-scalar(min)\n*/\nfunction isEmpty(ch) {\n    switch (ch) {\n        case undefined:\n        case ' ':\n        case '\\n':\n        case '\\r':\n        case '\\t':\n            return true;\n        default:\n            return false;\n    }\n}\nconst hexDigits = new Set('0123456789ABCDEFabcdef');\nconst tagChars = new Set(\"0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz-#;/?:@&=+$_.!~*'()\");\nconst flowIndicatorChars = new Set(',[]{}');\nconst invalidAnchorChars = new Set(' ,[]{}\\n\\r\\t');\nconst isNotAnchorChar = (ch) => !ch || invalidAnchorChars.has(ch);\n/**\n * Splits an input string into lexical tokens, i.e. smaller strings that are\n * easily identifiable by `tokens.tokenType()`.\n *\n * Lexing starts always in a \"stream\" context. Incomplete input may be buffered\n * until a complete token can be emitted.\n *\n * In addition to slices of the original input, the following control characters\n * may also be emitted:\n *\n * - `\\x02` (Start of Text): A document starts with the next token\n * - `\\x18` (Cancel): Unexpected end of flow-mode (indicates an error)\n * - `\\x1f` (Unit Separator): Next token is a scalar value\n * - `\\u{FEFF}` (Byte order mark): Emitted separately outside documents\n */\nclass Lexer {\n    constructor() {\n        /**\n         * Flag indicating whether the end of the current buffer marks the end of\n         * all input\n         */\n        this.atEnd = false;\n        /**\n         * Explicit indent set in block scalar header, as an offset from the current\n         * minimum indent, so e.g. set to 1 from a header `|2+`. Set to -1 if not\n         * explicitly set.\n         */\n        this.blockScalarIndent = -1;\n        /**\n         * Block scalars that include a + (keep) chomping indicator in their header\n         * include trailing empty lines, which are otherwise excluded from the\n         * scalar's contents.\n         */\n        this.blockScalarKeep = false;\n        /** Current input */\n        this.buffer = '';\n        /**\n         * Flag noting whether the map value indicator : can immediately follow this\n         * node within a flow context.\n         */\n        this.flowKey = false;\n        /** Count of surrounding flow collection levels. */\n        this.flowLevel = 0;\n        /**\n         * Minimum level of indentation required for next lines to be parsed as a\n         * part of the current scalar value.\n         */\n        this.indentNext = 0;\n        /** Indentation level of the current line. */\n        this.indentValue = 0;\n        /** Position of the next \\n character. */\n        this.lineEndPos = null;\n        /** Stores the state of the lexer if reaching the end of incpomplete input */\n        this.next = null;\n        /** A pointer to `buffer`; the current position of the lexer. */\n        this.pos = 0;\n    }\n    /**\n     * Generate YAML tokens from the `source` string. If `incomplete`,\n     * a part of the last line may be left as a buffer for the next call.\n     *\n     * @returns A generator of lexical tokens\n     */\n    *lex(source, incomplete = false) {\n        if (source) {\n            if (typeof source !== 'string')\n                throw TypeError('source is not a string');\n            this.buffer = this.buffer ? this.buffer + source : source;\n            this.lineEndPos = null;\n        }\n        this.atEnd = !incomplete;\n        let next = this.next ?? 'stream';\n        while (next && (incomplete || this.hasChars(1)))\n            next = yield* this.parseNext(next);\n    }\n    atLineEnd() {\n        let i = this.pos;\n        let ch = this.buffer[i];\n        while (ch === ' ' || ch === '\\t')\n            ch = this.buffer[++i];\n        if (!ch || ch === '#' || ch === '\\n')\n            return true;\n        if (ch === '\\r')\n            return this.buffer[i + 1] === '\\n';\n        return false;\n    }\n    charAt(n) {\n        return this.buffer[this.pos + n];\n    }\n    continueScalar(offset) {\n        let ch = this.buffer[offset];\n        if (this.indentNext > 0) {\n            let indent = 0;\n            while (ch === ' ')\n                ch = this.buffer[++indent + offset];\n            if (ch === '\\r') {\n                const next = this.buffer[indent + offset + 1];\n                if (next === '\\n' || (!next && !this.atEnd))\n                    return offset + indent + 1;\n            }\n            return ch === '\\n' || indent >= this.indentNext || (!ch && !this.atEnd)\n                ? offset + indent\n                : -1;\n        }\n        if (ch === '-' || ch === '.') {\n            const dt = this.buffer.substr(offset, 3);\n            if ((dt === '---' || dt === '...') && isEmpty(this.buffer[offset + 3]))\n                return -1;\n        }\n        return offset;\n    }\n    getLine() {\n        let end = this.lineEndPos;\n        if (typeof end !== 'number' || (end !== -1 && end < this.pos)) {\n            end = this.buffer.indexOf('\\n', this.pos);\n            this.lineEndPos = end;\n        }\n        if (end === -1)\n            return this.atEnd ? this.buffer.substring(this.pos) : null;\n        if (this.buffer[end - 1] === '\\r')\n            end -= 1;\n        return this.buffer.substring(this.pos, end);\n    }\n    hasChars(n) {\n        return this.pos + n <= this.buffer.length;\n    }\n    setNext(state) {\n        this.buffer = this.buffer.substring(this.pos);\n        this.pos = 0;\n        this.lineEndPos = null;\n        this.next = state;\n        return null;\n    }\n    peek(n) {\n        return this.buffer.substr(this.pos, n);\n    }\n    *parseNext(next) {\n        switch (next) {\n            case 'stream':\n                return yield* this.parseStream();\n            case 'line-start':\n                return yield* this.parseLineStart();\n            case 'block-start':\n                return yield* this.parseBlockStart();\n            case 'doc':\n                return yield* this.parseDocument();\n            case 'flow':\n                return yield* this.parseFlowCollection();\n            case 'quoted-scalar':\n                return yield* this.parseQuotedScalar();\n            case 'block-scalar':\n                return yield* this.parseBlockScalar();\n            case 'plain-scalar':\n                return yield* this.parsePlainScalar();\n        }\n    }\n    *parseStream() {\n        let line = this.getLine();\n        if (line === null)\n            return this.setNext('stream');\n        if (line[0] === cst.BOM) {\n            yield* this.pushCount(1);\n            line = line.substring(1);\n        }\n        if (line[0] === '%') {\n            let dirEnd = line.length;\n            let cs = line.indexOf('#');\n            while (cs !== -1) {\n                const ch = line[cs - 1];\n                if (ch === ' ' || ch === '\\t') {\n                    dirEnd = cs - 1;\n                    break;\n                }\n                else {\n                    cs = line.indexOf('#', cs + 1);\n                }\n            }\n            while (true) {\n                const ch = line[dirEnd - 1];\n                if (ch === ' ' || ch === '\\t')\n                    dirEnd -= 1;\n                else\n                    break;\n            }\n            const n = (yield* this.pushCount(dirEnd)) + (yield* this.pushSpaces(true));\n            yield* this.pushCount(line.length - n); // possible comment\n            this.pushNewline();\n            return 'stream';\n        }\n        if (this.atLineEnd()) {\n            const sp = yield* this.pushSpaces(true);\n            yield* this.pushCount(line.length - sp);\n            yield* this.pushNewline();\n            return 'stream';\n        }\n        yield cst.DOCUMENT;\n        return yield* this.parseLineStart();\n    }\n    *parseLineStart() {\n        const ch = this.charAt(0);\n        if (!ch && !this.atEnd)\n            return this.setNext('line-start');\n        if (ch === '-' || ch === '.') {\n            if (!this.atEnd && !this.hasChars(4))\n                return this.setNext('line-start');\n            const s = this.peek(3);\n            if ((s === '---' || s === '...') && isEmpty(this.charAt(3))) {\n                yield* this.pushCount(3);\n                this.indentValue = 0;\n                this.indentNext = 0;\n                return s === '---' ? 'doc' : 'stream';\n            }\n        }\n        this.indentValue = yield* this.pushSpaces(false);\n        if (this.indentNext > this.indentValue && !isEmpty(this.charAt(1)))\n            this.indentNext = this.indentValue;\n        return yield* this.parseBlockStart();\n    }\n    *parseBlockStart() {\n        const [ch0, ch1] = this.peek(2);\n        if (!ch1 && !this.atEnd)\n            return this.setNext('block-start');\n        if ((ch0 === '-' || ch0 === '?' || ch0 === ':') && isEmpty(ch1)) {\n            const n = (yield* this.pushCount(1)) + (yield* this.pushSpaces(true));\n            this.indentNext = this.indentValue + 1;\n            this.indentValue += n;\n            return 'block-start';\n        }\n        return 'doc';\n    }\n    *parseDocument() {\n        yield* this.pushSpaces(true);\n        const line = this.getLine();\n        if (line === null)\n            return this.setNext('doc');\n        let n = yield* this.pushIndicators();\n        switch (line[n]) {\n            case '#':\n                yield* this.pushCount(line.length - n);\n            // fallthrough\n            case undefined:\n                yield* this.pushNewline();\n                return yield* this.parseLineStart();\n            case '{':\n            case '[':\n                yield* this.pushCount(1);\n                this.flowKey = false;\n                this.flowLevel = 1;\n                return 'flow';\n            case '}':\n            case ']':\n                // this is an error\n                yield* this.pushCount(1);\n                return 'doc';\n            case '*':\n                yield* this.pushUntil(isNotAnchorChar);\n                return 'doc';\n            case '\"':\n            case \"'\":\n                return yield* this.parseQuotedScalar();\n            case '|':\n            case '>':\n                n += yield* this.parseBlockScalarHeader();\n                n += yield* this.pushSpaces(true);\n                yield* this.pushCount(line.length - n);\n                yield* this.pushNewline();\n                return yield* this.parseBlockScalar();\n            default:\n                return yield* this.parsePlainScalar();\n        }\n    }\n    *parseFlowCollection() {\n        let nl, sp;\n        let indent = -1;\n        do {\n            nl = yield* this.pushNewline();\n            if (nl > 0) {\n                sp = yield* this.pushSpaces(false);\n                this.indentValue = indent = sp;\n            }\n            else {\n                sp = 0;\n            }\n            sp += yield* this.pushSpaces(true);\n        } while (nl + sp > 0);\n        const line = this.getLine();\n        if (line === null)\n            return this.setNext('flow');\n        if ((indent !== -1 && indent < this.indentNext && line[0] !== '#') ||\n            (indent === 0 &&\n                (line.startsWith('---') || line.startsWith('...')) &&\n                isEmpty(line[3]))) {\n            // Allowing for the terminal ] or } at the same (rather than greater)\n            // indent level as the initial [ or { is technically invalid, but\n            // failing here would be surprising to users.\n            const atFlowEndMarker = indent === this.indentNext - 1 &&\n                this.flowLevel === 1 &&\n                (line[0] === ']' || line[0] === '}');\n            if (!atFlowEndMarker) {\n                // this is an error\n                this.flowLevel = 0;\n                yield cst.FLOW_END;\n                return yield* this.parseLineStart();\n            }\n        }\n        let n = 0;\n        while (line[n] === ',') {\n            n += yield* this.pushCount(1);\n            n += yield* this.pushSpaces(true);\n            this.flowKey = false;\n        }\n        n += yield* this.pushIndicators();\n        switch (line[n]) {\n            case undefined:\n                return 'flow';\n            case '#':\n                yield* this.pushCount(line.length - n);\n                return 'flow';\n            case '{':\n            case '[':\n                yield* this.pushCount(1);\n                this.flowKey = false;\n                this.flowLevel += 1;\n                return 'flow';\n            case '}':\n            case ']':\n                yield* this.pushCount(1);\n                this.flowKey = true;\n                this.flowLevel -= 1;\n                return this.flowLevel ? 'flow' : 'doc';\n            case '*':\n                yield* this.pushUntil(isNotAnchorChar);\n                return 'flow';\n            case '\"':\n            case \"'\":\n                this.flowKey = true;\n                return yield* this.parseQuotedScalar();\n            case ':': {\n                const next = this.charAt(1);\n                if (this.flowKey || isEmpty(next) || next === ',') {\n                    this.flowKey = false;\n                    yield* this.pushCount(1);\n                    yield* this.pushSpaces(true);\n                    return 'flow';\n                }\n            }\n            // fallthrough\n            default:\n                this.flowKey = false;\n                return yield* this.parsePlainScalar();\n        }\n    }\n    *parseQuotedScalar() {\n        const quote = this.charAt(0);\n        let end = this.buffer.indexOf(quote, this.pos + 1);\n        if (quote === \"'\") {\n            while (end !== -1 && this.buffer[end + 1] === \"'\")\n                end = this.buffer.indexOf(\"'\", end + 2);\n        }\n        else {\n            // double-quote\n            while (end !== -1) {\n                let n = 0;\n                while (this.buffer[end - 1 - n] === '\\\\')\n                    n += 1;\n                if (n % 2 === 0)\n                    break;\n                end = this.buffer.indexOf('\"', end + 1);\n            }\n        }\n        // Only looking for newlines within the quotes\n        const qb = this.buffer.substring(0, end);\n        let nl = qb.indexOf('\\n', this.pos);\n        if (nl !== -1) {\n            while (nl !== -1) {\n                const cs = this.continueScalar(nl + 1);\n                if (cs === -1)\n                    break;\n                nl = qb.indexOf('\\n', cs);\n            }\n            if (nl !== -1) {\n                // this is an error caused by an unexpected unindent\n                end = nl - (qb[nl - 1] === '\\r' ? 2 : 1);\n            }\n        }\n        if (end === -1) {\n            if (!this.atEnd)\n                return this.setNext('quoted-scalar');\n            end = this.buffer.length;\n        }\n        yield* this.pushToIndex(end + 1, false);\n        return this.flowLevel ? 'flow' : 'doc';\n    }\n    *parseBlockScalarHeader() {\n        this.blockScalarIndent = -1;\n        this.blockScalarKeep = false;\n        let i = this.pos;\n        while (true) {\n            const ch = this.buffer[++i];\n            if (ch === '+')\n                this.blockScalarKeep = true;\n            else if (ch > '0' && ch <= '9')\n                this.blockScalarIndent = Number(ch) - 1;\n            else if (ch !== '-')\n                break;\n        }\n        return yield* this.pushUntil(ch => isEmpty(ch) || ch === '#');\n    }\n    *parseBlockScalar() {\n        let nl = this.pos - 1; // may be -1 if this.pos === 0\n        let indent = 0;\n        let ch;\n        loop: for (let i = this.pos; (ch = this.buffer[i]); ++i) {\n            switch (ch) {\n                case ' ':\n                    indent += 1;\n                    break;\n                case '\\n':\n                    nl = i;\n                    indent = 0;\n                    break;\n                case '\\r': {\n                    const next = this.buffer[i + 1];\n                    if (!next && !this.atEnd)\n                        return this.setNext('block-scalar');\n                    if (next === '\\n')\n                        break;\n                } // fallthrough\n                default:\n                    break loop;\n            }\n        }\n        if (!ch && !this.atEnd)\n            return this.setNext('block-scalar');\n        if (indent >= this.indentNext) {\n            if (this.blockScalarIndent === -1)\n                this.indentNext = indent;\n            else {\n                this.indentNext =\n                    this.blockScalarIndent + (this.indentNext === 0 ? 1 : this.indentNext);\n            }\n            do {\n                const cs = this.continueScalar(nl + 1);\n                if (cs === -1)\n                    break;\n                nl = this.buffer.indexOf('\\n', cs);\n            } while (nl !== -1);\n            if (nl === -1) {\n                if (!this.atEnd)\n                    return this.setNext('block-scalar');\n                nl = this.buffer.length;\n            }\n        }\n        // Trailing insufficiently indented tabs are invalid.\n        // To catch that during parsing, we include them in the block scalar value.\n        let i = nl + 1;\n        ch = this.buffer[i];\n        while (ch === ' ')\n            ch = this.buffer[++i];\n        if (ch === '\\t') {\n            while (ch === '\\t' || ch === ' ' || ch === '\\r' || ch === '\\n')\n                ch = this.buffer[++i];\n            nl = i - 1;\n        }\n        else if (!this.blockScalarKeep) {\n            do {\n                let i = nl - 1;\n                let ch = this.buffer[i];\n                if (ch === '\\r')\n                    ch = this.buffer[--i];\n                const lastChar = i; // Drop the line if last char not more indented\n                while (ch === ' ')\n                    ch = this.buffer[--i];\n                if (ch === '\\n' && i >= this.pos && i + 1 + indent > lastChar)\n                    nl = i;\n                else\n                    break;\n            } while (true);\n        }\n        yield cst.SCALAR;\n        yield* this.pushToIndex(nl + 1, true);\n        return yield* this.parseLineStart();\n    }\n    *parsePlainScalar() {\n        const inFlow = this.flowLevel > 0;\n        let end = this.pos - 1;\n        let i = this.pos - 1;\n        let ch;\n        while ((ch = this.buffer[++i])) {\n            if (ch === ':') {\n                const next = this.buffer[i + 1];\n                if (isEmpty(next) || (inFlow && flowIndicatorChars.has(next)))\n                    break;\n                end = i;\n            }\n            else if (isEmpty(ch)) {\n                let next = this.buffer[i + 1];\n                if (ch === '\\r') {\n                    if (next === '\\n') {\n                        i += 1;\n                        ch = '\\n';\n                        next = this.buffer[i + 1];\n                    }\n                    else\n                        end = i;\n                }\n                if (next === '#' || (inFlow && flowIndicatorChars.has(next)))\n                    break;\n                if (ch === '\\n') {\n                    const cs = this.continueScalar(i + 1);\n                    if (cs === -1)\n                        break;\n                    i = Math.max(i, cs - 2); // to advance, but still account for ' #'\n                }\n            }\n            else {\n                if (inFlow && flowIndicatorChars.has(ch))\n                    break;\n                end = i;\n            }\n        }\n        if (!ch && !this.atEnd)\n            return this.setNext('plain-scalar');\n        yield cst.SCALAR;\n        yield* this.pushToIndex(end + 1, true);\n        return inFlow ? 'flow' : 'doc';\n    }\n    *pushCount(n) {\n        if (n > 0) {\n            yield this.buffer.substr(this.pos, n);\n            this.pos += n;\n            return n;\n        }\n        return 0;\n    }\n    *pushToIndex(i, allowEmpty) {\n        const s = this.buffer.slice(this.pos, i);\n        if (s) {\n            yield s;\n            this.pos += s.length;\n            return s.length;\n        }\n        else if (allowEmpty)\n            yield '';\n        return 0;\n    }\n    *pushIndicators() {\n        let n = 0;\n        loop: while (true) {\n            switch (this.charAt(0)) {\n                case '!':\n                    n += yield* this.pushTag();\n                    n += yield* this.pushSpaces(true);\n                    continue loop;\n                case '&':\n                    n += yield* this.pushUntil(isNotAnchorChar);\n                    n += yield* this.pushSpaces(true);\n                    continue loop;\n                case '-': // this is an error\n                case '?': // this is an error outside flow collections\n                case ':': {\n                    const inFlow = this.flowLevel > 0;\n                    const ch1 = this.charAt(1);\n                    if (isEmpty(ch1) || (inFlow && flowIndicatorChars.has(ch1))) {\n                        if (!inFlow)\n                            this.indentNext = this.indentValue + 1;\n                        else if (this.flowKey)\n                            this.flowKey = false;\n                        n += yield* this.pushCount(1);\n                        n += yield* this.pushSpaces(true);\n                        continue loop;\n                    }\n                }\n            }\n            break loop;\n        }\n        return n;\n    }\n    *pushTag() {\n        if (this.charAt(1) === '<') {\n            let i = this.pos + 2;\n            let ch = this.buffer[i];\n            while (!isEmpty(ch) && ch !== '>')\n                ch = this.buffer[++i];\n            return yield* this.pushToIndex(ch === '>' ? i + 1 : i, false);\n        }\n        else {\n            let i = this.pos + 1;\n            let ch = this.buffer[i];\n            while (ch) {\n                if (tagChars.has(ch))\n                    ch = this.buffer[++i];\n                else if (ch === '%' &&\n                    hexDigits.has(this.buffer[i + 1]) &&\n                    hexDigits.has(this.buffer[i + 2])) {\n                    ch = this.buffer[(i += 3)];\n                }\n                else\n                    break;\n            }\n            return yield* this.pushToIndex(i, false);\n        }\n    }\n    *pushNewline() {\n        const ch = this.buffer[this.pos];\n        if (ch === '\\n')\n            return yield* this.pushCount(1);\n        else if (ch === '\\r' && this.charAt(1) === '\\n')\n            return yield* this.pushCount(2);\n        else\n            return 0;\n    }\n    *pushSpaces(allowTabs) {\n        let i = this.pos - 1;\n        let ch;\n        do {\n            ch = this.buffer[++i];\n        } while (ch === ' ' || (allowTabs && ch === '\\t'));\n        const n = i - this.pos;\n        if (n > 0) {\n            yield this.buffer.substr(this.pos, n);\n            this.pos = i;\n        }\n        return n;\n    }\n    *pushUntil(test) {\n        let i = this.pos;\n        let ch = this.buffer[i];\n        while (!test(ch))\n            ch = this.buffer[++i];\n        return yield* this.pushToIndex(i, false);\n    }\n}\n\nexports.Lexer = Lexer;\n","'use strict';\n\n/**\n * Tracks newlines during parsing in order to provide an efficient API for\n * determining the one-indexed `{ line, col }` position for any offset\n * within the input.\n */\nclass LineCounter {\n    constructor() {\n        this.lineStarts = [];\n        /**\n         * Should be called in ascending order. Otherwise, call\n         * `lineCounter.lineStarts.sort()` before calling `linePos()`.\n         */\n        this.addNewLine = (offset) => this.lineStarts.push(offset);\n        /**\n         * Performs a binary search and returns the 1-indexed { line, col }\n         * position of `offset`. If `line === 0`, `addNewLine` has never been\n         * called or `offset` is before the first known newline.\n         */\n        this.linePos = (offset) => {\n            let low = 0;\n            let high = this.lineStarts.length;\n            while (low < high) {\n                const mid = (low + high) >> 1; // Math.floor((low + high) / 2)\n                if (this.lineStarts[mid] < offset)\n                    low = mid + 1;\n                else\n                    high = mid;\n            }\n            if (this.lineStarts[low] === offset)\n                return { line: low + 1, col: 1 };\n            if (low === 0)\n                return { line: 0, col: offset };\n            const start = this.lineStarts[low - 1];\n            return { line: low, col: offset - start + 1 };\n        };\n    }\n}\n\nexports.LineCounter = LineCounter;\n","'use strict';\n\nvar node_process = require('process');\nvar cst = require('./cst.js');\nvar lexer = require('./lexer.js');\n\nfunction includesToken(list, type) {\n    for (let i = 0; i < list.length; ++i)\n        if (list[i].type === type)\n            return true;\n    return false;\n}\nfunction findNonEmptyIndex(list) {\n    for (let i = 0; i < list.length; ++i) {\n        switch (list[i].type) {\n            case 'space':\n            case 'comment':\n            case 'newline':\n                break;\n            default:\n                return i;\n        }\n    }\n    return -1;\n}\nfunction isFlowToken(token) {\n    switch (token?.type) {\n        case 'alias':\n        case 'scalar':\n        case 'single-quoted-scalar':\n        case 'double-quoted-scalar':\n        case 'flow-collection':\n            return true;\n        default:\n            return false;\n    }\n}\nfunction getPrevProps(parent) {\n    switch (parent.type) {\n        case 'document':\n            return parent.start;\n        case 'block-map': {\n            const it = parent.items[parent.items.length - 1];\n            return it.sep ?? it.start;\n        }\n        case 'block-seq':\n            return parent.items[parent.items.length - 1].start;\n        /* istanbul ignore next should not happen */\n        default:\n            return [];\n    }\n}\n/** Note: May modify input array */\nfunction getFirstKeyStartProps(prev) {\n    if (prev.length === 0)\n        return [];\n    let i = prev.length;\n    loop: while (--i >= 0) {\n        switch (prev[i].type) {\n            case 'doc-start':\n            case 'explicit-key-ind':\n            case 'map-value-ind':\n            case 'seq-item-ind':\n            case 'newline':\n                break loop;\n        }\n    }\n    while (prev[++i]?.type === 'space') {\n        /* loop */\n    }\n    return prev.splice(i, prev.length);\n}\nfunction arrayPushArray(target, source) {\n    // May exhaust call stack with large `source` array\n    if (source.length < 1e5)\n        Array.prototype.push.apply(target, source);\n    else\n        for (let i = 0; i < source.length; ++i)\n            target.push(source[i]);\n}\nfunction fixFlowSeqItems(fc) {\n    if (fc.start.type === 'flow-seq-start') {\n        for (const it of fc.items) {\n            if (it.sep &&\n                !it.value &&\n                !includesToken(it.start, 'explicit-key-ind') &&\n                !includesToken(it.sep, 'map-value-ind')) {\n                if (it.key)\n                    it.value = it.key;\n                delete it.key;\n                if (isFlowToken(it.value)) {\n                    if (it.value.end)\n                        arrayPushArray(it.value.end, it.sep);\n                    else\n                        it.value.end = it.sep;\n                }\n                else\n                    arrayPushArray(it.start, it.sep);\n                delete it.sep;\n            }\n        }\n    }\n}\n/**\n * A YAML concrete syntax tree (CST) parser\n *\n * ```ts\n * const src: string = ...\n * for (const token of new Parser().parse(src)) {\n *   // token: Token\n * }\n * ```\n *\n * To use the parser with a user-provided lexer:\n *\n * ```ts\n * function* parse(source: string, lexer: Lexer) {\n *   const parser = new Parser()\n *   for (const lexeme of lexer.lex(source))\n *     yield* parser.next(lexeme)\n *   yield* parser.end()\n * }\n *\n * const src: string = ...\n * const lexer = new Lexer()\n * for (const token of parse(src, lexer)) {\n *   // token: Token\n * }\n * ```\n */\nclass Parser {\n    /**\n     * @param onNewLine - If defined, called separately with the start position of\n     *   each new line (in `parse()`, including the start of input).\n     */\n    constructor(onNewLine) {\n        /** If true, space and sequence indicators count as indentation */\n        this.atNewLine = true;\n        /** If true, next token is a scalar value */\n        this.atScalar = false;\n        /** Current indentation level */\n        this.indent = 0;\n        /** Current offset since the start of parsing */\n        this.offset = 0;\n        /** On the same line with a block map key */\n        this.onKeyLine = false;\n        /** Top indicates the node that's currently being built */\n        this.stack = [];\n        /** The source of the current token, set in parse() */\n        this.source = '';\n        /** The type of the current token, set in parse() */\n        this.type = '';\n        // Must be defined after `next()`\n        this.lexer = new lexer.Lexer();\n        this.onNewLine = onNewLine;\n    }\n    /**\n     * Parse `source` as a YAML stream.\n     * If `incomplete`, a part of the last line may be left as a buffer for the next call.\n     *\n     * Errors are not thrown, but yielded as `{ type: 'error', message }` tokens.\n     *\n     * @returns A generator of tokens representing each directive, document, and other structure.\n     */\n    *parse(source, incomplete = false) {\n        if (this.onNewLine && this.offset === 0)\n            this.onNewLine(0);\n        for (const lexeme of this.lexer.lex(source, incomplete))\n            yield* this.next(lexeme);\n        if (!incomplete)\n            yield* this.end();\n    }\n    /**\n     * Advance the parser by the `source` of one lexical token.\n     */\n    *next(source) {\n        this.source = source;\n        if (node_process.env.LOG_TOKENS)\n            console.log('|', cst.prettyToken(source));\n        if (this.atScalar) {\n            this.atScalar = false;\n            yield* this.step();\n            this.offset += source.length;\n            return;\n        }\n        const type = cst.tokenType(source);\n        if (!type) {\n            const message = `Not a YAML token: ${source}`;\n            yield* this.pop({ type: 'error', offset: this.offset, message, source });\n            this.offset += source.length;\n        }\n        else if (type === 'scalar') {\n            this.atNewLine = false;\n            this.atScalar = true;\n            this.type = 'scalar';\n        }\n        else {\n            this.type = type;\n            yield* this.step();\n            switch (type) {\n                case 'newline':\n                    this.atNewLine = true;\n                    this.indent = 0;\n                    if (this.onNewLine)\n                        this.onNewLine(this.offset + source.length);\n                    break;\n                case 'space':\n                    if (this.atNewLine && source[0] === ' ')\n                        this.indent += source.length;\n                    break;\n                case 'explicit-key-ind':\n                case 'map-value-ind':\n                case 'seq-item-ind':\n                    if (this.atNewLine)\n                        this.indent += source.length;\n                    break;\n                case 'doc-mode':\n                case 'flow-error-end':\n                    return;\n                default:\n                    this.atNewLine = false;\n            }\n            this.offset += source.length;\n        }\n    }\n    /** Call at end of input to push out any remaining constructions */\n    *end() {\n        while (this.stack.length > 0)\n            yield* this.pop();\n    }\n    get sourceToken() {\n        const st = {\n            type: this.type,\n            offset: this.offset,\n            indent: this.indent,\n            source: this.source\n        };\n        return st;\n    }\n    *step() {\n        const top = this.peek(1);\n        if (this.type === 'doc-end' && top?.type !== 'doc-end') {\n            while (this.stack.length > 0)\n                yield* this.pop();\n            this.stack.push({\n                type: 'doc-end',\n                offset: this.offset,\n                source: this.source\n            });\n            return;\n        }\n        if (!top)\n            return yield* this.stream();\n        switch (top.type) {\n            case 'document':\n                return yield* this.document(top);\n            case 'alias':\n            case 'scalar':\n            case 'single-quoted-scalar':\n            case 'double-quoted-scalar':\n                return yield* this.scalar(top);\n            case 'block-scalar':\n                return yield* this.blockScalar(top);\n            case 'block-map':\n                return yield* this.blockMap(top);\n            case 'block-seq':\n                return yield* this.blockSequence(top);\n            case 'flow-collection':\n                return yield* this.flowCollection(top);\n            case 'doc-end':\n                return yield* this.documentEnd(top);\n        }\n        /* istanbul ignore next should not happen */\n        yield* this.pop();\n    }\n    peek(n) {\n        return this.stack[this.stack.length - n];\n    }\n    *pop(error) {\n        const token = error ?? this.stack.pop();\n        /* istanbul ignore if should not happen */\n        if (!token) {\n            const message = 'Tried to pop an empty stack';\n            yield { type: 'error', offset: this.offset, source: '', message };\n        }\n        else if (this.stack.length === 0) {\n            yield token;\n        }\n        else {\n            const top = this.peek(1);\n            if (token.type === 'block-scalar') {\n                // Block scalars use their parent rather than header indent\n                token.indent = 'indent' in top ? top.indent : 0;\n            }\n            else if (token.type === 'flow-collection' && top.type === 'document') {\n                // Ignore all indent for top-level flow collections\n                token.indent = 0;\n            }\n            if (token.type === 'flow-collection')\n                fixFlowSeqItems(token);\n            switch (top.type) {\n                case 'document':\n                    top.value = token;\n                    break;\n                case 'block-scalar':\n                    top.props.push(token); // error\n                    break;\n                case 'block-map': {\n                    const it = top.items[top.items.length - 1];\n                    if (it.value) {\n                        top.items.push({ start: [], key: token, sep: [] });\n                        this.onKeyLine = true;\n                        return;\n                    }\n                    else if (it.sep) {\n                        it.value = token;\n                    }\n                    else {\n                        Object.assign(it, { key: token, sep: [] });\n                        this.onKeyLine = !it.explicitKey;\n                        return;\n                    }\n                    break;\n                }\n                case 'block-seq': {\n                    const it = top.items[top.items.length - 1];\n                    if (it.value)\n                        top.items.push({ start: [], value: token });\n                    else\n                        it.value = token;\n                    break;\n                }\n                case 'flow-collection': {\n                    const it = top.items[top.items.length - 1];\n                    if (!it || it.value)\n                        top.items.push({ start: [], key: token, sep: [] });\n                    else if (it.sep)\n                        it.value = token;\n                    else\n                        Object.assign(it, { key: token, sep: [] });\n                    return;\n                }\n                /* istanbul ignore next should not happen */\n                default:\n                    yield* this.pop();\n                    yield* this.pop(token);\n            }\n            if ((top.type === 'document' ||\n                top.type === 'block-map' ||\n                top.type === 'block-seq') &&\n                (token.type === 'block-map' || token.type === 'block-seq')) {\n                const last = token.items[token.items.length - 1];\n                if (last &&\n                    !last.sep &&\n                    !last.value &&\n                    last.start.length > 0 &&\n                    findNonEmptyIndex(last.start) === -1 &&\n                    (token.indent === 0 ||\n                        last.start.every(st => st.type !== 'comment' || st.indent < token.indent))) {\n                    if (top.type === 'document')\n                        top.end = last.start;\n                    else\n                        top.items.push({ start: last.start });\n                    token.items.splice(-1, 1);\n                }\n            }\n        }\n    }\n    *stream() {\n        switch (this.type) {\n            case 'directive-line':\n                yield { type: 'directive', offset: this.offset, source: this.source };\n                return;\n            case 'byte-order-mark':\n            case 'space':\n            case 'comment':\n            case 'newline':\n                yield this.sourceToken;\n                return;\n            case 'doc-mode':\n            case 'doc-start': {\n                const doc = {\n                    type: 'document',\n                    offset: this.offset,\n                    start: []\n                };\n                if (this.type === 'doc-start')\n                    doc.start.push(this.sourceToken);\n                this.stack.push(doc);\n                return;\n            }\n        }\n        yield {\n            type: 'error',\n            offset: this.offset,\n            message: `Unexpected ${this.type} token in YAML stream`,\n            source: this.source\n        };\n    }\n    *document(doc) {\n        if (doc.value)\n            return yield* this.lineEnd(doc);\n        switch (this.type) {\n            case 'doc-start': {\n                if (findNonEmptyIndex(doc.start) !== -1) {\n                    yield* this.pop();\n                    yield* this.step();\n                }\n                else\n                    doc.start.push(this.sourceToken);\n                return;\n            }\n            case 'anchor':\n            case 'tag':\n            case 'space':\n            case 'comment':\n            case 'newline':\n                doc.start.push(this.sourceToken);\n                return;\n        }\n        const bv = this.startBlockValue(doc);\n        if (bv)\n            this.stack.push(bv);\n        else {\n            yield {\n                type: 'error',\n                offset: this.offset,\n                message: `Unexpected ${this.type} token in YAML document`,\n                source: this.source\n            };\n        }\n    }\n    *scalar(scalar) {\n        if (this.type === 'map-value-ind') {\n            const prev = getPrevProps(this.peek(2));\n            const start = getFirstKeyStartProps(prev);\n            let sep;\n            if (scalar.end) {\n                sep = scalar.end;\n                sep.push(this.sourceToken);\n                delete scalar.end;\n            }\n            else\n                sep = [this.sourceToken];\n            const map = {\n                type: 'block-map',\n                offset: scalar.offset,\n                indent: scalar.indent,\n                items: [{ start, key: scalar, sep }]\n            };\n            this.onKeyLine = true;\n            this.stack[this.stack.length - 1] = map;\n        }\n        else\n            yield* this.lineEnd(scalar);\n    }\n    *blockScalar(scalar) {\n        switch (this.type) {\n            case 'space':\n            case 'comment':\n            case 'newline':\n                scalar.props.push(this.sourceToken);\n                return;\n            case 'scalar':\n                scalar.source = this.source;\n                // block-scalar source includes trailing newline\n                this.atNewLine = true;\n                this.indent = 0;\n                if (this.onNewLine) {\n                    let nl = this.source.indexOf('\\n') + 1;\n                    while (nl !== 0) {\n                        this.onNewLine(this.offset + nl);\n                        nl = this.source.indexOf('\\n', nl) + 1;\n                    }\n                }\n                yield* this.pop();\n                break;\n            /* istanbul ignore next should not happen */\n            default:\n                yield* this.pop();\n                yield* this.step();\n        }\n    }\n    *blockMap(map) {\n        const it = map.items[map.items.length - 1];\n        // it.sep is true-ish if pair already has key or : separator\n        switch (this.type) {\n            case 'newline':\n                this.onKeyLine = false;\n                if (it.value) {\n                    const end = 'end' in it.value ? it.value.end : undefined;\n                    const last = Array.isArray(end) ? end[end.length - 1] : undefined;\n                    if (last?.type === 'comment')\n                        end?.push(this.sourceToken);\n                    else\n                        map.items.push({ start: [this.sourceToken] });\n                }\n                else if (it.sep) {\n                    it.sep.push(this.sourceToken);\n                }\n                else {\n                    it.start.push(this.sourceToken);\n                }\n                return;\n            case 'space':\n            case 'comment':\n                if (it.value) {\n                    map.items.push({ start: [this.sourceToken] });\n                }\n                else if (it.sep) {\n                    it.sep.push(this.sourceToken);\n                }\n                else {\n                    if (this.atIndentedComment(it.start, map.indent)) {\n                        const prev = map.items[map.items.length - 2];\n                        const end = prev?.value?.end;\n                        if (Array.isArray(end)) {\n                            arrayPushArray(end, it.start);\n                            end.push(this.sourceToken);\n                            map.items.pop();\n                            return;\n                        }\n                    }\n                    it.start.push(this.sourceToken);\n                }\n                return;\n        }\n        if (this.indent >= map.indent) {\n            const atMapIndent = !this.onKeyLine && this.indent === map.indent;\n            const atNextItem = atMapIndent &&\n                (it.sep || it.explicitKey) &&\n                this.type !== 'seq-item-ind';\n            // For empty nodes, assign newline-separated not indented empty tokens to following node\n            let start = [];\n            if (atNextItem && it.sep && !it.value) {\n                const nl = [];\n                for (let i = 0; i < it.sep.length; ++i) {\n                    const st = it.sep[i];\n                    switch (st.type) {\n                        case 'newline':\n                            nl.push(i);\n                            break;\n                        case 'space':\n                            break;\n                        case 'comment':\n                            if (st.indent > map.indent)\n                                nl.length = 0;\n                            break;\n                        default:\n                            nl.length = 0;\n                    }\n                }\n                if (nl.length >= 2)\n                    start = it.sep.splice(nl[1]);\n            }\n            switch (this.type) {\n                case 'anchor':\n                case 'tag':\n                    if (atNextItem || it.value) {\n                        start.push(this.sourceToken);\n                        map.items.push({ start });\n                        this.onKeyLine = true;\n                    }\n                    else if (it.sep) {\n                        it.sep.push(this.sourceToken);\n                    }\n                    else {\n                        it.start.push(this.sourceToken);\n                    }\n                    return;\n                case 'explicit-key-ind':\n                    if (!it.sep && !it.explicitKey) {\n                        it.start.push(this.sourceToken);\n                        it.explicitKey = true;\n                    }\n                    else if (atNextItem || it.value) {\n                        start.push(this.sourceToken);\n                        map.items.push({ start, explicitKey: true });\n                    }\n                    else {\n                        this.stack.push({\n                            type: 'block-map',\n                            offset: this.offset,\n                            indent: this.indent,\n                            items: [{ start: [this.sourceToken], explicitKey: true }]\n                        });\n                    }\n                    this.onKeyLine = true;\n                    return;\n                case 'map-value-ind':\n                    if (it.explicitKey) {\n                        if (!it.sep) {\n                            if (includesToken(it.start, 'newline')) {\n                                Object.assign(it, { key: null, sep: [this.sourceToken] });\n                            }\n                            else {\n                                const start = getFirstKeyStartProps(it.start);\n                                this.stack.push({\n                                    type: 'block-map',\n                                    offset: this.offset,\n                                    indent: this.indent,\n                                    items: [{ start, key: null, sep: [this.sourceToken] }]\n                                });\n                            }\n                        }\n                        else if (it.value) {\n                            map.items.push({ start: [], key: null, sep: [this.sourceToken] });\n                        }\n                        else if (includesToken(it.sep, 'map-value-ind')) {\n                            this.stack.push({\n                                type: 'block-map',\n                                offset: this.offset,\n                                indent: this.indent,\n                                items: [{ start, key: null, sep: [this.sourceToken] }]\n                            });\n                        }\n                        else if (isFlowToken(it.key) &&\n                            !includesToken(it.sep, 'newline')) {\n                            const start = getFirstKeyStartProps(it.start);\n                            const key = it.key;\n                            const sep = it.sep;\n                            sep.push(this.sourceToken);\n                            // @ts-expect-error type guard is wrong here\n                            delete it.key;\n                            // @ts-expect-error type guard is wrong here\n                            delete it.sep;\n                            this.stack.push({\n                                type: 'block-map',\n                                offset: this.offset,\n                                indent: this.indent,\n                                items: [{ start, key, sep }]\n                            });\n                        }\n                        else if (start.length > 0) {\n                            // Not actually at next item\n                            it.sep = it.sep.concat(start, this.sourceToken);\n                        }\n                        else {\n                            it.sep.push(this.sourceToken);\n                        }\n                    }\n                    else {\n                        if (!it.sep) {\n                            Object.assign(it, { key: null, sep: [this.sourceToken] });\n                        }\n                        else if (it.value || atNextItem) {\n                            map.items.push({ start, key: null, sep: [this.sourceToken] });\n                        }\n                        else if (includesToken(it.sep, 'map-value-ind')) {\n                            this.stack.push({\n                                type: 'block-map',\n                                offset: this.offset,\n                                indent: this.indent,\n                                items: [{ start: [], key: null, sep: [this.sourceToken] }]\n                            });\n                        }\n                        else {\n                            it.sep.push(this.sourceToken);\n                        }\n                    }\n                    this.onKeyLine = true;\n                    return;\n                case 'alias':\n                case 'scalar':\n                case 'single-quoted-scalar':\n                case 'double-quoted-scalar': {\n                    const fs = this.flowScalar(this.type);\n                    if (atNextItem || it.value) {\n                        map.items.push({ start, key: fs, sep: [] });\n                        this.onKeyLine = true;\n                    }\n                    else if (it.sep) {\n                        this.stack.push(fs);\n                    }\n                    else {\n                        Object.assign(it, { key: fs, sep: [] });\n                        this.onKeyLine = true;\n                    }\n                    return;\n                }\n                default: {\n                    const bv = this.startBlockValue(map);\n                    if (bv) {\n                        if (bv.type === 'block-seq') {\n                            if (!it.explicitKey &&\n                                it.sep &&\n                                !includesToken(it.sep, 'newline')) {\n                                yield* this.pop({\n                                    type: 'error',\n                                    offset: this.offset,\n                                    message: 'Unexpected block-seq-ind on same line with key',\n                                    source: this.source\n                                });\n                                return;\n                            }\n                        }\n                        else if (atMapIndent) {\n                            map.items.push({ start });\n                        }\n                        this.stack.push(bv);\n                        return;\n                    }\n                }\n            }\n        }\n        yield* this.pop();\n        yield* this.step();\n    }\n    *blockSequence(seq) {\n        const it = seq.items[seq.items.length - 1];\n        switch (this.type) {\n            case 'newline':\n                if (it.value) {\n                    const end = 'end' in it.value ? it.value.end : undefined;\n                    const last = Array.isArray(end) ? end[end.length - 1] : undefined;\n                    if (last?.type === 'comment')\n                        end?.push(this.sourceToken);\n                    else\n                        seq.items.push({ start: [this.sourceToken] });\n                }\n                else\n                    it.start.push(this.sourceToken);\n                return;\n            case 'space':\n            case 'comment':\n                if (it.value)\n                    seq.items.push({ start: [this.sourceToken] });\n                else {\n                    if (this.atIndentedComment(it.start, seq.indent)) {\n                        const prev = seq.items[seq.items.length - 2];\n                        const end = prev?.value?.end;\n                        if (Array.isArray(end)) {\n                            arrayPushArray(end, it.start);\n                            end.push(this.sourceToken);\n                            seq.items.pop();\n                            return;\n                        }\n                    }\n                    it.start.push(this.sourceToken);\n                }\n                return;\n            case 'anchor':\n            case 'tag':\n                if (it.value || this.indent <= seq.indent)\n                    break;\n                it.start.push(this.sourceToken);\n                return;\n            case 'seq-item-ind':\n                if (this.indent !== seq.indent)\n                    break;\n                if (it.value || includesToken(it.start, 'seq-item-ind'))\n                    seq.items.push({ start: [this.sourceToken] });\n                else\n                    it.start.push(this.sourceToken);\n                return;\n        }\n        if (this.indent > seq.indent) {\n            const bv = this.startBlockValue(seq);\n            if (bv) {\n                this.stack.push(bv);\n                return;\n            }\n        }\n        yield* this.pop();\n        yield* this.step();\n    }\n    *flowCollection(fc) {\n        const it = fc.items[fc.items.length - 1];\n        if (this.type === 'flow-error-end') {\n            let top;\n            do {\n                yield* this.pop();\n                top = this.peek(1);\n            } while (top?.type === 'flow-collection');\n        }\n        else if (fc.end.length === 0) {\n            switch (this.type) {\n                case 'comma':\n                case 'explicit-key-ind':\n                    if (!it || it.sep)\n                        fc.items.push({ start: [this.sourceToken] });\n                    else\n                        it.start.push(this.sourceToken);\n                    return;\n                case 'map-value-ind':\n                    if (!it || it.value)\n                        fc.items.push({ start: [], key: null, sep: [this.sourceToken] });\n                    else if (it.sep)\n                        it.sep.push(this.sourceToken);\n                    else\n                        Object.assign(it, { key: null, sep: [this.sourceToken] });\n                    return;\n                case 'space':\n                case 'comment':\n                case 'newline':\n                case 'anchor':\n                case 'tag':\n                    if (!it || it.value)\n                        fc.items.push({ start: [this.sourceToken] });\n                    else if (it.sep)\n                        it.sep.push(this.sourceToken);\n                    else\n                        it.start.push(this.sourceToken);\n                    return;\n                case 'alias':\n                case 'scalar':\n                case 'single-quoted-scalar':\n                case 'double-quoted-scalar': {\n                    const fs = this.flowScalar(this.type);\n                    if (!it || it.value)\n                        fc.items.push({ start: [], key: fs, sep: [] });\n                    else if (it.sep)\n                        this.stack.push(fs);\n                    else\n                        Object.assign(it, { key: fs, sep: [] });\n                    return;\n                }\n                case 'flow-map-end':\n                case 'flow-seq-end':\n                    fc.end.push(this.sourceToken);\n                    return;\n            }\n            const bv = this.startBlockValue(fc);\n            /* istanbul ignore else should not happen */\n            if (bv)\n                this.stack.push(bv);\n            else {\n                yield* this.pop();\n                yield* this.step();\n            }\n        }\n        else {\n            const parent = this.peek(2);\n            if (parent.type === 'block-map' &&\n                ((this.type === 'map-value-ind' && parent.indent === fc.indent) ||\n                    (this.type === 'newline' &&\n                        !parent.items[parent.items.length - 1].sep))) {\n                yield* this.pop();\n                yield* this.step();\n            }\n            else if (this.type === 'map-value-ind' &&\n                parent.type !== 'flow-collection') {\n                const prev = getPrevProps(parent);\n                const start = getFirstKeyStartProps(prev);\n                fixFlowSeqItems(fc);\n                const sep = fc.end.splice(1, fc.end.length);\n                sep.push(this.sourceToken);\n                const map = {\n                    type: 'block-map',\n                    offset: fc.offset,\n                    indent: fc.indent,\n                    items: [{ start, key: fc, sep }]\n                };\n                this.onKeyLine = true;\n                this.stack[this.stack.length - 1] = map;\n            }\n            else {\n                yield* this.lineEnd(fc);\n            }\n        }\n    }\n    flowScalar(type) {\n        if (this.onNewLine) {\n            let nl = this.source.indexOf('\\n') + 1;\n            while (nl !== 0) {\n                this.onNewLine(this.offset + nl);\n                nl = this.source.indexOf('\\n', nl) + 1;\n            }\n        }\n        return {\n            type,\n            offset: this.offset,\n            indent: this.indent,\n            source: this.source\n        };\n    }\n    startBlockValue(parent) {\n        switch (this.type) {\n            case 'alias':\n            case 'scalar':\n            case 'single-quoted-scalar':\n            case 'double-quoted-scalar':\n                return this.flowScalar(this.type);\n            case 'block-scalar-header':\n                return {\n                    type: 'block-scalar',\n                    offset: this.offset,\n                    indent: this.indent,\n                    props: [this.sourceToken],\n                    source: ''\n                };\n            case 'flow-map-start':\n            case 'flow-seq-start':\n                return {\n                    type: 'flow-collection',\n                    offset: this.offset,\n                    indent: this.indent,\n                    start: this.sourceToken,\n                    items: [],\n                    end: []\n                };\n            case 'seq-item-ind':\n                return {\n                    type: 'block-seq',\n                    offset: this.offset,\n                    indent: this.indent,\n                    items: [{ start: [this.sourceToken] }]\n                };\n            case 'explicit-key-ind': {\n                this.onKeyLine = true;\n                const prev = getPrevProps(parent);\n                const start = getFirstKeyStartProps(prev);\n                start.push(this.sourceToken);\n                return {\n                    type: 'block-map',\n                    offset: this.offset,\n                    indent: this.indent,\n                    items: [{ start, explicitKey: true }]\n                };\n            }\n            case 'map-value-ind': {\n                this.onKeyLine = true;\n                const prev = getPrevProps(parent);\n                const start = getFirstKeyStartProps(prev);\n                return {\n                    type: 'block-map',\n                    offset: this.offset,\n                    indent: this.indent,\n                    items: [{ start, key: null, sep: [this.sourceToken] }]\n                };\n            }\n        }\n        return null;\n    }\n    atIndentedComment(start, indent) {\n        if (this.type !== 'comment')\n            return false;\n        if (this.indent <= indent)\n            return false;\n        return start.every(st => st.type === 'newline' || st.type === 'space');\n    }\n    *documentEnd(docEnd) {\n        if (this.type !== 'doc-mode') {\n            if (docEnd.end)\n                docEnd.end.push(this.sourceToken);\n            else\n                docEnd.end = [this.sourceToken];\n            if (this.type === 'newline')\n                yield* this.pop();\n        }\n    }\n    *lineEnd(token) {\n        switch (this.type) {\n            case 'comma':\n            case 'doc-start':\n            case 'doc-end':\n            case 'flow-seq-end':\n            case 'flow-map-end':\n            case 'map-value-ind':\n                yield* this.pop();\n                yield* this.step();\n                break;\n            case 'newline':\n                this.onKeyLine = false;\n            // fallthrough\n            case 'space':\n            case 'comment':\n            default:\n                // all other values are errors\n                if (token.end)\n                    token.end.push(this.sourceToken);\n                else\n                    token.end = [this.sourceToken];\n                if (this.type === 'newline')\n                    yield* this.pop();\n        }\n    }\n}\n\nexports.Parser = Parser;\n","'use strict';\n\nvar composer = require('./compose/composer.js');\nvar Document = require('./doc/Document.js');\nvar errors = require('./errors.js');\nvar log = require('./log.js');\nvar identity = require('./nodes/identity.js');\nvar lineCounter = require('./parse/line-counter.js');\nvar parser = require('./parse/parser.js');\n\nfunction parseOptions(options) {\n    const prettyErrors = options.prettyErrors !== false;\n    const lineCounter$1 = options.lineCounter || (prettyErrors && new lineCounter.LineCounter()) || null;\n    return { lineCounter: lineCounter$1, prettyErrors };\n}\n/**\n * Parse the input as a stream of YAML documents.\n *\n * Documents should be separated from each other by `...` or `---` marker lines.\n *\n * @returns If an empty `docs` array is returned, it will be of type\n *   EmptyStream and contain additional stream information. In\n *   TypeScript, you should use `'empty' in docs` as a type guard for it.\n */\nfunction parseAllDocuments(source, options = {}) {\n    const { lineCounter, prettyErrors } = parseOptions(options);\n    const parser$1 = new parser.Parser(lineCounter?.addNewLine);\n    const composer$1 = new composer.Composer(options);\n    const docs = Array.from(composer$1.compose(parser$1.parse(source)));\n    if (prettyErrors && lineCounter)\n        for (const doc of docs) {\n            doc.errors.forEach(errors.prettifyError(source, lineCounter));\n            doc.warnings.forEach(errors.prettifyError(source, lineCounter));\n        }\n    if (docs.length > 0)\n        return docs;\n    return Object.assign([], { empty: true }, composer$1.streamInfo());\n}\n/** Parse an input string into a single YAML.Document */\nfunction parseDocument(source, options = {}) {\n    const { lineCounter, prettyErrors } = parseOptions(options);\n    const parser$1 = new parser.Parser(lineCounter?.addNewLine);\n    const composer$1 = new composer.Composer(options);\n    // `doc` is always set by compose.end(true) at the very latest\n    let doc = null;\n    for (const _doc of composer$1.compose(parser$1.parse(source), true, source.length)) {\n        if (!doc)\n            doc = _doc;\n        else if (doc.options.logLevel !== 'silent') {\n            doc.errors.push(new errors.YAMLParseError(_doc.range.slice(0, 2), 'MULTIPLE_DOCS', 'Source contains multiple documents; please use YAML.parseAllDocuments()'));\n            break;\n        }\n    }\n    if (prettyErrors && lineCounter) {\n        doc.errors.forEach(errors.prettifyError(source, lineCounter));\n        doc.warnings.forEach(errors.prettifyError(source, lineCounter));\n    }\n    return doc;\n}\nfunction parse(src, reviver, options) {\n    let _reviver = undefined;\n    if (typeof reviver === 'function') {\n        _reviver = reviver;\n    }\n    else if (options === undefined && reviver && typeof reviver === 'object') {\n        options = reviver;\n    }\n    const doc = parseDocument(src, options);\n    if (!doc)\n        return null;\n    doc.warnings.forEach(warning => log.warn(doc.options.logLevel, warning));\n    if (doc.errors.length > 0) {\n        if (doc.options.logLevel !== 'silent')\n            throw doc.errors[0];\n        else\n            doc.errors = [];\n    }\n    return doc.toJS(Object.assign({ reviver: _reviver }, options));\n}\nfunction stringify(value, replacer, options) {\n    let _replacer = null;\n    if (typeof replacer === 'function' || Array.isArray(replacer)) {\n        _replacer = replacer;\n    }\n    else if (options === undefined && replacer) {\n        options = replacer;\n    }\n    if (typeof options === 'string')\n        options = options.length;\n    if (typeof options === 'number') {\n        const indent = Math.round(options);\n        options = indent < 1 ? undefined : indent > 8 ? { indent: 8 } : { indent };\n    }\n    if (value === undefined) {\n        const { keepUndefined } = options ?? replacer ?? {};\n        if (!keepUndefined)\n            return undefined;\n    }\n    if (identity.isDocument(value) && !_replacer)\n        return value.toString(options);\n    return new Document.Document(value, _replacer, options).toString(options);\n}\n\nexports.parse = parse;\nexports.parseAllDocuments = parseAllDocuments;\nexports.parseDocument = parseDocument;\nexports.stringify = stringify;\n","'use strict';\n\nvar composer = require('./compose/composer.js');\nvar Document = require('./doc/Document.js');\nvar Schema = require('./schema/Schema.js');\nvar errors = require('./errors.js');\nvar Alias = require('./nodes/Alias.js');\nvar identity = require('./nodes/identity.js');\nvar Pair = require('./nodes/Pair.js');\nvar Scalar = require('./nodes/Scalar.js');\nvar YAMLMap = require('./nodes/YAMLMap.js');\nvar YAMLSeq = require('./nodes/YAMLSeq.js');\nvar cst = require('./parse/cst.js');\nvar lexer = require('./parse/lexer.js');\nvar lineCounter = require('./parse/line-counter.js');\nvar parser = require('./parse/parser.js');\nvar publicApi = require('./public-api.js');\nvar visit = require('./visit.js');\n\n\n\nexports.Composer = composer.Composer;\nexports.Document = Document.Document;\nexports.Schema = Schema.Schema;\nexports.YAMLError = errors.YAMLError;\nexports.YAMLParseError = errors.YAMLParseError;\nexports.YAMLWarning = errors.YAMLWarning;\nexports.Alias = Alias.Alias;\nexports.isAlias = identity.isAlias;\nexports.isCollection = identity.isCollection;\nexports.isDocument = identity.isDocument;\nexports.isMap = identity.isMap;\nexports.isNode = identity.isNode;\nexports.isPair = identity.isPair;\nexports.isScalar = identity.isScalar;\nexports.isSeq = identity.isSeq;\nexports.Pair = Pair.Pair;\nexports.Scalar = Scalar.Scalar;\nexports.YAMLMap = YAMLMap.YAMLMap;\nexports.YAMLSeq = YAMLSeq.YAMLSeq;\nexports.CST = cst;\nexports.Lexer = lexer.Lexer;\nexports.LineCounter = lineCounter.LineCounter;\nexports.Parser = parser.Parser;\nexports.parse = publicApi.parse;\nexports.parseAllDocuments = publicApi.parseAllDocuments;\nexports.parseDocument = publicApi.parseDocument;\nexports.stringify = publicApi.stringify;\nexports.visit = visit.visit;\nexports.visitAsync = visit.visitAsync;\n","import { homedir } from 'node:os'\nimport { join, resolve } from 'node:path'\nimport { readFileSync, writeFileSync, existsSync } from 'node:fs'\nimport yaml from 'yaml'\n\nexport type ConfigFormat = 'json' | 'yaml'\n\nexport interface ConfigTarget {\n  name: string\n  path: string\n  format: ConfigFormat\n}\n\nexport function getConfigPaths(): Record<string, ConfigTarget> {\n  const home = homedir()\n  const platform = process.platform\n\n  const claudeDesktop =\n    platform === 'darwin'\n      ? join(home, 'Library', 'Application Support', 'Claude', 'claude_desktop_config.json')\n      : platform === 'win32'\n        ? join(process.env['APPDATA'] ?? join(home, 'AppData', 'Roaming'), 'Claude', 'claude_desktop_config.json')\n        : join(home, '.config', 'Claude', 'claude_desktop_config.json')\n\n  return {\n    'claude-code': {\n      name: 'claude-code',\n      path: join(home, '.claude.json'),\n      format: 'json',\n    },\n    'claude-desktop': {\n      name: 'claude-desktop',\n      path: claudeDesktop,\n      format: 'json',\n    },\n    cursor: {\n      name: 'cursor',\n      path: join(home, '.cursor', 'mcp.json'),\n      format: 'json',\n    },\n    gemini: {\n      name: 'gemini',\n      path: join(home, '.gemini', 'settings.json'),\n      format: 'json',\n    },\n    goose: {\n      name: 'goose',\n      path: join(home, '.config', 'goose', 'config.yaml'),\n      format: 'yaml',\n    },\n    'mcp-json': {\n      name: 'mcp-json',\n      path: resolve(process.cwd(), 'mcp.json'),\n      format: 'json',\n    },\n  }\n}\n\nexport function readConfig(path: string, format: ConfigFormat): unknown {\n  if (!existsSync(path)) return null\n  const raw = readFileSync(path, 'utf8')\n  return format === 'yaml' ? yaml.parse(raw) : JSON.parse(raw)\n}\n\nexport function writeConfig(path: string, data: unknown, format: ConfigFormat): void {\n  const content =\n    format === 'yaml' ? yaml.stringify(data) : JSON.stringify(data, null, 2) + '\\n'\n  writeFileSync(path, content, 'utf8')\n}\n","import { defineCommand } from 'citty'\nimport { output, setJsonMode } from '../ui/format.js'\nimport { renderTable } from '../ui/table.js'\nimport { log } from '../ui/output.js'\nimport { getConfigPaths, readConfig } from '../utils/config-paths.js'\n\ninterface DiscoveredServer {\n  source: string\n  name: string\n  transport: string\n  target: string\n}\n\nfunction extractServers(source: string, config: unknown): DiscoveredServer[] {\n  if (!config || typeof config !== 'object') return []\n\n  const servers: DiscoveredServer[] = []\n\n  // Standard MCP config shape: { mcpServers: { name: { command | url, ... } } }\n  const mcpServers = (config as Record<string, unknown>)['mcpServers']\n  if (mcpServers && typeof mcpServers === 'object') {\n    for (const [name, entry] of Object.entries(mcpServers as Record<string, unknown>)) {\n      if (!entry || typeof entry !== 'object') continue\n      const e = entry as Record<string, unknown>\n      if ('url' in e) {\n        servers.push({ source, name, transport: 'http', target: String(e['url']) })\n      } else if ('command' in e) {\n        const args = Array.isArray(e['args']) ? (e['args'] as string[]).join(' ') : ''\n        servers.push({ source, name, transport: 'stdio', target: `${String(e['command'])} ${args}`.trim() })\n      }\n    }\n  }\n\n  // Goose shape: { extensions: { name: { cmd, ... } } }\n  const extensions = (config as Record<string, unknown>)['extensions']\n  if (extensions && typeof extensions === 'object') {\n    for (const [name, entry] of Object.entries(extensions as Record<string, unknown>)) {\n      if (!entry || typeof entry !== 'object') continue\n      const e = entry as Record<string, unknown>\n      const cmd = e['cmd'] ?? e['command']\n      if (cmd) {\n        servers.push({ source, name, transport: 'stdio', target: String(cmd) })\n      }\n    }\n  }\n\n  return servers\n}\n\nexport default defineCommand({\n  meta: { name: 'discover', description: 'Discover MCP servers from known config files' },\n  args: {\n    source: { type: 'string', description: 'Filter by source (e.g. claude-desktop)' },\n    json: { type: 'boolean', description: 'Output JSON', default: false },\n  },\n  async run({ args }) {\n    if (args.json) setJsonMode(true)\n    const paths = getConfigPaths()\n    const all: DiscoveredServer[] = []\n\n    for (const [key, target] of Object.entries(paths)) {\n      if (args.source && key !== args.source) continue\n      try {\n        const config = readConfig(target.path, target.format)\n        if (config) {\n          all.push(...extractServers(key, config))\n        }\n      } catch {\n        // skip unreadable configs silently\n      }\n    }\n\n    output(all, (servers) => {\n      if (servers.length === 0) {\n        log.muted('No MCP servers discovered.')\n        return\n      }\n      renderTable(\n        ['Source', 'Name', 'Transport', 'Command / URL'],\n        servers.map((s) => [s.source, s.name, s.transport, s.target]),\n      )\n    })\n  },\n})\n","'use strict';\n\nvar has = Object.prototype.hasOwnProperty\n  , prefix = '~';\n\n/**\n * Constructor to create a storage for our `EE` objects.\n * An `Events` instance is a plain object whose properties are event names.\n *\n * @constructor\n * @private\n */\nfunction Events() {}\n\n//\n// We try to not inherit from `Object.prototype`. In some engines creating an\n// instance in this way is faster than calling `Object.create(null)` directly.\n// If `Object.create(null)` is not supported we prefix the event names with a\n// character to make sure that the built-in object properties are not\n// overridden or used as an attack vector.\n//\nif (Object.create) {\n  Events.prototype = Object.create(null);\n\n  //\n  // This hack is needed because the `__proto__` property is still inherited in\n  // some old browsers like Android 4, iPhone 5.1, Opera 11 and Safari 5.\n  //\n  if (!new Events().__proto__) prefix = false;\n}\n\n/**\n * Representation of a single event listener.\n *\n * @param {Function} fn The listener function.\n * @param {*} context The context to invoke the listener with.\n * @param {Boolean} [once=false] Specify if the listener is a one-time listener.\n * @constructor\n * @private\n */\nfunction EE(fn, context, once) {\n  this.fn = fn;\n  this.context = context;\n  this.once = once || false;\n}\n\n/**\n * Add a listener for a given event.\n *\n * @param {EventEmitter} emitter Reference to the `EventEmitter` instance.\n * @param {(String|Symbol)} event The event name.\n * @param {Function} fn The listener function.\n * @param {*} context The context to invoke the listener with.\n * @param {Boolean} once Specify if the listener is a one-time listener.\n * @returns {EventEmitter}\n * @private\n */\nfunction addListener(emitter, event, fn, context, once) {\n  if (typeof fn !== 'function') {\n    throw new TypeError('The listener must be a function');\n  }\n\n  var listener = new EE(fn, context || emitter, once)\n    , evt = prefix ? prefix + event : event;\n\n  if (!emitter._events[evt]) emitter._events[evt] = listener, emitter._eventsCount++;\n  else if (!emitter._events[evt].fn) emitter._events[evt].push(listener);\n  else emitter._events[evt] = [emitter._events[evt], listener];\n\n  return emitter;\n}\n\n/**\n * Clear event by name.\n *\n * @param {EventEmitter} emitter Reference to the `EventEmitter` instance.\n * @param {(String|Symbol)} evt The Event name.\n * @private\n */\nfunction clearEvent(emitter, evt) {\n  if (--emitter._eventsCount === 0) emitter._events = new Events();\n  else delete emitter._events[evt];\n}\n\n/**\n * Minimal `EventEmitter` interface that is molded against the Node.js\n * `EventEmitter` interface.\n *\n * @constructor\n * @public\n */\nfunction EventEmitter() {\n  this._events = new Events();\n  this._eventsCount = 0;\n}\n\n/**\n * Return an array listing the events for which the emitter has registered\n * listeners.\n *\n * @returns {Array}\n * @public\n */\nEventEmitter.prototype.eventNames = function eventNames() {\n  var names = []\n    , events\n    , name;\n\n  if (this._eventsCount === 0) return names;\n\n  for (name in (events = this._events)) {\n    if (has.call(events, name)) names.push(prefix ? name.slice(1) : name);\n  }\n\n  if (Object.getOwnPropertySymbols) {\n    return names.concat(Object.getOwnPropertySymbols(events));\n  }\n\n  return names;\n};\n\n/**\n * Return the listeners registered for a given event.\n *\n * @param {(String|Symbol)} event The event name.\n * @returns {Array} The registered listeners.\n * @public\n */\nEventEmitter.prototype.listeners = function listeners(event) {\n  var evt = prefix ? prefix + event : event\n    , handlers = this._events[evt];\n\n  if (!handlers) return [];\n  if (handlers.fn) return [handlers.fn];\n\n  for (var i = 0, l = handlers.length, ee = new Array(l); i < l; i++) {\n    ee[i] = handlers[i].fn;\n  }\n\n  return ee;\n};\n\n/**\n * Return the number of listeners listening to a given event.\n *\n * @param {(String|Symbol)} event The event name.\n * @returns {Number} The number of listeners.\n * @public\n */\nEventEmitter.prototype.listenerCount = function listenerCount(event) {\n  var evt = prefix ? prefix + event : event\n    , listeners = this._events[evt];\n\n  if (!listeners) return 0;\n  if (listeners.fn) return 1;\n  return listeners.length;\n};\n\n/**\n * Calls each of the listeners registered for a given event.\n *\n * @param {(String|Symbol)} event The event name.\n * @returns {Boolean} `true` if the event had listeners, else `false`.\n * @public\n */\nEventEmitter.prototype.emit = function emit(event, a1, a2, a3, a4, a5) {\n  var evt = prefix ? prefix + event : event;\n\n  if (!this._events[evt]) return false;\n\n  var listeners = this._events[evt]\n    , len = arguments.length\n    , args\n    , i;\n\n  if (listeners.fn) {\n    if (listeners.once) this.removeListener(event, listeners.fn, undefined, true);\n\n    switch (len) {\n      case 1: return listeners.fn.call(listeners.context), true;\n      case 2: return listeners.fn.call(listeners.context, a1), true;\n      case 3: return listeners.fn.call(listeners.context, a1, a2), true;\n      case 4: return listeners.fn.call(listeners.context, a1, a2, a3), true;\n      case 5: return listeners.fn.call(listeners.context, a1, a2, a3, a4), true;\n      case 6: return listeners.fn.call(listeners.context, a1, a2, a3, a4, a5), true;\n    }\n\n    for (i = 1, args = new Array(len -1); i < len; i++) {\n      args[i - 1] = arguments[i];\n    }\n\n    listeners.fn.apply(listeners.context, args);\n  } else {\n    var length = listeners.length\n      , j;\n\n    for (i = 0; i < length; i++) {\n      if (listeners[i].once) this.removeListener(event, listeners[i].fn, undefined, true);\n\n      switch (len) {\n        case 1: listeners[i].fn.call(listeners[i].context); break;\n        case 2: listeners[i].fn.call(listeners[i].context, a1); break;\n        case 3: listeners[i].fn.call(listeners[i].context, a1, a2); break;\n        case 4: listeners[i].fn.call(listeners[i].context, a1, a2, a3); break;\n        default:\n          if (!args) for (j = 1, args = new Array(len -1); j < len; j++) {\n            args[j - 1] = arguments[j];\n          }\n\n          listeners[i].fn.apply(listeners[i].context, args);\n      }\n    }\n  }\n\n  return true;\n};\n\n/**\n * Add a listener for a given event.\n *\n * @param {(String|Symbol)} event The event name.\n * @param {Function} fn The listener function.\n * @param {*} [context=this] The context to invoke the listener with.\n * @returns {EventEmitter} `this`.\n * @public\n */\nEventEmitter.prototype.on = function on(event, fn, context) {\n  return addListener(this, event, fn, context, false);\n};\n\n/**\n * Add a one-time listener for a given event.\n *\n * @param {(String|Symbol)} event The event name.\n * @param {Function} fn The listener function.\n * @param {*} [context=this] The context to invoke the listener with.\n * @returns {EventEmitter} `this`.\n * @public\n */\nEventEmitter.prototype.once = function once(event, fn, context) {\n  return addListener(this, event, fn, context, true);\n};\n\n/**\n * Remove the listeners of a given event.\n *\n * @param {(String|Symbol)} event The event name.\n * @param {Function} fn Only remove the listeners that match this function.\n * @param {*} context Only remove the listeners that have this context.\n * @param {Boolean} once Only remove one-time listeners.\n * @returns {EventEmitter} `this`.\n * @public\n */\nEventEmitter.prototype.removeListener = function removeListener(event, fn, context, once) {\n  var evt = prefix ? prefix + event : event;\n\n  if (!this._events[evt]) return this;\n  if (!fn) {\n    clearEvent(this, evt);\n    return this;\n  }\n\n  var listeners = this._events[evt];\n\n  if (listeners.fn) {\n    if (\n      listeners.fn === fn &&\n      (!once || listeners.once) &&\n      (!context || listeners.context === context)\n    ) {\n      clearEvent(this, evt);\n    }\n  } else {\n    for (var i = 0, events = [], length = listeners.length; i < length; i++) {\n      if (\n        listeners[i].fn !== fn ||\n        (once && !listeners[i].once) ||\n        (context && listeners[i].context !== context)\n      ) {\n        events.push(listeners[i]);\n      }\n    }\n\n    //\n    // Reset the array, or remove it completely if we have no more listeners.\n    //\n    if (events.length) this._events[evt] = events.length === 1 ? events[0] : events;\n    else clearEvent(this, evt);\n  }\n\n  return this;\n};\n\n/**\n * Remove all listeners, or those of the specified event.\n *\n * @param {(String|Symbol)} [event] The event name.\n * @returns {EventEmitter} `this`.\n * @public\n */\nEventEmitter.prototype.removeAllListeners = function removeAllListeners(event) {\n  var evt;\n\n  if (event) {\n    evt = prefix ? prefix + event : event;\n    if (this._events[evt]) clearEvent(this, evt);\n  } else {\n    this._events = new Events();\n    this._eventsCount = 0;\n  }\n\n  return this;\n};\n\n//\n// Alias methods names because people roll like that.\n//\nEventEmitter.prototype.off = EventEmitter.prototype.removeListener;\nEventEmitter.prototype.addListener = EventEmitter.prototype.on;\n\n//\n// Expose the prefix.\n//\nEventEmitter.prefixed = prefix;\n\n//\n// Allow `EventEmitter` to be imported as module namespace.\n//\nEventEmitter.EventEmitter = EventEmitter;\n\n//\n// Expose the module.\n//\nif ('undefined' !== typeof module) {\n  module.exports = EventEmitter;\n}\n","import EventEmitter from './index.js'\n\nexport { EventEmitter }\nexport default EventEmitter\n","'use strict'\nmodule.exports = rfdc\n\nfunction copyBuffer (cur) {\n  if (cur instanceof Buffer) {\n    return Buffer.from(cur)\n  }\n\n  return new cur.constructor(cur.buffer.slice(), cur.byteOffset, cur.length)\n}\n\nfunction rfdc (opts) {\n  opts = opts || {}\n  if (opts.circles) return rfdcCircles(opts)\n\n  const constructorHandlers = new Map()\n  constructorHandlers.set(Date, (o) => new Date(o))\n  constructorHandlers.set(Map, (o, fn) => new Map(cloneArray(Array.from(o), fn)))\n  constructorHandlers.set(Set, (o, fn) => new Set(cloneArray(Array.from(o), fn)))\n  if (opts.constructorHandlers) {\n    for (const handler of opts.constructorHandlers) {\n      constructorHandlers.set(handler[0], handler[1])\n    }\n  }\n\n  let handler = null\n\n  return opts.proto ? cloneProto : clone\n\n  function cloneArray (a, fn) {\n    const keys = Object.keys(a)\n    const a2 = new Array(keys.length)\n    for (let i = 0; i < keys.length; i++) {\n      const k = keys[i]\n      const cur = a[k]\n      if (typeof cur !== 'object' || cur === null) {\n        a2[k] = cur\n      } else if (cur.constructor !== Object && (handler = constructorHandlers.get(cur.constructor))) {\n        a2[k] = handler(cur, fn)\n      } else if (ArrayBuffer.isView(cur)) {\n        a2[k] = copyBuffer(cur)\n      } else {\n        a2[k] = fn(cur)\n      }\n    }\n    return a2\n  }\n\n  function clone (o) {\n    if (typeof o !== 'object' || o === null) return o\n    if (Array.isArray(o)) return cloneArray(o, clone)\n    if (o.constructor !== Object && (handler = constructorHandlers.get(o.constructor))) {\n      return handler(o, clone)\n    }\n    const o2 = {}\n    for (const k in o) {\n      if (Object.hasOwnProperty.call(o, k) === false) continue\n      const cur = o[k]\n      if (typeof cur !== 'object' || cur === null) {\n        o2[k] = cur\n      } else if (cur.constructor !== Object && (handler = constructorHandlers.get(cur.constructor))) {\n        o2[k] = handler(cur, clone)\n      } else if (ArrayBuffer.isView(cur)) {\n        o2[k] = copyBuffer(cur)\n      } else {\n        o2[k] = clone(cur)\n      }\n    }\n    return o2\n  }\n\n  function cloneProto (o) {\n    if (typeof o !== 'object' || o === null) return o\n    if (Array.isArray(o)) return cloneArray(o, cloneProto)\n    if (o.constructor !== Object && (handler = constructorHandlers.get(o.constructor))) {\n      return handler(o, cloneProto)\n    }\n    const o2 = {}\n    for (const k in o) {\n      const cur = o[k]\n      if (typeof cur !== 'object' || cur === null) {\n        o2[k] = cur\n      } else if (cur.constructor !== Object && (handler = constructorHandlers.get(cur.constructor))) {\n        o2[k] = handler(cur, cloneProto)\n      } else if (ArrayBuffer.isView(cur)) {\n        o2[k] = copyBuffer(cur)\n      } else {\n        o2[k] = cloneProto(cur)\n      }\n    }\n    return o2\n  }\n}\n\nfunction rfdcCircles (opts) {\n  const refs = []\n  const refsNew = []\n\n  const constructorHandlers = new Map()\n  constructorHandlers.set(Date, (o) => new Date(o))\n  constructorHandlers.set(Map, (o, fn) => new Map(cloneArray(Array.from(o), fn)))\n  constructorHandlers.set(Set, (o, fn) => new Set(cloneArray(Array.from(o), fn)))\n  if (opts.constructorHandlers) {\n    for (const handler of opts.constructorHandlers) {\n      constructorHandlers.set(handler[0], handler[1])\n    }\n  }\n\n  let handler = null\n  return opts.proto ? cloneProto : clone\n\n  function cloneArray (a, fn) {\n    const keys = Object.keys(a)\n    const a2 = new Array(keys.length)\n    for (let i = 0; i < keys.length; i++) {\n      const k = keys[i]\n      const cur = a[k]\n      if (typeof cur !== 'object' || cur === null) {\n        a2[k] = cur\n      } else if (cur.constructor !== Object && (handler = constructorHandlers.get(cur.constructor))) {\n        a2[k] = handler(cur, fn)\n      } else if (ArrayBuffer.isView(cur)) {\n        a2[k] = copyBuffer(cur)\n      } else {\n        const index = refs.indexOf(cur)\n        if (index !== -1) {\n          a2[k] = refsNew[index]\n        } else {\n          a2[k] = fn(cur)\n        }\n      }\n    }\n    return a2\n  }\n\n  function clone (o) {\n    if (typeof o !== 'object' || o === null) return o\n    if (Array.isArray(o)) return cloneArray(o, clone)\n    if (o.constructor !== Object && (handler = constructorHandlers.get(o.constructor))) {\n      return handler(o, clone)\n    }\n    const o2 = {}\n    refs.push(o)\n    refsNew.push(o2)\n    for (const k in o) {\n      if (Object.hasOwnProperty.call(o, k) === false) continue\n      const cur = o[k]\n      if (typeof cur !== 'object' || cur === null) {\n        o2[k] = cur\n      } else if (cur.constructor !== Object && (handler = constructorHandlers.get(cur.constructor))) {\n        o2[k] = handler(cur, clone)\n      } else if (ArrayBuffer.isView(cur)) {\n        o2[k] = copyBuffer(cur)\n      } else {\n        const i = refs.indexOf(cur)\n        if (i !== -1) {\n          o2[k] = refsNew[i]\n        } else {\n          o2[k] = clone(cur)\n        }\n      }\n    }\n    refs.pop()\n    refsNew.pop()\n    return o2\n  }\n\n  function cloneProto (o) {\n    if (typeof o !== 'object' || o === null) return o\n    if (Array.isArray(o)) return cloneArray(o, cloneProto)\n    if (o.constructor !== Object && (handler = constructorHandlers.get(o.constructor))) {\n      return handler(o, cloneProto)\n    }\n    const o2 = {}\n    refs.push(o)\n    refsNew.push(o2)\n    for (const k in o) {\n      const cur = o[k]\n      if (typeof cur !== 'object' || cur === null) {\n        o2[k] = cur\n      } else if (cur.constructor !== Object && (handler = constructorHandlers.get(cur.constructor))) {\n        o2[k] = handler(cur, cloneProto)\n      } else if (ArrayBuffer.isView(cur)) {\n        o2[k] = copyBuffer(cur)\n      } else {\n        const i = refs.indexOf(cur)\n        if (i !== -1) {\n          o2[k] = refsNew[i]\n        } else {\n          o2[k] = cloneProto(cur)\n        }\n      }\n    }\n    refs.pop()\n    refsNew.pop()\n    return o2\n  }\n}\n","/* globals WorkerGlobalScope, DedicatedWorkerGlobalScope, SharedWorkerGlobalScope, ServiceWorkerGlobalScope */\n\nexport const isBrowser = globalThis.window?.document !== undefined;\n\nexport const isNode = globalThis.process?.versions?.node !== undefined;\n\nexport const isBun = globalThis.process?.versions?.bun !== undefined;\n\nexport const isDeno = globalThis.Deno?.version?.deno !== undefined;\n\nexport const isElectron = globalThis.process?.versions?.electron !== undefined;\n\nexport const isJsDom = globalThis.navigator?.userAgent?.includes('jsdom') === true;\n\nexport const isWebWorker = typeof WorkerGlobalScope !== 'undefined' && globalThis instanceof WorkerGlobalScope;\n\nexport const isDedicatedWorker = typeof DedicatedWorkerGlobalScope !== 'undefined' && globalThis instanceof DedicatedWorkerGlobalScope;\n\nexport const isSharedWorker = typeof SharedWorkerGlobalScope !== 'undefined' && globalThis instanceof SharedWorkerGlobalScope;\n\nexport const isServiceWorker = typeof ServiceWorkerGlobalScope !== 'undefined' && globalThis instanceof ServiceWorkerGlobalScope;\n\n// Note: I'm intentionally not DRYing up the other variables to keep them \"lazy\".\nconst platform = globalThis.navigator?.userAgentData?.platform;\n\nexport const isMacOs = platform === 'macOS'\n\t|| globalThis.navigator?.platform === 'MacIntel' // Even on Apple silicon Macs.\n\t|| globalThis.navigator?.userAgent?.includes(' Mac ') === true\n\t|| globalThis.process?.platform === 'darwin';\n\nexport const isWindows = platform === 'Windows'\n\t|| globalThis.navigator?.platform === 'Win32'\n\t|| globalThis.process?.platform === 'win32';\n\nexport const isLinux = platform === 'Linux'\n\t|| globalThis.navigator?.platform?.startsWith('Linux') === true\n\t|| globalThis.navigator?.userAgent?.includes(' Linux ') === true\n\t|| globalThis.process?.platform === 'linux';\n\nexport const isIos = platform === 'iOS'\n\t|| (globalThis.navigator?.platform === 'MacIntel' && globalThis.navigator?.maxTouchPoints > 1)\n\t|| /iPad|iPhone|iPod/.test(globalThis.navigator?.platform);\n\nexport const isAndroid = platform === 'Android'\n\t|| globalThis.navigator?.platform === 'Android'\n\t|| globalThis.navigator?.userAgent?.includes(' Android ') === true\n\t|| globalThis.process?.platform === 'android';\n","import process from 'node:process';\nimport os from 'node:os';\nimport {isBrowser} from 'environment';\n\nconst ESC = '\\u001B[';\nconst OSC = '\\u001B]';\nconst BEL = '\\u0007';\nconst SEP = ';';\n\nconst isTerminalApp = !isBrowser && process.env.TERM_PROGRAM === 'Apple_Terminal';\nconst isWindows = !isBrowser && process.platform === 'win32';\nconst isTmux = !isBrowser && (process.env.TERM?.startsWith('screen') || process.env.TERM?.startsWith('tmux') || process.env.TMUX !== undefined);\n\nconst cwdFunction = isBrowser ? () => {\n\tthrow new Error('`process.cwd()` only works in Node.js, not the browser.');\n} : process.cwd;\n\nconst wrapOsc = sequence => {\n\tif (isTmux) {\n\t\t// Tmux requires OSC sequences to be wrapped with DCS tmux; <sequence> ST\n\t\t// and all ESCs in <sequence> to be replaced with ESC ESC.\n\t\t// It only accepts ESC backslash for ST.\n\t\treturn '\\u001BPtmux;' + sequence.replaceAll('\\u001B', '\\u001B\\u001B') + '\\u001B\\\\';\n\t}\n\n\treturn sequence;\n};\n\nexport const cursorTo = (x, y) => {\n\tif (typeof x !== 'number') {\n\t\tthrow new TypeError('The `x` argument is required');\n\t}\n\n\tif (typeof y !== 'number') {\n\t\treturn ESC + (x + 1) + 'G';\n\t}\n\n\treturn ESC + (y + 1) + SEP + (x + 1) + 'H';\n};\n\nexport const cursorMove = (x, y) => {\n\tif (typeof x !== 'number') {\n\t\tthrow new TypeError('The `x` argument is required');\n\t}\n\n\tlet returnValue = '';\n\n\tif (x < 0) {\n\t\treturnValue += ESC + (-x) + 'D';\n\t} else if (x > 0) {\n\t\treturnValue += ESC + x + 'C';\n\t}\n\n\tif (y < 0) {\n\t\treturnValue += ESC + (-y) + 'A';\n\t} else if (y > 0) {\n\t\treturnValue += ESC + y + 'B';\n\t}\n\n\treturn returnValue;\n};\n\nexport const cursorUp = (count = 1) => ESC + count + 'A';\nexport const cursorDown = (count = 1) => ESC + count + 'B';\nexport const cursorForward = (count = 1) => ESC + count + 'C';\nexport const cursorBackward = (count = 1) => ESC + count + 'D';\n\nexport const cursorLeft = ESC + 'G';\nexport const cursorSavePosition = isTerminalApp ? '\\u001B7' : ESC + 's';\nexport const cursorRestorePosition = isTerminalApp ? '\\u001B8' : ESC + 'u';\nexport const cursorGetPosition = ESC + '6n';\nexport const cursorNextLine = ESC + 'E';\nexport const cursorPrevLine = ESC + 'F';\nexport const cursorHide = ESC + '?25l';\nexport const cursorShow = ESC + '?25h';\n\nexport const eraseLines = count => {\n\tlet clear = '';\n\n\tfor (let i = 0; i < count; i++) {\n\t\tclear += eraseLine + (i < count - 1 ? cursorUp() : '');\n\t}\n\n\tif (count) {\n\t\tclear += cursorLeft;\n\t}\n\n\treturn clear;\n};\n\nexport const eraseEndLine = ESC + 'K';\nexport const eraseStartLine = ESC + '1K';\nexport const eraseLine = ESC + '2K';\nexport const eraseDown = ESC + 'J';\nexport const eraseUp = ESC + '1J';\nexport const eraseScreen = ESC + '2J';\nexport const scrollUp = ESC + 'S';\nexport const scrollDown = ESC + 'T';\n\nexport const clearScreen = '\\u001Bc';\n\nexport const clearViewport = `${eraseScreen}${ESC}H`;\n\nconst isOldWindows = () => {\n\tif (isBrowser || !isWindows) {\n\t\treturn false;\n\t}\n\n\tconst parts = os.release().split('.');\n\tconst major = Number(parts[0]);\n\tconst build = Number(parts[2] ?? 0);\n\n\tif (major < 10) {\n\t\treturn true;\n\t}\n\n\tif (major === 10 && build < 10_586) {\n\t\treturn true;\n\t}\n\n\treturn false;\n};\n\nexport const clearTerminal = isOldWindows()\n\t? `${eraseScreen}${ESC}0f`\n\t// 1. Erases the screen (Only done in case `2` is not supported)\n\t// 2. Erases the whole screen including scrollback buffer\n\t// 3. Moves cursor to the top-left position\n\t// More info: https://www.real-world-systems.com/docs/ANSIcode.html\n\t: `${eraseScreen}${ESC}3J${ESC}H`;\n\nexport const enterAlternativeScreen = ESC + '?1049h';\nexport const exitAlternativeScreen = ESC + '?1049l';\n\nexport const beginSynchronizedOutput = ESC + '?2026h';\nexport const endSynchronizedOutput = ESC + '?2026l';\nexport const synchronizedOutput = text => beginSynchronizedOutput + text + endSynchronizedOutput;\n\nexport const beep = BEL;\n\nexport const link = (text, url) => {\n\tconst openLink = wrapOsc(`${OSC}8${SEP}${SEP}${url}${BEL}`);\n\tconst closeLink = wrapOsc(`${OSC}8${SEP}${SEP}${BEL}`);\n\treturn openLink + text + closeLink;\n};\n\nexport const image = (data, options = {}) => {\n\tlet returnValue = `${OSC}1337;File=inline=1`;\n\n\tif (options.width) {\n\t\treturnValue += `;width=${options.width}`;\n\t}\n\n\tif (options.height) {\n\t\treturnValue += `;height=${options.height}`;\n\t}\n\n\tif (options.preserveAspectRatio === false) {\n\t\treturnValue += ';preserveAspectRatio=0';\n\t}\n\n\tconst imageBuffer = Buffer.from(data);\n\n\t// `size` is optional in the spec, but xterm.js requires it.\n\treturn wrapOsc(returnValue + `;size=${imageBuffer.byteLength}` + ':' + imageBuffer.toString('base64') + BEL);\n};\n\nexport const iTerm = {\n\tsetCwd: (cwd = cwdFunction()) => wrapOsc(`${OSC}50;CurrentDir=${cwd}${BEL}`),\n\n\tannotation(message, options = {}) {\n\t\tlet returnValue = `${OSC}1337;`;\n\n\t\tconst hasX = options.x !== undefined;\n\t\tconst hasY = options.y !== undefined;\n\t\tif ((hasX || hasY) && !(hasX && hasY && options.length !== undefined)) {\n\t\t\tthrow new Error('`x`, `y` and `length` must be defined when `x` or `y` is defined');\n\t\t}\n\n\t\tmessage = message.replaceAll('|', '');\n\n\t\treturnValue += options.isHidden ? 'AddHiddenAnnotation=' : 'AddAnnotation=';\n\n\t\tif (options.length > 0) {\n\t\t\treturnValue += (\n\t\t\t\thasX\n\t\t\t\t\t? [message, options.length, options.x, options.y]\n\t\t\t\t\t: [options.length, message]\n\t\t\t).join('|');\n\t\t} else {\n\t\t\treturnValue += message;\n\t\t}\n\n\t\treturn wrapOsc(returnValue + BEL);\n\t},\n};\n\nexport const ConEmu = {\n\tsetCwd: (cwd = cwdFunction()) => wrapOsc(`${OSC}9;9;${cwd}${BEL}`),\n};\n\nexport const setCwd = (cwd = cwdFunction()) => iTerm.setCwd(cwd) + ConEmu.setCwd(cwd);\n","export * from './base.js';\nexport * as default from './base.js';\n","const copyProperty = (to, from, property, ignoreNonConfigurable) => {\n\t// `Function#length` should reflect the parameters of `to` not `from` since we keep its body.\n\t// `Function#prototype` is non-writable and non-configurable so can never be modified.\n\tif (property === 'length' || property === 'prototype') {\n\t\treturn;\n\t}\n\n\t// `Function#arguments` and `Function#caller` should not be copied. They were reported to be present in `Reflect.ownKeys` for some devices in React Native (#41), so we explicitly ignore them here.\n\tif (property === 'arguments' || property === 'caller') {\n\t\treturn;\n\t}\n\n\tconst toDescriptor = Object.getOwnPropertyDescriptor(to, property);\n\tconst fromDescriptor = Object.getOwnPropertyDescriptor(from, property);\n\n\tif (!canCopyProperty(toDescriptor, fromDescriptor) && ignoreNonConfigurable) {\n\t\treturn;\n\t}\n\n\tObject.defineProperty(to, property, fromDescriptor);\n};\n\n// `Object.defineProperty()` throws if the property exists, is not configurable and either:\n// - one its descriptors is changed\n// - it is non-writable and its value is changed\nconst canCopyProperty = function (toDescriptor, fromDescriptor) {\n\treturn toDescriptor === undefined || toDescriptor.configurable || (\n\t\ttoDescriptor.writable === fromDescriptor.writable\n\t\t&& toDescriptor.enumerable === fromDescriptor.enumerable\n\t\t&& toDescriptor.configurable === fromDescriptor.configurable\n\t\t&& (toDescriptor.writable || toDescriptor.value === fromDescriptor.value)\n\t);\n};\n\nconst changePrototype = (to, from) => {\n\tconst fromPrototype = Object.getPrototypeOf(from);\n\tif (fromPrototype === Object.getPrototypeOf(to)) {\n\t\treturn;\n\t}\n\n\tObject.setPrototypeOf(to, fromPrototype);\n};\n\nconst wrappedToString = (withName, fromBody) => `/* Wrapped ${withName}*/\\n${fromBody}`;\n\nconst toStringDescriptor = Object.getOwnPropertyDescriptor(Function.prototype, 'toString');\nconst toStringName = Object.getOwnPropertyDescriptor(Function.prototype.toString, 'name');\n\n// We call `from.toString()` early (not lazily) to ensure `from` can be garbage collected.\n// We use `bind()` instead of a closure for the same reason.\n// Calling `from.toString()` early also allows caching it in case `to.toString()` is called several times.\nconst changeToString = (to, from, name) => {\n\tconst withName = name === '' ? '' : `with ${name.trim()}() `;\n\tconst newToString = wrappedToString.bind(null, withName, from.toString());\n\t// Ensure `to.toString.toString` is non-enumerable and has the same `same`\n\tObject.defineProperty(newToString, 'name', toStringName);\n\tconst {writable, enumerable, configurable} = toStringDescriptor; // We destructue to avoid a potential `get` descriptor.\n\tObject.defineProperty(to, 'toString', {value: newToString, writable, enumerable, configurable});\n};\n\nexport default function mimicFunction(to, from, {ignoreNonConfigurable = false} = {}) {\n\tconst {name} = to;\n\n\tfor (const property of Reflect.ownKeys(from)) {\n\t\tcopyProperty(to, from, property, ignoreNonConfigurable);\n\t}\n\n\tchangePrototype(to, from);\n\tchangeToString(to, from, name);\n\n\treturn to;\n}\n","import mimicFunction from 'mimic-function';\n\nconst calledFunctions = new WeakMap();\n\nconst onetime = (function_, options = {}) => {\n\tif (typeof function_ !== 'function') {\n\t\tthrow new TypeError('Expected a function');\n\t}\n\n\tlet returnValue;\n\tlet callCount = 0;\n\tconst functionName = function_.displayName || function_.name || '<anonymous>';\n\n\tconst onetime = function (...arguments_) {\n\t\tcalledFunctions.set(onetime, ++callCount);\n\n\t\tif (callCount === 1) {\n\t\t\treturnValue = function_.apply(this, arguments_);\n\t\t\tfunction_ = undefined;\n\t\t} else if (options.throw === true) {\n\t\t\tthrow new Error(`Function \\`${functionName}\\` can only be called once`);\n\t\t}\n\n\t\treturn returnValue;\n\t};\n\n\tmimicFunction(onetime, function_);\n\tcalledFunctions.set(onetime, callCount);\n\n\treturn onetime;\n};\n\nonetime.callCount = function_ => {\n\tif (!calledFunctions.has(function_)) {\n\t\tthrow new Error(`The given function \\`${function_.name}\\` is not wrapped by the \\`onetime\\` package`);\n\t}\n\n\treturn calledFunctions.get(function_);\n};\n\nexport default onetime;\n","/**\n * This is not the set of all possible signals.\n *\n * It IS, however, the set of all signals that trigger\n * an exit on either Linux or BSD systems.  Linux is a\n * superset of the signal names supported on BSD, and\n * the unknown signals just fail to register, so we can\n * catch that easily enough.\n *\n * Windows signals are a different set, since there are\n * signals that terminate Windows processes, but don't\n * terminate (or don't even exist) on Posix systems.\n *\n * Don't bother with SIGKILL.  It's uncatchable, which\n * means that we can't fire any callbacks anyway.\n *\n * If a user does happen to register a handler on a non-\n * fatal signal like SIGWINCH or something, and then\n * exit, it'll end up firing `process.emit('exit')`, so\n * the handler will be fired anyway.\n *\n * SIGBUS, SIGFPE, SIGSEGV and SIGILL, when not raised\n * artificially, inherently leave the process in a\n * state from which it is not safe to try and enter JS\n * listeners.\n */\nexport const signals: NodeJS.Signals[] = []\nsignals.push('SIGHUP', 'SIGINT', 'SIGTERM')\n\nif (process.platform !== 'win32') {\n  signals.push(\n    'SIGALRM',\n    'SIGABRT',\n    'SIGVTALRM',\n    'SIGXCPU',\n    'SIGXFSZ',\n    'SIGUSR2',\n    'SIGTRAP',\n    'SIGSYS',\n    'SIGQUIT',\n    'SIGIOT'\n    // should detect profiler and enable/disable accordingly.\n    // see #21\n    // 'SIGPROF'\n  )\n}\n\nif (process.platform === 'linux') {\n  signals.push('SIGIO', 'SIGPOLL', 'SIGPWR', 'SIGSTKFLT')\n}\n","// Note: since nyc uses this module to output coverage, any lines\n// that are in the direct sync flow of nyc's outputCoverage are\n// ignored, since we can never get coverage for them.\n// grab a reference to node's real process object right away\nimport { signals } from './signals.js'\nexport { signals }\n\n// just a loosened process type so we can do some evil things\ntype ProcessRE = NodeJS.Process & {\n  reallyExit: (code?: number | undefined | null) => any\n  emit: (ev: string, ...a: any[]) => any\n}\n\nconst processOk = (process: any): process is ProcessRE =>\n  !!process &&\n  typeof process === 'object' &&\n  typeof process.removeListener === 'function' &&\n  typeof process.emit === 'function' &&\n  typeof process.reallyExit === 'function' &&\n  typeof process.listeners === 'function' &&\n  typeof process.kill === 'function' &&\n  typeof process.pid === 'number' &&\n  typeof process.on === 'function'\n\nconst kExitEmitter = Symbol.for('signal-exit emitter')\nconst global: typeof globalThis & { [kExitEmitter]?: Emitter } = globalThis\nconst ObjectDefineProperty = Object.defineProperty.bind(Object)\n\n/**\n * A function that takes an exit code and signal as arguments\n *\n * In the case of signal exits *only*, a return value of true\n * will indicate that the signal is being handled, and we should\n * not synthetically exit with the signal we received. Regardless\n * of the handler return value, the handler is unloaded when an\n * otherwise fatal signal is received, so you get exactly 1 shot\n * at it, unless you add another onExit handler at that point.\n *\n * In the case of numeric code exits, we may already have committed\n * to exiting the process, for example via a fatal exception or\n * unhandled promise rejection, so it is impossible to stop safely.\n */\nexport type Handler = (\n  code: number | null | undefined,\n  signal: NodeJS.Signals | null\n) => true | void\ntype ExitEvent = 'afterExit' | 'exit'\ntype Emitted = { [k in ExitEvent]: boolean }\ntype Listeners = { [k in ExitEvent]: Handler[] }\n\n// teeny special purpose ee\nclass Emitter {\n  emitted: Emitted = {\n    afterExit: false,\n    exit: false,\n  }\n\n  listeners: Listeners = {\n    afterExit: [],\n    exit: [],\n  }\n\n  count: number = 0\n  id: number = Math.random()\n\n  constructor() {\n    if (global[kExitEmitter]) {\n      return global[kExitEmitter]\n    }\n    ObjectDefineProperty(global, kExitEmitter, {\n      value: this,\n      writable: false,\n      enumerable: false,\n      configurable: false,\n    })\n  }\n\n  on(ev: ExitEvent, fn: Handler) {\n    this.listeners[ev].push(fn)\n  }\n\n  removeListener(ev: ExitEvent, fn: Handler) {\n    const list = this.listeners[ev]\n    const i = list.indexOf(fn)\n    /* c8 ignore start */\n    if (i === -1) {\n      return\n    }\n    /* c8 ignore stop */\n    if (i === 0 && list.length === 1) {\n      list.length = 0\n    } else {\n      list.splice(i, 1)\n    }\n  }\n\n  emit(\n    ev: ExitEvent,\n    code: number | null | undefined,\n    signal: NodeJS.Signals | null\n  ): boolean {\n    if (this.emitted[ev]) {\n      return false\n    }\n    this.emitted[ev] = true\n    let ret: boolean = false\n    for (const fn of this.listeners[ev]) {\n      ret = fn(code, signal) === true || ret\n    }\n    if (ev === 'exit') {\n      ret = this.emit('afterExit', code, signal) || ret\n    }\n    return ret\n  }\n}\n\nabstract class SignalExitBase {\n  abstract onExit(cb: Handler, opts?: { alwaysLast?: boolean }): () => void\n  abstract load(): void\n  abstract unload(): void\n}\n\nconst signalExitWrap = <T extends SignalExitBase>(handler: T) => {\n  return {\n    onExit(cb: Handler, opts?: { alwaysLast?: boolean }) {\n      return handler.onExit(cb, opts)\n    },\n    load() {\n      return handler.load()\n    },\n    unload() {\n      return handler.unload()\n    },\n  }\n}\n\nclass SignalExitFallback extends SignalExitBase {\n  onExit() {\n    return () => {}\n  }\n  load() {}\n  unload() {}\n}\n\nclass SignalExit extends SignalExitBase {\n  // \"SIGHUP\" throws an `ENOSYS` error on Windows,\n  // so use a supported signal instead\n  /* c8 ignore start */\n  #hupSig = process.platform === 'win32' ? 'SIGINT' : 'SIGHUP'\n  /* c8 ignore stop */\n  #emitter = new Emitter()\n  #process: ProcessRE\n  #originalProcessEmit: ProcessRE['emit']\n  #originalProcessReallyExit: ProcessRE['reallyExit']\n\n  #sigListeners: { [k in NodeJS.Signals]?: () => void } = {}\n  #loaded: boolean = false\n\n  constructor(process: ProcessRE) {\n    super()\n    this.#process = process\n    // { <signal>: <listener fn>, ... }\n    this.#sigListeners = {}\n    for (const sig of signals) {\n      this.#sigListeners[sig] = () => {\n        // If there are no other listeners, an exit is coming!\n        // Simplest way: remove us and then re-send the signal.\n        // We know that this will kill the process, so we can\n        // safely emit now.\n        const listeners = this.#process.listeners(sig)\n        let { count } = this.#emitter\n        // This is a workaround for the fact that signal-exit v3 and signal\n        // exit v4 are not aware of each other, and each will attempt to let\n        // the other handle it, so neither of them do. To correct this, we\n        // detect if we're the only handler *except* for previous versions\n        // of signal-exit, and increment by the count of listeners it has\n        // created.\n        /* c8 ignore start */\n        const p = process as unknown as {\n          __signal_exit_emitter__?: { count: number }\n        }\n        if (\n          typeof p.__signal_exit_emitter__ === 'object' &&\n          typeof p.__signal_exit_emitter__.count === 'number'\n        ) {\n          count += p.__signal_exit_emitter__.count\n        }\n        /* c8 ignore stop */\n        if (listeners.length === count) {\n          this.unload()\n          const ret = this.#emitter.emit('exit', null, sig)\n          /* c8 ignore start */\n          const s = sig === 'SIGHUP' ? this.#hupSig : sig\n          if (!ret) process.kill(process.pid, s)\n          /* c8 ignore stop */\n        }\n      }\n    }\n\n    this.#originalProcessReallyExit = process.reallyExit\n    this.#originalProcessEmit = process.emit\n  }\n\n  onExit(cb: Handler, opts?: { alwaysLast?: boolean }) {\n    /* c8 ignore start */\n    if (!processOk(this.#process)) {\n      return () => {}\n    }\n    /* c8 ignore stop */\n\n    if (this.#loaded === false) {\n      this.load()\n    }\n\n    const ev = opts?.alwaysLast ? 'afterExit' : 'exit'\n    this.#emitter.on(ev, cb)\n    return () => {\n      this.#emitter.removeListener(ev, cb)\n      if (\n        this.#emitter.listeners['exit'].length === 0 &&\n        this.#emitter.listeners['afterExit'].length === 0\n      ) {\n        this.unload()\n      }\n    }\n  }\n\n  load() {\n    if (this.#loaded) {\n      return\n    }\n    this.#loaded = true\n\n    // This is the number of onSignalExit's that are in play.\n    // It's important so that we can count the correct number of\n    // listeners on signals, and don't wait for the other one to\n    // handle it instead of us.\n    this.#emitter.count += 1\n\n    for (const sig of signals) {\n      try {\n        const fn = this.#sigListeners[sig]\n        if (fn) this.#process.on(sig, fn)\n      } catch (_) {}\n    }\n\n    this.#process.emit = (ev: string, ...a: any[]) => {\n      return this.#processEmit(ev, ...a)\n    }\n    this.#process.reallyExit = (code?: number | null | undefined) => {\n      return this.#processReallyExit(code)\n    }\n  }\n\n  unload() {\n    if (!this.#loaded) {\n      return\n    }\n    this.#loaded = false\n\n    signals.forEach(sig => {\n      const listener = this.#sigListeners[sig]\n      /* c8 ignore start */\n      if (!listener) {\n        throw new Error('Listener not defined for signal: ' + sig)\n      }\n      /* c8 ignore stop */\n      try {\n        this.#process.removeListener(sig, listener)\n        /* c8 ignore start */\n      } catch (_) {}\n      /* c8 ignore stop */\n    })\n    this.#process.emit = this.#originalProcessEmit\n    this.#process.reallyExit = this.#originalProcessReallyExit\n    this.#emitter.count -= 1\n  }\n\n  #processReallyExit(code?: number | null | undefined) {\n    /* c8 ignore start */\n    if (!processOk(this.#process)) {\n      return 0\n    }\n    this.#process.exitCode = code || 0\n    /* c8 ignore stop */\n\n    this.#emitter.emit('exit', this.#process.exitCode, null)\n    return this.#originalProcessReallyExit.call(\n      this.#process,\n      this.#process.exitCode\n    )\n  }\n\n  #processEmit(ev: string, ...args: any[]): any {\n    const og = this.#originalProcessEmit\n    if (ev === 'exit' && processOk(this.#process)) {\n      if (typeof args[0] === 'number') {\n        this.#process.exitCode = args[0]\n        /* c8 ignore start */\n      }\n      /* c8 ignore start */\n      const ret = og.call(this.#process, ev, ...args)\n      /* c8 ignore start */\n      this.#emitter.emit('exit', this.#process.exitCode, null)\n      /* c8 ignore stop */\n      return ret\n    } else {\n      return og.call(this.#process, ev, ...args)\n    }\n  }\n}\n\nconst process = globalThis.process\n// wrap so that we call the method on the actual handler, without\n// exporting it directly.\nexport const {\n  /**\n   * Called when the process is exiting, whether via signal, explicit\n   * exit, or running out of stuff to do.\n   *\n   * If the global process object is not suitable for instrumentation,\n   * then this will be a no-op.\n   *\n   * Returns a function that may be used to unload signal-exit.\n   */\n  onExit,\n\n  /**\n   * Load the listeners.  Likely you never need to call this, unless\n   * doing a rather deep integration with signal-exit functionality.\n   * Mostly exposed for the benefit of testing.\n   *\n   * @internal\n   */\n  load,\n\n  /**\n   * Unload the listeners.  Likely you never need to call this, unless\n   * doing a rather deep integration with signal-exit functionality.\n   * Mostly exposed for the benefit of testing.\n   *\n   * @internal\n   */\n  unload,\n} = signalExitWrap(\n  processOk(process) ? new SignalExit(process) : new SignalExitFallback()\n)\n","import process from 'node:process';\nimport onetime from 'onetime';\nimport {onExit} from 'signal-exit';\n\nconst terminal = process.stderr.isTTY\n\t? process.stderr\n\t: (process.stdout.isTTY ? process.stdout : undefined);\n\nconst restoreCursor = terminal ? onetime(() => {\n\tonExit(() => {\n\t\tterminal.write('\\u001B[?25h');\n\t}, {alwaysLast: true});\n}) : () => {};\n\nexport default restoreCursor;\n","import process from 'node:process';\nimport restoreCursor from 'restore-cursor';\n\nlet isHidden = false;\n\nconst cliCursor = {};\n\ncliCursor.show = (writableStream = process.stderr) => {\n\tif (!writableStream.isTTY) {\n\t\treturn;\n\t}\n\n\tisHidden = false;\n\twritableStream.write('\\u001B[?25h');\n};\n\ncliCursor.hide = (writableStream = process.stderr) => {\n\tif (!writableStream.isTTY) {\n\t\treturn;\n\t}\n\n\trestoreCursor();\n\tisHidden = true;\n\twritableStream.write('\\u001B[?25l');\n};\n\ncliCursor.toggle = (force, writableStream) => {\n\tif (force !== undefined) {\n\t\tisHidden = force;\n\t}\n\n\tif (isHidden) {\n\t\tcliCursor.show(writableStream);\n\t} else {\n\t\tcliCursor.hide(writableStream);\n\t}\n};\n\nexport default cliCursor;\n","export default function ansiRegex({onlyFirst = false} = {}) {\n\t// Valid string terminator sequences are BEL, ESC\\, and 0x9c\n\tconst ST = '(?:\\\\u0007|\\\\u001B\\\\u005C|\\\\u009C)';\n\n\t// OSC sequences only: ESC ] ... ST (non-greedy until the first ST)\n\tconst osc = `(?:\\\\u001B\\\\][\\\\s\\\\S]*?${ST})`;\n\n\t// CSI and related: ESC/C1, optional intermediates, optional params (supports ; and :) then final byte\n\tconst csi = '[\\\\u001B\\\\u009B][[\\\\]()#;?]*(?:\\\\d{1,4}(?:[;:]\\\\d{0,4})*)?[\\\\dA-PR-TZcf-nq-uy=><~]';\n\n\tconst pattern = `${osc}|${csi}`;\n\n\treturn new RegExp(pattern, onlyFirst ? undefined : 'g');\n}\n","import ansiRegex from 'ansi-regex';\n\nconst regex = ansiRegex();\n\nexport default function stripAnsi(string) {\n\tif (typeof string !== 'string') {\n\t\tthrow new TypeError(`Expected a \\`string\\`, got \\`${typeof string}\\``);\n\t}\n\n\t// Fast path: ANSI codes require ESC (7-bit) or CSI (8-bit) introducer\n\tif (!string.includes('\\u001B') && !string.includes('\\u009B')) {\n\t\treturn string;\n\t}\n\n\t// Even though the regex is global, we don't need to reset the `.lastIndex`\n\t// because unlike `.exec()` and `.test()`, `.replace()` does it automatically\n\t// and doing it manually has a performance penalty.\n\treturn string.replace(regex, '');\n}\n","// Generated by scripts/build.js\n\n// prettier-ignore\nconst ambiguousRanges = [161, 161, 164, 164, 167, 168, 170, 170, 173, 174, 176, 180, 182, 186, 188, 191, 198, 198, 208, 208, 215, 216, 222, 225, 230, 230, 232, 234, 236, 237, 240, 240, 242, 243, 247, 250, 252, 252, 254, 254, 257, 257, 273, 273, 275, 275, 283, 283, 294, 295, 299, 299, 305, 307, 312, 312, 319, 322, 324, 324, 328, 331, 333, 333, 338, 339, 358, 359, 363, 363, 462, 462, 464, 464, 466, 466, 468, 468, 470, 470, 472, 472, 474, 474, 476, 476, 593, 593, 609, 609, 708, 708, 711, 711, 713, 715, 717, 717, 720, 720, 728, 731, 733, 733, 735, 735, 768, 879, 913, 929, 931, 937, 945, 961, 963, 969, 1025, 1025, 1040, 1103, 1105, 1105, 8208, 8208, 8211, 8214, 8216, 8217, 8220, 8221, 8224, 8226, 8228, 8231, 8240, 8240, 8242, 8243, 8245, 8245, 8251, 8251, 8254, 8254, 8308, 8308, 8319, 8319, 8321, 8324, 8364, 8364, 8451, 8451, 8453, 8453, 8457, 8457, 8467, 8467, 8470, 8470, 8481, 8482, 8486, 8486, 8491, 8491, 8531, 8532, 8539, 8542, 8544, 8555, 8560, 8569, 8585, 8585, 8592, 8601, 8632, 8633, 8658, 8658, 8660, 8660, 8679, 8679, 8704, 8704, 8706, 8707, 8711, 8712, 8715, 8715, 8719, 8719, 8721, 8721, 8725, 8725, 8730, 8730, 8733, 8736, 8739, 8739, 8741, 8741, 8743, 8748, 8750, 8750, 8756, 8759, 8764, 8765, 8776, 8776, 8780, 8780, 8786, 8786, 8800, 8801, 8804, 8807, 8810, 8811, 8814, 8815, 8834, 8835, 8838, 8839, 8853, 8853, 8857, 8857, 8869, 8869, 8895, 8895, 8978, 8978, 9312, 9449, 9451, 9547, 9552, 9587, 9600, 9615, 9618, 9621, 9632, 9633, 9635, 9641, 9650, 9651, 9654, 9655, 9660, 9661, 9664, 9665, 9670, 9672, 9675, 9675, 9678, 9681, 9698, 9701, 9711, 9711, 9733, 9734, 9737, 9737, 9742, 9743, 9756, 9756, 9758, 9758, 9792, 9792, 9794, 9794, 9824, 9825, 9827, 9829, 9831, 9834, 9836, 9837, 9839, 9839, 9886, 9887, 9919, 9919, 9926, 9933, 9935, 9939, 9941, 9953, 9955, 9955, 9960, 9961, 9963, 9969, 9972, 9972, 9974, 9977, 9979, 9980, 9982, 9983, 10045, 10045, 10102, 10111, 11094, 11097, 12872, 12879, 57344, 63743, 65024, 65039, 65533, 65533, 127232, 127242, 127248, 127277, 127280, 127337, 127344, 127373, 127375, 127376, 127387, 127404, 917760, 917999, 983040, 1048573, 1048576, 1114109];\n\n// prettier-ignore\nconst fullwidthRanges = [12288, 12288, 65281, 65376, 65504, 65510];\n\n// prettier-ignore\nconst halfwidthRanges = [8361, 8361, 65377, 65470, 65474, 65479, 65482, 65487, 65490, 65495, 65498, 65500, 65512, 65518];\n\n// prettier-ignore\nconst narrowRanges = [32, 126, 162, 163, 165, 166, 172, 172, 175, 175, 10214, 10221, 10629, 10630];\n\n// prettier-ignore\nconst wideRanges = [4352, 4447, 8986, 8987, 9001, 9002, 9193, 9196, 9200, 9200, 9203, 9203, 9725, 9726, 9748, 9749, 9776, 9783, 9800, 9811, 9855, 9855, 9866, 9871, 9875, 9875, 9889, 9889, 9898, 9899, 9917, 9918, 9924, 9925, 9934, 9934, 9940, 9940, 9962, 9962, 9970, 9971, 9973, 9973, 9978, 9978, 9981, 9981, 9989, 9989, 9994, 9995, 10024, 10024, 10060, 10060, 10062, 10062, 10067, 10069, 10071, 10071, 10133, 10135, 10160, 10160, 10175, 10175, 11035, 11036, 11088, 11088, 11093, 11093, 11904, 11929, 11931, 12019, 12032, 12245, 12272, 12287, 12289, 12350, 12353, 12438, 12441, 12543, 12549, 12591, 12593, 12686, 12688, 12773, 12783, 12830, 12832, 12871, 12880, 42124, 42128, 42182, 43360, 43388, 44032, 55203, 63744, 64255, 65040, 65049, 65072, 65106, 65108, 65126, 65128, 65131, 94176, 94180, 94192, 94198, 94208, 101589, 101631, 101662, 101760, 101874, 110576, 110579, 110581, 110587, 110589, 110590, 110592, 110882, 110898, 110898, 110928, 110930, 110933, 110933, 110948, 110951, 110960, 111355, 119552, 119638, 119648, 119670, 126980, 126980, 127183, 127183, 127374, 127374, 127377, 127386, 127488, 127490, 127504, 127547, 127552, 127560, 127568, 127569, 127584, 127589, 127744, 127776, 127789, 127797, 127799, 127868, 127870, 127891, 127904, 127946, 127951, 127955, 127968, 127984, 127988, 127988, 127992, 128062, 128064, 128064, 128066, 128252, 128255, 128317, 128331, 128334, 128336, 128359, 128378, 128378, 128405, 128406, 128420, 128420, 128507, 128591, 128640, 128709, 128716, 128716, 128720, 128722, 128725, 128728, 128732, 128735, 128747, 128748, 128756, 128764, 128992, 129003, 129008, 129008, 129292, 129338, 129340, 129349, 129351, 129535, 129648, 129660, 129664, 129674, 129678, 129734, 129736, 129736, 129741, 129756, 129759, 129770, 129775, 129784, 131072, 196605, 196608, 262141];\n\nexport {ambiguousRanges, fullwidthRanges, halfwidthRanges, narrowRanges, wideRanges};\n","/**\nBinary search on a sorted flat array of [start, end] pairs.\n\n@param {number[]} ranges - Flat array of inclusive [start, end] range pairs, e.g. [0, 5, 10, 20].\n@param {number} codePoint - The value to search for.\n@returns {boolean} Whether the value falls within any of the ranges.\n*/\nexport const isInRange = (ranges, codePoint) => {\n\tlet low = 0;\n\tlet high = Math.floor(ranges.length / 2) - 1;\n\twhile (low <= high) {\n\t\tconst mid = Math.floor((low + high) / 2);\n\t\tconst i = mid * 2;\n\t\tif (codePoint < ranges[i]) {\n\t\t\thigh = mid - 1;\n\t\t} else if (codePoint > ranges[i + 1]) {\n\t\t\tlow = mid + 1;\n\t\t} else {\n\t\t\treturn true;\n\t\t}\n\t}\n\n\treturn false;\n};\n","import {\n\tambiguousRanges,\n\tfullwidthRanges,\n\thalfwidthRanges,\n\tnarrowRanges,\n\twideRanges,\n} from './lookup-data.js';\nimport {isInRange} from './utilities.js';\n\nconst minimumAmbiguousCodePoint = ambiguousRanges[0];\nconst maximumAmbiguousCodePoint = ambiguousRanges.at(-1);\nconst minimumFullWidthCodePoint = fullwidthRanges[0];\nconst maximumFullWidthCodePoint = fullwidthRanges.at(-1);\nconst minimumHalfWidthCodePoint = halfwidthRanges[0];\nconst maximumHalfWidthCodePoint = halfwidthRanges.at(-1);\nconst minimumNarrowCodePoint = narrowRanges[0];\nconst maximumNarrowCodePoint = narrowRanges.at(-1);\nconst minimumWideCodePoint = wideRanges[0];\nconst maximumWideCodePoint = wideRanges.at(-1);\n\nconst commonCjkCodePoint = 0x4E_00;\nconst [wideFastPathStart, wideFastPathEnd] = findWideFastPathRange(wideRanges);\n\n// Use a hot-path range so common `isWide` calls can skip binary search.\n// The range containing U+4E00 covers common CJK ideographs;\n// fallback to the largest range for resilience to Unicode table changes.\nfunction findWideFastPathRange(ranges) {\n\tlet fastPathStart = ranges[0];\n\tlet fastPathEnd = ranges[1];\n\n\tfor (let index = 0; index < ranges.length; index += 2) {\n\t\tconst start = ranges[index];\n\t\tconst end = ranges[index + 1];\n\n\t\tif (\n\t\t\tcommonCjkCodePoint >= start\n\t\t\t&& commonCjkCodePoint <= end\n\t\t) {\n\t\t\treturn [start, end];\n\t\t}\n\n\t\tif ((end - start) > (fastPathEnd - fastPathStart)) {\n\t\t\tfastPathStart = start;\n\t\t\tfastPathEnd = end;\n\t\t}\n\t}\n\n\treturn [fastPathStart, fastPathEnd];\n}\n\nexport const isAmbiguous = codePoint => {\n\tif (\n\t\tcodePoint < minimumAmbiguousCodePoint\n\t\t|| codePoint > maximumAmbiguousCodePoint\n\t) {\n\t\treturn false;\n\t}\n\n\treturn isInRange(ambiguousRanges, codePoint);\n};\n\nexport const isFullWidth = codePoint => {\n\tif (\n\t\tcodePoint < minimumFullWidthCodePoint\n\t\t|| codePoint > maximumFullWidthCodePoint\n\t) {\n\t\treturn false;\n\t}\n\n\treturn isInRange(fullwidthRanges, codePoint);\n};\n\nconst isHalfWidth = codePoint => {\n\tif (\n\t\tcodePoint < minimumHalfWidthCodePoint\n\t\t|| codePoint > maximumHalfWidthCodePoint\n\t) {\n\t\treturn false;\n\t}\n\n\treturn isInRange(halfwidthRanges, codePoint);\n};\n\nconst isNarrow = codePoint => {\n\tif (\n\t\tcodePoint < minimumNarrowCodePoint\n\t\t|| codePoint > maximumNarrowCodePoint\n\t) {\n\t\treturn false;\n\t}\n\n\treturn isInRange(narrowRanges, codePoint);\n};\n\nexport const isWide = codePoint => {\n\tif (\n\t\tcodePoint >= wideFastPathStart\n\t\t&& codePoint <= wideFastPathEnd\n\t) {\n\t\treturn true;\n\t}\n\n\tif (\n\t\tcodePoint < minimumWideCodePoint\n\t\t|| codePoint > maximumWideCodePoint\n\t) {\n\t\treturn false;\n\t}\n\n\treturn isInRange(wideRanges, codePoint);\n};\n\nexport function getCategory(codePoint) {\n\tif (isAmbiguous(codePoint)) {\n\t\treturn 'ambiguous';\n\t}\n\n\tif (isFullWidth(codePoint)) {\n\t\treturn 'fullwidth';\n\t}\n\n\tif (isHalfWidth(codePoint)) {\n\t\treturn 'halfwidth';\n\t}\n\n\tif (isNarrow(codePoint)) {\n\t\treturn 'narrow';\n\t}\n\n\tif (isWide(codePoint)) {\n\t\treturn 'wide';\n\t}\n\n\treturn 'neutral';\n}\n","import {getCategory, isAmbiguous, isFullWidth, isWide} from './lookup.js';\n\nfunction validate(codePoint) {\n\tif (!Number.isSafeInteger(codePoint)) {\n\t\tthrow new TypeError(`Expected a code point, got \\`${typeof codePoint}\\`.`);\n\t}\n}\n\nexport function eastAsianWidthType(codePoint) {\n\tvalidate(codePoint);\n\n\treturn getCategory(codePoint);\n}\n\nexport function eastAsianWidth(codePoint, {ambiguousAsWide = false} = {}) {\n\tvalidate(codePoint);\n\n\tif (\n\t\tisFullWidth(codePoint)\n\t\t|| isWide(codePoint)\n\t\t|| (ambiguousAsWide && isAmbiguous(codePoint))\n\t) {\n\t\treturn 2;\n\t}\n\n\treturn 1;\n}\n\n// Private exports for https://github.com/sindresorhus/is-fullwidth-code-point\nexport {isFullWidth as _isFullWidth, isWide as _isWide} from './lookup.js';\n","export default () => {\n\t// https://mths.be/emoji\n\treturn /[#*0-9]\\uFE0F?\\u20E3|[\\xA9\\xAE\\u203C\\u2049\\u2122\\u2139\\u2194-\\u2199\\u21A9\\u21AA\\u231A\\u231B\\u2328\\u23CF\\u23ED-\\u23EF\\u23F1\\u23F2\\u23F8-\\u23FA\\u24C2\\u25AA\\u25AB\\u25B6\\u25C0\\u25FB\\u25FC\\u25FE\\u2600-\\u2604\\u260E\\u2611\\u2614\\u2615\\u2618\\u2620\\u2622\\u2623\\u2626\\u262A\\u262E\\u262F\\u2638-\\u263A\\u2640\\u2642\\u2648-\\u2653\\u265F\\u2660\\u2663\\u2665\\u2666\\u2668\\u267B\\u267E\\u267F\\u2692\\u2694-\\u2697\\u2699\\u269B\\u269C\\u26A0\\u26A7\\u26AA\\u26B0\\u26B1\\u26BD\\u26BE\\u26C4\\u26C8\\u26CF\\u26D1\\u26E9\\u26F0-\\u26F5\\u26F7\\u26F8\\u26FA\\u2702\\u2708\\u2709\\u270F\\u2712\\u2714\\u2716\\u271D\\u2721\\u2733\\u2734\\u2744\\u2747\\u2757\\u2763\\u27A1\\u2934\\u2935\\u2B05-\\u2B07\\u2B1B\\u2B1C\\u2B55\\u3030\\u303D\\u3297\\u3299]\\uFE0F?|[\\u261D\\u270C\\u270D](?:\\uD83C[\\uDFFB-\\uDFFF]|\\uFE0F)?|[\\u270A\\u270B](?:\\uD83C[\\uDFFB-\\uDFFF])?|[\\u23E9-\\u23EC\\u23F0\\u23F3\\u25FD\\u2693\\u26A1\\u26AB\\u26C5\\u26CE\\u26D4\\u26EA\\u26FD\\u2705\\u2728\\u274C\\u274E\\u2753-\\u2755\\u2795-\\u2797\\u27B0\\u27BF\\u2B50]|\\u26D3\\uFE0F?(?:\\u200D\\uD83D\\uDCA5)?|\\u26F9(?:\\uD83C[\\uDFFB-\\uDFFF]|\\uFE0F)?(?:\\u200D[\\u2640\\u2642]\\uFE0F?)?|\\u2764\\uFE0F?(?:\\u200D(?:\\uD83D\\uDD25|\\uD83E\\uDE79))?|\\uD83C(?:[\\uDC04\\uDD70\\uDD71\\uDD7E\\uDD7F\\uDE02\\uDE37\\uDF21\\uDF24-\\uDF2C\\uDF36\\uDF7D\\uDF96\\uDF97\\uDF99-\\uDF9B\\uDF9E\\uDF9F\\uDFCD\\uDFCE\\uDFD4-\\uDFDF\\uDFF5\\uDFF7]\\uFE0F?|[\\uDF85\\uDFC2\\uDFC7](?:\\uD83C[\\uDFFB-\\uDFFF])?|[\\uDFC4\\uDFCA](?:\\uD83C[\\uDFFB-\\uDFFF])?(?:\\u200D[\\u2640\\u2642]\\uFE0F?)?|[\\uDFCB\\uDFCC](?:\\uD83C[\\uDFFB-\\uDFFF]|\\uFE0F)?(?:\\u200D[\\u2640\\u2642]\\uFE0F?)?|[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\\uDC6A\\uDC79-\\uDC7B\\uDC7D-\\uDC80\\uDC84\\uDC88-\\uDC8E\\uDC90\\uDC92-\\uDCA9\\uDCAB-\\uDCFC\\uDCFF-\\uDD3D\\uDD4B-\\uDD4E\\uDD50-\\uDD67\\uDDA4\\uDDFB-\\uDE2D\\uDE2F-\\uDE34\\uDE37-\\uDE41\\uDE43\\uDE44\\uDE48-\\uDE4A\\uDE80-\\uDEA2\\uDEA4-\\uDEB3\\uDEB7-\\uDEBF\\uDEC1-\\uDEC5\\uDED0-\\uDED2\\uDED5-\\uDED8\\uDEDC-\\uDEDF\\uDEEB\\uDEEC\\uDEF4-\\uDEFC\\uDFE0-\\uDFEB\\uDFF0]|\\uDC08(?:\\u200D\\u2B1B)?|\\uDC15(?:\\u200D\\uD83E\\uDDBA)?|\\uDC26(?:\\u200D(?:\\u2B1B|\\uD83D\\uDD25))?|\\uDC3B(?:\\u200D\\u2744\\uFE0F?)?|\\uDC41\\uFE0F?(?:\\u200D\\uD83D\\uDDE8\\uFE0F?)?|\\uDC68(?:\\u200D(?:[\\u2695\\u2696\\u2708]\\uFE0F?|\\u2764\\uFE0F?\\u200D\\uD83D(?:\\uDC8B\\u200D\\uD83D)?\\uDC68|\\uD83C[\\uDF3E\\uDF73\\uDF7C\\uDF93\\uDFA4\\uDFA8\\uDFEB\\uDFED]|\\uD83D(?:[\\uDC68\\uDC69]\\u200D\\uD83D(?:\\uDC66(?:\\u200D\\uD83D\\uDC66)?|\\uDC67(?:\\u200D\\uD83D[\\uDC66\\uDC67])?)|[\\uDCBB\\uDCBC\\uDD27\\uDD2C\\uDE80\\uDE92]|\\uDC66(?:\\u200D\\uD83D\\uDC66)?|\\uDC67(?:\\u200D\\uD83D[\\uDC66\\uDC67])?)|\\uD83E(?:[\\uDDAF\\uDDBC\\uDDBD](?:\\u200D\\u27A1\\uFE0F?)?|[\\uDDB0-\\uDDB3]))|\\uD83C(?:\\uDFFB(?:\\u200D(?:[\\u2695\\u2696\\u2708]\\uFE0F?|\\u2764\\uFE0F?\\u200D\\uD83D(?:\\uDC8B\\u200D\\uD83D)?\\uDC68\\uD83C[\\uDFFB-\\uDFFF]|\\uD83C[\\uDF3E\\uDF73\\uDF7C\\uDF93\\uDFA4\\uDFA8\\uDFEB\\uDFED]|\\uD83D(?:[\\uDCBB\\uDCBC\\uDD27\\uDD2C\\uDE80\\uDE92]|\\uDC30\\u200D\\uD83D\\uDC68\\uD83C[\\uDFFC-\\uDFFF])|\\uD83E(?:[\\uDD1D\\uDEEF]\\u200D\\uD83D\\uDC68\\uD83C[\\uDFFC-\\uDFFF]|[\\uDDAF\\uDDBC\\uDDBD](?:\\u200D\\u27A1\\uFE0F?)?|[\\uDDB0-\\uDDB3])))?|\\uDFFC(?:\\u200D(?:[\\u2695\\u2696\\u2708]\\uFE0F?|\\u2764\\uFE0F?\\u200D\\uD83D(?:\\uDC8B\\u200D\\uD83D)?\\uDC68\\uD83C[\\uDFFB-\\uDFFF]|\\uD83C[\\uDF3E\\uDF73\\uDF7C\\uDF93\\uDFA4\\uDFA8\\uDFEB\\uDFED]|\\uD83D(?:[\\uDCBB\\uDCBC\\uDD27\\uDD2C\\uDE80\\uDE92]|\\uDC30\\u200D\\uD83D\\uDC68\\uD83C[\\uDFFB\\uDFFD-\\uDFFF])|\\uD83E(?:[\\uDD1D\\uDEEF]\\u200D\\uD83D\\uDC68\\uD83C[\\uDFFB\\uDFFD-\\uDFFF]|[\\uDDAF\\uDDBC\\uDDBD](?:\\u200D\\u27A1\\uFE0F?)?|[\\uDDB0-\\uDDB3])))?|\\uDFFD(?:\\u200D(?:[\\u2695\\u2696\\u2708]\\uFE0F?|\\u2764\\uFE0F?\\u200D\\uD83D(?:\\uDC8B\\u200D\\uD83D)?\\uDC68\\uD83C[\\uDFFB-\\uDFFF]|\\uD83C[\\uDF3E\\uDF73\\uDF7C\\uDF93\\uDFA4\\uDFA8\\uDFEB\\uDFED]|\\uD83D(?:[\\uDCBB\\uDCBC\\uDD27\\uDD2C\\uDE80\\uDE92]|\\uDC30\\u200D\\uD83D\\uDC68\\uD83C[\\uDFFB\\uDFFC\\uDFFE\\uDFFF])|\\uD83E(?:[\\uDD1D\\uDEEF]\\u200D\\uD83D\\uDC68\\uD83C[\\uDFFB\\uDFFC\\uDFFE\\uDFFF]|[\\uDDAF\\uDDBC\\uDDBD](?:\\u200D\\u27A1\\uFE0F?)?|[\\uDDB0-\\uDDB3])))?|\\uDFFE(?:\\u200D(?:[\\u2695\\u2696\\u2708]\\uFE0F?|\\u2764\\uFE0F?\\u200D\\uD83D(?:\\uDC8B\\u200D\\uD83D)?\\uDC68\\uD83C[\\uDFFB-\\uDFFF]|\\uD83C[\\uDF3E\\uDF73\\uDF7C\\uDF93\\uDFA4\\uDFA8\\uDFEB\\uDFED]|\\uD83D(?:[\\uDCBB\\uDCBC\\uDD27\\uDD2C\\uDE80\\uDE92]|\\uDC30\\u200D\\uD83D\\uDC68\\uD83C[\\uDFFB-\\uDFFD\\uDFFF])|\\uD83E(?:[\\uDD1D\\uDEEF]\\u200D\\uD83D\\uDC68\\uD83C[\\uDFFB-\\uDFFD\\uDFFF]|[\\uDDAF\\uDDBC\\uDDBD](?:\\u200D\\u27A1\\uFE0F?)?|[\\uDDB0-\\uDDB3])))?|\\uDFFF(?:\\u200D(?:[\\u2695\\u2696\\u2708]\\uFE0F?|\\u2764\\uFE0F?\\u200D\\uD83D(?:\\uDC8B\\u200D\\uD83D)?\\uDC68\\uD83C[\\uDFFB-\\uDFFF]|\\uD83C[\\uDF3E\\uDF73\\uDF7C\\uDF93\\uDFA4\\uDFA8\\uDFEB\\uDFED]|\\uD83D(?:[\\uDCBB\\uDCBC\\uDD27\\uDD2C\\uDE80\\uDE92]|\\uDC30\\u200D\\uD83D\\uDC68\\uD83C[\\uDFFB-\\uDFFE])|\\uD83E(?:[\\uDD1D\\uDEEF]\\u200D\\uD83D\\uDC68\\uD83C[\\uDFFB-\\uDFFE]|[\\uDDAF\\uDDBC\\uDDBD](?:\\u200D\\u27A1\\uFE0F?)?|[\\uDDB0-\\uDDB3])))?))?|\\uDC69(?:\\u200D(?:[\\u2695\\u2696\\u2708]\\uFE0F?|\\u2764\\uFE0F?\\u200D\\uD83D(?:\\uDC8B\\u200D\\uD83D)?[\\uDC68\\uDC69]|\\uD83C[\\uDF3E\\uDF73\\uDF7C\\uDF93\\uDFA4\\uDFA8\\uDFEB\\uDFED]|\\uD83D(?:[\\uDCBB\\uDCBC\\uDD27\\uDD2C\\uDE80\\uDE92]|\\uDC66(?:\\u200D\\uD83D\\uDC66)?|\\uDC67(?:\\u200D\\uD83D[\\uDC66\\uDC67])?|\\uDC69\\u200D\\uD83D(?:\\uDC66(?:\\u200D\\uD83D\\uDC66)?|\\uDC67(?:\\u200D\\uD83D[\\uDC66\\uDC67])?))|\\uD83E(?:[\\uDDAF\\uDDBC\\uDDBD](?:\\u200D\\u27A1\\uFE0F?)?|[\\uDDB0-\\uDDB3]))|\\uD83C(?:\\uDFFB(?:\\u200D(?:[\\u2695\\u2696\\u2708]\\uFE0F?|\\u2764\\uFE0F?\\u200D\\uD83D(?:[\\uDC68\\uDC69]|\\uDC8B\\u200D\\uD83D[\\uDC68\\uDC69])\\uD83C[\\uDFFB-\\uDFFF]|\\uD83C[\\uDF3E\\uDF73\\uDF7C\\uDF93\\uDFA4\\uDFA8\\uDFEB\\uDFED]|\\uD83D(?:[\\uDCBB\\uDCBC\\uDD27\\uDD2C\\uDE80\\uDE92]|\\uDC30\\u200D\\uD83D\\uDC69\\uD83C[\\uDFFC-\\uDFFF])|\\uD83E(?:[\\uDDAF\\uDDBC\\uDDBD](?:\\u200D\\u27A1\\uFE0F?)?|[\\uDDB0-\\uDDB3]|\\uDD1D\\u200D\\uD83D[\\uDC68\\uDC69]\\uD83C[\\uDFFC-\\uDFFF]|\\uDEEF\\u200D\\uD83D\\uDC69\\uD83C[\\uDFFC-\\uDFFF])))?|\\uDFFC(?:\\u200D(?:[\\u2695\\u2696\\u2708]\\uFE0F?|\\u2764\\uFE0F?\\u200D\\uD83D(?:[\\uDC68\\uDC69]|\\uDC8B\\u200D\\uD83D[\\uDC68\\uDC69])\\uD83C[\\uDFFB-\\uDFFF]|\\uD83C[\\uDF3E\\uDF73\\uDF7C\\uDF93\\uDFA4\\uDFA8\\uDFEB\\uDFED]|\\uD83D(?:[\\uDCBB\\uDCBC\\uDD27\\uDD2C\\uDE80\\uDE92]|\\uDC30\\u200D\\uD83D\\uDC69\\uD83C[\\uDFFB\\uDFFD-\\uDFFF])|\\uD83E(?:[\\uDDAF\\uDDBC\\uDDBD](?:\\u200D\\u27A1\\uFE0F?)?|[\\uDDB0-\\uDDB3]|\\uDD1D\\u200D\\uD83D[\\uDC68\\uDC69]\\uD83C[\\uDFFB\\uDFFD-\\uDFFF]|\\uDEEF\\u200D\\uD83D\\uDC69\\uD83C[\\uDFFB\\uDFFD-\\uDFFF])))?|\\uDFFD(?:\\u200D(?:[\\u2695\\u2696\\u2708]\\uFE0F?|\\u2764\\uFE0F?\\u200D\\uD83D(?:[\\uDC68\\uDC69]|\\uDC8B\\u200D\\uD83D[\\uDC68\\uDC69])\\uD83C[\\uDFFB-\\uDFFF]|\\uD83C[\\uDF3E\\uDF73\\uDF7C\\uDF93\\uDFA4\\uDFA8\\uDFEB\\uDFED]|\\uD83D(?:[\\uDCBB\\uDCBC\\uDD27\\uDD2C\\uDE80\\uDE92]|\\uDC30\\u200D\\uD83D\\uDC69\\uD83C[\\uDFFB\\uDFFC\\uDFFE\\uDFFF])|\\uD83E(?:[\\uDDAF\\uDDBC\\uDDBD](?:\\u200D\\u27A1\\uFE0F?)?|[\\uDDB0-\\uDDB3]|\\uDD1D\\u200D\\uD83D[\\uDC68\\uDC69]\\uD83C[\\uDFFB\\uDFFC\\uDFFE\\uDFFF]|\\uDEEF\\u200D\\uD83D\\uDC69\\uD83C[\\uDFFB\\uDFFC\\uDFFE\\uDFFF])))?|\\uDFFE(?:\\u200D(?:[\\u2695\\u2696\\u2708]\\uFE0F?|\\u2764\\uFE0F?\\u200D\\uD83D(?:[\\uDC68\\uDC69]|\\uDC8B\\u200D\\uD83D[\\uDC68\\uDC69])\\uD83C[\\uDFFB-\\uDFFF]|\\uD83C[\\uDF3E\\uDF73\\uDF7C\\uDF93\\uDFA4\\uDFA8\\uDFEB\\uDFED]|\\uD83D(?:[\\uDCBB\\uDCBC\\uDD27\\uDD2C\\uDE80\\uDE92]|\\uDC30\\u200D\\uD83D\\uDC69\\uD83C[\\uDFFB-\\uDFFD\\uDFFF])|\\uD83E(?:[\\uDDAF\\uDDBC\\uDDBD](?:\\u200D\\u27A1\\uFE0F?)?|[\\uDDB0-\\uDDB3]|\\uDD1D\\u200D\\uD83D[\\uDC68\\uDC69]\\uD83C[\\uDFFB-\\uDFFD\\uDFFF]|\\uDEEF\\u200D\\uD83D\\uDC69\\uD83C[\\uDFFB-\\uDFFD\\uDFFF])))?|\\uDFFF(?:\\u200D(?:[\\u2695\\u2696\\u2708]\\uFE0F?|\\u2764\\uFE0F?\\u200D\\uD83D(?:[\\uDC68\\uDC69]|\\uDC8B\\u200D\\uD83D[\\uDC68\\uDC69])\\uD83C[\\uDFFB-\\uDFFF]|\\uD83C[\\uDF3E\\uDF73\\uDF7C\\uDF93\\uDFA4\\uDFA8\\uDFEB\\uDFED]|\\uD83D(?:[\\uDCBB\\uDCBC\\uDD27\\uDD2C\\uDE80\\uDE92]|\\uDC30\\u200D\\uD83D\\uDC69\\uD83C[\\uDFFB-\\uDFFE])|\\uD83E(?:[\\uDDAF\\uDDBC\\uDDBD](?:\\u200D\\u27A1\\uFE0F?)?|[\\uDDB0-\\uDDB3]|\\uDD1D\\u200D\\uD83D[\\uDC68\\uDC69]\\uD83C[\\uDFFB-\\uDFFE]|\\uDEEF\\u200D\\uD83D\\uDC69\\uD83C[\\uDFFB-\\uDFFE])))?))?|\\uDD75(?:\\uD83C[\\uDFFB-\\uDFFF]|\\uFE0F)?(?:\\u200D[\\u2640\\u2642]\\uFE0F?)?|\\uDE2E(?:\\u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\uDF84\\uDF93\\uDFA4\\uDFA8\\uDFEB\\uDFED]|\\uD83D[\\uDCBB\\uDCBC\\uDD27\\uDD2C\\uDE80\\uDE92]|\\uD83E(?:[\\uDDAF\\uDDBC\\uDDBD](?:\\u200D\\u27A1\\uFE0F?)?|[\\uDDB0-\\uDDB3\\uDE70]|\\uDD1D\\u200D\\uD83E\\uDDD1|\\uDDD1\\u200D\\uD83E\\uDDD2(?:\\u200D\\uD83E\\uDDD2)?|\\uDDD2(?:\\u200D\\uD83E\\uDDD2)?))|\\uD83C(?:\\uDFFB(?:\\u200D(?:[\\u2695\\u2696\\u2708]\\uFE0F?|\\u2764\\uFE0F?\\u200D(?:\\uD83D\\uDC8B\\u200D)?\\uD83E\\uDDD1\\uD83C[\\uDFFC-\\uDFFF]|\\uD83C[\\uDF3E\\uDF73\\uDF7C\\uDF84\\uDF93\\uDFA4\\uDFA8\\uDFEB\\uDFED]|\\uD83D(?:[\\uDCBB\\uDCBC\\uDD27\\uDD2C\\uDE80\\uDE92]|\\uDC30\\u200D\\uD83E\\uDDD1\\uD83C[\\uDFFC-\\uDFFF])|\\uD83E(?:[\\uDDAF\\uDDBC\\uDDBD](?:\\u200D\\u27A1\\uFE0F?)?|[\\uDDB0-\\uDDB3\\uDE70]|\\uDD1D\\u200D\\uD83E\\uDDD1\\uD83C[\\uDFFB-\\uDFFF]|\\uDEEF\\u200D\\uD83E\\uDDD1\\uD83C[\\uDFFC-\\uDFFF])))?|\\uDFFC(?:\\u200D(?:[\\u2695\\u2696\\u2708]\\uFE0F?|\\u2764\\uFE0F?\\u200D(?:\\uD83D\\uDC8B\\u200D)?\\uD83E\\uDDD1\\uD83C[\\uDFFB\\uDFFD-\\uDFFF]|\\uD83C[\\uDF3E\\uDF73\\uDF7C\\uDF84\\uDF93\\uDFA4\\uDFA8\\uDFEB\\uDFED]|\\uD83D(?:[\\uDCBB\\uDCBC\\uDD27\\uDD2C\\uDE80\\uDE92]|\\uDC30\\u200D\\uD83E\\uDDD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DFFF])|\\uD83E(?:[\\uDDAF\\uDDBC\\uDDBD](?:\\u200D\\u27A1\\uFE0F?)?|[\\uDDB0-\\uDDB3\\uDE70]|\\uDD1D\\u200D\\uD83E\\uDDD1\\uD83C[\\uDFFB-\\uDFFF]|\\uDEEF\\u200D\\uD83E\\uDDD1\\uD83C[\\uDFFB-\\uDFFD\\uDFFF])))?|\\uDFFF(?:\\u200D(?:[\\u2695\\u2696\\u2708]\\uFE0F?|\\u2764\\uFE0F?\\u200D(?:\\uD83D\\uDC8B\\u200D)?\\uD83E\\uDDD1\\uD83C[\\uDFFB-\\uDFFE]|\\uD83C[\\uDF3E\\uDF73\\uDF7C\\uDF84\\uDF93\\uDFA4\\uDFA8\\uDFEB\\uDFED]|\\uD83D(?:[\\uDCBB\\uDCBC\\uDD27\\uDD2C\\uDE80\\uDE92]|\\uDC30\\u200D\\uD83E\\uDDD1\\uD83C[\\uDFFB-\\uDFFE])|\\uD83E(?:[\\uDDAF\\uDDBC\\uDDBD](?:\\u200D\\u27A1\\uFE0F?)?|[\\uDDB0-\\uDDB3\\uDE70]|\\uDD1D\\u200D\\uD83E\\uDDD1\\uD83C[\\uDFFB-\\uDFFF]|\\uDEEF\\u200D\\uD83E\\uDDD1\\uD83C[\\uDFFB-\\uDFFE])))?))?|\\uDEF1(?:\\uD83C(?:\\uDFFB(?:\\u200D\\uD83E\\uDEF2\\uD83C[\\uDFFC-\\uDFFF])?|\\uDFFC(?:\\u200D\\uD83E\\uDEF2\\uD83C[\\uDFFB\\uDFFD-\\uDFFF])?|\\uDFFD(?:\\u200D\\uD83E\\uDEF2\\uD83C[\\uDFFB\\uDFFC\\uDFFE\\uDFFF])?|\\uDFFE(?:\\u200D\\uD83E\\uDEF2\\uD83C[\\uDFFB-\\uDFFD\\uDFFF])?|\\uDFFF(?:\\u200D\\uD83E\\uDEF2\\uD83C[\\uDFFB-\\uDFFE])?))?)/g;\n};\n","import stripAnsi from 'strip-ansi';\nimport {eastAsianWidth} from 'get-east-asian-width';\nimport emojiRegex from 'emoji-regex';\n\nconst segmenter = new Intl.Segmenter();\n\nconst defaultIgnorableCodePointRegex = /^\\p{Default_Ignorable_Code_Point}$/u;\n\nexport default function stringWidth(string, options = {}) {\n\tif (typeof string !== 'string' || string.length === 0) {\n\t\treturn 0;\n\t}\n\n\tconst {\n\t\tambiguousIsNarrow = true,\n\t\tcountAnsiEscapeCodes = false,\n\t} = options;\n\n\tif (!countAnsiEscapeCodes) {\n\t\tstring = stripAnsi(string);\n\t}\n\n\tif (string.length === 0) {\n\t\treturn 0;\n\t}\n\n\tlet width = 0;\n\tconst eastAsianWidthOptions = {ambiguousAsWide: !ambiguousIsNarrow};\n\n\tfor (const {segment: character} of segmenter.segment(string)) {\n\t\tconst codePoint = character.codePointAt(0);\n\n\t\t// Ignore control characters\n\t\tif (codePoint <= 0x1F || (codePoint >= 0x7F && codePoint <= 0x9F)) {\n\t\t\tcontinue;\n\t\t}\n\n\t\t// Ignore zero-width characters\n\t\tif (\n\t\t\t(codePoint >= 0x20_0B && codePoint <= 0x20_0F) // Zero-width space, non-joiner, joiner, left-to-right mark, right-to-left mark\n\t\t\t|| codePoint === 0xFE_FF // Zero-width no-break space\n\t\t) {\n\t\t\tcontinue;\n\t\t}\n\n\t\t// Ignore combining characters\n\t\tif (\n\t\t\t(codePoint >= 0x3_00 && codePoint <= 0x3_6F) // Combining diacritical marks\n\t\t\t|| (codePoint >= 0x1A_B0 && codePoint <= 0x1A_FF) // Combining diacritical marks extended\n\t\t\t|| (codePoint >= 0x1D_C0 && codePoint <= 0x1D_FF) // Combining diacritical marks supplement\n\t\t\t|| (codePoint >= 0x20_D0 && codePoint <= 0x20_FF) // Combining diacritical marks for symbols\n\t\t\t|| (codePoint >= 0xFE_20 && codePoint <= 0xFE_2F) // Combining half marks\n\t\t) {\n\t\t\tcontinue;\n\t\t}\n\n\t\t// Ignore surrogate pairs\n\t\tif (codePoint >= 0xD8_00 && codePoint <= 0xDF_FF) {\n\t\t\tcontinue;\n\t\t}\n\n\t\t// Ignore variation selectors\n\t\tif (codePoint >= 0xFE_00 && codePoint <= 0xFE_0F) {\n\t\t\tcontinue;\n\t\t}\n\n\t\t// This covers some of the above cases, but we still keep them for performance reasons.\n\t\tif (defaultIgnorableCodePointRegex.test(character)) {\n\t\t\tcontinue;\n\t\t}\n\n\t\t// TODO: Use `/\\p{RGI_Emoji}/v` when targeting Node.js 20.\n\t\tif (emojiRegex().test(character)) {\n\t\t\twidth += 2;\n\t\t\tcontinue;\n\t\t}\n\n\t\twidth += eastAsianWidth(codePoint, eastAsianWidthOptions);\n\t}\n\n\treturn width;\n}\n","const ANSI_BACKGROUND_OFFSET = 10;\n\nconst wrapAnsi16 = (offset = 0) => code => `\\u001B[${code + offset}m`;\n\nconst wrapAnsi256 = (offset = 0) => code => `\\u001B[${38 + offset};5;${code}m`;\n\nconst wrapAnsi16m = (offset = 0) => (red, green, blue) => `\\u001B[${38 + offset};2;${red};${green};${blue}m`;\n\nconst styles = {\n\tmodifier: {\n\t\treset: [0, 0],\n\t\t// 21 isn't widely supported and 22 does the same thing\n\t\tbold: [1, 22],\n\t\tdim: [2, 22],\n\t\titalic: [3, 23],\n\t\tunderline: [4, 24],\n\t\toverline: [53, 55],\n\t\tinverse: [7, 27],\n\t\thidden: [8, 28],\n\t\tstrikethrough: [9, 29],\n\t},\n\tcolor: {\n\t\tblack: [30, 39],\n\t\tred: [31, 39],\n\t\tgreen: [32, 39],\n\t\tyellow: [33, 39],\n\t\tblue: [34, 39],\n\t\tmagenta: [35, 39],\n\t\tcyan: [36, 39],\n\t\twhite: [37, 39],\n\n\t\t// Bright color\n\t\tblackBright: [90, 39],\n\t\tgray: [90, 39], // Alias of `blackBright`\n\t\tgrey: [90, 39], // Alias of `blackBright`\n\t\tredBright: [91, 39],\n\t\tgreenBright: [92, 39],\n\t\tyellowBright: [93, 39],\n\t\tblueBright: [94, 39],\n\t\tmagentaBright: [95, 39],\n\t\tcyanBright: [96, 39],\n\t\twhiteBright: [97, 39],\n\t},\n\tbgColor: {\n\t\tbgBlack: [40, 49],\n\t\tbgRed: [41, 49],\n\t\tbgGreen: [42, 49],\n\t\tbgYellow: [43, 49],\n\t\tbgBlue: [44, 49],\n\t\tbgMagenta: [45, 49],\n\t\tbgCyan: [46, 49],\n\t\tbgWhite: [47, 49],\n\n\t\t// Bright color\n\t\tbgBlackBright: [100, 49],\n\t\tbgGray: [100, 49], // Alias of `bgBlackBright`\n\t\tbgGrey: [100, 49], // Alias of `bgBlackBright`\n\t\tbgRedBright: [101, 49],\n\t\tbgGreenBright: [102, 49],\n\t\tbgYellowBright: [103, 49],\n\t\tbgBlueBright: [104, 49],\n\t\tbgMagentaBright: [105, 49],\n\t\tbgCyanBright: [106, 49],\n\t\tbgWhiteBright: [107, 49],\n\t},\n};\n\nexport const modifierNames = Object.keys(styles.modifier);\nexport const foregroundColorNames = Object.keys(styles.color);\nexport const backgroundColorNames = Object.keys(styles.bgColor);\nexport const colorNames = [...foregroundColorNames, ...backgroundColorNames];\n\nfunction assembleStyles() {\n\tconst codes = new Map();\n\n\tfor (const [groupName, group] of Object.entries(styles)) {\n\t\tfor (const [styleName, style] of Object.entries(group)) {\n\t\t\tstyles[styleName] = {\n\t\t\t\topen: `\\u001B[${style[0]}m`,\n\t\t\t\tclose: `\\u001B[${style[1]}m`,\n\t\t\t};\n\n\t\t\tgroup[styleName] = styles[styleName];\n\n\t\t\tcodes.set(style[0], style[1]);\n\t\t}\n\n\t\tObject.defineProperty(styles, groupName, {\n\t\t\tvalue: group,\n\t\t\tenumerable: false,\n\t\t});\n\t}\n\n\tObject.defineProperty(styles, 'codes', {\n\t\tvalue: codes,\n\t\tenumerable: false,\n\t});\n\n\tstyles.color.close = '\\u001B[39m';\n\tstyles.bgColor.close = '\\u001B[49m';\n\n\tstyles.color.ansi = wrapAnsi16();\n\tstyles.color.ansi256 = wrapAnsi256();\n\tstyles.color.ansi16m = wrapAnsi16m();\n\tstyles.bgColor.ansi = wrapAnsi16(ANSI_BACKGROUND_OFFSET);\n\tstyles.bgColor.ansi256 = wrapAnsi256(ANSI_BACKGROUND_OFFSET);\n\tstyles.bgColor.ansi16m = wrapAnsi16m(ANSI_BACKGROUND_OFFSET);\n\n\t// From https://github.com/Qix-/color-convert/blob/3f0e0d4e92e235796ccb17f6e85c72094a651f49/conversions.js\n\tObject.defineProperties(styles, {\n\t\trgbToAnsi256: {\n\t\t\tvalue(red, green, blue) {\n\t\t\t\t// We use the extended greyscale palette here, with the exception of\n\t\t\t\t// black and white. normal palette only has 4 greyscale shades.\n\t\t\t\tif (red === green && green === blue) {\n\t\t\t\t\tif (red < 8) {\n\t\t\t\t\t\treturn 16;\n\t\t\t\t\t}\n\n\t\t\t\t\tif (red > 248) {\n\t\t\t\t\t\treturn 231;\n\t\t\t\t\t}\n\n\t\t\t\t\treturn Math.round(((red - 8) / 247) * 24) + 232;\n\t\t\t\t}\n\n\t\t\t\treturn 16\n\t\t\t\t\t+ (36 * Math.round(red / 255 * 5))\n\t\t\t\t\t+ (6 * Math.round(green / 255 * 5))\n\t\t\t\t\t+ Math.round(blue / 255 * 5);\n\t\t\t},\n\t\t\tenumerable: false,\n\t\t},\n\t\thexToRgb: {\n\t\t\tvalue(hex) {\n\t\t\t\tconst matches = /[a-f\\d]{6}|[a-f\\d]{3}/i.exec(hex.toString(16));\n\t\t\t\tif (!matches) {\n\t\t\t\t\treturn [0, 0, 0];\n\t\t\t\t}\n\n\t\t\t\tlet [colorString] = matches;\n\n\t\t\t\tif (colorString.length === 3) {\n\t\t\t\t\tcolorString = [...colorString].map(character => character + character).join('');\n\t\t\t\t}\n\n\t\t\t\tconst integer = Number.parseInt(colorString, 16);\n\n\t\t\t\treturn [\n\t\t\t\t\t/* eslint-disable no-bitwise */\n\t\t\t\t\t(integer >> 16) & 0xFF,\n\t\t\t\t\t(integer >> 8) & 0xFF,\n\t\t\t\t\tinteger & 0xFF,\n\t\t\t\t\t/* eslint-enable no-bitwise */\n\t\t\t\t];\n\t\t\t},\n\t\t\tenumerable: false,\n\t\t},\n\t\thexToAnsi256: {\n\t\t\tvalue: hex => styles.rgbToAnsi256(...styles.hexToRgb(hex)),\n\t\t\tenumerable: false,\n\t\t},\n\t\tansi256ToAnsi: {\n\t\t\tvalue(code) {\n\t\t\t\tif (code < 8) {\n\t\t\t\t\treturn 30 + code;\n\t\t\t\t}\n\n\t\t\t\tif (code < 16) {\n\t\t\t\t\treturn 90 + (code - 8);\n\t\t\t\t}\n\n\t\t\t\tlet red;\n\t\t\t\tlet green;\n\t\t\t\tlet blue;\n\n\t\t\t\tif (code >= 232) {\n\t\t\t\t\tred = (((code - 232) * 10) + 8) / 255;\n\t\t\t\t\tgreen = red;\n\t\t\t\t\tblue = red;\n\t\t\t\t} else {\n\t\t\t\t\tcode -= 16;\n\n\t\t\t\t\tconst remainder = code % 36;\n\n\t\t\t\t\tred = Math.floor(code / 36) / 5;\n\t\t\t\t\tgreen = Math.floor(remainder / 6) / 5;\n\t\t\t\t\tblue = (remainder % 6) / 5;\n\t\t\t\t}\n\n\t\t\t\tconst value = Math.max(red, green, blue) * 2;\n\n\t\t\t\tif (value === 0) {\n\t\t\t\t\treturn 30;\n\t\t\t\t}\n\n\t\t\t\t// eslint-disable-next-line no-bitwise\n\t\t\t\tlet result = 30 + ((Math.round(blue) << 2) | (Math.round(green) << 1) | Math.round(red));\n\n\t\t\t\tif (value === 2) {\n\t\t\t\t\tresult += 60;\n\t\t\t\t}\n\n\t\t\t\treturn result;\n\t\t\t},\n\t\t\tenumerable: false,\n\t\t},\n\t\trgbToAnsi: {\n\t\t\tvalue: (red, green, blue) => styles.ansi256ToAnsi(styles.rgbToAnsi256(red, green, blue)),\n\t\t\tenumerable: false,\n\t\t},\n\t\thexToAnsi: {\n\t\t\tvalue: hex => styles.ansi256ToAnsi(styles.hexToAnsi256(hex)),\n\t\t\tenumerable: false,\n\t\t},\n\t});\n\n\treturn styles;\n}\n\nconst ansiStyles = assembleStyles();\n\nexport default ansiStyles;\n","import stringWidth from 'string-width';\nimport stripAnsi from 'strip-ansi';\nimport ansiStyles from 'ansi-styles';\n\nconst ESCAPES = new Set([\n\t'\\u001B',\n\t'\\u009B',\n]);\n\nconst END_CODE = 39;\nconst ANSI_ESCAPE_BELL = '\\u0007';\nconst ANSI_CSI = '[';\nconst ANSI_OSC = ']';\nconst ANSI_SGR_TERMINATOR = 'm';\nconst ANSI_ESCAPE_LINK = `${ANSI_OSC}8;;`;\n\nconst wrapAnsiCode = code => `${ESCAPES.values().next().value}${ANSI_CSI}${code}${ANSI_SGR_TERMINATOR}`;\nconst wrapAnsiHyperlink = url => `${ESCAPES.values().next().value}${ANSI_ESCAPE_LINK}${url}${ANSI_ESCAPE_BELL}`;\n\n// Calculate the length of words split on ' ', ignoring\n// the extra characters added by ansi escape codes\nconst wordLengths = string => string.split(' ').map(character => stringWidth(character));\n\n// Wrap a long word across multiple rows\n// Ansi escape codes do not count towards length\nconst wrapWord = (rows, word, columns) => {\n\tconst characters = [...word];\n\n\tlet isInsideEscape = false;\n\tlet isInsideLinkEscape = false;\n\tlet visible = stringWidth(stripAnsi(rows.at(-1)));\n\n\tfor (const [index, character] of characters.entries()) {\n\t\tconst characterLength = stringWidth(character);\n\n\t\tif (visible + characterLength <= columns) {\n\t\t\trows[rows.length - 1] += character;\n\t\t} else {\n\t\t\trows.push(character);\n\t\t\tvisible = 0;\n\t\t}\n\n\t\tif (ESCAPES.has(character)) {\n\t\t\tisInsideEscape = true;\n\n\t\t\tconst ansiEscapeLinkCandidate = characters.slice(index + 1, index + 1 + ANSI_ESCAPE_LINK.length).join('');\n\t\t\tisInsideLinkEscape = ansiEscapeLinkCandidate === ANSI_ESCAPE_LINK;\n\t\t}\n\n\t\tif (isInsideEscape) {\n\t\t\tif (isInsideLinkEscape) {\n\t\t\t\tif (character === ANSI_ESCAPE_BELL) {\n\t\t\t\t\tisInsideEscape = false;\n\t\t\t\t\tisInsideLinkEscape = false;\n\t\t\t\t}\n\t\t\t} else if (character === ANSI_SGR_TERMINATOR) {\n\t\t\t\tisInsideEscape = false;\n\t\t\t}\n\n\t\t\tcontinue;\n\t\t}\n\n\t\tvisible += characterLength;\n\n\t\tif (visible === columns && index < characters.length - 1) {\n\t\t\trows.push('');\n\t\t\tvisible = 0;\n\t\t}\n\t}\n\n\t// It's possible that the last row we copy over is only\n\t// ansi escape characters, handle this edge-case\n\tif (!visible && rows.at(-1).length > 0 && rows.length > 1) {\n\t\trows[rows.length - 2] += rows.pop();\n\t}\n};\n\n// Trims spaces from a string ignoring invisible sequences\nconst stringVisibleTrimSpacesRight = string => {\n\tconst words = string.split(' ');\n\tlet last = words.length;\n\n\twhile (last > 0) {\n\t\tif (stringWidth(words[last - 1]) > 0) {\n\t\t\tbreak;\n\t\t}\n\n\t\tlast--;\n\t}\n\n\tif (last === words.length) {\n\t\treturn string;\n\t}\n\n\treturn words.slice(0, last).join(' ') + words.slice(last).join('');\n};\n\n// The wrap-ansi module can be invoked in either 'hard' or 'soft' wrap mode.\n//\n// 'hard' will never allow a string to take up more than columns characters.\n//\n// 'soft' allows long words to expand past the column length.\nconst exec = (string, columns, options = {}) => {\n\tif (options.trim !== false && string.trim() === '') {\n\t\treturn '';\n\t}\n\n\tlet returnValue = '';\n\tlet escapeCode;\n\tlet escapeUrl;\n\n\tconst lengths = wordLengths(string);\n\tlet rows = [''];\n\n\tfor (const [index, word] of string.split(' ').entries()) {\n\t\tif (options.trim !== false) {\n\t\t\trows[rows.length - 1] = rows.at(-1).trimStart();\n\t\t}\n\n\t\tlet rowLength = stringWidth(rows.at(-1));\n\n\t\tif (index !== 0) {\n\t\t\tif (rowLength >= columns && (options.wordWrap === false || options.trim === false)) {\n\t\t\t\t// If we start with a new word but the current row length equals the length of the columns, add a new row\n\t\t\t\trows.push('');\n\t\t\t\trowLength = 0;\n\t\t\t}\n\n\t\t\tif (rowLength > 0 || options.trim === false) {\n\t\t\t\trows[rows.length - 1] += ' ';\n\t\t\t\trowLength++;\n\t\t\t}\n\t\t}\n\n\t\t// In 'hard' wrap mode, the length of a line is never allowed to extend past 'columns'\n\t\tif (options.hard && lengths[index] > columns) {\n\t\t\tconst remainingColumns = (columns - rowLength);\n\t\t\tconst breaksStartingThisLine = 1 + Math.floor((lengths[index] - remainingColumns - 1) / columns);\n\t\t\tconst breaksStartingNextLine = Math.floor((lengths[index] - 1) / columns);\n\t\t\tif (breaksStartingNextLine < breaksStartingThisLine) {\n\t\t\t\trows.push('');\n\t\t\t}\n\n\t\t\twrapWord(rows, word, columns);\n\t\t\tcontinue;\n\t\t}\n\n\t\tif (rowLength + lengths[index] > columns && rowLength > 0 && lengths[index] > 0) {\n\t\t\tif (options.wordWrap === false && rowLength < columns) {\n\t\t\t\twrapWord(rows, word, columns);\n\t\t\t\tcontinue;\n\t\t\t}\n\n\t\t\trows.push('');\n\t\t}\n\n\t\tif (rowLength + lengths[index] > columns && options.wordWrap === false) {\n\t\t\twrapWord(rows, word, columns);\n\t\t\tcontinue;\n\t\t}\n\n\t\trows[rows.length - 1] += word;\n\t}\n\n\tif (options.trim !== false) {\n\t\trows = rows.map(row => stringVisibleTrimSpacesRight(row));\n\t}\n\n\tconst preString = rows.join('\\n');\n\tconst pre = [...preString];\n\n\t// We need to keep a separate index as `String#slice()` works on Unicode code units, while `pre` is an array of codepoints.\n\tlet preStringIndex = 0;\n\n\tfor (const [index, character] of pre.entries()) {\n\t\treturnValue += character;\n\n\t\tif (ESCAPES.has(character)) {\n\t\t\tconst {groups} = new RegExp(`(?:\\\\${ANSI_CSI}(?<code>\\\\d+)m|\\\\${ANSI_ESCAPE_LINK}(?<uri>.*)${ANSI_ESCAPE_BELL})`).exec(preString.slice(preStringIndex)) || {groups: {}};\n\t\t\tif (groups.code !== undefined) {\n\t\t\t\tconst code = Number.parseFloat(groups.code);\n\t\t\t\tescapeCode = code === END_CODE ? undefined : code;\n\t\t\t} else if (groups.uri !== undefined) {\n\t\t\t\tescapeUrl = groups.uri.length === 0 ? undefined : groups.uri;\n\t\t\t}\n\t\t}\n\n\t\tconst code = ansiStyles.codes.get(Number(escapeCode));\n\n\t\tif (pre[index + 1] === '\\n') {\n\t\t\tif (escapeUrl) {\n\t\t\t\treturnValue += wrapAnsiHyperlink('');\n\t\t\t}\n\n\t\t\tif (escapeCode && code) {\n\t\t\t\treturnValue += wrapAnsiCode(code);\n\t\t\t}\n\t\t} else if (character === '\\n') {\n\t\t\tif (escapeCode && code) {\n\t\t\t\treturnValue += wrapAnsiCode(escapeCode);\n\t\t\t}\n\n\t\t\tif (escapeUrl) {\n\t\t\t\treturnValue += wrapAnsiHyperlink(escapeUrl);\n\t\t\t}\n\t\t}\n\n\t\tpreStringIndex += character.length;\n\t}\n\n\treturn returnValue;\n};\n\n// For each newline, invoke the method separately\nexport default function wrapAnsi(string, columns, options) {\n\treturn String(string)\n\t\t.normalize()\n\t\t.replaceAll('\\r\\n', '\\n')\n\t\t.split('\\n')\n\t\t.map(line => exec(line, columns, options))\n\t\t.join('\\n');\n}\n","import {\n\t_isFullWidth as isFullWidth,\n\t_isWide as isWide,\n} from 'get-east-asian-width';\n\nexport default function isFullwidthCodePoint(codePoint) {\n\tif (!Number.isInteger(codePoint)) {\n\t\treturn false;\n\t}\n\n\treturn isFullWidth(codePoint) || isWide(codePoint);\n}\n","import ansiStyles from 'ansi-styles';\nimport isFullwidthCodePoint from 'is-fullwidth-code-point';\n\n// \\x1b and \\x9b\nconst ESCAPES = new Set([27, 155]);\n\nconst CODE_POINT_0 = '0'.codePointAt(0);\nconst CODE_POINT_9 = '9'.codePointAt(0);\n\nconst MAX_ANSI_SEQUENCE_LENGTH = 19;\n\nconst endCodesSet = new Set();\nconst endCodesMap = new Map();\nfor (const [start, end] of ansiStyles.codes) {\n\tendCodesSet.add(ansiStyles.color.ansi(end));\n\tendCodesMap.set(ansiStyles.color.ansi(start), ansiStyles.color.ansi(end));\n}\n\nfunction getEndCode(code) {\n\tif (endCodesSet.has(code)) {\n\t\treturn code;\n\t}\n\n\tif (endCodesMap.has(code)) {\n\t\treturn endCodesMap.get(code);\n\t}\n\n\tcode = code.slice(2);\n\tif (code.includes(';')) {\n\t\tcode = code[0] + '0';\n\t}\n\n\tconst returnValue = ansiStyles.codes.get(Number.parseInt(code, 10));\n\tif (returnValue) {\n\t\treturn ansiStyles.color.ansi(returnValue);\n\t}\n\n\treturn ansiStyles.reset.open;\n}\n\nfunction findNumberIndex(string) {\n\tfor (let index = 0; index < string.length; index++) {\n\t\tconst codePoint = string.codePointAt(index);\n\t\tif (codePoint >= CODE_POINT_0 && codePoint <= CODE_POINT_9) {\n\t\t\treturn index;\n\t\t}\n\t}\n\n\treturn -1;\n}\n\nfunction parseAnsiCode(string, offset) {\n\tstring = string.slice(offset, offset + MAX_ANSI_SEQUENCE_LENGTH);\n\tconst startIndex = findNumberIndex(string);\n\tif (startIndex !== -1) {\n\t\tlet endIndex = string.indexOf('m', startIndex);\n\t\tif (endIndex === -1) {\n\t\t\tendIndex = string.length;\n\t\t}\n\n\t\treturn string.slice(0, endIndex + 1);\n\t}\n}\n\nfunction tokenize(string, endCharacter = Number.POSITIVE_INFINITY) {\n\tconst returnValue = [];\n\n\tlet index = 0;\n\tlet visibleCount = 0;\n\twhile (index < string.length) {\n\t\tconst codePoint = string.codePointAt(index);\n\n\t\tif (ESCAPES.has(codePoint)) {\n\t\t\tconst code = parseAnsiCode(string, index);\n\t\t\tif (code) {\n\t\t\t\treturnValue.push({\n\t\t\t\t\ttype: 'ansi',\n\t\t\t\t\tcode,\n\t\t\t\t\tendCode: getEndCode(code),\n\t\t\t\t});\n\t\t\t\tindex += code.length;\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t}\n\n\t\tconst isFullWidth = isFullwidthCodePoint(codePoint);\n\t\tconst character = String.fromCodePoint(codePoint);\n\n\t\treturnValue.push({\n\t\t\ttype: 'character',\n\t\t\tvalue: character,\n\t\t\tisFullWidth,\n\t\t});\n\n\t\tindex += character.length;\n\t\tvisibleCount += isFullWidth ? 2 : character.length;\n\n\t\tif (visibleCount >= endCharacter) {\n\t\t\tbreak;\n\t\t}\n\t}\n\n\treturn returnValue;\n}\n\nfunction reduceAnsiCodes(codes) {\n\tlet returnValue = [];\n\n\tfor (const code of codes) {\n\t\tif (code.code === ansiStyles.reset.open) {\n\t\t\t// Reset code, disable all codes\n\t\t\treturnValue = [];\n\t\t} else if (endCodesSet.has(code.code)) {\n\t\t\t// This is an end code, disable all matching start codes\n\t\t\treturnValue = returnValue.filter(returnValueCode => returnValueCode.endCode !== code.code);\n\t\t} else {\n\t\t\t// This is a start code. Disable all styles this \"overrides\", then enable it\n\t\t\treturnValue = returnValue.filter(returnValueCode => returnValueCode.endCode !== code.endCode);\n\t\t\treturnValue.push(code);\n\t\t}\n\t}\n\n\treturn returnValue;\n}\n\nfunction undoAnsiCodes(codes) {\n\tconst reduced = reduceAnsiCodes(codes);\n\tconst endCodes = reduced.map(({endCode}) => endCode);\n\treturn endCodes.reverse().join('');\n}\n\nexport default function sliceAnsi(string, start, end) {\n\tconst tokens = tokenize(string, end);\n\tlet activeCodes = [];\n\tlet position = 0;\n\tlet returnValue = '';\n\tlet include = false;\n\n\tfor (const token of tokens) {\n\t\tif (end !== undefined && position >= end) {\n\t\t\tbreak;\n\t\t}\n\n\t\tif (token.type === 'ansi') {\n\t\t\tactiveCodes.push(token);\n\t\t\tif (include) {\n\t\t\t\treturnValue += token.code;\n\t\t\t}\n\t\t} else {\n\t\t\t// Character\n\t\t\tif (!include && position >= start) {\n\t\t\t\tinclude = true;\n\t\t\t\t// Simplify active codes\n\t\t\t\tactiveCodes = reduceAnsiCodes(activeCodes);\n\t\t\t\treturnValue = activeCodes.map(({code}) => code).join('');\n\t\t\t}\n\n\t\t\tif (include) {\n\t\t\t\treturnValue += token.value;\n\t\t\t}\n\n\t\t\tposition += token.isFullWidth ? 2 : token.value.length;\n\t\t}\n\t}\n\n\t// Disable active codes at the end\n\treturnValue += undoAnsiCodes(activeCodes);\n\treturn returnValue;\n}\n","import process from 'node:process';\nimport ansiEscapes from 'ansi-escapes';\nimport cliCursor from 'cli-cursor';\nimport wrapAnsi from 'wrap-ansi';\nimport sliceAnsi from 'slice-ansi';\nimport stripAnsi from 'strip-ansi';\n\nconst defaultTerminalHeight = 24;\n\nconst getWidth = ({columns = 80}) => columns;\n\nconst fitToTerminalHeight = (stream, text) => {\n\tconst terminalHeight = stream.rows ?? defaultTerminalHeight;\n\tconst lines = text.split('\\n');\n\tconst toRemove = Math.max(0, lines.length - terminalHeight);\n\treturn toRemove ? sliceAnsi(text, stripAnsi(lines.slice(0, toRemove).join('\\n')).length + 1) : text;\n};\n\nexport function createLogUpdate(stream, {showCursor = false} = {}) {\n\tlet previousLineCount = 0;\n\tlet previousWidth = getWidth(stream);\n\tlet previousOutput = '';\n\n\tconst reset = () => {\n\t\tpreviousOutput = '';\n\t\tpreviousWidth = getWidth(stream);\n\t\tpreviousLineCount = 0;\n\t};\n\n\tconst render = (...arguments_) => {\n\t\tif (!showCursor) {\n\t\t\tcliCursor.hide();\n\t\t}\n\n\t\tlet output = fitToTerminalHeight(stream, arguments_.join(' ') + '\\n');\n\t\tconst width = getWidth(stream);\n\n\t\tif (output === previousOutput && previousWidth === width) {\n\t\t\treturn;\n\t\t}\n\n\t\tpreviousOutput = output;\n\t\tpreviousWidth = width;\n\t\toutput = wrapAnsi(output, width, {trim: false, hard: true, wordWrap: false});\n\n\t\tstream.write(ansiEscapes.eraseLines(previousLineCount) + output);\n\t\tpreviousLineCount = output.split('\\n').length;\n\t};\n\n\trender.clear = () => {\n\t\tstream.write(ansiEscapes.eraseLines(previousLineCount));\n\t\treset();\n\t};\n\n\trender.done = () => {\n\t\treset();\n\t\tif (!showCursor) {\n\t\t\tcliCursor.show();\n\t\t}\n\t};\n\n\treturn render;\n}\n\nconst logUpdate = createLogUpdate(process.stdout);\nexport default logUpdate;\n\nexport const logUpdateStderr = createLogUpdate(process.stderr);\n","import {\n\t_isFullWidth as isFullWidth,\n\t_isWide as isWide,\n} from 'get-east-asian-width';\n\nexport default function isFullwidthCodePoint(codePoint) {\n\tif (!Number.isInteger(codePoint)) {\n\t\treturn false;\n\t}\n\n\treturn isFullWidth(codePoint) || isWide(codePoint);\n}\n","import ansiStyles from 'ansi-styles';\nimport isFullwidthCodePoint from 'is-fullwidth-code-point';\n\nconst ESCAPE_CODE_POINT = 27;\nconst C1_DCS_CODE_POINT = 144;\nconst C1_SOS_CODE_POINT = 152;\nconst C1_CSI_CODE_POINT = 155;\nconst C1_ST_CODE_POINT = 156;\nconst C1_OSC_CODE_POINT = 157;\nconst C1_PM_CODE_POINT = 158;\nconst C1_APC_CODE_POINT = 159;\nconst ESCAPES = new Set([\n\tESCAPE_CODE_POINT,\n\tC1_DCS_CODE_POINT,\n\tC1_SOS_CODE_POINT,\n\tC1_CSI_CODE_POINT,\n\tC1_ST_CODE_POINT,\n\tC1_OSC_CODE_POINT,\n\tC1_PM_CODE_POINT,\n\tC1_APC_CODE_POINT,\n]);\n\nconst ESCAPE = '\\u001B';\nconst ANSI_BELL = '\\u0007';\nconst ANSI_CSI = '[';\nconst ANSI_OSC = ']';\nconst ANSI_DCS = 'P';\nconst ANSI_SOS = 'X';\nconst ANSI_PM = '^';\nconst ANSI_APC = '_';\nconst ANSI_SGR_TERMINATOR = 'm';\nconst ANSI_OSC_TERMINATOR = '\\\\';\nconst ANSI_STRING_TERMINATOR = `${ESCAPE}${ANSI_OSC_TERMINATOR}`;\nconst C1_OSC = '\\u009D';\nconst C1_STRING_TERMINATOR = '\\u009C';\nconst ANSI_HYPERLINK_ESC_PREFIX = `${ESCAPE}${ANSI_OSC}8;`;\nconst ANSI_HYPERLINK_C1_PREFIX = `${C1_OSC}8;`;\nconst ANSI_HYPERLINK_ESC_CLOSE = `${ANSI_HYPERLINK_ESC_PREFIX};`;\nconst ANSI_HYPERLINK_C1_CLOSE = `${ANSI_HYPERLINK_C1_PREFIX};`;\n\nconst CODE_POINT_0 = '0'.codePointAt(0);\nconst CODE_POINT_9 = '9'.codePointAt(0);\nconst CODE_POINT_SEMICOLON = ';'.codePointAt(0);\nconst CODE_POINT_COLON = ':'.codePointAt(0);\n// ECMA-48 CSI format: parameter bytes 0x30-0x3F, intermediates 0x20-0x2F, final 0x40-0x7E.\nconst CODE_POINT_CSI_PARAMETER_START = '0'.codePointAt(0);\nconst CODE_POINT_CSI_PARAMETER_END = '?'.codePointAt(0);\nconst CODE_POINT_CSI_INTERMEDIATE_START = ' '.codePointAt(0);\nconst CODE_POINT_CSI_INTERMEDIATE_END = '/'.codePointAt(0);\nconst CODE_POINT_CSI_FINAL_START = '@'.codePointAt(0);\nconst CODE_POINT_CSI_FINAL_END = '~'.codePointAt(0);\nconst REGIONAL_INDICATOR_SYMBOL_LETTER_A = 127_462;\nconst REGIONAL_INDICATOR_SYMBOL_LETTER_Z = 127_487;\nconst SGR_RESET_CODE = 0;\nconst SGR_EXTENDED_FOREGROUND_CODE = 38;\nconst SGR_DEFAULT_FOREGROUND_CODE = 39;\nconst SGR_EXTENDED_BACKGROUND_CODE = 48;\nconst SGR_DEFAULT_BACKGROUND_CODE = 49;\nconst SGR_COLOR_TYPE_ANSI_256 = 5;\nconst SGR_COLOR_TYPE_TRUECOLOR = 2;\nconst SGR_ANSI_256_FRAGMENT_LENGTH = 3;\nconst SGR_TRUECOLOR_FRAGMENT_LENGTH = 5;\nconst SGR_ANSI_256_LAST_PARAMETER_OFFSET = 2;\nconst SGR_TRUECOLOR_LAST_PARAMETER_OFFSET = 4;\nconst VARIATION_SELECTOR_16_CODE_POINT = 65_039;\nconst COMBINING_ENCLOSING_KEYCAP_CODE_POINT = 8419;\nconst EMOJI_PRESENTATION_GRAPHEME_REGEX = /\\p{Emoji_Presentation}/u;\nconst GRAPHEME_SEGMENTER = new Intl.Segmenter(undefined, {granularity: 'grapheme'});\n\nconst endCodeNumbers = new Set();\nfor (const [, end] of ansiStyles.codes) {\n\tendCodeNumbers.add(end);\n}\n\nfunction isSgrParameterCharacter(codePoint) {\n\treturn (\n\t\t(codePoint >= CODE_POINT_0 && codePoint <= CODE_POINT_9)\n\t\t|| codePoint === CODE_POINT_SEMICOLON\n\t\t|| codePoint === CODE_POINT_COLON\n\t);\n}\n\nfunction isCsiParameterCharacter(codePoint) {\n\treturn codePoint >= CODE_POINT_CSI_PARAMETER_START && codePoint <= CODE_POINT_CSI_PARAMETER_END;\n}\n\nfunction isCsiIntermediateCharacter(codePoint) {\n\treturn codePoint >= CODE_POINT_CSI_INTERMEDIATE_START && codePoint <= CODE_POINT_CSI_INTERMEDIATE_END;\n}\n\nfunction isCsiFinalCharacter(codePoint) {\n\treturn codePoint >= CODE_POINT_CSI_FINAL_START && codePoint <= CODE_POINT_CSI_FINAL_END;\n}\n\nfunction isRegionalIndicatorCodePoint(codePoint) {\n\treturn codePoint >= REGIONAL_INDICATOR_SYMBOL_LETTER_A && codePoint <= REGIONAL_INDICATOR_SYMBOL_LETTER_Z;\n}\n\nfunction createControlParseResult(code, endIndex) {\n\treturn {\n\t\ttoken: {\n\t\t\ttype: 'control',\n\t\t\tcode,\n\t\t},\n\t\tendIndex,\n\t};\n}\n\nfunction isEmojiStyleGrapheme(grapheme) {\n\tif (EMOJI_PRESENTATION_GRAPHEME_REGEX.test(grapheme)) {\n\t\treturn true;\n\t}\n\n\tfor (const character of grapheme) {\n\t\tconst codePoint = character.codePointAt(0);\n\t\tif (\n\t\t\tcodePoint === VARIATION_SELECTOR_16_CODE_POINT\n\t\t\t|| codePoint === COMBINING_ENCLOSING_KEYCAP_CODE_POINT\n\t\t) {\n\t\t\treturn true;\n\t\t}\n\t}\n\n\treturn false;\n}\n\nfunction getGraphemeWidth(grapheme) {\n\tlet regionalIndicatorCount = 0;\n\tfor (const character of grapheme) {\n\t\tconst codePoint = character.codePointAt(0);\n\t\tif (isFullwidthCodePoint(codePoint)) {\n\t\t\treturn 2;\n\t\t}\n\n\t\tif (isRegionalIndicatorCodePoint(codePoint)) {\n\t\t\tregionalIndicatorCount++;\n\t\t}\n\t}\n\n\tif (regionalIndicatorCount >= 1) {\n\t\treturn 2;\n\t}\n\n\tif (isEmojiStyleGrapheme(grapheme)) {\n\t\treturn 2;\n\t}\n\n\treturn 1;\n}\n\nfunction getSgrPrefix(code) {\n\tif (code.startsWith('\\u009B')) {\n\t\treturn '\\u009B';\n\t}\n\n\treturn `${ESCAPE}${ANSI_CSI}`;\n}\n\nfunction createSgrCode(prefix, values) {\n\treturn `${prefix}${values.join(';')}${ANSI_SGR_TERMINATOR}`;\n}\n\nfunction getSgrFragments(code) {\n\tconst fragments = [];\n\tconst sgrPrefix = getSgrPrefix(code);\n\tlet parameterString;\n\n\tif (code.startsWith(`${ESCAPE}${ANSI_CSI}`)) {\n\t\tparameterString = code.slice(2, -1);\n\t} else if (code.startsWith('\\u009B')) {\n\t\tparameterString = code.slice(1, -1);\n\t} else {\n\t\treturn fragments;\n\t}\n\n\tconst rawCodes = parameterString.length === 0 ? [String(SGR_RESET_CODE)] : parameterString.split(';');\n\tlet index = 0;\n\twhile (index < rawCodes.length) {\n\t\tconst codeNumber = Number.parseInt(rawCodes[index], 10);\n\t\tif (Number.isNaN(codeNumber)) {\n\t\t\tindex++;\n\t\t\tcontinue;\n\t\t}\n\n\t\tif (codeNumber === SGR_RESET_CODE) {\n\t\t\tfragments.push({type: 'reset'});\n\t\t\tindex++;\n\t\t\tcontinue;\n\t\t}\n\n\t\tif (codeNumber === SGR_EXTENDED_FOREGROUND_CODE || codeNumber === SGR_EXTENDED_BACKGROUND_CODE) {\n\t\t\tconst colorType = Number.parseInt(rawCodes[index + 1], 10);\n\t\t\tif (colorType === SGR_COLOR_TYPE_ANSI_256 && index + SGR_ANSI_256_LAST_PARAMETER_OFFSET < rawCodes.length) {\n\t\t\t\tconst openCode = createSgrCode(sgrPrefix, rawCodes.slice(index, index + SGR_ANSI_256_FRAGMENT_LENGTH));\n\t\t\t\tfragments.push({\n\t\t\t\t\ttype: 'start',\n\t\t\t\t\tcode: openCode,\n\t\t\t\t\tendCode: ansiStyles.color.ansi(codeNumber === SGR_EXTENDED_FOREGROUND_CODE ? SGR_DEFAULT_FOREGROUND_CODE : SGR_DEFAULT_BACKGROUND_CODE),\n\t\t\t\t});\n\t\t\t\tindex += SGR_ANSI_256_FRAGMENT_LENGTH;\n\t\t\t\tcontinue;\n\t\t\t}\n\n\t\t\tif (colorType === SGR_COLOR_TYPE_TRUECOLOR && index + SGR_TRUECOLOR_LAST_PARAMETER_OFFSET < rawCodes.length) {\n\t\t\t\tconst openCode = createSgrCode(sgrPrefix, rawCodes.slice(index, index + SGR_TRUECOLOR_FRAGMENT_LENGTH));\n\t\t\t\tfragments.push({\n\t\t\t\t\ttype: 'start',\n\t\t\t\t\tcode: openCode,\n\t\t\t\t\tendCode: ansiStyles.color.ansi(codeNumber === SGR_EXTENDED_FOREGROUND_CODE ? SGR_DEFAULT_FOREGROUND_CODE : SGR_DEFAULT_BACKGROUND_CODE),\n\t\t\t\t});\n\t\t\t\tindex += SGR_TRUECOLOR_FRAGMENT_LENGTH;\n\t\t\t\tcontinue;\n\t\t\t}\n\n\t\t\tconst openCode = createSgrCode(sgrPrefix, [rawCodes[index]]);\n\t\t\tfragments.push({\n\t\t\t\ttype: 'start',\n\t\t\t\tcode: openCode,\n\t\t\t\tendCode: ansiStyles.color.ansi(codeNumber === SGR_EXTENDED_FOREGROUND_CODE ? SGR_DEFAULT_FOREGROUND_CODE : SGR_DEFAULT_BACKGROUND_CODE),\n\t\t\t});\n\t\t\tindex++;\n\t\t\tcontinue;\n\t\t}\n\n\t\tif (endCodeNumbers.has(codeNumber)) {\n\t\t\tfragments.push({\n\t\t\t\ttype: 'end',\n\t\t\t\tendCode: ansiStyles.color.ansi(codeNumber),\n\t\t\t});\n\t\t\tindex++;\n\t\t\tcontinue;\n\t\t}\n\n\t\tconst mappedEndCode = ansiStyles.codes.get(codeNumber);\n\t\tif (mappedEndCode !== undefined) {\n\t\t\tconst openCode = createSgrCode(sgrPrefix, [rawCodes[index]]);\n\t\t\tfragments.push({\n\t\t\t\ttype: 'start',\n\t\t\t\tcode: openCode,\n\t\t\t\tendCode: ansiStyles.color.ansi(mappedEndCode),\n\t\t\t});\n\t\t\tindex++;\n\t\t\tcontinue;\n\t\t}\n\n\t\tconst openCode = createSgrCode(sgrPrefix, [rawCodes[index]]);\n\t\tfragments.push({\n\t\t\ttype: 'start',\n\t\t\tcode: openCode,\n\t\t\tendCode: ansiStyles.reset.open,\n\t\t});\n\t\tindex++;\n\t}\n\n\tif (fragments.length === 0) {\n\t\tfragments.push({type: 'reset'});\n\t}\n\n\treturn fragments;\n}\n\nfunction parseCsiCode(string, index) {\n\tconst escapeCodePoint = string.codePointAt(index);\n\tlet sequenceStartIndex;\n\n\tif (escapeCodePoint === ESCAPE_CODE_POINT) {\n\t\tif (string[index + 1] !== ANSI_CSI) {\n\t\t\treturn;\n\t\t}\n\n\t\tsequenceStartIndex = index + 2;\n\t} else if (escapeCodePoint === C1_CSI_CODE_POINT) {\n\t\tsequenceStartIndex = index + 1;\n\t} else {\n\t\treturn;\n\t}\n\n\tlet hasCanonicalSgrParameters = true;\n\tfor (let sequenceIndex = sequenceStartIndex; sequenceIndex < string.length; sequenceIndex++) {\n\t\tconst codePoint = string.codePointAt(sequenceIndex);\n\n\t\tif (isCsiFinalCharacter(codePoint)) {\n\t\t\tconst code = string.slice(index, sequenceIndex + 1);\n\t\t\tif (string[sequenceIndex] !== ANSI_SGR_TERMINATOR || !hasCanonicalSgrParameters) {\n\t\t\t\treturn createControlParseResult(code, sequenceIndex + 1);\n\t\t\t}\n\n\t\t\treturn {\n\t\t\t\ttoken: {\n\t\t\t\t\ttype: 'sgr',\n\t\t\t\t\tcode,\n\t\t\t\t\tfragments: getSgrFragments(code),\n\t\t\t\t},\n\t\t\t\tendIndex: sequenceIndex + 1,\n\t\t\t};\n\t\t}\n\n\t\tif (isCsiParameterCharacter(codePoint)) {\n\t\t\tif (!isSgrParameterCharacter(codePoint)) {\n\t\t\t\thasCanonicalSgrParameters = false;\n\t\t\t}\n\n\t\t\tcontinue;\n\t\t}\n\n\t\tif (isCsiIntermediateCharacter(codePoint)) {\n\t\t\thasCanonicalSgrParameters = false;\n\t\t\tcontinue;\n\t\t}\n\n\t\tconst endIndex = sequenceIndex;\n\t\treturn createControlParseResult(string.slice(index, endIndex), endIndex);\n\t}\n\n\treturn createControlParseResult(string.slice(index), string.length);\n}\n\nfunction parseHyperlinkCode(string, index) {\n\tlet hyperlinkPrefix;\n\tlet hyperlinkClose;\n\tconst codePoint = string.codePointAt(index);\n\n\tif (\n\t\tcodePoint === ESCAPE_CODE_POINT\n\t\t&& string.startsWith(ANSI_HYPERLINK_ESC_PREFIX, index)\n\t) {\n\t\thyperlinkPrefix = ANSI_HYPERLINK_ESC_PREFIX;\n\t\thyperlinkClose = ANSI_HYPERLINK_ESC_CLOSE;\n\t} else if (\n\t\tcodePoint === C1_OSC_CODE_POINT\n\t\t&& string.startsWith(ANSI_HYPERLINK_C1_PREFIX, index)\n\t) {\n\t\thyperlinkPrefix = ANSI_HYPERLINK_C1_PREFIX;\n\t\thyperlinkClose = ANSI_HYPERLINK_C1_CLOSE;\n\t} else {\n\t\treturn;\n\t}\n\n\tconst uriStart = string.indexOf(';', index + hyperlinkPrefix.length);\n\tif (uriStart === -1) {\n\t\treturn createControlParseResult(string.slice(index), string.length);\n\t}\n\n\tfor (let sequenceIndex = uriStart + 1; sequenceIndex < string.length; sequenceIndex++) {\n\t\tconst character = string[sequenceIndex];\n\n\t\tif (character === ANSI_BELL) {\n\t\t\tconst code = string.slice(index, sequenceIndex + 1);\n\t\t\tconst action = sequenceIndex === uriStart + 1 ? 'close' : 'open';\n\t\t\treturn {\n\t\t\t\ttoken: {\n\t\t\t\t\ttype: 'hyperlink',\n\t\t\t\t\tcode,\n\t\t\t\t\taction,\n\t\t\t\t\tclosePrefix: hyperlinkClose,\n\t\t\t\t\tterminator: ANSI_BELL,\n\t\t\t\t},\n\t\t\t\tendIndex: sequenceIndex + 1,\n\t\t\t};\n\t\t}\n\n\t\tif (\n\t\t\tcharacter === ESCAPE\n\t\t\t&& string[sequenceIndex + 1] === ANSI_OSC_TERMINATOR\n\t\t) {\n\t\t\tconst code = string.slice(index, sequenceIndex + 2);\n\t\t\tconst action = sequenceIndex === uriStart + 1 ? 'close' : 'open';\n\t\t\treturn {\n\t\t\t\ttoken: {\n\t\t\t\t\ttype: 'hyperlink',\n\t\t\t\t\tcode,\n\t\t\t\t\taction,\n\t\t\t\t\tclosePrefix: hyperlinkClose,\n\t\t\t\t\tterminator: ANSI_STRING_TERMINATOR,\n\t\t\t\t},\n\t\t\t\tendIndex: sequenceIndex + 2,\n\t\t\t};\n\t\t}\n\n\t\tif (character === C1_STRING_TERMINATOR) {\n\t\t\tconst code = string.slice(index, sequenceIndex + 1);\n\t\t\tconst action = sequenceIndex === uriStart + 1 ? 'close' : 'open';\n\t\t\treturn {\n\t\t\t\ttoken: {\n\t\t\t\t\ttype: 'hyperlink',\n\t\t\t\t\tcode,\n\t\t\t\t\taction,\n\t\t\t\t\tclosePrefix: hyperlinkClose,\n\t\t\t\t\tterminator: C1_STRING_TERMINATOR,\n\t\t\t\t},\n\t\t\t\tendIndex: sequenceIndex + 1,\n\t\t\t};\n\t\t}\n\t}\n\n\treturn createControlParseResult(string.slice(index), string.length);\n}\n\nfunction parseControlStringCode(string, index) {\n\tconst codePoint = string.codePointAt(index);\n\tlet sequenceStartIndex;\n\tlet supportsBellTerminator = false;\n\n\tswitch (codePoint) {\n\t\tcase ESCAPE_CODE_POINT: {\n\t\t\tconst command = string[index + 1];\n\t\t\tswitch (command) {\n\t\t\t\tcase ANSI_OSC: {\n\t\t\t\t\t// OSC accepts ST (ECMA-48) and BEL (xterm compatibility extension).\n\t\t\t\t\tsequenceStartIndex = index + 2;\n\t\t\t\t\tsupportsBellTerminator = true;\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\n\t\t\t\tcase ANSI_DCS:\n\t\t\t\tcase ANSI_SOS:\n\t\t\t\tcase ANSI_PM:\n\t\t\t\tcase ANSI_APC: {\n\t\t\t\t\tsequenceStartIndex = index + 2;\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\n\t\t\t\tcase ANSI_OSC_TERMINATOR: {\n\t\t\t\t\treturn createControlParseResult(ANSI_STRING_TERMINATOR, index + 2);\n\t\t\t\t}\n\n\t\t\t\tdefault: {\n\t\t\t\t\treturn;\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tbreak;\n\t\t}\n\n\t\tcase C1_OSC_CODE_POINT: {\n\t\t\tsequenceStartIndex = index + 1;\n\t\t\tsupportsBellTerminator = true;\n\t\t\tbreak;\n\t\t}\n\n\t\tcase C1_DCS_CODE_POINT:\n\t\tcase C1_SOS_CODE_POINT:\n\t\tcase C1_PM_CODE_POINT:\n\t\tcase C1_APC_CODE_POINT: {\n\t\t\tsequenceStartIndex = index + 1;\n\t\t\tbreak;\n\t\t}\n\n\t\tcase C1_ST_CODE_POINT: {\n\t\t\treturn createControlParseResult(C1_STRING_TERMINATOR, index + 1);\n\t\t}\n\n\t\tdefault: {\n\t\t\treturn;\n\t\t}\n\t}\n\n\tfor (let sequenceIndex = sequenceStartIndex; sequenceIndex < string.length; sequenceIndex++) {\n\t\tif (supportsBellTerminator && string[sequenceIndex] === ANSI_BELL) {\n\t\t\treturn createControlParseResult(string.slice(index, sequenceIndex + 1), sequenceIndex + 1);\n\t\t}\n\n\t\tif (\n\t\t\tstring[sequenceIndex] === ESCAPE\n\t\t\t&& string[sequenceIndex + 1] === ANSI_OSC_TERMINATOR\n\t\t) {\n\t\t\treturn createControlParseResult(string.slice(index, sequenceIndex + 2), sequenceIndex + 2);\n\t\t}\n\n\t\tif (string[sequenceIndex] === C1_STRING_TERMINATOR) {\n\t\t\treturn createControlParseResult(string.slice(index, sequenceIndex + 1), sequenceIndex + 1);\n\t\t}\n\t}\n\n\treturn createControlParseResult(string.slice(index), string.length);\n}\n\nfunction parseAnsiCode(string, index) {\n\tconst codePoint = string.codePointAt(index);\n\tif (codePoint === ESCAPE_CODE_POINT || codePoint === C1_OSC_CODE_POINT) {\n\t\tconst hyperlinkCode = parseHyperlinkCode(string, index);\n\t\tif (hyperlinkCode) {\n\t\t\treturn hyperlinkCode;\n\t\t}\n\t}\n\n\tconst controlStringCode = parseControlStringCode(string, index);\n\tif (controlStringCode) {\n\t\treturn controlStringCode;\n\t}\n\n\treturn parseCsiCode(string, index);\n}\n\nfunction appendTrailingAnsiTokens(string, index, tokens) {\n\twhile (index < string.length) {\n\t\tconst nextCodePoint = string.codePointAt(index);\n\t\tif (!ESCAPES.has(nextCodePoint)) {\n\t\t\tbreak;\n\t\t}\n\n\t\tconst escapeCode = parseAnsiCode(string, index);\n\t\tif (!escapeCode) {\n\t\t\tbreak;\n\t\t}\n\n\t\ttokens.push(escapeCode.token);\n\t\tindex = escapeCode.endIndex;\n\t}\n\n\treturn index;\n}\n\nfunction parseCharacterTokenWithRawSegmentation(string, index, graphemeSegments) {\n\tconst segment = graphemeSegments.containing(index);\n\tif (!segment || segment.index !== index) {\n\t\treturn;\n\t}\n\n\treturn {\n\t\ttoken: {\n\t\t\ttype: 'character',\n\t\t\t// Intentionally preserve UAX29 behavior (GB3): CRLF is one grapheme cluster.\n\t\t\tvalue: segment.segment,\n\t\t\tvisibleWidth: getGraphemeWidth(segment.segment),\n\t\t\tisGraphemeContinuation: false,\n\t\t},\n\t\tendIndex: index + segment.segment.length,\n\t};\n}\n\nfunction collectVisibleCharacters(string) {\n\tconst visibleCharacters = [];\n\tlet index = 0;\n\n\twhile (index < string.length) {\n\t\tconst codePoint = string.codePointAt(index);\n\t\tif (ESCAPES.has(codePoint)) {\n\t\t\tconst code = parseAnsiCode(string, index);\n\t\t\tif (code) {\n\t\t\t\tindex = code.endIndex;\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t}\n\n\t\tconst value = String.fromCodePoint(codePoint);\n\t\tvisibleCharacters.push({\n\t\t\tvalue,\n\t\t\tvisibleWidth: 1,\n\t\t\tisGraphemeContinuation: false,\n\t\t});\n\t\tindex += value.length;\n\t}\n\n\treturn visibleCharacters;\n}\n\nfunction applyGraphemeMetadata(visibleCharacters) {\n\tif (visibleCharacters.length === 0) {\n\t\treturn;\n\t}\n\n\tconst visibleString = visibleCharacters.map(({value}) => value).join('');\n\tconst scalarOffsets = [];\n\tlet scalarOffset = 0;\n\n\tfor (const visibleCharacter of visibleCharacters) {\n\t\tscalarOffsets.push(scalarOffset);\n\t\tscalarOffset += visibleCharacter.value.length;\n\t}\n\n\tlet scalarIndex = 0;\n\tfor (const segment of GRAPHEME_SEGMENTER.segment(visibleString)) {\n\t\twhile (\n\t\t\tscalarIndex < visibleCharacters.length\n\t\t\t&& scalarOffsets[scalarIndex] < segment.index\n\t\t) {\n\t\t\tscalarIndex++;\n\t\t}\n\n\t\tlet graphemeIndex = scalarIndex;\n\t\tlet isFirstInGrapheme = true;\n\t\twhile (\n\t\t\tgraphemeIndex < visibleCharacters.length\n\t\t\t&& scalarOffsets[graphemeIndex] < segment.index + segment.segment.length\n\t\t) {\n\t\t\tvisibleCharacters[graphemeIndex].visibleWidth = isFirstInGrapheme ? getGraphemeWidth(segment.segment) : 0;\n\t\t\tvisibleCharacters[graphemeIndex].isGraphemeContinuation = !isFirstInGrapheme;\n\t\t\tisFirstInGrapheme = false;\n\t\t\tgraphemeIndex++;\n\t\t}\n\n\t\tscalarIndex = graphemeIndex;\n\t}\n}\n\nfunction tokenizeAnsiWithVisibleSegmentation(string, {endCharacter = Number.POSITIVE_INFINITY} = {}) {\n\tconst tokens = [];\n\tconst visibleCharacters = collectVisibleCharacters(string);\n\tapplyGraphemeMetadata(visibleCharacters);\n\n\tlet index = 0;\n\tlet visibleCharacterIndex = 0;\n\tlet visibleCount = 0;\n\twhile (index < string.length) {\n\t\tconst codePoint = string.codePointAt(index);\n\n\t\tif (ESCAPES.has(codePoint)) {\n\t\t\tconst code = parseAnsiCode(string, index);\n\t\t\tif (code) {\n\t\t\t\ttokens.push(code.token);\n\t\t\t\tindex = code.endIndex;\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t}\n\n\t\tconst value = String.fromCodePoint(codePoint);\n\t\tconst visibleCharacter = visibleCharacters[visibleCharacterIndex];\n\t\tlet visibleWidth = isFullwidthCodePoint(codePoint) ? 2 : value.length;\n\t\tif (visibleCharacter) {\n\t\t\tvisibleWidth = visibleCharacter.visibleWidth;\n\t\t}\n\n\t\tconst token = {\n\t\t\ttype: 'character',\n\t\t\tvalue,\n\t\t\tvisibleWidth,\n\t\t\tisGraphemeContinuation: visibleCharacter ? visibleCharacter.isGraphemeContinuation : false,\n\t\t};\n\n\t\ttokens.push(token);\n\t\tindex += value.length;\n\t\tvisibleCharacterIndex++;\n\t\tvisibleCount += token.visibleWidth;\n\n\t\tif (visibleCount >= endCharacter) {\n\t\t\tconst nextVisibleCharacter = visibleCharacters[visibleCharacterIndex];\n\t\t\tif (\n\t\t\t\t!nextVisibleCharacter\n\t\t\t\t|| !nextVisibleCharacter.isGraphemeContinuation\n\t\t\t) {\n\t\t\t\tindex = appendTrailingAnsiTokens(string, index, tokens);\n\t\t\t\tbreak;\n\t\t\t}\n\t\t}\n\t}\n\n\treturn tokens;\n}\n\nfunction areValuesInSameGrapheme(leftValue, rightValue) {\n\tconst pair = `${leftValue}${rightValue}`;\n\tconst splitIndex = leftValue.length;\n\n\tfor (const segment of GRAPHEME_SEGMENTER.segment(pair)) {\n\t\tif (segment.index === splitIndex) {\n\t\t\treturn false;\n\t\t}\n\n\t\tif (segment.index > splitIndex) {\n\t\t\treturn true;\n\t\t}\n\t}\n\n\treturn true;\n}\n\nfunction hasAnsiSplitContinuationAhead(string, startIndex, previousVisibleValue, graphemeSegments) {\n\tif (!previousVisibleValue) {\n\t\treturn false;\n\t}\n\n\tlet index = startIndex;\n\tlet hasAnsiCode = false;\n\twhile (index < string.length) {\n\t\tconst codePoint = string.codePointAt(index);\n\t\tif (ESCAPES.has(codePoint)) {\n\t\t\tconst code = parseAnsiCode(string, index);\n\t\t\tif (code) {\n\t\t\t\thasAnsiCode = true;\n\t\t\t\tindex = code.endIndex;\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t}\n\n\t\tif (!hasAnsiCode) {\n\t\t\treturn false;\n\t\t}\n\n\t\tconst characterToken = parseCharacterTokenWithRawSegmentation(string, index, graphemeSegments);\n\t\tif (!characterToken) {\n\t\t\treturn true;\n\t\t}\n\n\t\treturn areValuesInSameGrapheme(previousVisibleValue, characterToken.token.value);\n\t}\n\n\treturn false;\n}\n\nexport default function tokenizeAnsi(string, {endCharacter = Number.POSITIVE_INFINITY} = {}) {\n\tconst tokens = [];\n\tconst graphemeSegments = GRAPHEME_SEGMENTER.segment(string);\n\n\tlet index = 0;\n\tlet visibleCount = 0;\n\tlet previousVisibleValue;\n\tlet hasAnsiSinceLastVisible = false;\n\twhile (index < string.length) {\n\t\tconst codePoint = string.codePointAt(index);\n\n\t\tif (ESCAPES.has(codePoint)) {\n\t\t\tconst code = parseAnsiCode(string, index);\n\t\t\tif (code) {\n\t\t\t\ttokens.push(code.token);\n\t\t\t\tindex = code.endIndex;\n\t\t\t\thasAnsiSinceLastVisible = true;\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t}\n\n\t\tconst characterToken = parseCharacterTokenWithRawSegmentation(string, index, graphemeSegments);\n\t\tif (!characterToken) {\n\t\t\treturn tokenizeAnsiWithVisibleSegmentation(string, {endCharacter});\n\t\t}\n\n\t\tif (\n\t\t\thasAnsiSinceLastVisible\n\t\t\t&& previousVisibleValue\n\t\t\t&& areValuesInSameGrapheme(previousVisibleValue, characterToken.token.value)\n\t\t) {\n\t\t\treturn tokenizeAnsiWithVisibleSegmentation(string, {endCharacter});\n\t\t}\n\n\t\ttokens.push(characterToken.token);\n\t\tindex = characterToken.endIndex;\n\t\tvisibleCount += characterToken.token.visibleWidth;\n\t\thasAnsiSinceLastVisible = false;\n\t\tpreviousVisibleValue = characterToken.token.value;\n\n\t\tif (visibleCount >= endCharacter) {\n\t\t\tif (hasAnsiSplitContinuationAhead(string, index, previousVisibleValue, graphemeSegments)) {\n\t\t\t\treturn tokenizeAnsiWithVisibleSegmentation(string, {endCharacter});\n\t\t\t}\n\n\t\t\tindex = appendTrailingAnsiTokens(string, index, tokens);\n\t\t\tbreak;\n\t\t}\n\t}\n\n\treturn tokens;\n}\n","import tokenizeAnsi from './tokenize-ansi.js';\n\nfunction applySgrFragments(activeStyles, fragments) {\n\tfor (const fragment of fragments) {\n\t\tswitch (fragment.type) {\n\t\t\tcase 'reset': {\n\t\t\t\tactiveStyles.clear();\n\t\t\t\tbreak;\n\t\t\t}\n\n\t\t\tcase 'end': {\n\t\t\t\tactiveStyles.delete(fragment.endCode);\n\t\t\t\tbreak;\n\t\t\t}\n\n\t\t\tcase 'start': {\n\t\t\t\tactiveStyles.delete(fragment.endCode);\n\t\t\t\tactiveStyles.set(fragment.endCode, fragment.code);\n\t\t\t\tbreak;\n\t\t\t}\n\n\t\t\tdefault: {\n\t\t\t\tbreak;\n\t\t\t}\n\t\t}\n\t}\n\n\treturn activeStyles;\n}\n\nfunction undoAnsiCodes(activeStyles) {\n\treturn [...activeStyles.keys()].reverse().join('');\n}\n\nfunction closeHyperlink(hyperlinkToken) {\n\treturn `${hyperlinkToken.closePrefix}${hyperlinkToken.terminator}`;\n}\n\nfunction shouldIncludeSgrAfterEnd(token, activeStyles) {\n\tlet hasStartFragment = false;\n\tlet hasClosingEffect = false;\n\n\tfor (const fragment of token.fragments) {\n\t\tif (fragment.type === 'start') {\n\t\t\thasStartFragment = true;\n\t\t\tcontinue;\n\t\t}\n\n\t\tif (fragment.type === 'reset' && activeStyles.size > 0) {\n\t\t\thasClosingEffect = true;\n\t\t\tcontinue;\n\t\t}\n\n\t\tif (fragment.type === 'end' && activeStyles.has(fragment.endCode)) {\n\t\t\thasClosingEffect = true;\n\t\t}\n\t}\n\n\treturn hasClosingEffect && !hasStartFragment;\n}\n\nfunction applySgrToken({token, isPastEnd, activeStyles, returnValue, include, activeHyperlink, position}) {\n\tif (isPastEnd && !shouldIncludeSgrAfterEnd(token, activeStyles)) {\n\t\treturn {\n\t\t\tactiveStyles,\n\t\t\tactiveHyperlink,\n\t\t\tposition,\n\t\t\treturnValue,\n\t\t\tinclude,\n\t\t};\n\t}\n\n\tactiveStyles = applySgrFragments(activeStyles, token.fragments);\n\tif (include) {\n\t\treturnValue += token.code;\n\t}\n\n\treturn {\n\t\tactiveStyles,\n\t\tactiveHyperlink,\n\t\tposition,\n\t\treturnValue,\n\t\tinclude,\n\t};\n}\n\nfunction applyHyperlinkToken({token, isPastEnd, activeStyles, activeHyperlink, position, returnValue, include}) {\n\tif (\n\t\tisPastEnd\n\t\t&& (\n\t\t\ttoken.action !== 'close'\n\t\t\t|| !activeHyperlink\n\t\t)\n\t) {\n\t\treturn {\n\t\t\tactiveStyles,\n\t\t\tactiveHyperlink,\n\t\t\tposition,\n\t\t\treturnValue,\n\t\t\tinclude,\n\t\t};\n\t}\n\n\tif (token.action === 'open') {\n\t\tactiveHyperlink = token;\n\t} else if (token.action === 'close') {\n\t\tactiveHyperlink = undefined;\n\t}\n\n\tif (include) {\n\t\treturnValue += token.code;\n\t}\n\n\treturn {\n\t\tactiveStyles,\n\t\tactiveHyperlink,\n\t\tposition,\n\t\treturnValue,\n\t\tinclude,\n\t};\n}\n\nfunction applyControlToken({token, isPastEnd, activeStyles, activeHyperlink, position, returnValue, include}) {\n\tif (!isPastEnd && include) {\n\t\treturnValue += token.code;\n\t}\n\n\treturn {\n\t\tactiveStyles,\n\t\tactiveHyperlink,\n\t\tposition,\n\t\treturnValue,\n\t\tinclude,\n\t};\n}\n\nfunction applyCharacterToken({token, start, activeStyles, activeHyperlink, position, returnValue, include}) {\n\tif (\n\t\t!include\n\t\t&& position >= start\n\t\t&& !token.isGraphemeContinuation\n\t) {\n\t\tinclude = true;\n\t\treturnValue = [...activeStyles.values()].join('');\n\t\tif (activeHyperlink) {\n\t\t\treturnValue += activeHyperlink.code;\n\t\t}\n\t}\n\n\tif (include) {\n\t\treturnValue += token.value;\n\t}\n\n\tposition += token.visibleWidth;\n\treturn {\n\t\tactiveStyles,\n\t\tactiveHyperlink,\n\t\tposition,\n\t\treturnValue,\n\t\tinclude,\n\t};\n}\n\nconst tokenHandlers = {\n\tsgr: applySgrToken,\n\thyperlink: applyHyperlinkToken,\n\tcontrol: applyControlToken,\n\tcharacter: applyCharacterToken,\n};\n\nfunction applyToken(parameters) {\n\tconst tokenHandler = tokenHandlers[parameters.token.type];\n\tif (!tokenHandler) {\n\t\tconst {\n\t\t\tactiveStyles,\n\t\t\tactiveHyperlink,\n\t\t\tposition,\n\t\t\treturnValue,\n\t\t\tinclude,\n\t\t} = parameters;\n\n\t\treturn {\n\t\t\tactiveStyles,\n\t\t\tactiveHyperlink,\n\t\t\tposition,\n\t\t\treturnValue,\n\t\t\tinclude,\n\t\t};\n\t}\n\n\treturn tokenHandler(parameters);\n}\n\nfunction createHasContinuationAheadMap(tokens) {\n\tconst hasContinuationAhead = Array.from({length: tokens.length}, () => false);\n\tlet nextCharacterIsContinuation = false;\n\n\tfor (let tokenIndex = tokens.length - 1; tokenIndex >= 0; tokenIndex--) {\n\t\tconst token = tokens[tokenIndex];\n\t\thasContinuationAhead[tokenIndex] = nextCharacterIsContinuation;\n\t\tif (token.type === 'character') {\n\t\t\tnextCharacterIsContinuation = Boolean(token.isGraphemeContinuation);\n\t\t}\n\t}\n\n\treturn hasContinuationAhead;\n}\n\nexport default function sliceAnsi(string, start, end) {\n\tconst tokens = tokenizeAnsi(string, {endCharacter: end});\n\tconst hasContinuationAhead = createHasContinuationAheadMap(tokens);\n\tlet activeStyles = new Map();\n\tlet activeHyperlink;\n\tlet position = 0;\n\tlet returnValue = '';\n\tlet include = false;\n\n\tfor (const [tokenIndex, token] of tokens.entries()) {\n\t\tlet isPastEnd = end !== undefined && position >= end;\n\t\tif (\n\t\t\tisPastEnd\n\t\t\t&& token.type !== 'character'\n\t\t\t&& hasContinuationAhead[tokenIndex]\n\t\t) {\n\t\t\tisPastEnd = false;\n\t\t}\n\n\t\tif (\n\t\t\tisPastEnd\n\t\t\t&& token.type === 'character'\n\t\t\t&& !token.isGraphemeContinuation\n\t\t) {\n\t\t\tbreak;\n\t\t}\n\n\t\t({activeStyles, activeHyperlink, position, returnValue, include} = applyToken({\n\t\t\ttoken,\n\t\t\tisPastEnd,\n\t\t\tstart,\n\t\t\tactiveStyles,\n\t\t\tactiveHyperlink,\n\t\t\tposition,\n\t\t\treturnValue,\n\t\t\tinclude,\n\t\t}));\n\t}\n\n\tif (!include) {\n\t\treturn '';\n\t}\n\n\tif (activeHyperlink) {\n\t\treturnValue += closeHyperlink(activeHyperlink);\n\t}\n\n\t// Disable active codes at the end\n\treturnValue += undoAnsiCodes(activeStyles);\n\n\treturn returnValue;\n}\n","import stripAnsi from 'strip-ansi';\nimport {eastAsianWidth} from 'get-east-asian-width';\n\n/**\nLogic:\n- Segment graphemes to match how terminals render clusters.\n- Width rules:\n\t1. Skip non-printing clusters (Default_Ignorable, Control, pure Mark, lone Surrogates). Tabs are ignored by design.\n\t2. RGI emoji clusters (\\p{RGI_Emoji}) are double-width.\n\t3. Minimally-qualified/unqualified emoji clusters (ZWJ sequences with 2+ Extended_Pictographic, or keycap sequences) are double-width.\n\t4. Otherwise use East Asian Width of the cluster's first visible code point, and add widths for trailing Halfwidth/Fullwidth Forms within the same cluster (e.g., dakuten/handakuten/prolonged sound mark).\n*/\n\nconst segmenter = new Intl.Segmenter();\n\n// Whole-cluster zero-width\nconst zeroWidthClusterRegex = /^(?:\\p{Default_Ignorable_Code_Point}|\\p{Control}|\\p{Format}|\\p{Mark}|\\p{Surrogate})+$/v;\n\n// Pick the base scalar if the cluster starts with Prepend/Format/Marks\nconst leadingNonPrintingRegex = /^[\\p{Default_Ignorable_Code_Point}\\p{Control}\\p{Format}\\p{Mark}\\p{Surrogate}]+/v;\n\n// RGI emoji sequences\nconst rgiEmojiRegex = /^\\p{RGI_Emoji}$/v;\n\n// Detect minimally-qualified/unqualified emoji sequences (missing VS16 but still render as double-width)\nconst unqualifiedKeycapRegex = /^[\\d#*]\\u20E3$/;\nconst extendedPictographicRegex = /\\p{Extended_Pictographic}/gu;\n\nfunction isDoubleWidthNonRgiEmojiSequence(segment) {\n\t// Real emoji clusters are < 30 chars; guard against pathological input\n\tif (segment.length > 50) {\n\t\treturn false;\n\t}\n\n\tif (unqualifiedKeycapRegex.test(segment)) {\n\t\treturn true;\n\t}\n\n\t// ZWJ sequences with 2+ Extended_Pictographic\n\tif (segment.includes('\\u200D')) {\n\t\tconst pictographics = segment.match(extendedPictographicRegex);\n\t\treturn pictographics !== null && pictographics.length >= 2;\n\t}\n\n\treturn false;\n}\n\nfunction baseVisible(segment) {\n\treturn segment.replace(leadingNonPrintingRegex, '');\n}\n\nfunction isZeroWidthCluster(segment) {\n\treturn zeroWidthClusterRegex.test(segment);\n}\n\nfunction trailingHalfwidthWidth(segment, eastAsianWidthOptions) {\n\tlet extra = 0;\n\tif (segment.length > 1) {\n\t\tfor (const char of segment.slice(1)) {\n\t\t\tif (char >= '\\uFF00' && char <= '\\uFFEF') {\n\t\t\t\textra += eastAsianWidth(char.codePointAt(0), eastAsianWidthOptions);\n\t\t\t}\n\t\t}\n\t}\n\n\treturn extra;\n}\n\nexport default function stringWidth(input, options = {}) {\n\tif (typeof input !== 'string' || input.length === 0) {\n\t\treturn 0;\n\t}\n\n\tconst {\n\t\tambiguousIsNarrow = true,\n\t\tcountAnsiEscapeCodes = false,\n\t} = options;\n\n\tlet string = input;\n\n\t// Avoid calling stripAnsi when there are no ANSI escape sequences (ESC = 0x1B, CSI = 0x9B)\n\tif (!countAnsiEscapeCodes && (string.includes('\\u001B') || string.includes('\\u009B'))) {\n\t\tstring = stripAnsi(string);\n\t}\n\n\tif (string.length === 0) {\n\t\treturn 0;\n\t}\n\n\t// Fast path: printable ASCII (0x20–0x7E) needs no segmenter, regex, or EAW lookup — width equals length.\n\tif (/^[\\u0020-\\u007E]*$/.test(string)) {\n\t\treturn string.length;\n\t}\n\n\tlet width = 0;\n\tconst eastAsianWidthOptions = {ambiguousAsWide: !ambiguousIsNarrow};\n\n\tfor (const {segment} of segmenter.segment(string)) {\n\t\t// Zero-width / non-printing clusters\n\t\tif (isZeroWidthCluster(segment)) {\n\t\t\tcontinue;\n\t\t}\n\n\t\t// Emoji width logic\n\t\tif (rgiEmojiRegex.test(segment) || isDoubleWidthNonRgiEmojiSequence(segment)) {\n\t\t\twidth += 2;\n\t\t\tcontinue;\n\t\t}\n\n\t\t// Everything else: EAW of the cluster’s first visible scalar\n\t\tconst codePoint = baseVisible(segment).codePointAt(0);\n\t\twidth += eastAsianWidth(codePoint, eastAsianWidthOptions);\n\n\t\t// Add width for trailing Halfwidth and Fullwidth Forms (e.g., ﾞ, ﾟ, ｰ)\n\t\twidth += trailingHalfwidthWidth(segment, eastAsianWidthOptions);\n\t}\n\n\treturn width;\n}\n","import sliceAnsi from 'slice-ansi';\nimport stringWidth from 'string-width';\n\nfunction getIndexOfNearestSpace(string, wantedIndex, shouldSearchRight) {\n\tif (string.charAt(wantedIndex) === ' ') {\n\t\treturn wantedIndex;\n\t}\n\n\tconst direction = shouldSearchRight ? 1 : -1;\n\n\tfor (let index = 0; index <= 3; index++) {\n\t\tconst finalIndex = wantedIndex + (index * direction);\n\t\tif (string.charAt(finalIndex) === ' ') {\n\t\t\treturn finalIndex;\n\t\t}\n\t}\n\n\treturn wantedIndex;\n}\n\nexport default function cliTruncate(text, columns, options = {}) {\n\tconst {\n\t\tposition = 'end',\n\t\tspace = false,\n\t\tpreferTruncationOnSpace = false,\n\t} = options;\n\n\tlet {truncationCharacter = '…'} = options;\n\n\tif (typeof text !== 'string') {\n\t\tthrow new TypeError(`Expected \\`input\\` to be a string, got ${typeof text}`);\n\t}\n\n\tif (typeof columns !== 'number') {\n\t\tthrow new TypeError(`Expected \\`columns\\` to be a number, got ${typeof columns}`);\n\t}\n\n\tif (columns < 1) {\n\t\treturn '';\n\t}\n\n\tconst length = stringWidth(text);\n\n\tif (length <= columns) {\n\t\treturn text;\n\t}\n\n\tif (columns === 1) {\n\t\treturn truncationCharacter;\n\t}\n\n\t// ANSI escape sequence constants\n\tconst ANSI = {\n\t\tESC: 27,\n\t\tLEFT_BRACKET: 91,\n\t\tLETTER_M: 109,\n\t};\n\n\tconst isSgrParameter = code => (code >= 48 && code <= 57) || code === 59; // 0-9 or ;\n\n\tfunction leadingSgrSpanEndIndex(string) {\n\t\tlet index = 0;\n\t\twhile (index + 2 < string.length && string.codePointAt(index) === ANSI.ESC && string.codePointAt(index + 1) === ANSI.LEFT_BRACKET) {\n\t\t\tlet j = index + 2;\n\t\t\twhile (j < string.length && isSgrParameter(string.codePointAt(j))) {\n\t\t\t\tj++;\n\t\t\t}\n\n\t\t\tif (j < string.length && string.codePointAt(j) === ANSI.LETTER_M) {\n\t\t\t\tindex = j + 1;\n\t\t\t\tcontinue;\n\t\t\t}\n\n\t\t\tbreak;\n\t\t}\n\n\t\treturn index;\n\t}\n\n\tfunction trailingSgrSpanStartIndex(string) {\n\t\tlet start = string.length;\n\t\twhile (start > 1 && string.codePointAt(start - 1) === ANSI.LETTER_M) {\n\t\t\tlet j = start - 2;\n\t\t\twhile (j >= 0 && isSgrParameter(string.codePointAt(j))) {\n\t\t\t\tj--;\n\t\t\t}\n\n\t\t\tif (j >= 1 && string.codePointAt(j - 1) === ANSI.ESC && string.codePointAt(j) === ANSI.LEFT_BRACKET) {\n\t\t\t\tstart = j - 1;\n\t\t\t\tcontinue;\n\t\t\t}\n\n\t\t\tbreak;\n\t\t}\n\n\t\treturn start;\n\t}\n\n\tfunction appendWithInheritedStyleFromEnd(visible, suffix) {\n\t\tconst start = trailingSgrSpanStartIndex(visible);\n\t\tif (start === visible.length) {\n\t\t\treturn visible + suffix;\n\t\t}\n\n\t\treturn visible.slice(0, start) + suffix + visible.slice(start);\n\t}\n\n\tfunction prependWithInheritedStyleFromStart(prefix, visible) {\n\t\tconst end = leadingSgrSpanEndIndex(visible);\n\t\tif (end === 0) {\n\t\t\treturn prefix + visible;\n\t\t}\n\n\t\treturn visible.slice(0, end) + prefix + visible.slice(end);\n\t}\n\n\tif (position === 'start') {\n\t\tif (preferTruncationOnSpace) {\n\t\t\tconst nearestSpace = getIndexOfNearestSpace(text, length - columns + 1, true);\n\t\t\tconst right = sliceAnsi(text, nearestSpace, length).trim();\n\t\t\treturn prependWithInheritedStyleFromStart(truncationCharacter, right);\n\t\t}\n\n\t\tif (space) {\n\t\t\ttruncationCharacter += ' ';\n\t\t}\n\n\t\tconst right = sliceAnsi(text, length - columns + stringWidth(truncationCharacter), length);\n\t\treturn prependWithInheritedStyleFromStart(truncationCharacter, right);\n\t}\n\n\tif (position === 'middle') {\n\t\tif (space) {\n\t\t\ttruncationCharacter = ` ${truncationCharacter} `;\n\t\t}\n\n\t\tconst half = Math.floor(columns / 2);\n\n\t\tif (preferTruncationOnSpace) {\n\t\t\tconst spaceNearFirstBreakPoint = getIndexOfNearestSpace(text, half);\n\t\t\tconst spaceNearSecondBreakPoint = getIndexOfNearestSpace(text, length - (columns - half) + 1, true);\n\t\t\treturn sliceAnsi(text, 0, spaceNearFirstBreakPoint) + truncationCharacter + sliceAnsi(text, spaceNearSecondBreakPoint, length).trim();\n\t\t}\n\n\t\treturn (\n\t\t\tsliceAnsi(text, 0, half)\n\t\t\t+ truncationCharacter\n\t\t\t+ sliceAnsi(text, length - (columns - half) + stringWidth(truncationCharacter), length)\n\t\t);\n\t}\n\n\tif (position === 'end') {\n\t\tif (preferTruncationOnSpace) {\n\t\t\tconst nearestSpace = getIndexOfNearestSpace(text, columns - 1);\n\t\t\tconst left = sliceAnsi(text, 0, nearestSpace);\n\t\t\treturn appendWithInheritedStyleFromEnd(left, truncationCharacter);\n\t\t}\n\n\t\tif (space) {\n\t\t\ttruncationCharacter = ` ${truncationCharacter}`;\n\t\t}\n\n\t\tconst left = sliceAnsi(text, 0, columns - stringWidth(truncationCharacter));\n\t\treturn appendWithInheritedStyleFromEnd(left, truncationCharacter);\n\t}\n\n\tthrow new Error(`Expected \\`options.position\\` to be either \\`start\\`, \\`middle\\` or \\`end\\`, got ${position}`);\n}\n","import stripAnsi from 'strip-ansi';\nimport {eastAsianWidth} from 'get-east-asian-width';\n\n/**\nLogic:\n- Segment graphemes to match how terminals render clusters.\n- Width rules:\n\t1. Skip non-printing clusters (Default_Ignorable, Control, pure Mark, lone Surrogates). Tabs are ignored by design.\n\t2. RGI emoji clusters (\\p{RGI_Emoji}) are double-width.\n\t3. Minimally-qualified/unqualified emoji clusters (ZWJ sequences with 2+ Extended_Pictographic, or keycap sequences) are double-width.\n\t4. Otherwise use East Asian Width of the cluster's first visible code point, and add widths for trailing Halfwidth/Fullwidth Forms within the same cluster (e.g., dakuten/handakuten/prolonged sound mark).\n*/\n\nconst segmenter = new Intl.Segmenter();\n\n// Whole-cluster zero-width\nconst zeroWidthClusterRegex = /^(?:\\p{Default_Ignorable_Code_Point}|\\p{Control}|\\p{Format}|\\p{Mark}|\\p{Surrogate})+$/v;\n\n// Pick the base scalar if the cluster starts with Prepend/Format/Marks\nconst leadingNonPrintingRegex = /^[\\p{Default_Ignorable_Code_Point}\\p{Control}\\p{Format}\\p{Mark}\\p{Surrogate}]+/v;\n\n// RGI emoji sequences\nconst rgiEmojiRegex = /^\\p{RGI_Emoji}$/v;\n\n// Detect minimally-qualified/unqualified emoji sequences (missing VS16 but still render as double-width)\nconst unqualifiedKeycapRegex = /^[\\d#*]\\u20E3$/;\nconst extendedPictographicRegex = /\\p{Extended_Pictographic}/gu;\n\nfunction isDoubleWidthNonRgiEmojiSequence(segment) {\n\t// Real emoji clusters are < 30 chars; guard against pathological input\n\tif (segment.length > 50) {\n\t\treturn false;\n\t}\n\n\tif (unqualifiedKeycapRegex.test(segment)) {\n\t\treturn true;\n\t}\n\n\t// ZWJ sequences with 2+ Extended_Pictographic\n\tif (segment.includes('\\u200D')) {\n\t\tconst pictographics = segment.match(extendedPictographicRegex);\n\t\treturn pictographics !== null && pictographics.length >= 2;\n\t}\n\n\treturn false;\n}\n\nfunction baseVisible(segment) {\n\treturn segment.replace(leadingNonPrintingRegex, '');\n}\n\nfunction isZeroWidthCluster(segment) {\n\treturn zeroWidthClusterRegex.test(segment);\n}\n\nfunction trailingHalfwidthWidth(segment, eastAsianWidthOptions) {\n\tlet extra = 0;\n\tif (segment.length > 1) {\n\t\tfor (const char of segment.slice(1)) {\n\t\t\tif (char >= '\\uFF00' && char <= '\\uFFEF') {\n\t\t\t\textra += eastAsianWidth(char.codePointAt(0), eastAsianWidthOptions);\n\t\t\t}\n\t\t}\n\t}\n\n\treturn extra;\n}\n\nexport default function stringWidth(input, options = {}) {\n\tif (typeof input !== 'string' || input.length === 0) {\n\t\treturn 0;\n\t}\n\n\tconst {\n\t\tambiguousIsNarrow = true,\n\t\tcountAnsiEscapeCodes = false,\n\t} = options;\n\n\tlet string = input;\n\n\t// Avoid calling stripAnsi when there are no ANSI escape sequences (ESC = 0x1B, CSI = 0x9B)\n\tif (!countAnsiEscapeCodes && (string.includes('\\u001B') || string.includes('\\u009B'))) {\n\t\tstring = stripAnsi(string);\n\t}\n\n\tif (string.length === 0) {\n\t\treturn 0;\n\t}\n\n\t// Fast path: printable ASCII (0x20–0x7E) needs no segmenter, regex, or EAW lookup — width equals length.\n\tif (/^[\\u0020-\\u007E]*$/.test(string)) {\n\t\treturn string.length;\n\t}\n\n\tlet width = 0;\n\tconst eastAsianWidthOptions = {ambiguousAsWide: !ambiguousIsNarrow};\n\n\tfor (const {segment} of segmenter.segment(string)) {\n\t\t// Zero-width / non-printing clusters\n\t\tif (isZeroWidthCluster(segment)) {\n\t\t\tcontinue;\n\t\t}\n\n\t\t// Emoji width logic\n\t\tif (rgiEmojiRegex.test(segment) || isDoubleWidthNonRgiEmojiSequence(segment)) {\n\t\t\twidth += 2;\n\t\t\tcontinue;\n\t\t}\n\n\t\t// Everything else: EAW of the cluster’s first visible scalar\n\t\tconst codePoint = baseVisible(segment).codePointAt(0);\n\t\twidth += eastAsianWidth(codePoint, eastAsianWidthOptions);\n\n\t\t// Add width for trailing Halfwidth and Fullwidth Forms (e.g., ﾞ, ﾟ, ｰ)\n\t\twidth += trailingHalfwidthWidth(segment, eastAsianWidthOptions);\n\t}\n\n\treturn width;\n}\n","import stringWidth from 'string-width';\nimport stripAnsi from 'strip-ansi';\nimport ansiStyles from 'ansi-styles';\n\nconst ANSI_ESCAPE = '\\u001B';\nconst ANSI_ESCAPE_CSI = '\\u009B';\nconst ESCAPES = new Set([\n\tANSI_ESCAPE,\n\tANSI_ESCAPE_CSI,\n]);\n\nconst ANSI_ESCAPE_BELL = '\\u0007';\nconst ANSI_CSI = '[';\nconst ANSI_OSC = ']';\nconst ANSI_SGR_TERMINATOR = 'm';\nconst ANSI_SGR_RESET = 0;\nconst ANSI_SGR_RESET_FOREGROUND = 39;\nconst ANSI_SGR_RESET_BACKGROUND = 49;\nconst ANSI_SGR_RESET_UNDERLINE_COLOR = 59;\nconst ANSI_SGR_FOREGROUND_EXTENDED = 38;\nconst ANSI_SGR_BACKGROUND_EXTENDED = 48;\nconst ANSI_SGR_UNDERLINE_COLOR_EXTENDED = 58;\nconst ANSI_SGR_COLOR_MODE_256 = 5;\nconst ANSI_SGR_COLOR_MODE_RGB = 2;\nconst ANSI_ESCAPE_LINK = `${ANSI_OSC}8;;`;\nconst ANSI_ESCAPE_REGEX = new RegExp(`^\\\\u001B(?:\\\\${ANSI_CSI}(?<sgr>[0-9;]*)${ANSI_SGR_TERMINATOR}|${ANSI_ESCAPE_LINK}(?<uri>[^\\\\u0007\\\\u001B]*)(?:\\\\u0007|\\\\u001B\\\\\\\\))`);\nconst ANSI_ESCAPE_CSI_REGEX = new RegExp(`^\\\\u009B(?<sgr>[0-9;]*)${ANSI_SGR_TERMINATOR}`);\nconst ANSI_SGR_MODIFIER_CLOSE_CODES = new Set(ansiStyles.codes.values());\nANSI_SGR_MODIFIER_CLOSE_CODES.delete(ANSI_SGR_RESET);\n\nconst segmenter = new Intl.Segmenter();\nconst getGraphemes = string => Array.from(segmenter.segment(string), ({segment}) => segment);\nconst TAB_SIZE = 8;\n\nconst wrapAnsiCode = code => `${ANSI_ESCAPE}${ANSI_CSI}${code}${ANSI_SGR_TERMINATOR}`;\nconst wrapAnsiHyperlink = url => `${ANSI_ESCAPE}${ANSI_ESCAPE_LINK}${url}${ANSI_ESCAPE_BELL}`;\n\nconst getSgrTokens = sgrParameters => {\n\tconst codes = sgrParameters.split(';').map(sgrParameter => sgrParameter === '' ? ANSI_SGR_RESET : Number.parseInt(sgrParameter, 10));\n\tconst sgrTokens = [];\n\n\tfor (let index = 0; index < codes.length; index++) {\n\t\tconst code = codes[index];\n\n\t\tif (!Number.isFinite(code)) {\n\t\t\tcontinue;\n\t\t}\n\n\t\tif (\n\t\t\t(\n\t\t\t\tcode === ANSI_SGR_FOREGROUND_EXTENDED\n\t\t\t\t|| code === ANSI_SGR_BACKGROUND_EXTENDED\n\t\t\t\t|| code === ANSI_SGR_UNDERLINE_COLOR_EXTENDED\n\t\t\t)\n\t\t) {\n\t\t\tif (index + 1 >= codes.length) {\n\t\t\t\tbreak;\n\t\t\t}\n\n\t\t\tconst mode = codes[index + 1];\n\n\t\t\tif (mode === ANSI_SGR_COLOR_MODE_256 && Number.isFinite(codes[index + 2])) {\n\t\t\t\tsgrTokens.push([code, mode, codes[index + 2]]);\n\t\t\t\tindex += 2;\n\t\t\t\tcontinue;\n\t\t\t}\n\n\t\t\tconst red = codes[index + 2];\n\t\t\tconst green = codes[index + 3];\n\t\t\tconst blue = codes[index + 4];\n\t\t\tif (\n\t\t\t\tmode === ANSI_SGR_COLOR_MODE_RGB\n\t\t\t\t&& Number.isFinite(red)\n\t\t\t\t&& Number.isFinite(green)\n\t\t\t\t&& Number.isFinite(blue)\n\t\t\t) {\n\t\t\t\tsgrTokens.push([code, mode, red, green, blue]);\n\t\t\t\tindex += 4;\n\t\t\t\tcontinue;\n\t\t\t}\n\n\t\t\tbreak;\n\t\t}\n\n\t\tsgrTokens.push([code]);\n\t}\n\n\treturn sgrTokens;\n};\n\nconst removeActiveStyle = (activeStyles, family) => {\n\tconst activeStyleIndex = activeStyles.findIndex(activeStyle => activeStyle.family === family);\n\n\tif (activeStyleIndex !== -1) {\n\t\tactiveStyles.splice(activeStyleIndex, 1);\n\t}\n};\n\nconst upsertActiveStyle = (activeStyles, nextActiveStyle) => {\n\tremoveActiveStyle(activeStyles, nextActiveStyle.family);\n\tactiveStyles.push(nextActiveStyle);\n};\n\nconst removeModifierStylesByClose = (activeStyles, closeCode) => {\n\tfor (let index = activeStyles.length - 1; index >= 0; index--) {\n\t\tconst activeStyle = activeStyles[index];\n\t\tif (activeStyle.family.startsWith('modifier-') && activeStyle.close === closeCode) {\n\t\t\tactiveStyles.splice(index, 1);\n\t\t}\n\t}\n};\n\nconst getColorStyle = (code, sgrToken) => {\n\tif ((code >= 30 && code <= 37) || (code >= 90 && code <= 97) || (code === ANSI_SGR_FOREGROUND_EXTENDED && sgrToken.length > 1)) {\n\t\treturn {\n\t\t\tfamily: 'foreground',\n\t\t\topen: sgrToken.join(';'),\n\t\t\tclose: ANSI_SGR_RESET_FOREGROUND,\n\t\t};\n\t}\n\n\tif ((code >= 40 && code <= 47) || (code >= 100 && code <= 107) || (code === ANSI_SGR_BACKGROUND_EXTENDED && sgrToken.length > 1)) {\n\t\treturn {\n\t\t\tfamily: 'background',\n\t\t\topen: sgrToken.join(';'),\n\t\t\tclose: ANSI_SGR_RESET_BACKGROUND,\n\t\t};\n\t}\n\n\tif (code === ANSI_SGR_UNDERLINE_COLOR_EXTENDED && sgrToken.length > 1) {\n\t\treturn {\n\t\t\tfamily: 'underlineColor',\n\t\t\topen: sgrToken.join(';'),\n\t\t\tclose: ANSI_SGR_RESET_UNDERLINE_COLOR,\n\t\t};\n\t}\n};\n\nconst applySgrResetCode = (code, activeStyles) => {\n\tif (code === ANSI_SGR_RESET) {\n\t\tactiveStyles.length = 0;\n\t\treturn true;\n\t}\n\n\tif (code === ANSI_SGR_RESET_FOREGROUND) {\n\t\tremoveActiveStyle(activeStyles, 'foreground');\n\t\treturn true;\n\t}\n\n\tif (code === ANSI_SGR_RESET_BACKGROUND) {\n\t\tremoveActiveStyle(activeStyles, 'background');\n\t\treturn true;\n\t}\n\n\tif (code === ANSI_SGR_RESET_UNDERLINE_COLOR) {\n\t\tremoveActiveStyle(activeStyles, 'underlineColor');\n\t\treturn true;\n\t}\n\n\tif (ANSI_SGR_MODIFIER_CLOSE_CODES.has(code)) {\n\t\tremoveModifierStylesByClose(activeStyles, code);\n\t\treturn true;\n\t}\n\n\treturn false;\n};\n\nconst applySgrToken = (sgrToken, activeStyles) => {\n\tconst [code] = sgrToken;\n\n\tif (applySgrResetCode(code, activeStyles)) {\n\t\treturn;\n\t}\n\n\tconst colorStyle = getColorStyle(code, sgrToken);\n\tif (colorStyle) {\n\t\tupsertActiveStyle(activeStyles, colorStyle);\n\t\treturn;\n\t}\n\n\tconst close = ansiStyles.codes.get(code);\n\tif (close !== undefined && close !== ANSI_SGR_RESET) {\n\t\tupsertActiveStyle(activeStyles, {\n\t\t\tfamily: `modifier-${code}`,\n\t\t\topen: sgrToken.join(';'),\n\t\t\tclose,\n\t\t});\n\t}\n};\n\nconst applySgrParameters = (sgrParameters, activeStyles) => {\n\tfor (const sgrToken of getSgrTokens(sgrParameters)) {\n\t\tapplySgrToken(sgrToken, activeStyles);\n\t}\n};\n\nconst applySgrResets = (sgrParameters, activeStyles) => {\n\tfor (const sgrToken of getSgrTokens(sgrParameters)) {\n\t\tconst [code] = sgrToken;\n\t\tapplySgrResetCode(code, activeStyles);\n\t}\n};\n\nconst applyLeadingSgrResets = (string, activeStyles) => {\n\tlet remainder = string;\n\n\twhile (remainder.length > 0) {\n\t\tif (remainder.startsWith(ANSI_ESCAPE) && remainder[1] !== '\\\\') {\n\t\t\tconst match = ANSI_ESCAPE_REGEX.exec(remainder);\n\t\t\tif (!match) {\n\t\t\t\tbreak;\n\t\t\t}\n\n\t\t\tif (match.groups.sgr !== undefined) {\n\t\t\t\tapplySgrResets(match.groups.sgr, activeStyles);\n\t\t\t}\n\n\t\t\tremainder = remainder.slice(match[0].length);\n\t\t\tcontinue;\n\t\t}\n\n\t\tif (remainder.startsWith(ANSI_ESCAPE_CSI)) {\n\t\t\tconst match = ANSI_ESCAPE_CSI_REGEX.exec(remainder);\n\t\t\tif (!match || match.groups.sgr === undefined) {\n\t\t\t\tbreak;\n\t\t\t}\n\n\t\t\tapplySgrResets(match.groups.sgr, activeStyles);\n\t\t\tremainder = remainder.slice(match[0].length);\n\t\t\tcontinue;\n\t\t}\n\n\t\tbreak;\n\t}\n};\n\nconst getClosingSgrSequence = activeStyles => [...activeStyles].reverse().map(activeStyle => wrapAnsiCode(activeStyle.close)).join('');\nconst getOpeningSgrSequence = activeStyles => activeStyles.map(activeStyle => wrapAnsiCode(activeStyle.open)).join('');\n\n// Calculate the length of words split on ' ', ignoring\n// the extra characters added by ANSI escape codes\nconst wordLengths = string => string.split(' ').map(word => stringWidth(word));\n\n// Wrap a long word across multiple rows\n// ANSI escape codes do not count towards length\nconst wrapWord = (rows, word, columns) => {\n\tconst characters = getGraphemes(word);\n\n\tlet isInsideEscape = false;\n\tlet isInsideLinkEscape = false;\n\tlet visible = stringWidth(stripAnsi(rows.at(-1)));\n\n\tfor (const [index, character] of characters.entries()) {\n\t\tconst characterLength = stringWidth(character);\n\n\t\tif (visible + characterLength <= columns) {\n\t\t\trows[rows.length - 1] += character;\n\t\t} else {\n\t\t\trows.push(character);\n\t\t\tvisible = 0;\n\t\t}\n\n\t\tif (ESCAPES.has(character) && !(isInsideLinkEscape && character === ANSI_ESCAPE && characters[index + 1] === '\\\\')) {\n\t\t\tisInsideEscape = true;\n\n\t\t\tconst ansiEscapeLinkCandidate = characters.slice(index + 1, index + 1 + ANSI_ESCAPE_LINK.length).join('');\n\t\t\tisInsideLinkEscape = ansiEscapeLinkCandidate === ANSI_ESCAPE_LINK;\n\t\t}\n\n\t\tif (isInsideEscape) {\n\t\t\tif (isInsideLinkEscape) {\n\t\t\t\tif (\n\t\t\t\t\tcharacter === ANSI_ESCAPE_BELL\n\t\t\t\t\t|| (character === '\\\\' && index > 0 && characters[index - 1] === ANSI_ESCAPE) // ST terminator (ESC \\)\n\t\t\t\t) {\n\t\t\t\t\tisInsideEscape = false;\n\t\t\t\t\tisInsideLinkEscape = false;\n\t\t\t\t}\n\t\t\t} else if (character === ANSI_SGR_TERMINATOR) {\n\t\t\t\tisInsideEscape = false;\n\t\t\t}\n\n\t\t\tcontinue;\n\t\t}\n\n\t\tvisible += characterLength;\n\n\t\tif (visible === columns && index < characters.length - 1) {\n\t\t\trows.push('');\n\t\t\tvisible = 0;\n\t\t}\n\t}\n\n\t// It's possible that the last row we copy over is only\n\t// ANSI escape characters, handle this edge-case\n\tif (!visible && rows.at(-1).length > 0 && rows.length > 1) {\n\t\trows[rows.length - 2] += rows.pop();\n\t}\n};\n\n// Trims spaces from a string ignoring invisible sequences\nconst stringVisibleTrimSpacesRight = string => {\n\tconst words = string.split(' ');\n\tlet last = words.length;\n\n\twhile (last > 0) {\n\t\tif (stringWidth(words[last - 1]) > 0) {\n\t\t\tbreak;\n\t\t}\n\n\t\tlast--;\n\t}\n\n\tif (last === words.length) {\n\t\treturn string;\n\t}\n\n\treturn words.slice(0, last).join(' ') + words.slice(last).join('');\n};\n\nconst expandTabs = line => {\n\tif (!line.includes('\\t')) {\n\t\treturn line;\n\t}\n\n\tconst segments = line.split('\\t');\n\tlet visible = 0;\n\tlet expandedLine = '';\n\n\tfor (const [index, segment] of segments.entries()) {\n\t\texpandedLine += segment;\n\t\tvisible += stringWidth(segment);\n\n\t\tif (index < segments.length - 1) {\n\t\t\tconst spaces = TAB_SIZE - (visible % TAB_SIZE);\n\t\t\texpandedLine += ' '.repeat(spaces);\n\t\t\tvisible += spaces;\n\t\t}\n\t}\n\n\treturn expandedLine;\n};\n\n// The wrap-ansi module can be invoked in either 'hard' or 'soft' wrap mode.\n//\n// 'hard' will never allow a string to take up more than columns characters.\n//\n// 'soft' allows long words to expand past the column length.\nconst exec = (string, columns, options = {}) => {\n\tif (options.trim !== false && string.trim() === '') {\n\t\treturn '';\n\t}\n\n\tlet returnValue = '';\n\tlet escapeUrl;\n\tconst activeStyles = [];\n\n\tconst lengths = wordLengths(string);\n\tlet rows = [''];\n\n\tfor (const [index, word] of string.split(' ').entries()) {\n\t\tif (options.trim !== false) {\n\t\t\trows[rows.length - 1] = rows.at(-1).trimStart();\n\t\t}\n\n\t\tlet rowLength = stringWidth(rows.at(-1));\n\n\t\tif (index !== 0) {\n\t\t\tif (rowLength >= columns && (options.wordWrap === false || options.trim === false)) {\n\t\t\t\t// If we start with a new word but the current row length equals the length of the columns, add a new row\n\t\t\t\trows.push('');\n\t\t\t\trowLength = 0;\n\t\t\t}\n\n\t\t\tif (rowLength > 0 || options.trim === false) {\n\t\t\t\trows[rows.length - 1] += ' ';\n\t\t\t\trowLength++;\n\t\t\t}\n\t\t}\n\n\t\t// In 'hard' wrap mode, the length of a line is never allowed to extend past 'columns'\n\t\tif (options.hard && options.wordWrap !== false && lengths[index] > columns) {\n\t\t\tconst remainingColumns = columns - rowLength;\n\t\t\tconst breaksStartingThisLine = 1 + Math.floor((lengths[index] - remainingColumns - 1) / columns);\n\t\t\tconst breaksStartingNextLine = Math.floor((lengths[index] - 1) / columns);\n\t\t\tif (breaksStartingNextLine < breaksStartingThisLine) {\n\t\t\t\trows.push('');\n\t\t\t}\n\n\t\t\twrapWord(rows, word, columns);\n\t\t\tcontinue;\n\t\t}\n\n\t\tif (rowLength + lengths[index] > columns && rowLength > 0 && lengths[index] > 0) {\n\t\t\tif (options.wordWrap === false && rowLength < columns) {\n\t\t\t\twrapWord(rows, word, columns);\n\t\t\t\tcontinue;\n\t\t\t}\n\n\t\t\trows.push('');\n\t\t}\n\n\t\tif (rowLength + lengths[index] > columns && options.wordWrap === false) {\n\t\t\twrapWord(rows, word, columns);\n\t\t\tcontinue;\n\t\t}\n\n\t\trows[rows.length - 1] += word;\n\t}\n\n\tif (options.trim !== false) {\n\t\trows = rows.map(row => stringVisibleTrimSpacesRight(row));\n\t}\n\n\tconst preString = rows.join('\\n');\n\tconst pre = getGraphemes(preString);\n\n\t// We need to keep a separate index as `String#slice()` works on Unicode code units, while `pre` is an array of grapheme clusters.\n\tlet preStringIndex = 0;\n\n\tfor (const [index, character] of pre.entries()) {\n\t\treturnValue += character;\n\n\t\tif (character === ANSI_ESCAPE && pre[index + 1] !== '\\\\') {\n\t\t\tconst {groups} = ANSI_ESCAPE_REGEX.exec(preString.slice(preStringIndex)) || {groups: {}};\n\t\t\tif (groups.sgr !== undefined) {\n\t\t\t\tapplySgrParameters(groups.sgr, activeStyles);\n\t\t\t} else if (groups.uri !== undefined) {\n\t\t\t\tescapeUrl = groups.uri.length === 0 ? undefined : groups.uri;\n\t\t\t}\n\t\t} else if (character === ANSI_ESCAPE_CSI) {\n\t\t\tconst {groups} = ANSI_ESCAPE_CSI_REGEX.exec(preString.slice(preStringIndex)) || {groups: {}};\n\t\t\tif (groups.sgr !== undefined) {\n\t\t\t\tapplySgrParameters(groups.sgr, activeStyles);\n\t\t\t}\n\t\t}\n\n\t\tif (pre[index + 1] === '\\n') {\n\t\t\tif (escapeUrl) {\n\t\t\t\treturnValue += wrapAnsiHyperlink('');\n\t\t\t}\n\n\t\t\treturnValue += getClosingSgrSequence(activeStyles);\n\t\t} else if (character === '\\n') {\n\t\t\tconst openingStyles = [...activeStyles];\n\t\t\tapplyLeadingSgrResets(preString.slice(preStringIndex + 1), openingStyles);\n\t\t\treturnValue += getOpeningSgrSequence(openingStyles);\n\n\t\t\tif (escapeUrl) {\n\t\t\t\treturnValue += wrapAnsiHyperlink(escapeUrl);\n\t\t\t}\n\t\t}\n\n\t\tpreStringIndex += character.length;\n\t}\n\n\treturn returnValue;\n};\n\n// For each newline, invoke the method separately\nexport default function wrapAnsi(string, columns, options) {\n\treturn String(string)\n\t\t.normalize()\n\t\t.replaceAll('\\r\\n', '\\n')\n\t\t.split('\\n')\n\t\t.map(line => exec(expandTabs(line), columns, options))\n\t\t.join('\\n');\n}\n","import EventEmitter from \"eventemitter3\";\nimport { inspect, styleText } from \"node:util\";\nimport { format } from \"util\";\nimport { EOL } from \"os\";\nimport { StringDecoder } from \"string_decoder\";\nimport { Writable } from \"stream\";\nimport rfdc from \"rfdc\";\nimport { randomUUID } from \"crypto\";\n\n//#region src/constants/ansi-escape-codes.constants.ts\n/**\n* Indicates an UNICODE characters is coming up.\n*/\nconst ANSI_ESCAPE = \"\\x1B[\";\n/**\n* Generic ANSI escape characters for terminal based operations.\n*/\nconst ANSI_ESCAPE_CODES = {\n\tCURSOR_HIDE: ANSI_ESCAPE + \"?25l\",\n\tCURSOR_SHOW: ANSI_ESCAPE + \"?25h\"\n};\n\n//#endregion\n//#region src/constants/environment-variables.constants.ts\n/**\n* Environment variables for Listr.\n*/\nlet ListrEnvironmentVariables = /* @__PURE__ */ function(ListrEnvironmentVariables) {\n\tListrEnvironmentVariables[\"FORCE_UNICODE\"] = \"LISTR_FORCE_UNICODE\";\n\tListrEnvironmentVariables[\"FORCE_TTY\"] = \"LISTR_FORCE_TTY\";\n\tListrEnvironmentVariables[\"DISABLE_COLOR\"] = \"NO_COLOR\";\n\tListrEnvironmentVariables[\"FORCE_COLOR\"] = \"FORCE_COLOR\";\n\treturn ListrEnvironmentVariables;\n}({});\n\n//#endregion\n//#region src/constants/listr-error.constants.ts\n/**\n* The actual error type that is collected and to help identify where the error is triggered from.\n*/\nlet ListrErrorTypes = /* @__PURE__ */ function(ListrErrorTypes) {\n\t/** Task has failed and will try to retry. */\n\tListrErrorTypes[\"WILL_RETRY\"] = \"WILL_RETRY\";\n\t/** Task has failed and will try to rollback. */\n\tListrErrorTypes[\"WILL_ROLLBACK\"] = \"WILL_ROLLBACK\";\n\t/** Task has failed, ran the rollback action but the rollback action itself has failed. */\n\tListrErrorTypes[\"HAS_FAILED_TO_ROLLBACK\"] = \"HAS_FAILED_TO_ROLLBACK\";\n\t/** Task has failed. */\n\tListrErrorTypes[\"HAS_FAILED\"] = \"HAS_FAILED\";\n\t/** Task has failed, but exitOnError is set to false, so will ignore this error. */\n\tListrErrorTypes[\"HAS_FAILED_WITHOUT_ERROR\"] = \"HAS_FAILED_WITHOUT_ERROR\";\n\treturn ListrErrorTypes;\n}({});\n\n//#endregion\n//#region src/constants/listr-events.constants.ts\n/**\n* Events that are triggered by Listr.\n*\n* These are stateful and singleton events by being attached to the main Listr class and propagating to the subtasks.\n*\n* @see {@link https://listr2.kilic.dev/listr/events.html}\n*/\nlet ListrEventType = /* @__PURE__ */ function(ListrEventType) {\n\t/** Indicates that underlying renderer should refresh the current render. */\n\tListrEventType[\"SHOULD_REFRESH_RENDER\"] = \"SHOUD_REFRESH_RENDER\";\n\treturn ListrEventType;\n}({});\n\n//#endregion\n//#region src/constants/listr-renderer.constants.ts\nlet ListrRendererSelection = /* @__PURE__ */ function(ListrRendererSelection) {\n\tListrRendererSelection[\"PRIMARY\"] = \"PRIMARY\";\n\tListrRendererSelection[\"SECONDARY\"] = \"SECONDARY\";\n\tListrRendererSelection[\"SILENT\"] = \"SILENT\";\n\treturn ListrRendererSelection;\n}({});\n\n//#endregion\n//#region src/constants/listr-task-events.constants.ts\n/**\n* Internal events that are fired from the Task.\n*\n* @see {@link https://listr2.kilic.dev/task/events.html}\n*/\nlet ListrTaskEventType = /* @__PURE__ */ function(ListrTaskEventType) {\n\t/** Title has changed for the current Task. */\n\tListrTaskEventType[\"TITLE\"] = \"TITLE\";\n\t/**\n\t* State has changed for the current Task.\n\t*\n\t* @see {@link module:listr2.ListrTaskState}\n\t*/\n\tListrTaskEventType[\"STATE\"] = \"STATE\";\n\t/** The current Task has been marked as enabled. */\n\tListrTaskEventType[\"ENABLED\"] = \"ENABLED\";\n\t/** The current Task is currently processing subtasks. */\n\tListrTaskEventType[\"SUBTASK\"] = \"SUBTASK\";\n\t/** The current Task is now processing a prompt. */\n\tListrTaskEventType[\"PROMPT\"] = \"PROMPT\";\n\t/** The current Task is now dumping output. */\n\tListrTaskEventType[\"OUTPUT\"] = \"OUTPUT\";\n\t/**\n\t* The current Task is now dumping a message.\n\t*\n\t* @see {module:Listr2.ListrTaskMessage}\n\t*/\n\tListrTaskEventType[\"MESSAGE\"] = \"MESSAGE\";\n\t/** The current Task is closed and no further action in expected. */\n\tListrTaskEventType[\"CLOSED\"] = \"CLOSED\";\n\treturn ListrTaskEventType;\n}({});\n\n//#endregion\n//#region src/constants/listr-task-state.constants.ts\n/**\n* Tasks can be in various states during the execution.\n*\n* Whenever a state change occurs, the task will emit a {@link module:listr2.ListrTaskEventType.STATE} with the appropriate state.\n*/\nlet ListrTaskState = /* @__PURE__ */ function(ListrTaskState) {\n\t/** Task has not started yet, waiting for pick-up. */\n\tListrTaskState[\"WAITING\"] = \"WAITING\";\n\t/** Task has started. */\n\tListrTaskState[\"STARTED\"] = \"STARTED\";\n\t/** Task has been completed. */\n\tListrTaskState[\"COMPLETED\"] = \"COMPLETED\";\n\t/** Task has failed. */\n\tListrTaskState[\"FAILED\"] = \"FAILED\";\n\t/** Task has been skipped. */\n\tListrTaskState[\"SKIPPED\"] = \"SKIPPED\";\n\t/** Task is currently trying to rollback. */\n\tListrTaskState[\"ROLLING_BACK\"] = \"ROLLING_BACK\";\n\t/** Task has rolledback successfully after failing. */\n\tListrTaskState[\"ROLLED_BACK\"] = \"ROLLED_BACK\";\n\t/** Task is currently retrying. */\n\tListrTaskState[\"RETRY\"] = \"RETRY\";\n\t/** Task is currently paused. */\n\tListrTaskState[\"PAUSED\"] = \"PAUSED\";\n\t/** Task is currently trying to process a prompt. */\n\tListrTaskState[\"PROMPT\"] = \"PROMPT\";\n\t/** Task has successfully processed the prompt. */\n\tListrTaskState[\"PROMPT_COMPLETED\"] = \"PROMPT_COMPLETED\";\n\t/** Task has failed to process the prompt. */\n\tListrTaskState[\"PROMPT_FAILED\"] = \"PROMPT_FAILED\";\n\treturn ListrTaskState;\n}({});\n\n//#endregion\n//#region src/lib/event-manager.ts\nvar EventManager = class {\n\temitter = new EventEmitter();\n\temit(dispatch, args) {\n\t\tthis.emitter.emit(dispatch, args);\n\t}\n\ton(dispatch, handler) {\n\t\tthis.emitter.addListener(dispatch, handler);\n\t}\n\tonce(dispatch, handler) {\n\t\tthis.emitter.once(dispatch, handler);\n\t}\n\toff(dispatch, handler) {\n\t\tthis.emitter.off(dispatch, handler);\n\t}\n\tcomplete() {\n\t\tthis.emitter.removeAllListeners();\n\t}\n};\n\n//#endregion\n//#region src/interfaces/event.interface.ts\n/**\n* Give event map a set of indexes to not make it go crazy when some events are missing from it.\n* They are optional after all.\n*/\nvar BaseEventMap = class {};\n\n//#endregion\n//#region src/utils/environment/is-observable.ts\n/**\n* Tests to see if the object is an RxJS {@link Observable}\n* @param obj the object to test\n*/\nfunction isObservable(obj) {\n\treturn !!obj && typeof obj === \"object\" && typeof obj.subscribe === \"function\";\n}\n\n//#endregion\n//#region src/utils/environment/is-readable.ts\n/**\n* Tests to see if the object is an Readable or NodeJS.ReadableStream {@link Readable, NodeJS.ReadableStream}\n* @param obj the object to test\n*/\nfunction isReadable(obj) {\n\treturn !!obj && typeof obj === \"object\" && obj.readable === true && typeof obj.read === \"function\" && typeof obj.on === \"function\";\n}\n\n//#endregion\n//#region src/utils/environment/is-unicode-supported.ts\nfunction isUnicodeSupported() {\n\t/* istanbul ignore next */\n\treturn !!process.env[ListrEnvironmentVariables.FORCE_UNICODE] || process.platform !== \"win32\" || !!process.env.CI || !!process.env.WT_SESSION || process.env.TERM_PROGRAM === \"vscode\" || process.env.TERM === \"xterm-256color\" || process.env.TERM === \"alacritty\";\n}\n\n//#endregion\n//#region src/utils/format/cleanse-ansi.constants.ts\nconst CLEAR_LINE_REGEX = \"(?:\\\\u001b|\\\\u009b)\\\\[[\\\\=><~/#&.:=?%@~_-]*[0-9]*[\\\\a-ln-tqyz=><~/#&.:=?%@~_-]+\";\nconst BELL_REGEX = /\\u0007/;\n\n//#endregion\n//#region src/utils/format/cleanse-ansi.ts\nfunction cleanseAnsi(chunk) {\n\treturn String(chunk).replace(new RegExp(CLEAR_LINE_REGEX, \"gmi\"), \"\").replace(new RegExp(BELL_REGEX, \"gmi\"), \"\").trim();\n}\n\n//#endregion\n//#region src/utils/format/color.ts\n/**\n* Color palette.\n*/\nconst color = Object.fromEntries(Object.keys(inspect.colors).map((color) => [color, (text) => styleText(color, String(text))]));\n\n//#endregion\n//#region src/utils/format/indent.ts\nfunction indent(string, count) {\n\treturn string.replace(/^(?!\\s*$)/gm, \" \".repeat(count));\n}\n\n//#endregion\n//#region src/utils/format/figures.ts\nconst FIGURES_MAIN = {\n\twarning: \"⚠\",\n\tcross: \"✖\",\n\tarrowDown: \"↓\",\n\ttick: \"✔\",\n\tarrowRight: \"→\",\n\tpointer: \"❯\",\n\tcheckboxOn: \"☒\",\n\tarrowLeft: \"←\",\n\tsquareSmallFilled: \"◼\",\n\tpointerSmall: \"›\"\n};\nconst FIGURES_FALLBACK = {\n\t...FIGURES_MAIN,\n\twarning: \"‼\",\n\tcross: \"×\",\n\ttick: \"√\",\n\tpointer: \">\",\n\tcheckboxOn: \"[×]\",\n\tsquareSmallFilled: \"■\"\n};\nconst figures = isUnicodeSupported() ? FIGURES_MAIN : FIGURES_FALLBACK;\n\n//#endregion\n//#region src/utils/format/splat.ts\nfunction splat(message, ...splat) {\n\treturn format(String(message), ...splat);\n}\n\n//#endregion\n//#region src/utils/logger/logger.constants.ts\n/** Default ListrLogLevels for the logger */\nlet ListrLogLevels = /* @__PURE__ */ function(ListrLogLevels) {\n\tListrLogLevels[\"STARTED\"] = \"STARTED\";\n\tListrLogLevels[\"COMPLETED\"] = \"COMPLETED\";\n\tListrLogLevels[\"FAILED\"] = \"FAILED\";\n\tListrLogLevels[\"SKIPPED\"] = \"SKIPPED\";\n\tListrLogLevels[\"OUTPUT\"] = \"OUTPUT\";\n\tListrLogLevels[\"TITLE\"] = \"TITLE\";\n\tListrLogLevels[\"ROLLBACK\"] = \"ROLLBACK\";\n\tListrLogLevels[\"RETRY\"] = \"RETRY\";\n\tListrLogLevels[\"PROMPT\"] = \"PROMPT\";\n\tListrLogLevels[\"PAUSED\"] = \"PAUSED\";\n\treturn ListrLogLevels;\n}({});\nconst LISTR_LOGGER_STYLE = {\n\ticon: {\n\t\t[ListrLogLevels.STARTED]: figures.pointer,\n\t\t[ListrLogLevels.FAILED]: figures.cross,\n\t\t[ListrLogLevels.SKIPPED]: figures.arrowDown,\n\t\t[ListrLogLevels.COMPLETED]: figures.tick,\n\t\t[ListrLogLevels.OUTPUT]: figures.pointerSmall,\n\t\t[ListrLogLevels.TITLE]: figures.arrowRight,\n\t\t[ListrLogLevels.RETRY]: figures.warning,\n\t\t[ListrLogLevels.ROLLBACK]: figures.arrowLeft,\n\t\t[ListrLogLevels.PAUSED]: figures.squareSmallFilled\n\t},\n\tcolor: {\n\t\t[ListrLogLevels.STARTED]: color.yellow,\n\t\t[ListrLogLevels.FAILED]: color.red,\n\t\t[ListrLogLevels.SKIPPED]: color.yellow,\n\t\t[ListrLogLevels.COMPLETED]: color.green,\n\t\t[ListrLogLevels.RETRY]: color.yellowBright,\n\t\t[ListrLogLevels.ROLLBACK]: color.redBright,\n\t\t[ListrLogLevels.PAUSED]: color.yellowBright\n\t}\n};\nconst LISTR_LOGGER_STDERR_LEVELS = [\n\tListrLogLevels.RETRY,\n\tListrLogLevels.ROLLBACK,\n\tListrLogLevels.FAILED\n];\n\n//#endregion\n//#region src/utils/logger/logger.ts\n/**\n* Creates a new Listr2 logger.\n*\n* This logger is used throughout the renderers for consistency.\n*\n* @see {@link https://listr2.kilic.dev/renderer/logger.html}\n*/\nvar ListrLogger = class {\n\tprocess;\n\tconstructor(options) {\n\t\tthis.options = options;\n\t\tthis.options = {\n\t\t\tuseIcons: true,\n\t\t\ttoStderr: [],\n\t\t\t...options ?? {}\n\t\t};\n\t\tthis.options.fields ??= {};\n\t\tthis.options.fields.prefix ??= [];\n\t\tthis.options.fields.suffix ??= [];\n\t\tthis.process = this.options.processOutput ?? new ProcessOutput();\n\t}\n\tlog(level, message, options) {\n\t\tconst output = this.format(level, message, options);\n\t\tif (this.options.toStderr.includes(level)) {\n\t\t\tthis.process.toStderr(output);\n\t\t\treturn;\n\t\t}\n\t\tthis.process.toStdout(output);\n\t}\n\ttoStdout(message, options, eol = true) {\n\t\tthis.process.toStdout(this.format(null, message, options), eol);\n\t}\n\ttoStderr(message, options, eol = true) {\n\t\tthis.process.toStderr(this.format(null, message, options), eol);\n\t}\n\twrap(message, options) {\n\t\tif (!message) return message;\n\t\treturn this.applyFormat(`[${message}]`, options);\n\t}\n\tsplat(...args) {\n\t\tconst message = args.shift() ?? \"\";\n\t\treturn args.length === 0 ? message : splat(message, args);\n\t}\n\tsuffix(message, ...suffixes) {\n\t\tsuffixes.filter(Boolean).forEach((suffix) => {\n\t\t\tmessage += this.spacing(message);\n\t\t\tif (typeof suffix === \"string\") message += this.wrap(suffix);\n\t\t\telse if (typeof suffix === \"object\") {\n\t\t\t\tsuffix.args ??= [];\n\t\t\t\tif (typeof suffix.condition === \"function\" ? !suffix.condition(...suffix.args) : !(suffix.condition ?? true)) return message;\n\t\t\t\tmessage += this.wrap(typeof suffix.field === \"function\" ? suffix.field(...suffix.args) : suffix.field, { format: suffix?.format(...suffix.args) });\n\t\t\t}\n\t\t});\n\t\treturn message;\n\t}\n\tprefix(message, ...prefixes) {\n\t\tprefixes.filter(Boolean).forEach((prefix) => {\n\t\t\tmessage = this.spacing(message) + message;\n\t\t\tif (typeof prefix === \"string\") message = this.wrap(prefix) + message;\n\t\t\telse if (typeof prefix === \"object\") {\n\t\t\t\tprefix.args ??= [];\n\t\t\t\tif (typeof prefix.condition === \"function\" ? !prefix.condition(...prefix.args) : !(prefix.condition ?? true)) return message;\n\t\t\t\tmessage = this.wrap(typeof prefix.field === \"function\" ? prefix.field(...prefix.args) : prefix.field, { format: prefix?.format() }) + message;\n\t\t\t}\n\t\t});\n\t\treturn message;\n\t}\n\tfields(message, options) {\n\t\tif (this.options?.fields?.prefix) message = this.prefix(message, ...this.options.fields.prefix);\n\t\tif (options?.prefix) message = this.prefix(message, ...options.prefix);\n\t\tif (options?.suffix) message = this.suffix(message, ...options.suffix);\n\t\tif (this.options?.fields?.suffix) message = this.suffix(message, ...this.options.fields.suffix);\n\t\treturn message;\n\t}\n\ticon(level, icon) {\n\t\tif (!level) return null;\n\t\tif (!icon) {\n\t\t\tconst i = this.options.icon?.[level];\n\t\t\ticon = typeof i === \"function\" ? i() : i;\n\t\t}\n\t\tconst coloring = this.options.color?.[level];\n\t\tif (icon && coloring) icon = coloring(icon);\n\t\treturn icon;\n\t}\n\tformat(level, message, options) {\n\t\tif (!Array.isArray(message)) message = [message];\n\t\tmessage = this.splat(message.shift(), ...message).toString().split(EOL).filter((m) => !m || m.trim() !== \"\").map((m) => {\n\t\t\treturn this.style(level, this.fields(m, {\n\t\t\t\tprefix: Array.isArray(options?.prefix) ? options.prefix : [options?.prefix],\n\t\t\t\tsuffix: Array.isArray(options?.suffix) ? options.suffix : [options?.suffix]\n\t\t\t}));\n\t\t}).join(EOL);\n\t\treturn message;\n\t}\n\tstyle(level, message) {\n\t\tif (!level || !message) return message;\n\t\tconst icon = this.icon(level, !this.options.useIcons && this.wrap(level));\n\t\tif (icon) message = icon + \" \" + message;\n\t\treturn message;\n\t}\n\tapplyFormat(message, options) {\n\t\tif (options?.format) return options.format(message);\n\t\treturn message;\n\t}\n\tspacing(message) {\n\t\treturn typeof message === \"undefined\" || message.trim() === \"\" ? \"\" : \" \";\n\t}\n};\n\n//#endregion\n//#region src/utils/process-output/process-output-buffer.ts\nvar ProcessOutputBuffer = class {\n\tbuffer = [];\n\tdecoder = new StringDecoder();\n\tconstructor(options) {\n\t\tthis.options = options;\n\t}\n\tget all() {\n\t\treturn this.buffer;\n\t}\n\tget last() {\n\t\treturn this.buffer.at(-1);\n\t}\n\tget length() {\n\t\treturn this.buffer.length;\n\t}\n\twrite(data, ...args) {\n\t\tconst callback = args[args.length - 1];\n\t\tthis.buffer.push({\n\t\t\ttime: Date.now(),\n\t\t\tstream: this.options?.stream,\n\t\t\tentry: this.decoder.write(typeof data === \"string\" ? Buffer.from(data, typeof args[0] === \"string\" ? args[0] : void 0) : Buffer.from(data))\n\t\t});\n\t\tif (this.options?.limit) this.buffer = this.buffer.slice(-this.options.limit);\n\t\tif (typeof callback === \"function\") callback();\n\t\treturn true;\n\t}\n\treset() {\n\t\tthis.buffer = [];\n\t}\n};\n\n//#endregion\n//#region src/utils/process-output/process-output-stream.ts\nvar ProcessOutputStream = class {\n\tmethod;\n\tbuffer;\n\tconstructor(stream) {\n\t\tthis.stream = stream;\n\t\tthis.method = stream.write;\n\t\tthis.buffer = new ProcessOutputBuffer({ stream });\n\t}\n\tget out() {\n\t\tconst self = this;\n\t\treturn new Proxy(this.stream, { get(target, prop, receiver) {\n\t\t\tif (prop === \"write\") return self.write.bind(self);\n\t\t\treturn Reflect.get(target, prop, receiver);\n\t\t} });\n\t}\n\thijack() {\n\t\tthis.stream.write = this.buffer.write.bind(this.buffer);\n\t}\n\trelease() {\n\t\tthis.stream.write = this.method;\n\t\tconst buffer = [...this.buffer.all];\n\t\tthis.buffer.reset();\n\t\treturn buffer;\n\t}\n\twrite(...args) {\n\t\treturn this.method.apply(this.stream, args);\n\t}\n};\n\n//#endregion\n//#region src/utils/process-output/process-output.ts\n/**\n* Creates a new Listr2 process-output controller.\n*\n* This is used to control the flow to `process.stdout` and `process.stderr` for all renderers.\n*\n* @see {@link https://listr2.kilic.dev/renderer/process-output.html}\n*/\nvar ProcessOutput = class {\n\tstream;\n\tactive;\n\tconstructor(stdout, stderr, options) {\n\t\tthis.options = options;\n\t\tthis.stream = {\n\t\t\tstdout: new ProcessOutputStream(stdout ?? process.stdout),\n\t\t\tstderr: new ProcessOutputStream(stderr ?? process.stderr)\n\t\t};\n\t\tthis.options = {\n\t\t\tdump: [\"stdout\", \"stderr\"],\n\t\t\tleaveEmptyLine: true,\n\t\t\t...options\n\t\t};\n\t}\n\tget stdout() {\n\t\treturn this.stream.stdout.out;\n\t}\n\tget stderr() {\n\t\treturn this.stream.stderr.out;\n\t}\n\thijack() {\n\t\tif (this.active) throw new Error(\"ProcessOutput has been already hijacked!\");\n\t\tthis.stream.stdout.write(ANSI_ESCAPE_CODES.CURSOR_HIDE);\n\t\tObject.values(this.stream).forEach((stream) => stream.hijack());\n\t\tthis.active = true;\n\t}\n\trelease() {\n\t\tconst output = Object.entries(this.stream).map(([name, stream]) => ({\n\t\t\tname,\n\t\t\tbuffer: stream.release()\n\t\t})).filter((output) => this.options.dump.includes(output.name)).flatMap((output) => output.buffer).sort((a, b) => a.time - b.time).map((message) => {\n\t\t\treturn {\n\t\t\t\t...message,\n\t\t\t\tentry: cleanseAnsi(message.entry)\n\t\t\t};\n\t\t}).filter((message) => message.entry);\n\t\tif (output.length > 0) {\n\t\t\tif (this.options.leaveEmptyLine) this.stdout.write(EOL);\n\t\t\toutput.forEach((message) => {\n\t\t\t\t(message.stream ?? this.stdout).write(message.entry + EOL);\n\t\t\t});\n\t\t}\n\t\tthis.stream.stdout.write(ANSI_ESCAPE_CODES.CURSOR_SHOW);\n\t\tthis.active = false;\n\t}\n\ttoStdout(buffer, eol = true) {\n\t\tif (eol) buffer = buffer + EOL;\n\t\treturn this.stream.stdout.write(buffer);\n\t}\n\ttoStderr(buffer, eol = true) {\n\t\tif (eol) buffer = buffer + EOL;\n\t\treturn this.stream.stderr.write(buffer);\n\t}\n};\n\n//#endregion\n//#region src/utils/process-output/writable.ts\n/* istanbul ignore next */\nfunction createWritable(cb) {\n\tconst writable = new Writable();\n\twritable.rows = Infinity;\n\twritable.columns = Infinity;\n\twritable.write = (chunk) => {\n\t\tcb(chunk.toString());\n\t\treturn true;\n\t};\n\treturn writable;\n}\n\n//#endregion\n//#region src/utils/prompts/adapter.ts\n/* istanbul ignore next */\nvar ListrPromptAdapter = class {\n\tstate;\n\tconstructor(task, wrapper) {\n\t\tthis.task = task;\n\t\tthis.wrapper = wrapper;\n\t}\n\treportStarted() {\n\t\tthis.state = this.task.state;\n\t\tif (this.task.prompt) throw new PromptError(\"There is already an active prompt attached to this task which may not be cleaned up properly.\");\n\t\tthis.task.prompt = this;\n\t\tthis.task.state$ = ListrTaskState.PROMPT;\n\t}\n\treportFailed() {\n\t\tthis.task.state$ = ListrTaskState.PROMPT_FAILED;\n\t\tthis.restoreState();\n\t}\n\treportCompleted() {\n\t\tthis.task.state$ = ListrTaskState.PROMPT_COMPLETED;\n\t\tthis.restoreState();\n\t}\n\trestoreState() {\n\t\tthis.task.prompt = void 0;\n\t\tif (this.state) this.task.state = this.state;\n\t}\n};\n\n//#endregion\n//#region src/utils/ui/spinner.ts\n/* istanbul ignore next */\nvar Spinner = class {\n\tspinner = !isUnicodeSupported() ? [\n\t\t\"-\",\n\t\t\"\\\\\",\n\t\t\"|\",\n\t\t\"/\"\n\t] : [\n\t\t\"⠋\",\n\t\t\"⠙\",\n\t\t\"⠹\",\n\t\t\"⠸\",\n\t\t\"⠼\",\n\t\t\"⠴\",\n\t\t\"⠦\",\n\t\t\"⠧\",\n\t\t\"⠇\",\n\t\t\"⠏\"\n\t];\n\tid;\n\tspinnerPosition = 0;\n\tspin() {\n\t\tthis.spinnerPosition = ++this.spinnerPosition % this.spinner.length;\n\t}\n\tfetch() {\n\t\treturn this.spinner[this.spinnerPosition];\n\t}\n\tisRunning() {\n\t\treturn !!this.id;\n\t}\n\tstart(cb, interval = 100) {\n\t\tthis.id = setInterval(() => {\n\t\t\tthis.spin();\n\t\t\tif (cb) cb();\n\t\t}, interval);\n\t}\n\tstop() {\n\t\tclearInterval(this.id);\n\t\tthis.id = void 0;\n\t}\n};\n\n//#endregion\n//#region src/renderer/default/renderer.constants.ts\nlet ListrDefaultRendererLogLevels = /* @__PURE__ */ function(ListrDefaultRendererLogLevels) {\n\tListrDefaultRendererLogLevels[\"SKIPPED_WITH_COLLAPSE\"] = \"SKIPPED_WITH_COLLAPSE\";\n\tListrDefaultRendererLogLevels[\"SKIPPED_WITHOUT_COLLAPSE\"] = \"SKIPPED_WITHOUT_COLLAPSE\";\n\tListrDefaultRendererLogLevels[\"OUTPUT\"] = \"OUTPUT\";\n\tListrDefaultRendererLogLevels[\"OUTPUT_WITH_BOTTOMBAR\"] = \"OUTPUT_WITH_BOTTOMBAR\";\n\tListrDefaultRendererLogLevels[\"PENDING\"] = \"PENDING\";\n\tListrDefaultRendererLogLevels[\"COMPLETED\"] = \"COMPLETED\";\n\tListrDefaultRendererLogLevels[\"COMPLETED_WITH_FAILED_SUBTASKS\"] = \"COMPLETED_WITH_FAILED_SUBTASKS\";\n\tListrDefaultRendererLogLevels[\"COMPLETED_WITH_FAILED_SISTER_TASKS\"] = \"COMPLETED_WITH_SISTER_TASKS_FAILED\";\n\tListrDefaultRendererLogLevels[\"RETRY\"] = \"RETRY\";\n\tListrDefaultRendererLogLevels[\"ROLLING_BACK\"] = \"ROLLING_BACK\";\n\tListrDefaultRendererLogLevels[\"ROLLED_BACK\"] = \"ROLLED_BACK\";\n\tListrDefaultRendererLogLevels[\"FAILED\"] = \"FAILED\";\n\tListrDefaultRendererLogLevels[\"FAILED_WITH_FAILED_SUBTASKS\"] = \"FAILED_WITH_SUBTASKS\";\n\tListrDefaultRendererLogLevels[\"WAITING\"] = \"WAITING\";\n\tListrDefaultRendererLogLevels[\"PAUSED\"] = \"PAUSED\";\n\treturn ListrDefaultRendererLogLevels;\n}({});\nconst LISTR_DEFAULT_RENDERER_STYLE = {\n\ticon: {\n\t\t[ListrDefaultRendererLogLevels.SKIPPED_WITH_COLLAPSE]: figures.arrowDown,\n\t\t[ListrDefaultRendererLogLevels.SKIPPED_WITHOUT_COLLAPSE]: figures.warning,\n\t\t[ListrDefaultRendererLogLevels.OUTPUT]: figures.pointerSmall,\n\t\t[ListrDefaultRendererLogLevels.OUTPUT_WITH_BOTTOMBAR]: figures.pointerSmall,\n\t\t[ListrDefaultRendererLogLevels.PENDING]: figures.pointer,\n\t\t[ListrDefaultRendererLogLevels.COMPLETED]: figures.tick,\n\t\t[ListrDefaultRendererLogLevels.COMPLETED_WITH_FAILED_SUBTASKS]: figures.warning,\n\t\t[ListrDefaultRendererLogLevels.COMPLETED_WITH_FAILED_SISTER_TASKS]: figures.squareSmallFilled,\n\t\t[ListrDefaultRendererLogLevels.RETRY]: figures.warning,\n\t\t[ListrDefaultRendererLogLevels.ROLLING_BACK]: figures.warning,\n\t\t[ListrDefaultRendererLogLevels.ROLLED_BACK]: figures.arrowLeft,\n\t\t[ListrDefaultRendererLogLevels.FAILED]: figures.cross,\n\t\t[ListrDefaultRendererLogLevels.FAILED_WITH_FAILED_SUBTASKS]: figures.pointer,\n\t\t[ListrDefaultRendererLogLevels.WAITING]: figures.squareSmallFilled,\n\t\t[ListrDefaultRendererLogLevels.PAUSED]: figures.squareSmallFilled\n\t},\n\tcolor: {\n\t\t[ListrDefaultRendererLogLevels.SKIPPED_WITH_COLLAPSE]: color.yellow,\n\t\t[ListrDefaultRendererLogLevels.SKIPPED_WITHOUT_COLLAPSE]: color.yellow,\n\t\t[ListrDefaultRendererLogLevels.PENDING]: color.yellow,\n\t\t[ListrDefaultRendererLogLevels.COMPLETED]: color.green,\n\t\t[ListrDefaultRendererLogLevels.COMPLETED_WITH_FAILED_SUBTASKS]: color.yellow,\n\t\t[ListrDefaultRendererLogLevels.COMPLETED_WITH_FAILED_SISTER_TASKS]: color.red,\n\t\t[ListrDefaultRendererLogLevels.RETRY]: color.yellowBright,\n\t\t[ListrDefaultRendererLogLevels.ROLLING_BACK]: color.redBright,\n\t\t[ListrDefaultRendererLogLevels.ROLLED_BACK]: color.redBright,\n\t\t[ListrDefaultRendererLogLevels.FAILED]: color.red,\n\t\t[ListrDefaultRendererLogLevels.FAILED_WITH_FAILED_SUBTASKS]: color.red,\n\t\t[ListrDefaultRendererLogLevels.WAITING]: color.dim,\n\t\t[ListrDefaultRendererLogLevels.PAUSED]: color.yellowBright\n\t}\n};\n\n//#endregion\n//#region src/presets/timer/parser.ts\n/**\n* A basic function to parse minutes and tasks passed given a duration.\n* Useful for renderers to show the task time.\n*/\n/* istanbul ignore next */\nfunction parseTimer(duration) {\n\tconst seconds = Math.floor(duration / 1e3);\n\tconst minutes = Math.floor(seconds / 60);\n\tlet parsedTime;\n\tif (seconds === 0 && minutes === 0) parsedTime = `0.${Math.floor(duration / 100)}s`;\n\tif (seconds > 0) parsedTime = `${seconds % 60}s`;\n\tif (minutes > 0) parsedTime = `${minutes}m${parsedTime}`;\n\treturn parsedTime;\n}\n\n//#endregion\n//#region src/presets/timer/preset.ts\n/* istanbul ignore next */\nconst PRESET_TIMER = {\n\tcondition: true,\n\tfield: parseTimer,\n\tformat: () => color.dim\n};\n\n//#endregion\n//#region src/presets/timestamp/parser.ts\n/* istanbul ignore next */\nfunction parseTimestamp() {\n\tconst now = /* @__PURE__ */ new Date();\n\treturn String(now.getHours()).padStart(2, \"0\") + \":\" + String(now.getMinutes()).padStart(2, \"0\") + \":\" + String(now.getSeconds()).padStart(2, \"0\");\n}\n\n//#endregion\n//#region src/presets/timestamp/preset.ts\n/* istanbul ignore next */\nconst PRESET_TIMESTAMP = {\n\tcondition: true,\n\tfield: parseTimestamp,\n\tformat: () => color.dim\n};\n\n//#endregion\n//#region src/renderer/default/renderer.ts\nvar DefaultRenderer = class DefaultRenderer {\n\tstatic nonTTY = false;\n\tstatic rendererOptions = {\n\t\tindentation: 2,\n\t\tclearOutput: false,\n\t\tshowSubtasks: true,\n\t\tcollapseSubtasks: true,\n\t\tcollapseSkips: true,\n\t\tshowSkipMessage: true,\n\t\tsuffixSkips: false,\n\t\tcollapseErrors: true,\n\t\tshowErrorMessage: true,\n\t\tsuffixRetries: true,\n\t\tlazy: false,\n\t\tremoveEmptyLines: true,\n\t\tformatOutput: \"wrap\",\n\t\tpausedTimer: {\n\t\t\t...PRESET_TIMER,\n\t\t\tformat: () => color.yellowBright\n\t\t}\n\t};\n\tstatic rendererTaskOptions = { outputBar: true };\n\tprompt;\n\tactivePrompt;\n\tspinner;\n\tlogger;\n\tupdater;\n\ttruncate;\n\twrap;\n\tbuffer = {\n\t\toutput: /* @__PURE__ */ new Map(),\n\t\tbottom: /* @__PURE__ */ new Map()\n\t};\n\tcache = {\n\t\trender: /* @__PURE__ */ new Map(),\n\t\trendererOptions: /* @__PURE__ */ new Map(),\n\t\trendererTaskOptions: /* @__PURE__ */ new Map()\n\t};\n\tconstructor(tasks, options, events) {\n\t\tthis.tasks = tasks;\n\t\tthis.options = options;\n\t\tthis.events = events;\n\t\tthis.options = {\n\t\t\t...DefaultRenderer.rendererOptions,\n\t\t\t...this.options,\n\t\t\ticon: {\n\t\t\t\t...LISTR_DEFAULT_RENDERER_STYLE.icon,\n\t\t\t\t...options?.icon ?? {}\n\t\t\t},\n\t\t\tcolor: {\n\t\t\t\t...LISTR_DEFAULT_RENDERER_STYLE.color,\n\t\t\t\t...options?.color ?? {}\n\t\t\t}\n\t\t};\n\t\tthis.spinner = this.options.spinner ?? new Spinner();\n\t\tthis.logger = this.options.logger ?? new ListrLogger({\n\t\t\tuseIcons: true,\n\t\t\ttoStderr: []\n\t\t});\n\t\tthis.logger.options.icon = this.options.icon;\n\t\tthis.logger.options.color = this.options.color;\n\t}\n\tasync render() {\n\t\tconst { createLogUpdate } = await import(\"log-update\");\n\t\tconst { default: truncate } = await import(\"cli-truncate\");\n\t\tconst { default: wrap } = await import(\"wrap-ansi\");\n\t\tthis.updater = createLogUpdate(this.logger.process.stdout);\n\t\tthis.truncate = truncate;\n\t\tthis.wrap = wrap;\n\t\tthis.logger.process.hijack();\n\t\t/* istanbul ignore if */\n\t\tif (!this.options?.lazy) this.spinner.start(() => {\n\t\t\tthis.update();\n\t\t});\n\t\tthis.events.on(ListrEventType.SHOULD_REFRESH_RENDER, () => {\n\t\t\tthis.update();\n\t\t});\n\t}\n\tupdate() {\n\t\tthis.updater(this.create());\n\t}\n\tend() {\n\t\tthis.spinner.stop();\n\t\tthis.updater.clear();\n\t\tthis.updater.done();\n\t\tif (!this.options.clearOutput) this.logger.process.toStdout(this.create({ prompt: false }));\n\t\tthis.logger.process.release();\n\t}\n\tcreate(options) {\n\t\toptions = {\n\t\t\ttasks: true,\n\t\t\tbottomBar: true,\n\t\t\tprompt: true,\n\t\t\t...options\n\t\t};\n\t\tconst render = [];\n\t\tconst renderTasks = this.renderer(this.tasks);\n\t\tconst renderBottomBar = this.renderBottomBar();\n\t\tconst renderPrompt = this.renderPrompt();\n\t\tif (options.tasks && renderTasks.length > 0) render.push(...renderTasks);\n\t\tif (options.bottomBar && renderBottomBar.length > 0) {\n\t\t\tif (render.length > 0) render.push(\"\");\n\t\t\trender.push(...renderBottomBar);\n\t\t}\n\t\tif (options.prompt && renderPrompt.length > 0) {\n\t\t\tif (render.length > 0) render.push(\"\");\n\t\t\trender.push(...renderPrompt);\n\t\t}\n\t\treturn render.join(EOL);\n\t}\n\tstyle(task, output = false) {\n\t\tconst rendererOptions = this.cache.rendererOptions.get(task.id);\n\t\tif (task.isSkipped()) {\n\t\t\tif (output || rendererOptions.collapseSkips) return this.logger.icon(ListrDefaultRendererLogLevels.SKIPPED_WITH_COLLAPSE);\n\t\t\telse if (rendererOptions.collapseSkips === false) return this.logger.icon(ListrDefaultRendererLogLevels.SKIPPED_WITHOUT_COLLAPSE);\n\t\t}\n\t\tif (output) {\n\t\t\tif (this.shouldOutputToBottomBar(task)) return this.logger.icon(ListrDefaultRendererLogLevels.OUTPUT_WITH_BOTTOMBAR);\n\t\t\treturn this.logger.icon(ListrDefaultRendererLogLevels.OUTPUT);\n\t\t}\n\t\tif (task.hasSubtasks()) {\n\t\t\tif (task.isStarted() || task.isPrompt() && rendererOptions.showSubtasks !== false && !task.subtasks.every((subtask) => !subtask.hasTitle())) return this.logger.icon(ListrDefaultRendererLogLevels.PENDING);\n\t\t\telse if (task.isCompleted() && task.subtasks.some((subtask) => subtask.hasFailed())) return this.logger.icon(ListrDefaultRendererLogLevels.COMPLETED_WITH_FAILED_SUBTASKS);\n\t\t\telse if (task.hasFailed()) return this.logger.icon(ListrDefaultRendererLogLevels.FAILED_WITH_FAILED_SUBTASKS);\n\t\t}\n\t\tif (task.isStarted() || task.isPrompt()) return this.logger.icon(ListrDefaultRendererLogLevels.PENDING, !this.options?.lazy && this.spinner.fetch());\n\t\telse if (task.isCompleted()) return this.logger.icon(ListrDefaultRendererLogLevels.COMPLETED);\n\t\telse if (task.isRetrying()) return this.logger.icon(ListrDefaultRendererLogLevels.RETRY, !this.options?.lazy && this.spinner.fetch());\n\t\telse if (task.isRollingBack()) return this.logger.icon(ListrDefaultRendererLogLevels.ROLLING_BACK, !this.options?.lazy && this.spinner.fetch());\n\t\telse if (task.hasRolledBack()) return this.logger.icon(ListrDefaultRendererLogLevels.ROLLED_BACK);\n\t\telse if (task.hasFailed()) return this.logger.icon(ListrDefaultRendererLogLevels.FAILED);\n\t\telse if (task.isPaused()) return this.logger.icon(ListrDefaultRendererLogLevels.PAUSED);\n\t\treturn this.logger.icon(ListrDefaultRendererLogLevels.WAITING);\n\t}\n\tformat(message, icon, level) {\n\t\tif (message.trim() === \"\") return [];\n\t\tif (icon) message = icon + \" \" + message;\n\t\tlet parsed;\n\t\tconst columns = (process.stdout.columns ?? 80) - level * this.options.indentation - 2;\n\t\tswitch (this.options.formatOutput) {\n\t\t\tcase \"truncate\":\n\t\t\t\tparsed = message.split(EOL).map((s, i) => {\n\t\t\t\t\treturn this.truncate(this.indent(s, i), columns);\n\t\t\t\t});\n\t\t\t\tbreak;\n\t\t\tcase \"wrap\":\n\t\t\t\tparsed = this.wrap(message, columns, {\n\t\t\t\t\thard: true,\n\t\t\t\t\ttrim: false\n\t\t\t\t}).split(EOL).map((s, i) => this.indent(s, i));\n\t\t\t\tbreak;\n\t\t\tdefault: throw new ListrRendererError(\"Format option for the renderer is wrong.\");\n\t\t}\n\t\tif (this.options.removeEmptyLines) parsed = parsed.filter(Boolean);\n\t\treturn parsed.map((str) => indent(str, level * this.options.indentation));\n\t}\n\tshouldOutputToOutputBar(task) {\n\t\tconst outputBar = this.cache.rendererTaskOptions.get(task.id).outputBar;\n\t\treturn typeof outputBar === \"number\" && outputBar !== 0 || typeof outputBar === \"boolean\" && outputBar !== false;\n\t}\n\tshouldOutputToBottomBar(task) {\n\t\tconst bottomBar = this.cache.rendererTaskOptions.get(task.id).bottomBar;\n\t\treturn typeof bottomBar === \"number\" && bottomBar !== 0 || typeof bottomBar === \"boolean\" && bottomBar !== false || !task.hasTitle();\n\t}\n\trenderer(tasks, level = 0) {\n\t\treturn tasks.flatMap((task) => {\n\t\t\tif (!task.isEnabled()) return [];\n\t\t\tif (this.cache.render.has(task.id)) return this.cache.render.get(task.id);\n\t\t\tthis.calculate(task);\n\t\t\tthis.setupBuffer(task);\n\t\t\tconst rendererOptions = this.cache.rendererOptions.get(task.id);\n\t\t\tconst rendererTaskOptions = this.cache.rendererTaskOptions.get(task.id);\n\t\t\tconst output = [];\n\t\t\tif (task.isPrompt()) {\n\t\t\t\tif (this.activePrompt && this.activePrompt !== task.id) throw new ListrRendererError(\"Only one prompt can be active at the given time, please re-evaluate your task design.\");\n\t\t\t\telse if (!this.activePrompt) {\n\t\t\t\t\ttask.on(ListrTaskEventType.PROMPT, (prompt) => {\n\t\t\t\t\t\tconst cleansed = cleanseAnsi(prompt);\n\t\t\t\t\t\tif (cleansed) this.prompt = cleansed;\n\t\t\t\t\t});\n\t\t\t\t\ttask.on(ListrTaskEventType.STATE, (state) => {\n\t\t\t\t\t\tif (state === ListrTaskState.PROMPT_COMPLETED || task.hasFinalized() || task.hasReset()) {\n\t\t\t\t\t\t\tthis.prompt = null;\n\t\t\t\t\t\t\tthis.activePrompt = null;\n\t\t\t\t\t\t\ttask.off(ListrTaskEventType.PROMPT);\n\t\t\t\t\t\t}\n\t\t\t\t\t});\n\t\t\t\t\tthis.activePrompt = task.id;\n\t\t\t\t}\n\t\t\t}\n\t\t\tif (task.hasTitle()) if (!(tasks.some((task) => task.hasFailed()) && !task.hasFailed() && task.options.exitOnError !== false && !(task.isCompleted() || task.isSkipped()))) if (task.hasFailed() && rendererOptions.collapseErrors) output.push(...this.format(!task.hasSubtasks() && task.message.error && rendererOptions.showErrorMessage ? task.message.error : task.title, this.style(task), level));\n\t\t\telse if (task.isSkipped() && rendererOptions.collapseSkips) output.push(...this.format(this.logger.suffix(task.message.skip && rendererOptions.showSkipMessage ? task.message.skip : task.title, {\n\t\t\t\tfield: ListrLogLevels.SKIPPED,\n\t\t\t\tcondition: rendererOptions.suffixSkips,\n\t\t\t\tformat: () => color.dim\n\t\t\t}), this.style(task), level));\n\t\t\telse if (task.isRetrying()) output.push(...this.format(this.logger.suffix(task.title, {\n\t\t\t\tfield: `${ListrLogLevels.RETRY}:${task.message.retry.count}`,\n\t\t\t\tformat: () => color.yellow,\n\t\t\t\tcondition: rendererOptions.suffixRetries\n\t\t\t}), this.style(task), level));\n\t\t\telse if (task.isCompleted() && task.hasTitle() && assertFunctionOrSelf(rendererTaskOptions.timer?.condition, task.message.duration)) output.push(...this.format(this.logger.suffix(task?.title, {\n\t\t\t\t...rendererTaskOptions.timer,\n\t\t\t\targs: [task.message.duration]\n\t\t\t}), this.style(task), level));\n\t\t\telse if (task.isPaused()) output.push(...this.format(this.logger.suffix(task.title, {\n\t\t\t\t...rendererOptions.pausedTimer,\n\t\t\t\targs: [task.message.paused - Date.now()]\n\t\t\t}), this.style(task), level));\n\t\t\telse output.push(...this.format(task.title, this.style(task), level));\n\t\t\telse output.push(...this.format(task.title, this.logger.icon(ListrDefaultRendererLogLevels.COMPLETED_WITH_FAILED_SISTER_TASKS), level));\n\t\t\tif (!task.hasSubtasks() || !rendererOptions.showSubtasks) {\n\t\t\t\tif (task.hasFailed() && rendererOptions.collapseErrors === false && (rendererOptions.showErrorMessage || !rendererOptions.showSubtasks)) output.push(...this.dump(task, level, ListrLogLevels.FAILED));\n\t\t\t\telse if (task.isSkipped() && rendererOptions.collapseSkips === false && (rendererOptions.showSkipMessage || !rendererOptions.showSubtasks)) output.push(...this.dump(task, level, ListrLogLevels.SKIPPED));\n\t\t\t}\n\t\t\tif (task.isPending() || rendererTaskOptions.persistentOutput) output.push(...this.renderOutputBar(task, level));\n\t\t\tif (rendererOptions.showSubtasks !== false && task.hasSubtasks() && (task.isPending() || task.hasFinalized() && !task.hasTitle() || task.isCompleted() && rendererOptions.collapseSubtasks === false && !task.subtasks.some((subtask) => this.cache.rendererOptions.get(subtask.id)?.collapseSubtasks === true) || task.subtasks.some((subtask) => this.cache.rendererOptions.get(subtask.id)?.collapseSubtasks === false) || task.subtasks.some((subtask) => subtask.hasFailed()) || task.subtasks.some((subtask) => subtask.hasRolledBack()))) {\n\t\t\t\tconst subtaskLevel = !task.hasTitle() ? level : level + 1;\n\t\t\t\tconst subtaskRender = this.renderer(task.subtasks, subtaskLevel);\n\t\t\t\toutput.push(...subtaskRender);\n\t\t\t}\n\t\t\tif (task.hasFinalized()) {\n\t\t\t\tif (!rendererTaskOptions.persistentOutput) {\n\t\t\t\t\tthis.buffer.bottom.delete(task.id);\n\t\t\t\t\tthis.buffer.output.delete(task.id);\n\t\t\t\t}\n\t\t\t}\n\t\t\tif (task.isClosed()) {\n\t\t\t\tthis.cache.render.set(task.id, output);\n\t\t\t\tthis.reset(task);\n\t\t\t}\n\t\t\treturn output;\n\t\t});\n\t}\n\trenderOutputBar(task, level) {\n\t\tconst output = this.buffer.output.get(task.id);\n\t\tif (!output) return [];\n\t\treturn output.all.flatMap((o) => this.dump(task, level, ListrLogLevels.OUTPUT, o.entry));\n\t}\n\trenderBottomBar() {\n\t\tif (this.buffer.bottom.size === 0) return [];\n\t\treturn Array.from(this.buffer.bottom.values()).flatMap((output) => output.all).sort((a, b) => a.time - b.time).map((output) => output.entry);\n\t}\n\trenderPrompt() {\n\t\tif (!this.prompt) return [];\n\t\treturn [this.prompt];\n\t}\n\tcalculate(task) {\n\t\tif (this.cache.rendererOptions.has(task.id) && this.cache.rendererTaskOptions.has(task.id)) return;\n\t\tconst rendererOptions = {\n\t\t\t...this.options,\n\t\t\t...task.rendererOptions\n\t\t};\n\t\tthis.cache.rendererOptions.set(task.id, rendererOptions);\n\t\tthis.cache.rendererTaskOptions.set(task.id, {\n\t\t\t...DefaultRenderer.rendererTaskOptions,\n\t\t\ttimer: rendererOptions.timer,\n\t\t\t...task.rendererTaskOptions\n\t\t});\n\t}\n\tsetupBuffer(task) {\n\t\tif (this.buffer.bottom.has(task.id) || this.buffer.output.has(task.id)) return;\n\t\tconst rendererTaskOptions = this.cache.rendererTaskOptions.get(task.id);\n\t\tif (this.shouldOutputToBottomBar(task) && !this.buffer.bottom.has(task.id)) {\n\t\t\tthis.buffer.bottom.set(task.id, new ProcessOutputBuffer({ limit: typeof rendererTaskOptions.bottomBar === \"number\" ? rendererTaskOptions.bottomBar : 1 }));\n\t\t\ttask.on(ListrTaskEventType.OUTPUT, (output) => {\n\t\t\t\tconst data = this.dump(task, -1, ListrLogLevels.OUTPUT, output);\n\t\t\t\tthis.buffer.bottom.get(task.id).write(data.join(EOL));\n\t\t\t});\n\t\t\ttask.on(ListrTaskEventType.STATE, (state) => {\n\t\t\t\tswitch (state) {\n\t\t\t\t\tcase ListrTaskState.RETRY || ListrTaskState.ROLLING_BACK:\n\t\t\t\t\t\tthis.buffer.bottom.delete(task.id);\n\t\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t});\n\t\t} else if (this.shouldOutputToOutputBar(task) && !this.buffer.output.has(task.id)) {\n\t\t\tthis.buffer.output.set(task.id, new ProcessOutputBuffer({ limit: typeof rendererTaskOptions.outputBar === \"number\" ? rendererTaskOptions.outputBar : 1 }));\n\t\t\ttask.on(ListrTaskEventType.OUTPUT, (output) => {\n\t\t\t\tthis.buffer.output.get(task.id).write(output);\n\t\t\t});\n\t\t\ttask.on(ListrTaskEventType.STATE, (state) => {\n\t\t\t\tswitch (state) {\n\t\t\t\t\tcase ListrTaskState.RETRY || ListrTaskState.ROLLING_BACK:\n\t\t\t\t\t\tthis.buffer.output.delete(task.id);\n\t\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t});\n\t\t}\n\t}\n\treset(task) {\n\t\tthis.cache.rendererOptions.delete(task.id);\n\t\tthis.cache.rendererTaskOptions.delete(task.id);\n\t\tthis.buffer.output.delete(task.id);\n\t}\n\tdump(task, level, source = ListrLogLevels.OUTPUT, data) {\n\t\tif (!data) switch (source) {\n\t\t\tcase ListrLogLevels.OUTPUT:\n\t\t\t\tdata = task.output;\n\t\t\t\tbreak;\n\t\t\tcase ListrLogLevels.SKIPPED:\n\t\t\t\tdata = task.message.skip;\n\t\t\t\tbreak;\n\t\t\tcase ListrLogLevels.FAILED:\n\t\t\t\tdata = task.message.error;\n\t\t\t\tbreak;\n\t\t}\n\t\tif (task.hasTitle() && source === ListrLogLevels.FAILED && data === task.title || typeof data !== \"string\") return [];\n\t\tif (source === ListrLogLevels.OUTPUT) data = cleanseAnsi(data);\n\t\treturn this.format(data, this.style(task, true), level + 1);\n\t}\n\tindent(str, i) {\n\t\treturn i > 0 ? indent(str.trimEnd(), this.options.indentation) : str.trimEnd();\n\t}\n};\n\n//#endregion\n//#region src/renderer/silent/renderer.ts\nvar SilentRenderer = class {\n\tstatic nonTTY = true;\n\tstatic rendererOptions;\n\tstatic rendererTaskOptions;\n\tconstructor(tasks, options) {\n\t\tthis.tasks = tasks;\n\t\tthis.options = options;\n\t}\n\trender() {}\n\tend() {}\n};\n\n//#endregion\n//#region src/renderer/simple/renderer.ts\nvar SimpleRenderer = class SimpleRenderer {\n\tstatic nonTTY = true;\n\tstatic rendererOptions = { pausedTimer: {\n\t\t...PRESET_TIMER,\n\t\tfield: (time) => `${ListrLogLevels.PAUSED}:${time}`,\n\t\tformat: () => color.yellowBright\n\t} };\n\tstatic rendererTaskOptions = {};\n\tlogger;\n\tcache = {\n\t\trendererOptions: /* @__PURE__ */ new Map(),\n\t\trendererTaskOptions: /* @__PURE__ */ new Map()\n\t};\n\tconstructor(tasks, options) {\n\t\tthis.tasks = tasks;\n\t\tthis.options = options;\n\t\tthis.options = {\n\t\t\t...SimpleRenderer.rendererOptions,\n\t\t\t...options,\n\t\t\ticon: {\n\t\t\t\t...LISTR_LOGGER_STYLE.icon,\n\t\t\t\t...options?.icon ?? {}\n\t\t\t},\n\t\t\tcolor: {\n\t\t\t\t...LISTR_LOGGER_STYLE.color,\n\t\t\t\t...options?.color ?? {}\n\t\t\t}\n\t\t};\n\t\tthis.logger = this.options.logger ?? new ListrLogger({\n\t\t\tuseIcons: true,\n\t\t\ttoStderr: LISTR_LOGGER_STDERR_LEVELS\n\t\t});\n\t\tthis.logger.options.icon = this.options.icon;\n\t\tthis.logger.options.color = this.options.color;\n\t\tif (this.options.timestamp) this.logger.options.fields.prefix.unshift(this.options.timestamp);\n\t}\n\tend() {}\n\trender() {\n\t\tthis.renderer(this.tasks);\n\t}\n\trenderer(tasks) {\n\t\ttasks.forEach((task) => {\n\t\t\tthis.calculate(task);\n\t\t\ttask.once(ListrTaskEventType.CLOSED, () => {\n\t\t\t\tthis.reset(task);\n\t\t\t});\n\t\t\tconst rendererOptions = this.cache.rendererOptions.get(task.id);\n\t\t\tconst rendererTaskOptions = this.cache.rendererTaskOptions.get(task.id);\n\t\t\ttask.on(ListrTaskEventType.SUBTASK, (subtasks) => {\n\t\t\t\tthis.renderer(subtasks);\n\t\t\t});\n\t\t\ttask.on(ListrTaskEventType.STATE, (state) => {\n\t\t\t\tif (!task.hasTitle()) return;\n\t\t\t\tif (state === ListrTaskState.STARTED) this.logger.log(ListrLogLevels.STARTED, task.title);\n\t\t\t\telse if (state === ListrTaskState.COMPLETED) {\n\t\t\t\t\tconst timer = rendererTaskOptions?.timer;\n\t\t\t\t\tthis.logger.log(ListrLogLevels.COMPLETED, task.title, timer && { suffix: {\n\t\t\t\t\t\t...timer,\n\t\t\t\t\t\tcondition: !!task.message?.duration && timer.condition,\n\t\t\t\t\t\targs: [task.message.duration]\n\t\t\t\t\t} });\n\t\t\t\t} else if (state === ListrTaskState.PROMPT) {\n\t\t\t\t\tthis.logger.process.hijack();\n\t\t\t\t\ttask.on(ListrTaskEventType.PROMPT, (prompt) => {\n\t\t\t\t\t\tthis.logger.process.toStderr(prompt, false);\n\t\t\t\t\t});\n\t\t\t\t} else if (state === ListrTaskState.PROMPT_COMPLETED) {\n\t\t\t\t\ttask.off(ListrTaskEventType.PROMPT);\n\t\t\t\t\tthis.logger.process.release();\n\t\t\t\t}\n\t\t\t});\n\t\t\ttask.on(ListrTaskEventType.OUTPUT, (output) => {\n\t\t\t\tthis.logger.log(ListrLogLevels.OUTPUT, output);\n\t\t\t});\n\t\t\ttask.on(ListrTaskEventType.MESSAGE, (message) => {\n\t\t\t\tif (message.error) this.logger.log(ListrLogLevels.FAILED, task.title, { suffix: {\n\t\t\t\t\tfield: `${ListrLogLevels.FAILED}: ${message.error}`,\n\t\t\t\t\tformat: () => color.red\n\t\t\t\t} });\n\t\t\t\telse if (message.skip) this.logger.log(ListrLogLevels.SKIPPED, task.title, { suffix: {\n\t\t\t\t\tfield: `${ListrLogLevels.SKIPPED}: ${message.skip}`,\n\t\t\t\t\tformat: () => color.yellow\n\t\t\t\t} });\n\t\t\t\telse if (message.rollback) this.logger.log(ListrLogLevels.ROLLBACK, task.title, { suffix: {\n\t\t\t\t\tfield: `${ListrLogLevels.ROLLBACK}: ${message.rollback}`,\n\t\t\t\t\tformat: () => color.red\n\t\t\t\t} });\n\t\t\t\telse if (message.retry) this.logger.log(ListrLogLevels.RETRY, task.title, { suffix: {\n\t\t\t\t\tfield: `${ListrLogLevels.RETRY}:${message.retry.count}`,\n\t\t\t\t\tformat: () => color.red\n\t\t\t\t} });\n\t\t\t\telse if (message.paused) {\n\t\t\t\t\tconst timer = rendererOptions?.pausedTimer;\n\t\t\t\t\tthis.logger.log(ListrLogLevels.PAUSED, task.title, timer && { suffix: {\n\t\t\t\t\t\t...timer,\n\t\t\t\t\t\tcondition: !!message?.paused && timer.condition,\n\t\t\t\t\t\targs: [message.paused - Date.now()]\n\t\t\t\t\t} });\n\t\t\t\t}\n\t\t\t});\n\t\t});\n\t}\n\tcalculate(task) {\n\t\tif (this.cache.rendererOptions.has(task.id) && this.cache.rendererTaskOptions.has(task.id)) return;\n\t\tconst rendererOptions = {\n\t\t\t...this.options,\n\t\t\t...task.rendererOptions\n\t\t};\n\t\tthis.cache.rendererOptions.set(task.id, rendererOptions);\n\t\tthis.cache.rendererTaskOptions.set(task.id, {\n\t\t\t...SimpleRenderer.rendererTaskOptions,\n\t\t\ttimer: rendererOptions.timer,\n\t\t\t...task.rendererTaskOptions\n\t\t});\n\t}\n\treset(task) {\n\t\tthis.cache.rendererOptions.delete(task.id);\n\t\tthis.cache.rendererTaskOptions.delete(task.id);\n\t}\n};\n\n//#endregion\n//#region src/renderer/test/serializer.ts\nvar TestRendererSerializer = class {\n\tconstructor(options) {\n\t\tthis.options = options;\n\t}\n\tserialize(event, data, task) {\n\t\treturn JSON.stringify(this.generate(event, data, task));\n\t}\n\tgenerate(event, data, task) {\n\t\tconst output = {\n\t\t\tevent,\n\t\t\tdata\n\t\t};\n\t\tif (typeof this.options?.task !== \"boolean\") {\n\t\t\tconst t = Object.fromEntries(this.options.task.map((entity) => {\n\t\t\t\tconst property = task[entity];\n\t\t\t\tif (typeof property === \"function\") return [entity, property.call(task)];\n\t\t\t\treturn [entity, property];\n\t\t\t}));\n\t\t\tif (Object.keys(task).length > 0) output.task = t;\n\t\t}\n\t\treturn output;\n\t}\n};\n\n//#endregion\n//#region src/renderer/test/renderer.ts\nvar TestRenderer = class TestRenderer {\n\tstatic nonTTY = true;\n\tstatic rendererOptions = {\n\t\tsubtasks: true,\n\t\tstate: Object.values(ListrTaskState),\n\t\toutput: true,\n\t\tprompt: true,\n\t\ttitle: true,\n\t\tmessages: [\n\t\t\t\"skip\",\n\t\t\t\"error\",\n\t\t\t\"retry\",\n\t\t\t\"rollback\",\n\t\t\t\"paused\"\n\t\t],\n\t\tmessagesToStderr: [\n\t\t\t\"error\",\n\t\t\t\"rollback\",\n\t\t\t\"retry\"\n\t\t],\n\t\ttask: [\n\t\t\t\"hasRolledBack\",\n\t\t\t\"isRollingBack\",\n\t\t\t\"isCompleted\",\n\t\t\t\"isSkipped\",\n\t\t\t\"hasFinalized\",\n\t\t\t\"hasSubtasks\",\n\t\t\t\"title\",\n\t\t\t\"hasReset\",\n\t\t\t\"hasTitle\",\n\t\t\t\"isPrompt\",\n\t\t\t\"isPaused\",\n\t\t\t\"isPending\",\n\t\t\t\"isSkipped\",\n\t\t\t\"isStarted\",\n\t\t\t\"hasFailed\",\n\t\t\t\"isEnabled\",\n\t\t\t\"isRetrying\",\n\t\t\t\"path\"\n\t\t]\n\t};\n\tstatic rendererTaskOptions;\n\tlogger;\n\tserializer;\n\tconstructor(tasks, options) {\n\t\tthis.tasks = tasks;\n\t\tthis.options = options;\n\t\tthis.options = {\n\t\t\t...TestRenderer.rendererOptions,\n\t\t\t...this.options\n\t\t};\n\t\tthis.logger = this.options.logger ?? new ListrLogger({ useIcons: false });\n\t\tthis.serializer = new TestRendererSerializer(this.options);\n\t}\n\trender() {\n\t\tthis.renderer(this.tasks);\n\t}\n\tend() {}\n\trenderer(tasks) {\n\t\ttasks.forEach((task) => {\n\t\t\tif (this.options.subtasks) task.on(ListrTaskEventType.SUBTASK, (subtasks) => {\n\t\t\t\tthis.renderer(subtasks);\n\t\t\t});\n\t\t\tif (this.options.state) task.on(ListrTaskEventType.STATE, (state) => {\n\t\t\t\tthis.logger.toStdout(this.serializer.serialize(ListrTaskEventType.STATE, state, task));\n\t\t\t});\n\t\t\tif (this.options.output) task.on(ListrTaskEventType.OUTPUT, (data) => {\n\t\t\t\tthis.logger.toStdout(this.serializer.serialize(ListrTaskEventType.OUTPUT, data, task));\n\t\t\t});\n\t\t\tif (this.options.prompt) task.on(ListrTaskEventType.PROMPT, (prompt) => {\n\t\t\t\tthis.logger.toStdout(this.serializer.serialize(ListrTaskEventType.PROMPT, prompt, task));\n\t\t\t});\n\t\t\tif (this.options.title) task.on(ListrTaskEventType.TITLE, (title) => {\n\t\t\t\tthis.logger.toStdout(this.serializer.serialize(ListrTaskEventType.TITLE, title, task));\n\t\t\t});\n\t\t\ttask.on(ListrTaskEventType.MESSAGE, (message) => {\n\t\t\t\tconst parsed = Object.fromEntries(Object.entries(message).map(([key, value]) => {\n\t\t\t\t\tif (this.options.messages.includes(key)) return [key, value];\n\t\t\t\t}).filter(Boolean));\n\t\t\t\tif (Object.keys(parsed).length > 0) {\n\t\t\t\t\tconst output = this.serializer.serialize(ListrTaskEventType.MESSAGE, parsed, task);\n\t\t\t\t\tif (this.options.messagesToStderr.some((state) => Object.keys(parsed).includes(state))) this.logger.toStderr(output);\n\t\t\t\t\telse this.logger.toStdout(output);\n\t\t\t\t}\n\t\t\t});\n\t\t});\n\t}\n};\n\n//#endregion\n//#region src/renderer/verbose/renderer.ts\nvar VerboseRenderer = class VerboseRenderer {\n\tstatic nonTTY = true;\n\tstatic rendererOptions = {\n\t\tlogTitleChange: false,\n\t\tpausedTimer: {\n\t\t\t...PRESET_TIMER,\n\t\t\tformat: () => color.yellowBright\n\t\t}\n\t};\n\tstatic rendererTaskOptions;\n\tlogger;\n\tcache = {\n\t\trendererOptions: /* @__PURE__ */ new Map(),\n\t\trendererTaskOptions: /* @__PURE__ */ new Map()\n\t};\n\tconstructor(tasks, options) {\n\t\tthis.tasks = tasks;\n\t\tthis.options = options;\n\t\tthis.options = {\n\t\t\t...VerboseRenderer.rendererOptions,\n\t\t\t...this.options,\n\t\t\ticon: {\n\t\t\t\t...LISTR_LOGGER_STYLE.icon,\n\t\t\t\t...options?.icon ?? {}\n\t\t\t},\n\t\t\tcolor: {\n\t\t\t\t...LISTR_LOGGER_STYLE.color,\n\t\t\t\t...options?.color ?? {}\n\t\t\t}\n\t\t};\n\t\tthis.logger = this.options.logger ?? new ListrLogger({\n\t\t\tuseIcons: false,\n\t\t\ttoStderr: LISTR_LOGGER_STDERR_LEVELS\n\t\t});\n\t\tthis.logger.options.icon = this.options.icon;\n\t\tthis.logger.options.color = this.options.color;\n\t\tif (this.options.timestamp) this.logger.options.fields.prefix.unshift(this.options.timestamp);\n\t}\n\trender() {\n\t\tthis.renderer(this.tasks);\n\t}\n\tend() {}\n\trenderer(tasks) {\n\t\ttasks.forEach((task) => {\n\t\t\tthis.calculate(task);\n\t\t\ttask.once(ListrTaskEventType.CLOSED, () => {\n\t\t\t\tthis.reset(task);\n\t\t\t});\n\t\t\tconst rendererOptions = this.cache.rendererOptions.get(task.id);\n\t\t\tconst rendererTaskOptions = this.cache.rendererTaskOptions.get(task.id);\n\t\t\ttask.on(ListrTaskEventType.SUBTASK, (subtasks) => {\n\t\t\t\tthis.renderer(subtasks);\n\t\t\t});\n\t\t\ttask.on(ListrTaskEventType.STATE, (state) => {\n\t\t\t\tif (!task.hasTitle()) return;\n\t\t\t\tif (state === ListrTaskState.STARTED) this.logger.log(ListrLogLevels.STARTED, task.title);\n\t\t\t\telse if (state === ListrTaskState.COMPLETED) {\n\t\t\t\t\tconst timer = rendererTaskOptions.timer;\n\t\t\t\t\tthis.logger.log(ListrLogLevels.COMPLETED, task.title, timer && { suffix: {\n\t\t\t\t\t\t...timer,\n\t\t\t\t\t\tcondition: !!task.message?.duration && timer.condition,\n\t\t\t\t\t\targs: [task.message.duration]\n\t\t\t\t\t} });\n\t\t\t\t}\n\t\t\t});\n\t\t\ttask.on(ListrTaskEventType.OUTPUT, (data) => {\n\t\t\t\tthis.logger.log(ListrLogLevels.OUTPUT, data);\n\t\t\t});\n\t\t\ttask.on(ListrTaskEventType.PROMPT, (prompt) => {\n\t\t\t\tconst cleansed = cleanseAnsi(prompt);\n\t\t\t\tif (cleansed) this.logger.log(ListrLogLevels.PROMPT, cleansed);\n\t\t\t});\n\t\t\tif (this.options?.logTitleChange !== false) task.on(ListrTaskEventType.TITLE, (title) => {\n\t\t\t\tthis.logger.log(ListrLogLevels.TITLE, title);\n\t\t\t});\n\t\t\ttask.on(ListrTaskEventType.MESSAGE, (message) => {\n\t\t\t\tif (message?.error) this.logger.log(ListrLogLevels.FAILED, message.error);\n\t\t\t\telse if (message?.skip) this.logger.log(ListrLogLevels.SKIPPED, message.skip);\n\t\t\t\telse if (message?.rollback) this.logger.log(ListrLogLevels.ROLLBACK, message.rollback);\n\t\t\t\telse if (message?.retry) this.logger.log(ListrLogLevels.RETRY, task.title, { suffix: message.retry.count.toString() });\n\t\t\t\telse if (message?.paused) {\n\t\t\t\t\tconst timer = rendererOptions?.pausedTimer;\n\t\t\t\t\tthis.logger.log(ListrLogLevels.PAUSED, task.title, timer && { suffix: {\n\t\t\t\t\t\t...timer,\n\t\t\t\t\t\tcondition: !!message?.paused && timer.condition,\n\t\t\t\t\t\targs: [message.paused - Date.now()]\n\t\t\t\t\t} });\n\t\t\t\t}\n\t\t\t});\n\t\t});\n\t}\n\tcalculate(task) {\n\t\tif (this.cache.rendererOptions.has(task.id) && this.cache.rendererTaskOptions.has(task.id)) return;\n\t\tconst rendererOptions = {\n\t\t\t...this.options,\n\t\t\t...task.rendererOptions\n\t\t};\n\t\tthis.cache.rendererOptions.set(task.id, rendererOptions);\n\t\tthis.cache.rendererTaskOptions.set(task.id, {\n\t\t\t...VerboseRenderer.rendererTaskOptions,\n\t\t\ttimer: rendererOptions.timer,\n\t\t\t...task.rendererTaskOptions\n\t\t});\n\t}\n\treset(task) {\n\t\tthis.cache.rendererOptions.delete(task.id);\n\t\tthis.cache.rendererTaskOptions.delete(task.id);\n\t}\n};\n\n//#endregion\n//#region src/utils/ui/renderer.ts\nconst RENDERERS = {\n\tdefault: DefaultRenderer,\n\tsimple: SimpleRenderer,\n\tverbose: VerboseRenderer,\n\ttest: TestRenderer,\n\tsilent: SilentRenderer\n};\nfunction isRendererSupported(renderer) {\n\treturn process.stdout.isTTY === true || renderer.nonTTY === true;\n}\nfunction getRendererClass(renderer) {\n\tif (typeof renderer === \"string\") return RENDERERS[renderer] ?? RENDERERS.default;\n\treturn typeof renderer === \"function\" ? renderer : RENDERERS.default;\n}\nfunction getRenderer(options) {\n\tif (assertFunctionOrSelf(options?.silentRendererCondition)) return {\n\t\trenderer: getRendererClass(\"silent\"),\n\t\tselection: ListrRendererSelection.SILENT\n\t};\n\tconst r = {\n\t\trenderer: getRendererClass(options.renderer),\n\t\toptions: options.rendererOptions,\n\t\tselection: ListrRendererSelection.PRIMARY\n\t};\n\tif (!isRendererSupported(r.renderer) || assertFunctionOrSelf(options?.fallbackRendererCondition)) return {\n\t\trenderer: getRendererClass(options.fallbackRenderer),\n\t\toptions: options.fallbackRendererOptions,\n\t\tselection: ListrRendererSelection.SECONDARY\n\t};\n\treturn r;\n}\n\n//#endregion\n//#region src/utils/assert.ts\n/**\n* This function asserts the given value as a function or itself.\n* If the value itself is a function it will evaluate it with the passed in arguments,\n* elsewise it will directly return itself.\n*/\nfunction assertFunctionOrSelf(functionOrSelf, ...args) {\n\tif (typeof functionOrSelf === \"function\") return functionOrSelf(...args);\n\telse return functionOrSelf;\n}\n\n//#endregion\n//#region src/utils/clone.ts\nconst clone = rfdc({ circles: true });\n/**\n* Deep clones a object in the easiest manner.\n*/\nfunction cloneObject(obj) {\n\treturn clone(obj);\n}\n\n//#endregion\n//#region src/utils/concurrency.ts\nvar Concurrency = class {\n\tconcurrency;\n\tcount;\n\tqueue;\n\tconstructor(options) {\n\t\tthis.concurrency = options.concurrency;\n\t\tthis.count = 0;\n\t\tthis.queue = /* @__PURE__ */ new Set();\n\t}\n\tadd(fn) {\n\t\tif (this.count < this.concurrency) return this.run(fn);\n\t\treturn new Promise((resolve) => {\n\t\t\tconst callback = () => resolve(this.run(fn));\n\t\t\tthis.queue.add(callback);\n\t\t});\n\t}\n\tflush() {\n\t\tfor (const callback of this.queue) {\n\t\t\tif (this.count >= this.concurrency) break;\n\t\t\tthis.queue.delete(callback);\n\t\t\tcallback();\n\t\t}\n\t}\n\trun(fn) {\n\t\tthis.count++;\n\t\tconst promise = fn();\n\t\tconst cleanup = () => {\n\t\t\tthis.count--;\n\t\t\tthis.flush();\n\t\t};\n\t\tpromise.then(cleanup, () => {\n\t\t\tthis.queue.clear();\n\t\t});\n\t\treturn promise;\n\t}\n};\n\n//#endregion\n//#region src/utils/delay.ts\nfunction delay(time) {\n\treturn new Promise((resolve) => {\n\t\tsetTimeout(resolve, time);\n\t});\n}\n\n//#endregion\n//#region src/interfaces/listr-error.interface.ts\n/**\n* Internal error handling mechanism for Listr collects the errors and details for a failed task.\n*\n* @see {@link https://listr2.kilic.dev/task/error-handling.html}\n*/\nvar ListrError = class extends Error {\n\tpath;\n\tctx;\n\tconstructor(error, type, task) {\n\t\tsuper(error.message);\n\t\tthis.error = error;\n\t\tthis.type = type;\n\t\tthis.task = task;\n\t\tthis.name = \"ListrError\";\n\t\tthis.path = task.path;\n\t\tif (task?.options.collectErrors === \"full\") {\n\t\t\tthis.task = cloneObject(task);\n\t\t\tthis.ctx = cloneObject(task.listr.ctx);\n\t\t}\n\t\tthis.stack = error?.stack;\n\t}\n};\n\n//#endregion\n//#region src/interfaces/listr-renderer-error.interface.ts\n/**\n* Internal error coming from renderer.\n*/\nvar ListrRendererError = class extends Error {};\n\n//#endregion\n//#region src/interfaces/prompt-error.interface.ts\n/**\n* Internal error handling mechanism for Listr prompts to identify the failing cause is coming from a prompt.\n*\n* @see {@link https://listr2.kilic.dev/task/prompts.html}\n*/\nvar PromptError = class extends Error {};\n\n//#endregion\n//#region src/lib/task-wrapper.ts\n/**\n* The original Task that is defined by the user is wrapped with the TaskWrapper to provide additional functionality.\n*\n* @see {@link https://listr2.kilic.dev/task/task.html}\n*/\nvar TaskWrapper = class {\n\tconstructor(task) {\n\t\tthis.task = task;\n\t}\n\t/* istanbul ignore next */\n\tget title() {\n\t\treturn this.task.title;\n\t}\n\t/**\n\t* Title of the current task.\n\t*\n\t* @see {@link https://listr2.kilic.dev/task/title.html}\n\t*/\n\tset title(title) {\n\t\ttitle = Array.isArray(title) ? title : [title];\n\t\tthis.task.title$ = splat(title.shift(), ...title);\n\t}\n\t/* istanbul ignore next */\n\tget output() {\n\t\treturn this.task.output;\n\t}\n\t/* istanbul ignore next */\n\t/**\n\t* Send output from the current task to the renderer.\n\t*\n\t* @see {@link https://listr2.kilic.dev/task/output.html}\n\t*/\n\tset output(output) {\n\t\toutput = Array.isArray(output) ? output : [output];\n\t\tthis.task.output$ = splat(output.shift(), ...output);\n\t}\n\t/* istanbul ignore next */\n\t/** Send an output to the output channel as prompt. */\n\tset promptOutput(output) {\n\t\tthis.task.promptOutput$ = output;\n\t}\n\t/**\n\t* Creates a new set of Listr subtasks.\n\t*\n\t* @see {@link https://listr2.kilic.dev/task/subtasks.html}\n\t*/\n\tnewListr(task, options) {\n\t\tlet tasks;\n\t\tif (typeof task === \"function\") tasks = task(this);\n\t\telse tasks = task;\n\t\treturn new Listr(tasks, options, this.task);\n\t}\n\t/**\n\t* Report an error that has to be collected and handled.\n\t*\n\t* @see {@link https://listr2.kilic.dev/task/error-handling.html}\n\t*/\n\treport(error, type) {\n\t\tif (this.task.options.collectErrors !== false) this.task.listr.errors.push(new ListrError(error, type, this.task));\n\t\tthis.task.message$ = { error: error.message ?? this.task?.title };\n\t}\n\t/**\n\t* Skip the current task.\n\t*\n\t* @see {@link https://listr2.kilic.dev/task/skip.html}\n\t*/\n\tskip(message, ...metadata) {\n\t\tthis.task.state$ = ListrTaskState.SKIPPED;\n\t\tif (message) this.task.message$ = { skip: message ? splat(message, ...metadata) : this.task?.title };\n\t}\n\t/**\n\t* Check whether this task is currently in a retry state.\n\t*\n\t* @see {@link https://listr2.kilic.dev/task/retry.html}\n\t*/\n\tisRetrying() {\n\t\treturn this.task.isRetrying() ? this.task.retry : { count: 0 };\n\t}\n\t/* istanbul ignore next */\n\t/**\n\t* Create a new prompt for getting user input through the prompt adapter.\n\t* This will create a new prompt through the adapter if the task is not currently rendering a prompt or will return the active instance.\n\t*\n\t* This part of the application requires optional peer dependencies, please refer to documentation.\n\t*\n\t* @see {@link https://listr2.kilic.dev/task/prompt.html}\n\t*/\n\tprompt(adapter) {\n\t\tif (this.task.prompt) return this.task.prompt;\n\t\treturn new adapter(this.task, this);\n\t}\n\t/* istanbul ignore next */\n\t/**\n\t* Generates a fake stdout for your use case, where it will be tunnelled through Listr to handle the rendering process.\n\t*\n\t* @see {@link https://listr2.kilic.dev/renderer/process-output.html}\n\t*/\n\tstdout(type) {\n\t\treturn createWritable((chunk) => {\n\t\t\tswitch (type) {\n\t\t\t\tcase ListrTaskEventType.PROMPT:\n\t\t\t\t\tthis.promptOutput = chunk;\n\t\t\t\t\tbreak;\n\t\t\t\tdefault: this.output = chunk;\n\t\t\t}\n\t\t});\n\t}\n\t/** Run this task. */\n\trun(ctx) {\n\t\treturn this.task.run(ctx, this);\n\t}\n};\n\n//#endregion\n//#region src/lib/listr-task-event-manager.ts\nvar ListrTaskEventManager = class extends EventManager {};\n\n//#endregion\n//#region src/lib/task.ts\n/**\n* Creates and handles a runnable instance of the Task.\n*/\nvar Task = class extends ListrTaskEventManager {\n\t/** Unique id per task, can be used for identifying a Task. */\n\tid = randomUUID();\n\t/** The current state of the task. */\n\tstate = ListrTaskState.WAITING;\n\t/** Subtasks of the current task. */\n\tsubtasks;\n\t/** Title of the task. */\n\ttitle;\n\t/** Initial/Untouched version of the title for using whenever task has a reset. */\n\tinitialTitle;\n\t/** Output channel for the task. */\n\toutput;\n\t/** Current state of the retry process whenever the task is retrying. */\n\tretry;\n\t/**\n\t* A channel for messages.\n\t*\n\t* This requires a separate channel for messages like error, skip or runtime messages to further utilize in the renderers.\n\t*/\n\tmessage = {};\n\t/** Current prompt instance or prompt error whenever the task is prompting. */\n\tprompt;\n\t/** Parent task of the current task. */\n\tparent;\n\t/** Enable flag of this task. */\n\tenabled;\n\t/** User provided Task callback function to run. */\n\ttaskFn;\n\t/** Marks the task as closed. This is different from finalized since this is not really related to task itself. */\n\tclosed;\n\tconstructor(listr, task, options, rendererOptions, rendererTaskOptions) {\n\t\tsuper();\n\t\tthis.listr = listr;\n\t\tthis.task = task;\n\t\tthis.options = options;\n\t\tthis.rendererOptions = rendererOptions;\n\t\tthis.rendererTaskOptions = rendererTaskOptions;\n\t\tif (task.title) {\n\t\t\tconst title = Array.isArray(task?.title) ? task.title : [task.title];\n\t\t\tthis.title = splat(title.shift(), ...title);\n\t\t\tthis.initialTitle = this.title;\n\t\t}\n\t\tthis.taskFn = task.task;\n\t\tthis.parent = listr.parentTask;\n\t}\n\t/**\n\t* Update the current state of the Task and emit the neccassary events.\n\t*/\n\tset state$(state) {\n\t\tthis.state = state;\n\t\tthis.emit(ListrTaskEventType.STATE, state);\n\t\tif (this.hasSubtasks() && this.hasFailed()) {\n\t\t\tfor (const subtask of this.subtasks) if (subtask.state === ListrTaskState.STARTED) subtask.state$ = ListrTaskState.FAILED;\n\t\t}\n\t\tthis.listr.events.emit(ListrEventType.SHOULD_REFRESH_RENDER);\n\t}\n\t/**\n\t* Update the current output of the Task and emit the neccassary events.\n\t*/\n\tset output$(data) {\n\t\tthis.output = data;\n\t\tthis.emit(ListrTaskEventType.OUTPUT, data);\n\t\tthis.listr.events.emit(ListrEventType.SHOULD_REFRESH_RENDER);\n\t}\n\t/**\n\t* Update the current prompt output of the Task and emit the neccassary events.\n\t*/\n\tset promptOutput$(data) {\n\t\tthis.emit(ListrTaskEventType.PROMPT, data);\n\t\tif (cleanseAnsi(data)) this.listr.events.emit(ListrEventType.SHOULD_REFRESH_RENDER);\n\t}\n\t/**\n\t* Update or extend the current message of the Task and emit the neccassary events.\n\t*/\n\tset message$(data) {\n\t\tthis.message = {\n\t\t\t...this.message,\n\t\t\t...data\n\t\t};\n\t\tthis.emit(ListrTaskEventType.MESSAGE, data);\n\t\tthis.listr.events.emit(ListrEventType.SHOULD_REFRESH_RENDER);\n\t}\n\t/**\n\t* Update the current title of the Task and emit the neccassary events.\n\t*/\n\tset title$(title) {\n\t\tthis.title = title;\n\t\tthis.emit(ListrTaskEventType.TITLE, title);\n\t\tthis.listr.events.emit(ListrEventType.SHOULD_REFRESH_RENDER);\n\t}\n\t/**\n\t* Current task path in the hierarchy.\n\t*/\n\tget path() {\n\t\treturn [...this.listr.path, this.initialTitle];\n\t}\n\t/**\n\t* Checks whether the current task with the given context should be set as enabled.\n\t*/\n\tasync check(ctx) {\n\t\tif (this.state === ListrTaskState.WAITING) {\n\t\t\tthis.enabled = await assertFunctionOrSelf(this.task?.enabled ?? true, ctx);\n\t\t\tthis.emit(ListrTaskEventType.ENABLED, this.enabled);\n\t\t\tthis.listr.events.emit(ListrEventType.SHOULD_REFRESH_RENDER);\n\t\t}\n\t\treturn this.enabled;\n\t}\n\t/** Returns whether this task has subtasks. */\n\thasSubtasks() {\n\t\treturn this.subtasks?.length > 0;\n\t}\n\t/** Returns whether this task is finalized in someform. */\n\thasFinalized() {\n\t\treturn this.isCompleted() || this.hasFailed() || this.isSkipped() || this.hasRolledBack();\n\t}\n\t/** Returns whether this task is in progress. */\n\tisPending() {\n\t\treturn this.isStarted() || this.isPrompt() || this.hasReset();\n\t}\n\t/** Returns whether this task has started. */\n\tisStarted() {\n\t\treturn this.state === ListrTaskState.STARTED;\n\t}\n\t/** Returns whether this task is skipped. */\n\tisSkipped() {\n\t\treturn this.state === ListrTaskState.SKIPPED;\n\t}\n\t/** Returns whether this task has been completed. */\n\tisCompleted() {\n\t\treturn this.state === ListrTaskState.COMPLETED;\n\t}\n\t/** Returns whether this task has been failed. */\n\thasFailed() {\n\t\treturn this.state === ListrTaskState.FAILED;\n\t}\n\t/** Returns whether this task has an active rollback task going on. */\n\tisRollingBack() {\n\t\treturn this.state === ListrTaskState.ROLLING_BACK;\n\t}\n\t/** Returns whether the rollback action was successful. */\n\thasRolledBack() {\n\t\treturn this.state === ListrTaskState.ROLLED_BACK;\n\t}\n\t/** Returns whether this task has an actively retrying task going on. */\n\tisRetrying() {\n\t\treturn this.state === ListrTaskState.RETRY;\n\t}\n\t/** Returns whether this task has some kind of reset like retry and rollback going on. */\n\thasReset() {\n\t\treturn this.state === ListrTaskState.RETRY || this.state === ListrTaskState.ROLLING_BACK;\n\t}\n\t/** Returns whether enabled function resolves to true. */\n\tisEnabled() {\n\t\treturn this.enabled;\n\t}\n\t/** Returns whether this task actually has a title. */\n\thasTitle() {\n\t\treturn typeof this?.title === \"string\";\n\t}\n\t/** Returns whether this task has a prompt inside. */\n\tisPrompt() {\n\t\treturn this.state === ListrTaskState.PROMPT;\n\t}\n\t/** Returns whether this task is currently paused. */\n\tisPaused() {\n\t\treturn this.state === ListrTaskState.PAUSED;\n\t}\n\t/** Returns whether this task is closed. */\n\tisClosed() {\n\t\treturn this.closed;\n\t}\n\t/** Pause the given task for certain time. */\n\tasync pause(time) {\n\t\tconst state = this.state;\n\t\tthis.state$ = ListrTaskState.PAUSED;\n\t\tthis.message$ = { paused: Date.now() + time };\n\t\tawait delay(time);\n\t\tthis.state$ = state;\n\t\tthis.message$ = { paused: null };\n\t}\n\t/** Run the current task. */\n\tasync run(context, wrapper) {\n\t\tconst handleResult = (result) => {\n\t\t\tif (result instanceof Listr) {\n\t\t\t\tresult.options = {\n\t\t\t\t\t...this.options,\n\t\t\t\t\t...result.options\n\t\t\t\t};\n\t\t\t\tresult.rendererClass = getRendererClass(\"silent\");\n\t\t\t\tthis.subtasks = result.tasks;\n\t\t\t\tresult.errors = this.listr.errors;\n\t\t\t\tthis.emit(ListrTaskEventType.SUBTASK, this.subtasks);\n\t\t\t\tresult = result.run(context);\n\t\t\t} else if (result instanceof Promise) result = result.then(handleResult);\n\t\t\telse if (isReadable(result)) result = new Promise((resolve, reject) => {\n\t\t\t\tresult.on(\"data\", (data) => {\n\t\t\t\t\tthis.output$ = data.toString();\n\t\t\t\t});\n\t\t\t\tresult.on(\"error\", (error) => reject(error));\n\t\t\t\tresult.on(\"end\", () => resolve(null));\n\t\t\t});\n\t\t\telse if (isObservable(result)) result = new Promise((resolve, reject) => {\n\t\t\t\tresult.subscribe({\n\t\t\t\t\tnext: (data) => {\n\t\t\t\t\t\tthis.output$ = data;\n\t\t\t\t\t},\n\t\t\t\t\terror: reject,\n\t\t\t\t\tcomplete: resolve\n\t\t\t\t});\n\t\t\t});\n\t\t\treturn result;\n\t\t};\n\t\tconst startTime = Date.now();\n\t\tthis.state$ = ListrTaskState.STARTED;\n\t\tconst skipped = await assertFunctionOrSelf(this.task?.skip ?? false, context);\n\t\tif (skipped) {\n\t\t\tif (typeof skipped === \"string\") this.message$ = { skip: skipped };\n\t\t\telse if (this.hasTitle()) this.message$ = { skip: this.title };\n\t\t\telse this.message$ = { skip: \"Skipped task without a title.\" };\n\t\t\tthis.state$ = ListrTaskState.SKIPPED;\n\t\t\treturn;\n\t\t}\n\t\ttry {\n\t\t\tconst retryCount = typeof this.task?.retry === \"number\" && this.task.retry > 0 ? this.task.retry + 1 : typeof this.task?.retry === \"object\" && this.task.retry.tries > 0 ? this.task.retry.tries + 1 : 1;\n\t\t\tconst retryDelay = typeof this.task.retry === \"object\" && this.task.retry.delay;\n\t\t\tfor (let retries = 1; retries <= retryCount; retries++) try {\n\t\t\t\tawait handleResult(this.taskFn(context, wrapper));\n\t\t\t\tbreak;\n\t\t\t} catch (err) {\n\t\t\t\tif (retries !== retryCount) {\n\t\t\t\t\tthis.retry = {\n\t\t\t\t\t\tcount: retries,\n\t\t\t\t\t\terror: err\n\t\t\t\t\t};\n\t\t\t\t\tthis.message$ = { retry: this.retry };\n\t\t\t\t\tthis.title$ = this.initialTitle;\n\t\t\t\t\tthis.output = void 0;\n\t\t\t\t\twrapper.report(err, ListrErrorTypes.WILL_RETRY);\n\t\t\t\t\tthis.state$ = ListrTaskState.RETRY;\n\t\t\t\t\tif (retryDelay) await this.pause(retryDelay);\n\t\t\t\t} else throw err;\n\t\t\t}\n\t\t\tif (this.isStarted() || this.isRetrying()) {\n\t\t\t\tthis.message$ = { duration: Date.now() - startTime };\n\t\t\t\tthis.state$ = ListrTaskState.COMPLETED;\n\t\t\t}\n\t\t} catch (error) {\n\t\t\tif (this.prompt instanceof PromptError) error = this.prompt;\n\t\t\tif (this.task?.rollback) {\n\t\t\t\twrapper.report(error, ListrErrorTypes.WILL_ROLLBACK);\n\t\t\t\ttry {\n\t\t\t\t\tthis.state$ = ListrTaskState.ROLLING_BACK;\n\t\t\t\t\tawait this.task.rollback(context, wrapper);\n\t\t\t\t\tthis.message$ = { rollback: this.title };\n\t\t\t\t\tthis.state$ = ListrTaskState.ROLLED_BACK;\n\t\t\t\t} catch (err) {\n\t\t\t\t\tthis.state$ = ListrTaskState.FAILED;\n\t\t\t\t\twrapper.report(err, ListrErrorTypes.HAS_FAILED_TO_ROLLBACK);\n\t\t\t\t\tthis.close();\n\t\t\t\t\tthrow err;\n\t\t\t\t}\n\t\t\t\tif (this.listr.options?.exitAfterRollback !== false) {\n\t\t\t\t\tthis.close();\n\t\t\t\t\tthrow error;\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\tthis.state$ = ListrTaskState.FAILED;\n\t\t\t\tif (this.listr.options.exitOnError !== false && await assertFunctionOrSelf(this.task?.exitOnError, context) !== false) {\n\t\t\t\t\twrapper.report(error, ListrErrorTypes.HAS_FAILED);\n\t\t\t\t\tthis.close();\n\t\t\t\t\tthrow error;\n\t\t\t\t} else if (!this.hasSubtasks()) wrapper.report(error, ListrErrorTypes.HAS_FAILED_WITHOUT_ERROR);\n\t\t\t}\n\t\t} finally {\n\t\t\tthis.close();\n\t\t}\n\t}\n\tclose() {\n\t\tthis.emit(ListrTaskEventType.CLOSED);\n\t\tthis.listr.events.emit(ListrEventType.SHOULD_REFRESH_RENDER);\n\t\tthis.complete();\n\t}\n};\n\n//#endregion\n//#region src/lib/listr-event-manager.ts\nvar ListrEventManager = class extends EventManager {};\n\n//#endregion\n//#region src/listr.ts\n/**\n* Create a new task list with Listr.\n*\n* @see {@link https://listr2.kilic.dev/listr/listr.html}\n*/\nvar Listr = class {\n\ttasks = [];\n\terrors = [];\n\tctx;\n\tevents;\n\tpath = [];\n\trendererClass;\n\trendererClassOptions;\n\trendererSelection;\n\tboundSignalHandler;\n\tconcurrency;\n\trenderer;\n\tconstructor(task, options, parentTask) {\n\t\tthis.task = task;\n\t\tthis.options = options;\n\t\tthis.parentTask = parentTask;\n\t\tthis.options = {\n\t\t\tconcurrent: false,\n\t\t\trenderer: \"default\",\n\t\t\tfallbackRenderer: \"simple\",\n\t\t\texitOnError: true,\n\t\t\texitAfterRollback: true,\n\t\t\tcollectErrors: false,\n\t\t\tregisterSignalListeners: true,\n\t\t\t...this.parentTask?.options ?? {},\n\t\t\t...options\n\t\t};\n\t\tif (this.options.concurrent === true) this.options.concurrent = Infinity;\n\t\telse if (typeof this.options.concurrent !== \"number\") this.options.concurrent = 1;\n\t\tthis.concurrency = new Concurrency({ concurrency: this.options.concurrent });\n\t\tif (parentTask) {\n\t\t\tthis.path = [...parentTask.listr.path, parentTask.title];\n\t\t\tthis.errors = parentTask.listr.errors;\n\t\t}\n\t\tif (this.parentTask?.listr.events instanceof ListrEventManager) this.events = this.parentTask.listr.events;\n\t\telse this.events = new ListrEventManager();\n\t\t/* istanbul ignore if */\n\t\tif (this.options?.forceTTY || process.env[ListrEnvironmentVariables.FORCE_TTY]) {\n\t\t\tprocess.stdout.isTTY = true;\n\t\t\tprocess.stderr.isTTY = true;\n\t\t}\n\t\t/* istanbul ignore if */\n\t\tif (this.options?.forceUnicode) process.env[ListrEnvironmentVariables.FORCE_UNICODE] = \"1\";\n\t\tconst renderer = getRenderer({\n\t\t\trenderer: this.options.renderer,\n\t\t\trendererOptions: this.options.rendererOptions,\n\t\t\tfallbackRenderer: this.options.fallbackRenderer,\n\t\t\tfallbackRendererOptions: this.options.fallbackRendererOptions,\n\t\t\tfallbackRendererCondition: this.options?.fallbackRendererCondition,\n\t\t\tsilentRendererCondition: this.options?.silentRendererCondition\n\t\t});\n\t\tthis.rendererClass = renderer.renderer;\n\t\tthis.rendererClassOptions = renderer.options;\n\t\tthis.rendererSelection = renderer.selection;\n\t\t/* istanbul ignore next */\n\t\tthis.add(task ?? []);\n\t\t/* istanbul ignore if */\n\t\tif (this.options.registerSignalListeners) {\n\t\t\tthis.boundSignalHandler = this.signalHandler.bind(this);\n\t\t\tprocess.once(\"SIGINT\", this.boundSignalHandler).setMaxListeners(0);\n\t\t}\n\t}\n\t/**\n\t* Whether this is the root task.\n\t*/\n\tisRoot() {\n\t\treturn !this.parentTask;\n\t}\n\t/**\n\t* Whether this is a subtask of another task list.\n\t*/\n\tisSubtask() {\n\t\treturn !!this.parentTask;\n\t}\n\t/**\n\t* Add tasks to current task list.\n\t*\n\t* @see {@link https://listr2.kilic.dev/task/task.html}\n\t*/\n\tadd(tasks) {\n\t\tthis.tasks.push(...this.generate(tasks));\n\t}\n\t/**\n\t* Run the task list.\n\t*\n\t* @see {@link https://listr2.kilic.dev/listr/listr.html#run-the-generated-task-list}\n\t*/\n\tasync run(context) {\n\t\tif (!this.renderer) this.renderer = new this.rendererClass(this.tasks, this.rendererClassOptions, this.events);\n\t\tawait this.renderer.render();\n\t\tthis.ctx = this.options?.ctx ?? context ?? {};\n\t\ttry {\n\t\t\tawait Promise.all(this.tasks.map((task) => task.check(this.ctx)));\n\t\t\tawait Promise.all(this.tasks.map((task) => this.concurrency.add(() => this.runTask(task))));\n\t\t\tthis.renderer.end();\n\t\t\tthis.removeSignalHandler();\n\t\t} catch (err) {\n\t\t\tif (this.options.exitOnError !== false) {\n\t\t\t\tthis.renderer.end(err);\n\t\t\t\tthis.removeSignalHandler();\n\t\t\t\tthrow err;\n\t\t\t}\n\t\t}\n\t\treturn this.ctx;\n\t}\n\tgenerate(tasks) {\n\t\ttasks = Array.isArray(tasks) ? tasks : [tasks];\n\t\treturn tasks.map((task) => {\n\t\t\tlet rendererTaskOptions;\n\t\t\tif (this.rendererSelection === ListrRendererSelection.PRIMARY) rendererTaskOptions = task.rendererOptions;\n\t\t\telse if (this.rendererSelection === ListrRendererSelection.SECONDARY) rendererTaskOptions = task.fallbackRendererOptions;\n\t\t\treturn new Task(this, task, this.options, this.rendererClassOptions, rendererTaskOptions);\n\t\t});\n\t}\n\tasync runTask(task) {\n\t\tif (!await task.check(this.ctx)) return;\n\t\treturn new TaskWrapper(task).run(this.ctx);\n\t}\n\tsignalHandler() {\n\t\tthis.tasks?.forEach(async (task) => {\n\t\t\tif (task.isPending()) task.state$ = ListrTaskState.FAILED;\n\t\t});\n\t\tif (this.isRoot()) {\n\t\t\tthis.renderer?.end(/* @__PURE__ */ new Error(\"Interrupted.\"));\n\t\t\tprocess.exit(127);\n\t\t}\n\t}\n\tremoveSignalHandler() {\n\t\tif (this.boundSignalHandler) process.removeListener(\"SIGINT\", this.boundSignalHandler);\n\t}\n};\n\n//#endregion\nexport { ANSI_ESCAPE, ANSI_ESCAPE_CODES, BaseEventMap, Concurrency, DefaultRenderer, EventManager, LISTR_DEFAULT_RENDERER_STYLE, LISTR_LOGGER_STDERR_LEVELS, LISTR_LOGGER_STYLE, Listr, ListrDefaultRendererLogLevels, ListrEnvironmentVariables, ListrError, ListrErrorTypes, ListrEventManager, ListrEventType, ListrLogLevels, ListrLogger, ListrPromptAdapter, ListrRendererError, ListrRendererSelection, ListrTaskEventManager, ListrTaskEventType, ListrTaskState, PRESET_TIMER, PRESET_TIMESTAMP, ProcessOutput, ProcessOutputBuffer, ProcessOutputStream, PromptError, SilentRenderer, SimpleRenderer, Spinner, TestRenderer, TestRendererSerializer, VerboseRenderer, assertFunctionOrSelf, cleanseAnsi, cloneObject, color, createWritable, delay, figures, getRenderer, getRendererClass, indent, isObservable, isReadable, isUnicodeSupported, parseTimer, parseTimestamp, splat };","import { mkdirSync, existsSync } from 'node:fs'\nimport { dirname } from 'node:path'\nimport { Listr } from 'listr2'\nimport { confirm } from '@clack/prompts'\nimport { readConfig, writeConfig } from '../../utils/config-paths.js'\nimport type { ConfigFormat } from '../../utils/config-paths.js'\nimport { cliError } from '../../utils/error.js'\n\nexport interface ServerEntry {\n  name: string\n  command: string\n  args?: string[]\n  env?: Record<string, string>\n}\n\nexport function parseArgList(raw: string): string[] {\n  return raw.trim().split(/\\s+/).filter(Boolean)\n}\n\nexport function parseEnvMap(raw: string): Record<string, string> {\n  return Object.fromEntries(\n    raw.split(',').map((kv) => {\n      const i = kv.indexOf('=')\n      return i === -1 ? [kv, ''] : [kv.slice(0, i), kv.slice(i + 1)]\n    }),\n  )\n}\n\nfunction ensureDir(path: string): void {\n  const dir = dirname(path)\n  if (!existsSync(dir)) {\n    mkdirSync(dir, { recursive: true })\n  }\n}\n\ntype InstallCtx = {\n  config: Record<string, unknown>\n  exists: boolean\n  overwrite: boolean\n}\n\nexport async function installServer(opts: {\n  configPath: string\n  format: ConfigFormat\n  entry: ServerEntry\n  force?: boolean\n  configSection?: string\n  configWriter?: (config: Record<string, unknown>, entry: ServerEntry) => void\n}): Promise<void> {\n  const { configPath, format, entry } = opts\n  const configSection = opts.configSection ?? 'mcpServers'\n\n  const tasks = new Listr<InstallCtx>(\n    [\n      {\n        title: 'Resolving config file',\n        task: async (ctx) => {\n          ctx.exists = existsSync(configPath)\n          if (!ctx.exists) {\n            ensureDir(configPath)\n            ctx.config = {}\n          } else {\n            try {\n              ctx.config = (readConfig(configPath, format) as Record<string, unknown>) ?? {}\n            } catch {\n              throw new Error(`Could not parse ${configPath} — is it valid ${format.toUpperCase()}?`)\n            }\n          }\n        },\n      },\n      {\n        title: 'Checking for existing entry',\n        task: async (ctx, task) => {\n          const section = ctx.config[configSection] as Record<string, unknown> | undefined\n          if (section?.[entry.name]) {\n            if (opts.force) {\n              ctx.overwrite = true\n              return\n            }\n            if (!process.stdin.isTTY || process.env['CI']) {\n              throw new Error(`Server \"${entry.name}\" already exists. Use --force to overwrite.`)\n            }\n            const overwrite = await confirm({\n              message: `Server \"${entry.name}\" already exists. Overwrite?`,\n            })\n            if (!overwrite || typeof overwrite !== 'boolean') {\n              task.skip('Skipped — entry unchanged')\n              ctx.overwrite = false\n              return\n            }\n          }\n          ctx.overwrite = true\n        },\n      },\n      {\n        title: 'Writing config',\n        skip: (ctx) => !ctx.overwrite,\n        task: async (ctx) => {\n          if (opts.configWriter) {\n            opts.configWriter(ctx.config, entry)\n          } else {\n            if (!ctx.config[configSection]) ctx.config[configSection] = {}\n            ;(ctx.config[configSection] as Record<string, unknown>)[entry.name] = {\n              command: entry.command,\n              ...(entry.args ? { args: entry.args } : {}),\n              ...(entry.env ? { env: entry.env } : {}),\n            }\n          }\n          writeConfig(configPath, ctx.config, format)\n        },\n      },\n      {\n        title: 'Verifying config',\n        skip: (ctx) => !ctx.overwrite,\n        task: async () => {\n          try {\n            readConfig(configPath, format)\n          } catch {\n            throw new Error(`Config verification failed — ${configPath} may be malformed`)\n          }\n        },\n      },\n    ],\n    { rendererOptions: { collapseErrors: false } },\n  )\n\n  try {\n    await tasks.run()\n  } catch (err) {\n    cliError(err instanceof Error ? err.message : String(err))\n  }\n}\n","import { defineCommand } from 'citty'\nimport { getConfigPaths } from '../../utils/config-paths.js'\nimport { installServer, parseArgList, parseEnvMap } from './shared.js'\n\nexport default defineCommand({\n  meta: { name: 'claude-code', description: 'Install MCP server into Claude Code (~/.claude.json)' },\n  args: {\n    name: { type: 'positional', description: 'Server name', required: true },\n    command: { type: 'positional', description: 'Command to run the server', required: true },\n    args: { type: 'string', description: 'Space-separated server args (quoted)' },\n    env: { type: 'string', description: 'Comma-separated KEY=VALUE env vars' },\n    force: { type: 'boolean', description: 'Overwrite existing entry without prompting', default: false },\n  },\n  async run({ args }) {\n    const target = getConfigPaths()['claude-code']!\n    await installServer({\n      configPath: target.path,\n      format: target.format,\n      force: args.force,\n      entry: {\n        name: args.name,\n        command: args.command,\n        args: args.args ? parseArgList(args.args) : undefined,\n        env: args.env ? parseEnvMap(args.env) : undefined,\n      },\n    })\n  },\n})\n","import { defineCommand } from 'citty'\nimport { getConfigPaths } from '../../utils/config-paths.js'\nimport { installServer, parseArgList, parseEnvMap } from './shared.js'\n\nexport default defineCommand({\n  meta: { name: 'claude-desktop', description: 'Install MCP server into Claude Desktop' },\n  args: {\n    name: { type: 'positional', description: 'Server name', required: true },\n    command: { type: 'positional', description: 'Command to run the server', required: true },\n    args: { type: 'string', description: 'Space-separated server args (quoted)' },\n    env: { type: 'string', description: 'Comma-separated KEY=VALUE env vars' },\n    force: { type: 'boolean', description: 'Overwrite existing entry without prompting', default: false },\n  },\n  async run({ args }) {\n    const target = getConfigPaths()['claude-desktop']!\n    await installServer({\n      configPath: target.path,\n      format: target.format,\n      force: args.force,\n      entry: {\n        name: args.name,\n        command: args.command,\n        args: args.args ? parseArgList(args.args) : undefined,\n        env: args.env ? parseEnvMap(args.env) : undefined,\n      },\n    })\n  },\n})\n","import { defineCommand } from 'citty'\nimport { getConfigPaths } from '../../utils/config-paths.js'\nimport { installServer, parseArgList, parseEnvMap } from './shared.js'\n\nexport default defineCommand({\n  meta: { name: 'cursor', description: 'Install MCP server into Cursor (~/.cursor/mcp.json)' },\n  args: {\n    name: { type: 'positional', description: 'Server name', required: true },\n    command: { type: 'positional', description: 'Command to run the server', required: true },\n    args: { type: 'string', description: 'Space-separated server args (quoted)' },\n    env: { type: 'string', description: 'Comma-separated KEY=VALUE env vars' },\n    force: { type: 'boolean', description: 'Overwrite existing entry without prompting', default: false },\n  },\n  async run({ args }) {\n    const target = getConfigPaths()['cursor']!\n    await installServer({\n      configPath: target.path,\n      format: target.format,\n      force: args.force,\n      entry: {\n        name: args.name,\n        command: args.command,\n        args: args.args ? parseArgList(args.args) : undefined,\n        env: args.env ? parseEnvMap(args.env) : undefined,\n      },\n    })\n  },\n})\n","import { defineCommand } from 'citty'\nimport { getConfigPaths } from '../../utils/config-paths.js'\nimport { installServer, parseArgList, parseEnvMap } from './shared.js'\n\nexport default defineCommand({\n  meta: { name: 'gemini', description: 'Install MCP server into Gemini CLI (~/.gemini/settings.json)' },\n  args: {\n    name: { type: 'positional', description: 'Server name', required: true },\n    command: { type: 'positional', description: 'Command to run the server', required: true },\n    args: { type: 'string', description: 'Space-separated server args (quoted)' },\n    env: { type: 'string', description: 'Comma-separated KEY=VALUE env vars' },\n    force: { type: 'boolean', description: 'Overwrite existing entry without prompting', default: false },\n  },\n  async run({ args }) {\n    const target = getConfigPaths()['gemini']!\n    await installServer({\n      configPath: target.path,\n      format: target.format,\n      force: args.force,\n      entry: {\n        name: args.name,\n        command: args.command,\n        args: args.args ? parseArgList(args.args) : undefined,\n        env: args.env ? parseEnvMap(args.env) : undefined,\n      },\n    })\n  },\n})\n","import { defineCommand } from 'citty'\nimport { getConfigPaths } from '../../utils/config-paths.js'\nimport { installServer, parseArgList, parseEnvMap, type ServerEntry } from './shared.js'\n\nexport default defineCommand({\n  meta: { name: 'goose', description: 'Install MCP server into Goose (~/.config/goose/config.yaml)' },\n  args: {\n    name: { type: 'positional', description: 'Server name', required: true },\n    command: { type: 'positional', description: 'Command to run the server', required: true },\n    args: { type: 'string', description: 'Space-separated server args (quoted)' },\n    env: { type: 'string', description: 'Comma-separated KEY=VALUE env vars' },\n    force: { type: 'boolean', description: 'Overwrite existing entry without prompting', default: false },\n  },\n  async run({ args }) {\n    const target = getConfigPaths()['goose']!\n    await installServer({\n      configPath: target.path,\n      format: target.format,\n      force: args.force,\n      configSection: 'extensions',\n      configWriter: (config: Record<string, unknown>, entry: ServerEntry) => {\n        if (!config['extensions']) config['extensions'] = {}\n        ;(config['extensions'] as Record<string, unknown>)[entry.name] = {\n          cmd: entry.command,\n          ...(entry.args?.length ? { args: entry.args } : {}),\n          ...(entry.env ? { env: entry.env } : {}),\n          enabled: true,\n          type: 'stdio',\n        }\n      },\n      entry: {\n        name: args.name,\n        command: args.command,\n        args: args.args ? parseArgList(args.args) : undefined,\n        env: args.env ? parseEnvMap(args.env) : undefined,\n      },\n    })\n  },\n})\n","import { defineCommand } from 'citty'\nimport { getConfigPaths } from '../../utils/config-paths.js'\nimport { installServer, parseArgList, parseEnvMap } from './shared.js'\n\nexport default defineCommand({\n  meta: { name: 'mcp-json', description: 'Install MCP server into local mcp.json' },\n  args: {\n    name: { type: 'positional', description: 'Server name', required: true },\n    command: { type: 'positional', description: 'Command to run the server', required: true },\n    args: { type: 'string', description: 'Space-separated server args (quoted)' },\n    env: { type: 'string', description: 'Comma-separated KEY=VALUE env vars' },\n    force: { type: 'boolean', description: 'Overwrite existing entry without prompting', default: false },\n  },\n  async run({ args }) {\n    const target = getConfigPaths()['mcp-json']!\n    await installServer({\n      configPath: target.path,\n      format: target.format,\n      force: args.force,\n      entry: {\n        name: args.name,\n        command: args.command,\n        args: args.args ? parseArgList(args.args) : undefined,\n        env: args.env ? parseEnvMap(args.env) : undefined,\n      },\n    })\n  },\n})\n","import { defineCommand } from 'citty'\n\nexport default defineCommand({\n  meta: { name: 'install', description: 'Install an MCP server into a client config' },\n  subCommands: {\n    'claude-code': () => import('./claude-code.js').then((m) => m.default),\n    'claude-desktop': () => import('./claude-desktop.js').then((m) => m.default),\n    cursor: () => import('./cursor.js').then((m) => m.default),\n    gemini: () => import('./gemini.js').then((m) => m.default),\n    goose: () => import('./goose.js').then((m) => m.default),\n    'mcp-json': () => import('./mcp-json.js').then((m) => m.default),\n  },\n})\n","import { defineCommand } from 'citty'\nimport { spawn } from 'node:child_process'\nimport { parseFileSpec } from '../../utils/file-spec.js'\nimport { resolveEntrypointBootstrapPath, buildEntrypointEnv } from '../../utils/entrypoint-bootstrap.js'\nimport { cliError, formatError } from '../../utils/error.js'\nimport { log } from '../../ui/output.js'\nimport { theme } from '../../ui/theme.js'\nimport { symbols } from '../../ui/symbols.js'\nimport { withSpinner } from '../../ui/spinner.js'\n\n/**\n * Builds the server command + args the inspector expects as trailing\n * positional arguments — tsx for TypeScript, node for JS — e.g.\n * `['node', '/abs/dist/cli/entrypoint-runtime.cjs']`.\n *\n * The inspector's CLI takes the server's command and args this way\n * (`npx @modelcontextprotocol/inspector node file.js`), not as a single\n * quoted string. Inspector 1.0 repurposed `--server <name>` to select a\n * server from a `--config` file, so passing a command string to `--server`\n * fails outright (\"--server requires --config to be specified\").\n *\n * The command spawns the entrypoint bootstrap rather than the user's file\n * directly, so `file:export` entrypoint specs resolve the same way `run` and\n * `inspect` do — the user's file travels in the entrypoint env\n * (see `buildEntrypointEnv`), and the runner (tsx vs node) still follows the\n * USER file's type so the bootstrap can import a TypeScript entrypoint.\n */\nexport function buildInspectorServerArgs(\n  fileSpec: { isTypeScript: boolean },\n  bootstrapPath: string,\n): string[] {\n  return fileSpec.isTypeScript ? ['npx', 'tsx', bootstrapPath] : ['node', bootstrapPath]\n}\n\nexport default defineCommand({\n  meta: { name: 'inspector', description: 'Launch the MCP inspector for a server file' },\n  args: {\n    spec: { type: 'positional', description: 'File spec (e.g. server.ts or server.ts:app)', required: true },\n    port: { type: 'string', description: 'Inspector UI port', default: '6274' },\n  },\n  async run({ args }) {\n    let fileSpec\n    try {\n      fileSpec = parseFileSpec(args.spec)\n    } catch (err) {\n      cliError(formatError(err))\n    }\n\n    const serverArgs = buildInspectorServerArgs(fileSpec, resolveEntrypointBootstrapPath())\n\n    await withSpinner('Starting inspector…', () =>\n      new Promise<void>((resolve) => setTimeout(resolve, 300)),\n    )\n\n    // Era note: the published inspector bundles the legacy `@modelcontextprotocol/sdk`\n    // client (protocol versions up to 2025-11-25), so it cannot negotiate the\n    // 2026-07-28 (modern) era. A fastmcp server pins its era per stdio connection,\n    // so it still serves the inspector's legacy-era client correctly — the\n    // inspector just never exercises the modern era. This is an inspector-side\n    // limit, not something this CLI can work around.\n    const inspectorProcess = spawn(\n      'npx',\n      ['@modelcontextprotocol/inspector', ...serverArgs],\n      {\n        stdio: 'inherit',\n        shell: true,\n        env: { ...process.env, MCP_TRANSPORT: 'stdio', ...buildEntrypointEnv(fileSpec) },\n      },\n    )\n\n    log.info(`Inspector running — ${theme.url(`http://localhost:${args.port}`)}`)\n\n    const { watch } = await import('chokidar')\n    const watcher = watch(fileSpec.filePath, { ignoreInitial: true })\n\n    watcher.on('change', () => {\n      process.stderr.write(`${theme.muted(symbols.reload)} File changed, reloading inspector…\\n`)\n      inspectorProcess.kill()\n    })\n\n    process.on('SIGINT', () => {\n      watcher.close()\n      inspectorProcess.kill()\n      process.exit(0)\n    })\n\n    await new Promise<void>((resolve) => inspectorProcess.on('exit', resolve))\n  },\n})\n","import { defineCommand } from 'citty'\n\nexport default defineCommand({\n  meta: { name: 'dev', description: 'Development utilities' },\n  subCommands: {\n    inspector: () => import('./inspector.js').then((m) => m.default),\n  },\n})\n","import { defineCommand, runMain } from 'citty'\nimport { setQuiet } from './ui/output.js'\nimport { setJsonMode } from './ui/format.js'\n\ndeclare const __FASTMCP_VERSION__: string\n\nconst main = defineCommand({\n  meta: {\n    name: 'fastmcp',\n    version: __FASTMCP_VERSION__,\n    description: 'FastMCP CLI — build, run, and manage MCP servers',\n  },\n  args: {\n    quiet: { type: 'boolean', description: 'Suppress informational output', default: false },\n    json: { type: 'boolean', description: 'Output JSON to stdout', default: false },\n  },\n  setup({ args }) {\n    if (args.quiet) setQuiet(true)\n    if (args.json) setJsonMode(true)\n  },\n  subCommands: {\n    version: () => import('./commands/version.js').then((m) => m.default),\n    run: () => import('./commands/run.js').then((m) => m.default),\n    inspect: () => import('./commands/inspect.js').then((m) => m.default),\n    list: () => import('./commands/list.js').then((m) => m.default),\n    call: () => import('./commands/call.js').then((m) => m.default),\n    discover: () => import('./commands/discover.js').then((m) => m.default),\n    install: () => import('./commands/install/index.js').then((m) => m.default),\n    dev: () => import('./commands/dev/index.js').then((m) => m.default),\n  },\n})\n\nrunMain(main)\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAQA,SAAS,YAAY,OAAO,IAAI;AAC/B,MAAI,eAAe,KAAK,IAAI,EAAG;AAC/B,SAAO,SAAS,KAAK,YAAY;AAClC;AACA,SAAS,YAAY,KAAK,YAAY;AACrC,QAAM,YAAY,cAAc;AAChC,QAAM,QAAQ,CAAC;AACf,MAAI,CAAC,OAAO,OAAO,QAAQ,SAAU,QAAO;AAC5C,MAAI,OAAO;AACX,MAAI;AACJ,MAAI;AACJ,aAAW,QAAQ,KAAK;AACvB,UAAM,aAAa,UAAU,SAAS,IAAI;AAC1C,QAAI,eAAe,MAAM;AACxB,YAAM,KAAK,IAAI;AACf,aAAO;AACP,sBAAgB;AAChB;AAAA,IACD;AACA,UAAM,UAAU,YAAY,IAAI;AAChC,QAAI,qBAAqB,OAAO;AAC/B,UAAI,kBAAkB,SAAS,YAAY,MAAM;AAChD,cAAM,KAAK,IAAI;AACf,eAAO;AACP,wBAAgB;AAChB;AAAA,MACD;AACA,UAAI,kBAAkB,QAAQ,Y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AA;IACA,2BAAA;IACA,oBAAA;IACA,cAAA;IACA,iBAAA;IACA,mBAAA;IACA,mCAAA;IACA,6BAAA;IACA,YAAA;IACA,aAAA;IACA,oBAAA;IACA,sBAAA;IACA,6BAAA;IACA,6BAAA;IACA,0BAAA;IACA,+BAAA;IACA,yBAAA;IACA,0BAAA;IACA,wBAAA;IACA,+BAAA;IACA,mBAAA;IACA,gBAAA;IACA,kCAAA;IACA,4BAAA;IACA,8BAAA;IACA,wBAAA;IACA,uBAAA;IACA,wBAAA;IACA,4BAAA;IACA,4BAAA;IACA,YAAA;IACA,mBAAA;IACA,gBAAA;IACA,wBAAA;IACA,4BAAA;IACA,2BAAA;IACA,oCAAA;IACA,mCAAA;IACA,6BAAA;IACA,iCAAA;IACA,2BAAA;IACA,0BAAA;IACA,uCAAA;IACA,8BAAA;IACA,wBAAA;IACA,gCAAA;IACA,0BAAA;IACA,yCAAA;IACA,mCAAA;IACA,sBAAA;IACA,cAAA;IACA,0BAAA;IACA,yBAAA;IACA,8BAAA;IACA,wBAAA;IACA,mBAAA;IACA,oBAAA;IACA,oBAAA;IACA,sBAAA;IACA,wBAAA;IACA,oBAAA;IACA,oBAAA;IACA,qBAAA;IACA,uBAAA;IACA,qCAAA;IACA,uBAAA;IACA,qBAAA;IACA,YAAA;IACA,wBAAA;IACA,uBAAA;IACA,sBAAA;IACA,6BAAA;IACA,uBAAA;IACA,mCAAA;IACA,oBAAA;IACA,6BAAA;IACA,uBAAA;IACA,wCAAA;IACA,kCAAA;IACA,iBAAA;IACA,wBAAA;IACA,kBAAA;IACA,yBAAA;IACA,uBAAA;IACA,mCAAA;IACA,uBAAA;IACA,kCAAA;IACA,4BAAA;IACA,2BAAA;IACA,oCAAA;IACA,qBAAA;IACA,oBAAA;IACA,oBAAA;IACA,sCAAA;IACA,oCAAA;IACA,8BAAA;IACA,8BAAA;IACA,qCAAA;IACA,mCAAA;IACA,6BAAA;IACA,kBAAA;IACA,iCAAA;IACA,+BAAA;IACA,8BA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;MACA;MACA;MACA;MACA;MACA;MACA;MACA;MACA;MACA;MACA;MACA;MACA;MACA;MACA;MACA;MACA;MACA;MACA;MACA;MACA;MACA;MACA;MACA;MACA;MACA;MACA;MACA;MACA;MACA;MACA;MACA;MACA;MACA;MACA;MACA;MACA;MACA;MACA;MACA;MACA;MACA;MACA;MACA;MACA;MACA;MACA;MACA;MACA;MACA;MACA;MACA;MACA;MACA;MACA;MACA;MACA;MACA;MACA;MACA;MACA;MACA;MACA;MACA;MACA;MACA;MACA;MACA;MACA;MACA;MACA;MACA;MACA;MACA;MACA;MACA;MACA;MACA;MACA;MACA;MACA;MACA;MACA;MACA;MACA;MACA;MACA;MACA;MACA;MACA;MACA;MACA;MACA;MACA;MACA;MACA;MACA;MACA;MACA;MACA;MACA;MACA;MACA;MACA;MACA;MACA;MACA;MACA;MACA;MACA;MACA;MACA;MACA;MACA;MACA;MACA;MACA;MACA;MACA;MACA;MACA;MACA;MACA;MACA;MACA;MACA;MACA;MACA;MACA;MACA;MACA;MACA;MACA;MACA;MACA;MACA;MACA;MACA;MACA;MACA;MACA;MACA;MACA;MACA;MACA;MACA;MACA;MACA;MACA;;AAGJ,IAAM,cAAc;MAChB;MACA;MACA;MACA;MACA;MACA;MACA;MACA;MACA;MACA;MACA;MACA;;AAgDJ,IAAMmD,mBAAqD,CAAA;AAC3D,IAAMC,cAA2D,CAAA;AAMjE,eAAW,OAAO,iBAEd,UAAS,KAAKe,iBAAQ,GAAA,CAAA;AAE1B,eAAW,CAAC,KAAK,MAAA,KAAW,OAAO,QAAQ,WAAA,EACvC,UAAS,KAAK,MAAA;AAqBlB,IAAad,kBAAgC,OAAO,OAAO,gBAAA;AAsB3D,IAAaC,aAA0B,OAAO,OAAO,WAAA;AElNrD,IAAa,+BAA+B;AA0F5C,IAAMC,8BAAiD;MACnD;MACA;MACA;MACA;;AASJ,IAAM,oBAAoB,CAAC,kBAAkB,cAAA;AA2G7C,IAAM,mBAAmB,qBAAqB,MAAA;AA4P9C,I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EAAE,OAAO;AAAA,IAC1E,KAAK,MAAM,wDAAkC,KAAK,CAAC,MAAM,EAAE,OAAO;AAAA,EACpE;AACF,CAAC;AAED,QAAQ,IAAI;","names":["i","l","main","parseArgs$1","error","meta","a","version","required","env","r","t","integer","process","os","version","tty","string","styles","object","chalk","open","string","env","import_node_path","__create","__defProp","__getOwnPropDesc","__getOwnPropNames","__getProtoOf","__hasOwnProp","__copyProps","__toESM","symbols","i","n","DRAFT_2020_12_URIS: ReadonlySet<string>","DRAFT_2019_09_URIS: ReadonlySet<string>","DRAFT_07_URIS: ReadonlySet<string>","DRAFT_06_URIS: ReadonlySet<string>","array","object","i","a","Class","_a","config","t","base64","base64url","proto","initializer","proto","own","error","issue","i","terminal","node","proto","error","parse","parseAsync","regex","version","_a","validateAsync","r","url","base64","parse","n","t","a","_a","checks","checkResult","canary","result","_","memo","i","isObject","allowsEval","results","value","left","right","output","resolve","cached","merge","_a","r","issue","_a","meta","Class","_emoji","_null","issue","_a","meta","id","schema","members","required","object","union","i","t","format","record","registry","ctx","regex","a","optional","init_core","init_checks","init_core","proto","initializer","init_errors","init_core","issue","issues","init_parse","init_core","init_errors","string","email","number","boolean","_null","init_schemas","init_core","init_checks","init_parse","meta","_parse","_parseAsync","_encode","_decode","_encodeAsync","_decodeAsync","_emoji","n","issue","output","ZodFirstPartyTypeKind","date","datetime","duration","time","init_core","init_schemas","bigint","boolean","date","number","string","init_core","init_schemas","init_core","init_schemas","init_checks","init_errors","init_parse","JSONValueSchema: z.ZodType<JSONValue, JSONValue>","JSONObjectSchema: z.ZodType<JSONObject, JSONObject>","JSONArraySchema: z.ZodType<JSONArray, JSONArray>","string","number","boolean","_null","url","u","string","boolean","number","current: unknown","url","copy: Record<string, unknown>","version","build","JSONValueSchema: z.ZodType<JSONValue, JSONValue>","string","number","boolean","_null","JSONValueSchema","JSONObjectSchema: z.ZodType<JSONObject, JSONObject>","ProgressTokenSchema","CursorSchema","TaskMetadataSchema","RelatedTaskMetadataSchema","RequestMetaSchema","BaseRequestParamsSchema","TaskAugmentedRequestParamsSchema","RequestSchema","NotificationsParamsSchema","NotificationSchema","ResultSchema","RequestIdSchema","EmptyResultSchema","CancelledNotificationParamsSchema","CancelledNotificationSchema","IconSchema","IconsSchema","BaseMetadataSchema","ImplementationSchema","FormElicitationCapabilitySchema","JSONObjectSchema","ElicitationCapabilitySchema","ClientTasksCapabilitySchema","ServerTasksCapabilitySchema","ClientCapabilitiesSchema","InitializeRequestParamsSchema","InitializeRequestSchema","ServerCapabilitiesSchema","InitializeResultSchema","InitializedNotificationSchema","PingRequestSchema","ProgressSchema","ProgressNotificationParamsSchema","ProgressNotificationSchema","PaginatedRequestParamsSchema","PaginatedRequestSchema","PaginatedResultSchema","ResourceContentsSchema","TextResourceContentsSchema","Base64Schema","BlobResourceContentsSchema","RoleSchema","AnnotationsSchema","ResourceSchema","ResourceTemplateSchema","ListResourcesRequestSchema","ListResourcesResultSchema","ListResourceTemplatesRequestSchema","ListResourceTemplatesResultSchema","ResourceRequestParamsSchema","ReadResourceRequestParamsSchema","ReadResourceRequestSchema","ReadResourceResultSchema","ResourceListChangedNotificationSchema","SubscribeRequestParamsSchema","SubscribeRequestSchema","UnsubscribeRequestParamsSchema","UnsubscribeRequestSchema","ResourceUpdatedNotificationParamsSchema","ResourceUpdatedNotificationSchema","PromptArgumentSchema","PromptSchema","ListPromptsRequestSchema","ListPromptsResultSchema","GetPromptRequestParamsSchema","GetPromptRequestSchema","TextContentSchema","ImageContentSchema","AudioContentSchema","ToolUseContentSchema","EmbeddedResourceSchema","ResourceLinkSchema","ContentBlockSchema","PromptMessageSchema","GetPromptResultSchema","PromptListChangedNotificationSchema","ToolAnnotationsSchema","ToolExecutionSchema","ToolSchema","ListToolsRequestSchema","ListToolsResultSchema","CallToolResultSchema","CallToolRequestParamsSchema","CallToolRequestSchema","ToolListChangedNotificationSchema","LoggingLevelSchema","SetLevelRequestParamsSchema","SetLevelRequestSchema","LoggingMessageNotificationParamsSchema","LoggingMessageNotificationSchema","ModelHintSchema","ModelPreferencesSchema","ToolChoiceSchema","ToolResultContentSchema","SamplingContentSchema","SamplingMessageContentBlockSchema","SamplingMessageSchema","CreateMessageRequestParamsSchema","CreateMessageRequestSchema","CreateMessageResultSchema","CreateMessageResultWithToolsSchema","BooleanSchemaSchema","StringSchemaSchema","NumberSchemaSchema","UntitledSingleSelectEnumSchemaSchema","TitledSingleSelectEnumSchemaSchema","LegacyTitledEnumSchemaSchema","SingleSelectEnumSchemaSchema","UntitledMultiSelectEnumSchemaSchema","TitledMultiSelectEnumSchemaSchema","MultiSelectEnumSchemaSchema","EnumSchemaSchema","PrimitiveSchemaDefinitionSchema","ElicitRequestFormParamsSchema","ElicitRequestURLParamsSchema","ElicitRequestParamsSchema","ElicitRequestSchema","ElicitationCompleteNotificationParamsSchema","ElicitationCompleteNotificationSchema","ElicitResultSchema","ResourceTemplateReferenceSchema","PromptReferenceSchema","CompleteRequestParamsSchema","CompleteRequestSchema","CompleteResultSchema","RootSchema","ListRootsRequestSchema","ListRootsResultSchema","RootsListChangedNotificationSchema","TaskCreationParamsSchema","TaskStatusSchema","TaskSchema","CreateTaskResultSchema","TaskStatusNotificationParamsSchema","TaskStatusNotificationSchema","GetTaskRequestSchema","GetTaskResultSchema","GetTaskPayloadRequestSchema","GetTaskPayloadResultSchema","ListTasksRequestSchema","ListTasksResultSchema","CancelTaskRequestSchema","node","out: Record<string, unknown>","maps","requestMethodKeys","notificationMethodKeys","isPlainObject","triState","t","DiscoverResultSchema","DiscoverRequestSchema","SubscriptionFilterSchema","SubscriptionsListenRequestSchema","SubscriptionsListenResultMetaSchema","SubscriptionsListenResultSchema","dispatchRequestSchemas: { readonly [M in Rev2026RequestMethod]: z.ZodType<{ method: M }> }","dispatchResultSchemas: { readonly [M in Rev2026RequestMethod]: z.ZodType }","SubscriptionsAcknowledgedNotificationSchema","notificationSchemas2026: { readonly [M in Rev2026NotificationMethod]: z.ZodType<{ method: M }> }","memo","meta","next: Record<string, unknown>","declarations: XMcpHeaderDeclaration[]","numberFault: string | undefined","fault","branches: unknown[]","i","node: unknown","out: Record<string, string>","result: Record<string, unknown>","members","issue","precisions: Array<number | undefined>","format","referenceSchemas: z.ZodType[]","email","error","unsupported","pruned: Record<string, unknown>","unsupported: string[]","resolve","config","responses: Record<string, unknown> | undefined","round","legOptions: InputRequiredRetryLegOptions","lifted: LiftedWireMaterial","nextParams: Record<string, unknown>","envelope: Record<string, unknown>","nextMeta: Record<string, unknown>","result: T","accepted: Record<string, unknown>","droppedKeys: string[]","firstPayload: InputRequiredPayload","hooks: InputRequiredDriverHooks","copy: FetchLike","BRANDS: unique symbol","memo: Rev2025WireSchemas | undefined","REF_REWRITE_DATA_POSITION_KEYS: ReadonlySet<string>","REF_REWRITE_NAME_MAP_KEYS: ReadonlySet<string>","requestMethodKeys: { readonly [M in Rev2025RequestMethod]: null }","notificationMethodKeys: { readonly [M in Rev2025NotificationMethod]: null }","resultMethodKeys: { readonly [M in Rev2025TypedRequestMethod]: null }","maps: RegistryMaps | undefined","rev2025RequestMethods: readonly string[]","rev2025NotificationMethods: readonly string[]","NOT_IN_ERA: ValidateOutcome<never>","rev2025Codec: WireCodec","memo: Rev2026WireSchemas | undefined","RESULT_CACHE_HINT_FALLBACK: unique symbol","EXTENDED_RESULT_TYPE_METHODS: readonly string[]","maps: InputSchemaMaps | undefined","requestMethodKeys: { readonly [M in Rev2026RequestMethod]: null }","notificationMethodKeys: { readonly [M in Rev2026NotificationMethod]: null }","rev2026RequestMethods: readonly string[]","rev2026NotificationMethods: readonly string[]","REQUIRED_ENVELOPE_KEYS: readonly string[]","rev2026Codec: WireCodec & {\n    /**\n     * @deprecated Off-interface in-band registry probe retained for the\n     * existing inputRequiredFunnel pin. Use {@link WireCodec.validateInputRequest}\n     * — its `not-in-era` outcome is the membership signal.\n     */\n    inputRequestSchema(method: string): unknown;\n}","wireResultSchemasMemo: Record<string, z.ZodType> | undefined","ALL_CODECS: readonly WireCodec[]","PERMITTED_X_MCP_HEADER_TYPES: ReadonlySet<string>","OBJECT_VALUED_SUBSCHEMA_KEYWORDS: ReadonlySet<string>","INBOUND_VALIDATION_LADDER: readonly InboundValidationRungDescriptor[]","LADDER_ERROR_HTTP_STATUS: Readonly<Record<number, number>>","MCP_NAME_HEADER_SOURCE: Readonly<Record<string, McpNameSourceField>>","PROPERTY_KEYS_BY_TYPE: Record<string, ReadonlySet<string>>","SUPPORTED_STRING_FORMATS: ReadonlySet<string>","inputRequired: InputRequiredBuilder","_specTypeSchemas: Record<string, StandardSchemaV1>","_isSpecType: Record<string, (value: unknown) => boolean>","specTypeSchemas: SchemaRecord","isSpecType: GuardRecord","RESERVED_ENVELOPE_META_KEYS: readonly string[]","writeNegotiatedProtocolVersion: <ContextT extends BaseContext>(instance: Protocol<ContextT>, version: string | undefined) => void","OAuthError","code: OAuthErrorCode | string","errorUri?: string","response: OAuthErrorResponse","code: SdkErrorCode","data?: unknown","NOT_IN_ERA","ProtocolError","code: number","issues: EnvelopeIssue[]","schemas","_options?: ProtocolOptions","errorResponse: JSONRPCErrorResponse","r","baseCtx: BaseContext","validate","encoded: Result","response: JSONRPCResponse","onAbort: (() => void) | undefined","cleanupMessageId: number | undefined","jsonrpcRequest: JSONRPCRequest","decoded: ReturnType<WireCodec['decodeResult']>","flow: NonCompleteResultFlow<T>","stored: (request: JSONRPCRequest, ctx: ContextT) => Promise<Result>","exports","parse","InMemoryTransport","exports","_a","i","a","UsedValueState","error","n","If","node","mergeValues","Type","DataType","t","u","validateAsync","module","normalize","anchor","env","validate","resolve","output","parse","relative","_c","Ajv","meta","format","regex","log","l","block","DiscrError","required","date","time","addFormats","_addFormats","Ajv2020","Ajv2019","Draft7Ajv","a","union","error","url","url: URL","resourceMetadata: OAuthProtectedResourceMetadata | undefined","authorizationServerUrl: string | URL","metadata: AuthorizationServerMetadata | undefined","freshDiscoveryState: OAuthDiscoveryState | undefined","infoCtx: OAuthClientInformationContext","resource: string | URL | undefined","tokens","newTokens: OAuthTokens | undefined","resourceMetadataUrl: URL | undefined","urlsToTry: { url: URL; type: 'oauth' | 'oidc' }[]","authorizationServerUrl: string | undefined","authorizationUrl: URL","json: unknown","tokenRequestParams: URLSearchParams | undefined","registrationUrl: URL","submittedMetadata: OAuthClientMetadata","json: string | undefined","version","parsed: unknown","verdict: ProbeVerdict","result: NegotiationResult","proto","signalClosed: (() => void) | undefined","CAP_EXEMPT_METHODS: ReadonlySet<string>","DEFAULT_VERSION_NEGOTIATION_MODE: VersionNegotiationMode","LIST_CHANGED_EVICTIONS: Readonly<Record<string, readonly string[]>>","recordedIssuer: string","currentIssuer: string","_store: ResponseCacheStore","_isUserSupplied: boolean","_reportError: (error: unknown) => void","_cachePartition: string","_now: () => number","own","compile","t","ProbeWindow","_transport: Transport","resolve","settle","_clientInfo: Implementation","config","result: Awaited<ReturnType<typeof negotiateEra>>","effective: ListChangedHandlers","filter: SubscriptionFilter","r","finalize","cursor","scope: CacheScope","state: 'opening' | 'open' | 'closed'","ackTimer: ReturnType<typeof setTimeout> | undefined","onCallerAbort: (() => void) | undefined","resolveOpening!: (honored: SubscriptionFilter) => void","rejectOpening!: (error: Error) => void","resolveClosed!: (cause: 'local' | 'graceful' | 'remote') => void","jsonrpcRequest: JSONRPCRequest","scan: XMcpHeaderScanResult | undefined","result: CallToolResult","trailing","value","line","i","init_dist","flattenError","_url","_a","inspect","url","open","error","a","DEFAULT_STREAMABLE_HTTP_RECONNECTION_OPTIONS: StreamableHTTPReconnectionOptions","RESERVED_REQUEST_HEADER_NAMES: ReadonlySet<string>","url","error","code: number | undefined","event: ErrorEvent","token: string | undefined","redirect: string | undefined","resolve","message: JSONRPCMessage","version","delay","lastEventId: string | undefined","r","formatError","init_dist","init_dist","i","l","NO_TRUNCATION","dist_default","init_dist","string","init_dist","url","dist_default","i","exports","module","ESC","CSI","beep","cursor","erase","i","n","i","t","r","a","import_node_util","import_node_process","import_node_tty","init_dist","l__default","h","process$1","import_node_util","import_node_process","import_node_fs","import_node_path","import_sisteransi","u","init_dist","i","a","l","r","h","n","t","init_dist","import_node_path","error","presolve","basename","pjoin","prelative","psep","fs_watch","error","import_node_fs","import_promises","import_node_os","osType","main","rawEmitter","listener","basename","dirname","newStats","closer","fsrealpath","resolve","realpath","stats","string","relative","testString","import_node_fs","import_promises","sp","path","stats","error","statcb","now","stat","env","formatError","watch","url","spawn","init_dist","resolve","error","SKILL_LIMITS: Readonly<{ files: number; bytes: number }>","string","number","boolean","base64","yaml","number: number | undefined","number","escape","open","list: unknown[]","map: Record<string, unknown>","safeDecode","url","url: URL","problems: string[]","issue","keyOf","skills: Skill[]","invalid: InvalidSkillEntry[]","object","isPlainObject","error","uri: string","SKILLS_EXTENSION_ID","SIMPLE_ESCAPES: Readonly<Record<string, string>>","HEX_ESCAPE_WIDTH: Readonly<Record<string, number>>","cacheFields","lines: Line[]","indent","items: unknown[]","contents: string[]","string","#client","SKILLS_LIST_METHOD","#envelopes","SKILLS_GET_METHOD","cached","file: SkillFile","parse","RESOURCES_DIRECTORY_READ_METHOD","cursor","exports","module","i","stat","exports","module","stat","u","exports","module","resolve","exports","module","isWindows","i","resolve","exports","module","platform","exports","module","env","exports","module","exports","module","exports","module","string","exports","module","exports","module","escape","parse","exports","module","exports","module","parse","spawn","env: Record<string, string>","process","env","resolve","spawn","error","StdioClientTransport","normalizeHeaders","auth","url","init_dist","init_dist","config","r","t","serverName","a","h","auth","resolve","Client","init_dist","init_skills","h","resolveVersionNegotiation","auth","client","Client","transport","env","resolveAuth","init_auth","t","a","r","init_dist","exports","module","exports","module","exports","module","ansiRegex","string","exports","module","isFullwidthCodePoint","exports","module","exports","module","stripAnsi","isFullwidthCodePoint","stringWidth","string","i","require_utils","exports","module","stringWidth","memo","pad","i","defaultOptions","output","url","OSC","BEL","SEP","exports","module","styles","exports","module","exports","module","os","hasFlag","env","translateLevel","supportsColor","version","exports","module","exports","module","r","i","text","options","l","exports","module","i","exports","module","i","exports","module","i","exports","module","i","exports","module","ansiStyles","stylize","build","builder","applyStyle","proto","styles","colors","i","theme","style","sequencer","map","exports","module","exports","module","i","a","exports","module","i","exports","module","Table","array","exports","module","Table","h","init_auth","resolveAuth","formatError","tools","resources","prompts","t","r","required","init_auth","resolveAuth","formatError","tools","resources","prompts","t","r","a","n","i","mv","pv","start","vlen","a","init_auth","resolveAuth","formatError","t","r","a","block","exports","node","isNode","exports","node","i","exports","yaml","version","error","node","exports","anchor","node","i","error","exports","i","exports","i","res","exports","res","exports","node","anchors","anchor","exports","exports","t","node","exports","i","a","node","n","exports","indent","exports","indent","i","end","exports","i","indent","literal","t","exports","t","node","anchor","exports","indent","exports","exports","merge","value","exports","log","merge","node","exports","exports","stringify","indent","i","comment","str","exports","i","node","exports","map","exports","i","exports","seq","exports","string","exports","exports","exports","format","n","i","exports","node","exports","node","_onError","int","require_schema","exports","_null","string","int","require_schema","exports","_onError","exports","i","n","exports","i","pairs","exports","omap","require_bool","exports","require_float","exports","node","require_int","exports","n","node","_onError","int","exports","set","exports","n","res","node","_onError","date","require_schema","exports","_null","string","int","merge","exports","_null","string","int","merge","tags","exports","string","a","merge","exports","exports","version","node","res","require_errors","exports","prettifyError","error","exports","anchor","exports","exports","indent","exports","a","exports","exports","node","exports","exports","i","exports","anchor","t","node","exports","i","value","end","indent","error","n","exports","_onError","i","exports","error","tag","exports","i","exports","anchor","node","error","exports","exports","i","error","exports","_onError","indent","exports","exports","i","exports","exports","i","n","indent","sp","ch","exports","exports","i","Parser","n","error","start","indent","exports","log","lineCounter","parse","indent","require_dist","exports","platform","format","yaml","import_node_os","import_node_path","import_node_fs","config","exports","module","EventEmitter","i","l","import_index","EventEmitter","exports","module","rfdc","handler","clone","a","a2","i","isWindows","isLinux","import_node_process","import_node_os","ESC","isWindows","process","i","os","build","url","onetime","global","process","i","a","import_node_process","process","import_node_process","process","string","init_utilities","i","isFullWidth","init_utilities","validate","isFullWidth","string","assembleStyles","styles","wrapAnsi16","wrapAnsi256","wrapAnsi16m","ANSI_BACKGROUND_OFFSET","integer","modifierNames","foregroundColorNames","backgroundColorNames","colorNames","ansiStyles","ansi_styles_default","init_ansi_styles","wrapAnsi","string","exec","END_CODE","ANSI_ESCAPE_BELL","ANSI_CSI","ANSI_OSC","ANSI_SGR_TERMINATOR","ANSI_ESCAPE_LINK","wrapAnsiCode","wrapAnsiHyperlink","wrapWord","stringVisibleTrimSpacesRight","init_ansi_styles","url","code","ansi_styles_default","isFullWidth","ansi_styles_default","string","ESCAPES","isFullWidth","init_ansi_styles","output","wrapAnsi","import_node_process","process","isFullwidthCodePoint","isFullWidth","init_is_fullwidth_code_point","CODE_POINT_0","CODE_POINT_9","isFullwidthCodePoint","ANSI_CSI","ANSI_SGR_TERMINATOR","openCode","ansi_styles_default","string","ANSI_OSC","parseAnsiCode","ESCAPES","init_ansi_styles","init_is_fullwidth_code_point","undoAnsiCodes","sliceAnsi","string","init_slice_ansi","stringWidth","string","segmenter","init_string_width","string","stringWidth","right","sliceAnsi","left","init_slice_ansi","init_string_width","isDoubleWidthNonRgiEmojiSequence","unqualifiedKeycapRegex","extendedPictographicRegex","baseVisible","leadingNonPrintingRegex","isZeroWidthCluster","zeroWidthClusterRegex","trailingHalfwidthWidth","stringWidth","string","segmenter","rgiEmojiRegex","init_string_width","wrapAnsi","string","exec","ESCAPES","ANSI_ESCAPE_BELL","ANSI_CSI","ANSI_OSC","ANSI_SGR_TERMINATOR","ANSI_ESCAPE_LINK","segmenter","wrapAnsiCode","wrapAnsiHyperlink","applySgrToken","wordLengths","wrapWord","stringVisibleTrimSpacesRight","init_wrap_ansi","init_string_width","init_ansi_styles","ansi_styles_default","url","stringWidth","isUnicodeSupported","string","splat","duration","r","clone","time","resolve","import_node_util","import_util","import_stream","ANSI_ESCAPE","init_dist","ListrEnvironmentVariables","ListrErrorTypes","ListrEventType","ListrRendererSelection","ListrTaskEventType","ListrTaskState","color","ListrLogLevels","output","i","stdout","a","ListrDefaultRendererLogLevels","DefaultRenderer","createLogUpdate","task","SimpleRenderer","t","TestRenderer","VerboseRenderer","rfdc","error","i","format","import_node_fs","import_node_path","init_dist","config","import_node_child_process","formatError","resolve","watch"]}