{"version":3,"sources":["../src/env-detection.ts","../../../node_modules/zod/v4/core/core.js","../../../node_modules/zod/v4/core/util.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/locales/ar.js","../../../node_modules/zod/v4/locales/az.js","../../../node_modules/zod/v4/locales/be.js","../../../node_modules/zod/v4/locales/bg.js","../../../node_modules/zod/v4/locales/ca.js","../../../node_modules/zod/v4/locales/cs.js","../../../node_modules/zod/v4/locales/da.js","../../../node_modules/zod/v4/locales/de.js","../../../node_modules/zod/v4/locales/el.js","../../../node_modules/zod/v4/locales/en.js","../../../node_modules/zod/v4/locales/eo.js","../../../node_modules/zod/v4/locales/es.js","../../../node_modules/zod/v4/locales/fa.js","../../../node_modules/zod/v4/locales/fi.js","../../../node_modules/zod/v4/locales/fr.js","../../../node_modules/zod/v4/locales/fr-CA.js","../../../node_modules/zod/v4/locales/he.js","../../../node_modules/zod/v4/locales/hr.js","../../../node_modules/zod/v4/locales/hu.js","../../../node_modules/zod/v4/locales/hy.js","../../../node_modules/zod/v4/locales/id.js","../../../node_modules/zod/v4/locales/is.js","../../../node_modules/zod/v4/locales/it.js","../../../node_modules/zod/v4/locales/ja.js","../../../node_modules/zod/v4/locales/ka.js","../../../node_modules/zod/v4/locales/km.js","../../../node_modules/zod/v4/locales/kh.js","../../../node_modules/zod/v4/locales/ko.js","../../../node_modules/zod/v4/locales/lt.js","../../../node_modules/zod/v4/locales/mk.js","../../../node_modules/zod/v4/locales/ms.js","../../../node_modules/zod/v4/locales/nl.js","../../../node_modules/zod/v4/locales/no.js","../../../node_modules/zod/v4/locales/ota.js","../../../node_modules/zod/v4/locales/ps.js","../../../node_modules/zod/v4/locales/pl.js","../../../node_modules/zod/v4/locales/pt.js","../../../node_modules/zod/v4/locales/ro.js","../../../node_modules/zod/v4/locales/ru.js","../../../node_modules/zod/v4/locales/sl.js","../../../node_modules/zod/v4/locales/sv.js","../../../node_modules/zod/v4/locales/ta.js","../../../node_modules/zod/v4/locales/th.js","../../../node_modules/zod/v4/locales/tr.js","../../../node_modules/zod/v4/locales/uk.js","../../../node_modules/zod/v4/locales/ua.js","../../../node_modules/zod/v4/locales/ur.js","../../../node_modules/zod/v4/locales/uz.js","../../../node_modules/zod/v4/locales/vi.js","../../../node_modules/zod/v4/locales/zh-CN.js","../../../node_modules/zod/v4/locales/zh-TW.js","../../../node_modules/zod/v4/locales/yo.js","../../../node_modules/zod/v4/locales/index.js","../../../node_modules/zod/v4/core/registries.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-generator.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/iso.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/from-json-schema.js","../../../node_modules/zod/v4/classic/coerce.js","../../../node_modules/zod/v4/classic/external.js","../../../node_modules/zod/index.js","../../protocol/src/ids.ts","../../protocol/src/enums.ts","../../protocol/src/config.ts","../../protocol/src/wire.ts","../../protocol/src/constants.ts","../../protocol/src/sha256.ts","../../protocol/src/session.ts","../../protocol/src/side-effect.ts","../../protocol/src/error-evidence.ts","../../../node_modules/@opentelemetry/api/src/version.ts","../../../node_modules/@opentelemetry/api/src/internal/semver.ts","../../../node_modules/@opentelemetry/api/src/internal/global-utils.ts","../../../node_modules/@opentelemetry/api/src/diag/ComponentLogger.ts","../../../node_modules/@opentelemetry/api/src/diag/types.ts","../../../node_modules/@opentelemetry/api/src/diag/internal/logLevelLogger.ts","../../../node_modules/@opentelemetry/api/src/api/diag.ts","../../../node_modules/@opentelemetry/api/src/baggage/internal/baggage-impl.ts","../../../node_modules/@opentelemetry/api/src/baggage/internal/symbol.ts","../../../node_modules/@opentelemetry/api/src/baggage/utils.ts","../../../node_modules/@opentelemetry/api/src/context/context.ts","../../../node_modules/@opentelemetry/api/src/diag/consoleLogger.ts","../../../node_modules/@opentelemetry/api/src/metrics/NoopMeter.ts","../../../node_modules/@opentelemetry/api/src/metrics/Metric.ts","../../../node_modules/@opentelemetry/api/src/propagation/TextMapPropagator.ts","../../../node_modules/@opentelemetry/api/src/context/NoopContextManager.ts","../../../node_modules/@opentelemetry/api/src/api/context.ts","../../../node_modules/@opentelemetry/api/src/trace/trace_flags.ts","../../../node_modules/@opentelemetry/api/src/trace/invalid-span-constants.ts","../../../node_modules/@opentelemetry/api/src/trace/NonRecordingSpan.ts","../../../node_modules/@opentelemetry/api/src/trace/context-utils.ts","../../../node_modules/@opentelemetry/api/src/trace/spancontext-utils.ts","../../../node_modules/@opentelemetry/api/src/trace/NoopTracer.ts","../../../node_modules/@opentelemetry/api/src/trace/ProxyTracer.ts","../../../node_modules/@opentelemetry/api/src/trace/NoopTracerProvider.ts","../../../node_modules/@opentelemetry/api/src/trace/ProxyTracerProvider.ts","../../../node_modules/@opentelemetry/api/src/trace/SamplingResult.ts","../../../node_modules/@opentelemetry/api/src/trace/span_kind.ts","../../../node_modules/@opentelemetry/api/src/trace/status.ts","../../../node_modules/@opentelemetry/api/src/trace/internal/tracestate-validators.ts","../../../node_modules/@opentelemetry/api/src/trace/internal/tracestate-impl.ts","../../../node_modules/@opentelemetry/api/src/trace/internal/utils.ts","../../../node_modules/@opentelemetry/api/src/context-api.ts","../../../node_modules/@opentelemetry/api/src/diag-api.ts","../../../node_modules/@opentelemetry/api/src/metrics/NoopMeterProvider.ts","../../../node_modules/@opentelemetry/api/src/api/metrics.ts","../../../node_modules/@opentelemetry/api/src/metrics-api.ts","../../../node_modules/@opentelemetry/api/src/propagation/NoopTextMapPropagator.ts","../../../node_modules/@opentelemetry/api/src/baggage/context-helpers.ts","../../../node_modules/@opentelemetry/api/src/api/propagation.ts","../../../node_modules/@opentelemetry/api/src/propagation-api.ts","../../../node_modules/@opentelemetry/api/src/api/trace.ts","../../../node_modules/@opentelemetry/api/src/trace-api.ts","../../../node_modules/@opentelemetry/api/src/index.ts","../src/nudge/error-nudge.ts","../src/console-capture.ts","../src/signal-handler.ts","../src/optional-lifecycle.ts","../src/lifecycle.ts","../src/build-info.ts","../src/decision-trace.ts","../src/source-map-uploader.ts","../src/node-entry.ts","../src/errors.ts","../src/session.ts","../src/fetch-classifier.ts","../src/span-processor.ts","../src/correlation-id.ts","../src/anon-key.ts","../src/init-client.ts","../src/health-collector.ts","../src/https-transport.ts","../src/mcp-runtime.ts","../src/atomic-write.ts","../src/active-config-store.ts","../src/enriching-exporter.ts","../src/error-response-body.ts","../src/error-stack.ts","../src/export-circuit-breaker.ts","../src/register.ts","../src/discovery-endpoint.ts","../../../node_modules/@opentelemetry/otlp-exporter-base/src/OTLPExporterBase.ts","../../../node_modules/@opentelemetry/otlp-exporter-base/src/types.ts","../../../node_modules/@opentelemetry/otlp-exporter-base/src/configuration/shared-configuration.ts","../../../node_modules/@opentelemetry/otlp-exporter-base/src/bounded-queue-export-promise-handler.ts","../../../node_modules/@opentelemetry/core/src/trace/suppress-tracing.ts","../../../node_modules/@opentelemetry/core/src/baggage/constants.ts","../../../node_modules/@opentelemetry/core/src/baggage/utils.ts","../../../node_modules/@opentelemetry/core/src/common/attributes.ts","../../../node_modules/@opentelemetry/core/src/common/logging-error-handler.ts","../../../node_modules/@opentelemetry/core/src/common/global-error-handler.ts","../../../node_modules/@opentelemetry/core/src/platform/node/environment.ts","../../../node_modules/@opentelemetry/core/src/version.ts","../../../node_modules/@opentelemetry/semantic-conventions/src/stable_attributes.ts","../../../node_modules/@opentelemetry/core/src/semconv.ts","../../../node_modules/@opentelemetry/core/src/platform/node/sdk-info.ts","../../../node_modules/@opentelemetry/core/src/platform/node/index.ts","../../../node_modules/@opentelemetry/core/src/common/time.ts","../../../node_modules/@opentelemetry/core/src/ExportResult.ts","../../../node_modules/@opentelemetry/core/src/utils/lodash.merge.ts","../../../node_modules/@opentelemetry/core/src/utils/merge.ts","../../../node_modules/@opentelemetry/core/src/utils/promise.ts","../../../node_modules/@opentelemetry/core/src/utils/callback.ts","../../../node_modules/@opentelemetry/otlp-exporter-base/src/logging-response-handler.ts","../../../node_modules/@opentelemetry/otlp-exporter-base/src/otlp-export-delegate.ts","../../../node_modules/@opentelemetry/resources/src/ResourceImpl.ts","../../../node_modules/@opentelemetry/resources/src/default-service-name.ts","../../../node_modules/@opentelemetry/resources/src/utils.ts","../../../node_modules/@opentelemetry/otlp-transformer/src/common/internal.ts","../../../node_modules/@opentelemetry/otlp-transformer/src/common/utils.ts","../../../node_modules/@opentelemetry/otlp-transformer/src/trace/internal.ts","../../../node_modules/@opentelemetry/otlp-transformer/src/trace/json/trace.ts","../../../node_modules/@opentelemetry/otlp-exporter-base/src/util.ts","../../../node_modules/@opentelemetry/otlp-exporter-base/src/configuration/otlp-http-configuration.ts","../../../node_modules/@opentelemetry/otlp-exporter-base/src/configuration/otlp-node-http-configuration.ts","../../../node_modules/@opentelemetry/otlp-exporter-base/src/transport/http-transport-utils.ts","../../../node_modules/@opentelemetry/otlp-exporter-base/src/is-export-retryable.ts","../../../node_modules/@opentelemetry/otlp-exporter-base/src/version.ts","../../../node_modules/@opentelemetry/otlp-exporter-base/src/transport/http-exporter-transport.ts","../../../node_modules/@opentelemetry/otlp-exporter-base/src/retrying-transport.ts","../../../node_modules/@opentelemetry/otlp-exporter-base/src/otlp-http-export-delegate.ts","../../../node_modules/@opentelemetry/otlp-exporter-base/src/configuration/shared-env-configuration.ts","../../../node_modules/@opentelemetry/otlp-exporter-base/src/configuration/convert-legacy-node-http-options.ts","../../../node_modules/@opentelemetry/otlp-exporter-base/src/configuration/otlp-node-http-env-configuration.ts","../../../node_modules/@opentelemetry/otlp-exporter-base/src/configuration/convert-legacy-http-options.ts","../../../node_modules/@opentelemetry/exporter-trace-otlp-http/src/platform/node/OTLPTraceExporter.ts","../../../node_modules/@opentelemetry/sdk-trace-base/src/Tracer.ts","../../../node_modules/@opentelemetry/sdk-trace-base/src/Span.ts","../../../node_modules/@opentelemetry/sdk-trace-base/src/enums.ts","../../../node_modules/@opentelemetry/sdk-trace-base/src/inspect.ts","../../../node_modules/@opentelemetry/sdk-trace-base/src/config.ts","../../../node_modules/@opentelemetry/sdk-trace-base/src/Sampler.ts","../../../node_modules/@opentelemetry/sdk-trace-base/src/sampler/AlwaysOffSampler.ts","../../../node_modules/@opentelemetry/sdk-trace-base/src/sampler/AlwaysOnSampler.ts","../../../node_modules/@opentelemetry/sdk-trace-base/src/sampler/ParentBasedSampler.ts","../../../node_modules/@opentelemetry/sdk-trace-base/src/sampler/TraceIdRatioBasedSampler.ts","../../../node_modules/@opentelemetry/sdk-trace-base/src/utility.ts","../../../node_modules/@opentelemetry/sdk-trace-base/src/export/BatchSpanProcessorBase.ts","../../../node_modules/@opentelemetry/sdk-trace-base/src/platform/node/export/BatchSpanProcessor.ts","../../../node_modules/@opentelemetry/sdk-trace-base/src/platform/node/RandomIdGenerator.ts","../../../node_modules/@opentelemetry/sdk-trace-base/src/semconv.ts","../../../node_modules/@opentelemetry/sdk-trace-base/src/TracerMetrics.ts","../../../node_modules/@opentelemetry/sdk-trace-base/src/version.ts","../../../node_modules/@opentelemetry/sdk-trace-base/src/MultiSpanProcessor.ts","../../../node_modules/@opentelemetry/sdk-trace-base/src/BasicTracerProvider.ts","../src/otel-config.ts","../src/api-key-hash.ts","../src/coexistence.ts","../src/proxy-detection.ts","../src/context-manager.ts","../src/heartbeat.ts","../src/side-effect/index.ts","../src/runtime-state.ts","../src/agent-detection/upgrade-notice.ts","../src/agent-detection/inject.ts","../src/mask-key.ts","../src/config-wrapper.ts","../src/capture-error.ts","../src/stack-frame.ts","../src/import-graph.ts"],"sourcesContent":["import type { GlasstraceEnvVars, GlasstraceOptions } from \"@glasstrace/protocol\";\n\n/**\n * Resolved configuration after merging explicit options with environment variables.\n */\nexport interface ResolvedConfig {\n  apiKey: string | undefined;\n  endpoint: string;\n  forceEnable: boolean;\n  verbose: boolean;\n  /**\n   * Whether the explicit decision-trace opt-in is set. Optional on the\n   * exported shape so existing consumers that construct a `ResolvedConfig`\n   * literal for the public helpers keep compiling; `resolveConfig` always\n   * populates it, and the gate reads it as falsy when absent.\n   */\n  decisionTrace?: boolean;\n  environment: string | undefined;\n  coverageMapEnabled: boolean;\n  nodeEnv: string | undefined;\n  vercelEnv: string | undefined;\n}\n\nconst DEFAULT_ENDPOINT = \"https://api.glasstrace.dev\";\n\n/**\n * Reads all recognized Glasstrace environment variables from process.env.\n * Returns undefined for any variable not set. Never throws.\n */\nexport function readEnvVars(): GlasstraceEnvVars {\n  return {\n    GLASSTRACE_API_KEY: process.env.GLASSTRACE_API_KEY?.trim() || undefined,\n    GLASSTRACE_FORCE_ENABLE: process.env.GLASSTRACE_FORCE_ENABLE,\n    GLASSTRACE_ENV: process.env.GLASSTRACE_ENV,\n    GLASSTRACE_COVERAGE_MAP: process.env.GLASSTRACE_COVERAGE_MAP,\n    GLASSTRACE_DECISION_TRACE: process.env.GLASSTRACE_DECISION_TRACE,\n    NODE_ENV: process.env.NODE_ENV,\n    VERCEL_ENV: process.env.VERCEL_ENV,\n  };\n}\n\n/**\n * Merges explicit GlasstraceOptions with environment variables.\n * Explicit options take precedence over environment variables.\n */\nexport function resolveConfig(options?: GlasstraceOptions): ResolvedConfig {\n  const env = readEnvVars();\n\n  return {\n    apiKey: options?.apiKey ?? env.GLASSTRACE_API_KEY,\n    endpoint: options?.endpoint ?? DEFAULT_ENDPOINT,\n    forceEnable: options?.forceEnable ?? env.GLASSTRACE_FORCE_ENABLE === \"true\",\n    verbose: options?.verbose ?? false,\n    // Decision tracing resolves from the option or the env var; the\n    // `|| verbose` fold is applied at the gate (`decisionTraceEnabled`),\n    // not here, so the resolved flag records only the explicit opt-in.\n    decisionTrace: options?.decisionTrace ?? env.GLASSTRACE_DECISION_TRACE === \"true\",\n    environment: env.GLASSTRACE_ENV,\n    coverageMapEnabled: env.GLASSTRACE_COVERAGE_MAP === \"true\",\n    nodeEnv: env.NODE_ENV,\n    vercelEnv: env.VERCEL_ENV,\n  };\n}\n\n/**\n * Returns true when the SDK should be inactive (production detected without force-enable).\n * Logic order:\n *   1. forceEnable === true → return false (override)\n *   2. NODE_ENV === 'production' → return true\n *   3. VERCEL_ENV === 'production' → return true\n *   4. Otherwise → return false\n */\nexport function isProductionDisabled(config: ResolvedConfig): boolean {\n  if (config.forceEnable) {\n    return false;\n  }\n  if (config.nodeEnv === \"production\") {\n    return true;\n  }\n  if (config.vercelEnv === \"production\") {\n    return true;\n  }\n  return false;\n}\n\n/**\n * Returns true when no API key is configured (anonymous mode).\n * Treats undefined, empty string, whitespace-only, and gt_anon_* keys as anonymous.\n */\nexport function isAnonymousMode(config: ResolvedConfig): boolean {\n  if (config.apiKey === undefined) {\n    return true;\n  }\n  if (config.apiKey.trim() === \"\") {\n    return true;\n  }\n  if (config.apiKey.startsWith(\"gt_anon_\")) {\n    return true;\n  }\n  return false;\n}\n","var _a;\n/** A special constant with type `never` */\nexport const NEVER = /*@__PURE__*/ Object.freeze({\n    status: \"aborted\",\n});\nexport /*@__NO_SIDE_EFFECTS__*/ function $constructor(name, initializer, params) {\n    function init(inst, def) {\n        if (!inst._zod) {\n            Object.defineProperty(inst, \"_zod\", {\n                value: {\n                    def,\n                    constr: _,\n                    traits: new Set(),\n                },\n                enumerable: false,\n            });\n        }\n        if (inst._zod.traits.has(name)) {\n            return;\n        }\n        inst._zod.traits.add(name);\n        initializer(inst, def);\n        // support prototype modifications\n        const proto = _.prototype;\n        const keys = Object.keys(proto);\n        for (let i = 0; i < keys.length; i++) {\n            const k = keys[i];\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        var _a;\n        const inst = params?.Parent ? new Definition() : this;\n        init(inst, def);\n        (_a = inst._zod).deferred ?? (_a.deferred = []);\n        for (const fn of inst._zod.deferred) {\n            fn();\n        }\n        return inst;\n    }\n    Object.defineProperty(_, \"init\", { value: init });\n    Object.defineProperty(_, Symbol.hasInstance, {\n        value: (inst) => {\n            if (params?.Parent && inst instanceof params.Parent)\n                return true;\n            return inst?._zod?.traits?.has(name);\n        },\n    });\n    Object.defineProperty(_, \"name\", { value: name });\n    return _;\n}\n//////////////////////////////   UTILITIES   ///////////////////////////////////////\nexport const $brand = Symbol(\"zod_brand\");\nexport class $ZodAsyncError extends Error {\n    constructor() {\n        super(`Encountered Promise during synchronous parse. Use .parseAsync() instead.`);\n    }\n}\nexport 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 { globalConfig } from \"./core.js\";\n// functions\nexport function assertEqual(val) {\n    return val;\n}\nexport function assertNotEqual(val) {\n    return val;\n}\nexport function assertIs(_arg) { }\nexport function assertNever(_x) {\n    throw new Error(\"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}\nexport function cached(getter) {\n    const set = false;\n    return {\n        get value() {\n            if (!set) {\n                const value = getter();\n                Object.defineProperty(this, \"value\", { value });\n                return value;\n            }\n            throw new Error(\"cached value already set\");\n        },\n    };\n}\nexport function nullish(input) {\n    return input === null || input === undefined;\n}\nexport function cleanRegex(source) {\n    const start = source.startsWith(\"^\") ? 1 : 0;\n    const end = source.endsWith(\"$\") ? source.length - 1 : source.length;\n    return source.slice(start, end);\n}\nexport function floatSafeRemainder(val, step) {\n    const ratio = val / step;\n    const roundedRatio = Math.round(ratio);\n    // Use a relative epsilon scaled to the magnitude of the result\n    const tolerance = 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}\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`\n    // 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 === \"optional\" && shape[k]._zod.optout === \"optional\";\n    });\n}\nexport const NUMBER_FORMAT_RANGES = {\n    safeint: [Number.MIN_SAFE_INTEGER, Number.MAX_SAFE_INTEGER],\n    int32: [-2147483648, 2147483647],\n    uint32: [0, 4294967295],\n    float32: [-3.4028234663852886e38, 3.4028234663852886e38],\n    float64: [-Number.MAX_VALUE, Number.MAX_VALUE],\n};\nexport const BIGINT_FORMAT_RANGES = {\n    int64: [/* @__PURE__*/ BigInt(\"-9223372036854775808\"), /* @__PURE__*/ BigInt(\"9223372036854775807\")],\n    uint64: [/* @__PURE__*/ BigInt(0), /* @__PURE__*/ BigInt(\"18446744073709551615\")],\n};\nexport function pick(schema, mask) {\n    const 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 def = mergeDefs(schema._zod.def, {\n        get shape() {\n            const newShape = {};\n            for (const key in mask) {\n                if (!(key in currDef.shape)) {\n                    throw new Error(`Unrecognized key: \"${key}\"`);\n                }\n                if (!mask[key])\n                    continue;\n                newShape[key] = currDef.shape[key];\n            }\n            assignProp(this, \"shape\", newShape); // self-caching\n            return newShape;\n        },\n        checks: [],\n    });\n    return clone(schema, def);\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 def = mergeDefs(schema._zod.def, {\n        get shape() {\n            const newShape = { ...schema._zod.def.shape };\n            for (const key in mask) {\n                if (!(key in currDef.shape)) {\n                    throw new Error(`Unrecognized key: \"${key}\"`);\n                }\n                if (!mask[key])\n                    continue;\n                delete newShape[key];\n            }\n            assignProp(this, \"shape\", newShape); // self-caching\n            return newShape;\n        },\n        checks: [],\n    });\n    return clone(schema, def);\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\n        // Use getOwnPropertyDescriptor to check key existence without accessing values\n        const existingShape = schema._zod.def.shape;\n        for (const key in 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    const def = mergeDefs(schema._zod.def, {\n        get shape() {\n            const _shape = { ...schema._zod.def.shape, ...shape };\n            assignProp(this, \"shape\", _shape); // self-caching\n            return _shape;\n        },\n    });\n    return clone(schema, def);\n}\nexport function safeExtend(schema, shape) {\n    if (!isPlainObject(shape)) {\n        throw new Error(\"Invalid input to safeExtend: expected a plain object\");\n    }\n    const def = mergeDefs(schema._zod.def, {\n        get shape() {\n            const _shape = { ...schema._zod.def.shape, ...shape };\n            assignProp(this, \"shape\", _shape); // self-caching\n            return _shape;\n        },\n    });\n    return clone(schema, def);\n}\nexport function merge(a, b) {\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 def = mergeDefs(a._zod.def, {\n        get shape() {\n            const _shape = { ...a._zod.def.shape, ...b._zod.def.shape };\n            assignProp(this, \"shape\", _shape); // self-caching\n            return _shape;\n        },\n        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) {\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(\".partial() cannot be used on object schemas containing refinements\");\n    }\n    const def = mergeDefs(schema._zod.def, {\n        get shape() {\n            const oldShape = schema._zod.def.shape;\n            const shape = { ...oldShape };\n            if (mask) {\n                for (const key in mask) {\n                    if (!(key in oldShape)) {\n                        throw new Error(`Unrecognized key: \"${key}\"`);\n                    }\n                    if (!mask[key])\n                        continue;\n                    // if (oldShape[key]!._zod.optin === \"optional\") continue;\n                    shape[key] = Class\n                        ? new Class({\n                            type: \"optional\",\n                            innerType: oldShape[key],\n                        })\n                        : oldShape[key];\n                }\n            }\n            else {\n                for (const key in oldShape) {\n                    // if (oldShape[key]!._zod.optin === \"optional\") continue;\n                    shape[key] = Class\n                        ? new Class({\n                            type: \"optional\",\n                            innerType: oldShape[key],\n                        })\n                        : oldShape[key];\n                }\n            }\n            assignProp(this, \"shape\", shape); // self-caching\n            return shape;\n        },\n        checks: [],\n    });\n    return clone(schema, def);\n}\nexport function required(Class, schema, mask) {\n    const def = mergeDefs(schema._zod.def, {\n        get shape() {\n            const oldShape = schema._zod.def.shape;\n            const shape = { ...oldShape };\n            if (mask) {\n                for (const key in mask) {\n                    if (!(key in shape)) {\n                        throw new Error(`Unrecognized key: \"${key}\"`);\n                    }\n                    if (!mask[key])\n                        continue;\n                    // overwrite with non-optional\n                    shape[key] = new Class({\n                        type: \"nonoptional\",\n                        innerType: oldShape[key],\n                    });\n                }\n            }\n            else {\n                for (const key in oldShape) {\n                    // overwrite with non-optional\n                    shape[key] = new Class({\n                        type: \"nonoptional\",\n                        innerType: oldShape[key],\n                    });\n                }\n            }\n            assignProp(this, \"shape\", shape); // self-caching\n            return shape;\n        },\n    });\n    return clone(schema, def);\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).\n// 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}\nexport function finalizeIssue(iss, ctx, config) {\n    const message = iss.message\n        ? iss.message\n        : (unwrapMessage(iss.inst?._zod.def?.error?.(iss)) ??\n            unwrapMessage(ctx?.error?.(iss)) ??\n            unwrapMessage(config.customError?.(iss)) ??\n            unwrapMessage(config.localeError?.(iss)) ??\n            \"Invalid input\");\n    const { inst: _inst, continue: _continue, input: _input, ...rest } = iss;\n    rest.path ?? (rest.path = []);\n    rest.message = message;\n    if (ctx?.reportInput) {\n        rest.input = _input;\n    }\n    return rest;\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}\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","import { $constructor } from \"./core.js\";\nimport * as util from \"./util.js\";\nconst initializer = (inst, def) => {\n    inst.name = \"$ZodError\";\n    Object.defineProperty(inst, \"_zod\", {\n        value: inst._zod,\n        enumerable: false,\n    });\n    Object.defineProperty(inst, \"issues\", {\n        value: def,\n        enumerable: false,\n    });\n    inst.message = JSON.stringify(def, util.jsonStringifyReplacer, 2);\n    Object.defineProperty(inst, \"toString\", {\n        value: () => inst.message,\n        enumerable: false,\n    });\n};\nexport const $ZodError = $constructor(\"$ZodError\", initializer);\nexport const $ZodRealError = $constructor(\"$ZodError\", initializer, { Parent: Error });\nexport function flattenError(error, mapper = (issue) => issue.message) {\n    const fieldErrors = {};\n    const formErrors = [];\n    for (const sub of error.issues) {\n        if (sub.path.length > 0) {\n            fieldErrors[sub.path[0]] = fieldErrors[sub.path[0]] || [];\n            fieldErrors[sub.path[0]].push(mapper(sub));\n        }\n        else {\n            formErrors.push(mapper(sub));\n        }\n    }\n    return { formErrors, fieldErrors };\n}\nexport function formatError(error, mapper = (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                        if (!terminal) {\n                            curr[el] = curr[el] || { _errors: [] };\n                        }\n                        else {\n                            curr[el] = curr[el] || { _errors: [] };\n                            curr[el]._errors.push(mapper(issue));\n                        }\n                        curr = curr[el];\n                        i++;\n                    }\n                }\n            }\n        }\n    };\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, _b;\n        for (const issue of error.issues) {\n            if (issue.code === \"invalid_union\" && issue.errors.length) {\n                // regular union error\n                issue.errors.map((issues) => processError({ issues }, [...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                        (_a = curr.properties)[el] ?? (_a[el] = { errors: [] });\n                        curr = curr.properties[el];\n                    }\n                    else {\n                        curr.items ?? (curr.items = []);\n                        (_b = curr.items)[el] ?? (_b[el] = { errors: [] });\n                        curr = curr.items[el];\n                    }\n                    if (terminal) {\n                        curr.errors.push(mapper(issue));\n                    }\n                    i++;\n                }\n            }\n        }\n    };\n    processError(error);\n    return result;\n}\n/** Format a ZodError as a human-readable 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\";\nexport const _parse = (_Err) => (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);\n        throw e;\n    }\n    return result.value;\n};\nexport const parse = /* @__PURE__*/ _parse(errors.$ZodRealError);\nexport const _parseAsync = (_Err) => 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);\n        throw e;\n    }\n    return result.value;\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\n        ? {\n            success: false,\n            error: new (_Err ?? errors.$ZodError)(result.issues.map((iss) => util.finalizeIssue(iss, ctx, core.config()))),\n        }\n        : { success: true, data: result.value };\n};\nexport const safeParse = /* @__PURE__*/ _safeParse(errors.$ZodRealError);\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\n        ? {\n            success: false,\n            error: new _Err(result.issues.map((iss) => util.finalizeIssue(iss, ctx, core.config()))),\n        }\n        : { success: true, data: result.value };\n};\nexport const safeParseAsync = /* @__PURE__*/ _safeParseAsync(errors.$ZodRealError);\nexport const _encode = (_Err) => (schema, value, _ctx) => {\n    const ctx = _ctx ? { ..._ctx, direction: \"backward\" } : { direction: \"backward\" };\n    return _parse(_Err)(schema, value, ctx);\n};\nexport const encode = /* @__PURE__*/ _encode(errors.$ZodRealError);\nexport const _decode = (_Err) => (schema, value, _ctx) => {\n    return _parse(_Err)(schema, value, _ctx);\n};\nexport const decode = /* @__PURE__*/ _decode(errors.$ZodRealError);\nexport const _encodeAsync = (_Err) => async (schema, value, _ctx) => {\n    const ctx = _ctx ? { ..._ctx, direction: \"backward\" } : { direction: \"backward\" };\n    return _parseAsync(_Err)(schema, value, ctx);\n};\nexport const encodeAsync = /* @__PURE__*/ _encodeAsync(errors.$ZodRealError);\nexport const _decodeAsync = (_Err) => async (schema, value, _ctx) => {\n    return _parseAsync(_Err)(schema, value, _ctx);\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-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{26}$/;\nexport const xid = /^[0-9a-vA-V]{20}$/;\nexport const ksuid = /^[A-Za-z0-9]{27}$/;\nexport const nanoid = /^[a-zA-Z0-9_-]{21}$/;\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-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\nconst _emoji = `^(\\\\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})?::([0-9a-fA-F]{1,4}:?){0,6})\\/(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_-]*$/;\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 = /^([a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?\\.)+[a-zA-Z]{2,}$/;\nexport const httpProtocol = /^https?$/;\n// https://blog.stevenlevithan.com/archives/validate-phone-number#r4-3 (regex sans spaces)\n// E.164: leading digit must be 1-9; total digits (excluding '+') between 7-15\nexport const e164 = /^\\+[1-9]\\d{6,14}$/;\n// const dateSource = `((\\\\d\\\\d[2468][048]|\\\\d\\\\d[13579][26]|\\\\d\\\\d0[48]|[02468][048]00|[13579][26]00)-02-29|\\\\d{4}-((0[13578]|1[02])-(0[1-9]|[12]\\\\d|3[01])|(0[469]|11)-(0[1-9]|[12]\\\\d|30)|(02)-(0[1-9]|1\\\\d|2[0-8])))`;\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])))`;\nexport const date = /*@__PURE__*/ new RegExp(`^${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        : `${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 time = timeSource({ precision: args.precision });\n    const opts = [\"Z\"];\n    if (args.local)\n        opts.push(\"\");\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    const timeRegex = `${time}(?:${opts.join(\"|\")})`;\n    return new RegExp(`^${dateSource}T(?:${timeRegex})$`);\n}\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});\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.onattach.push((inst) => {\n        const bag = inst._zod.bag;\n        const curr = (def.inclusive ? bag.maximum : bag.exclusiveMaximum) ?? Number.POSITIVE_INFINITY;\n        if (def.value < curr) {\n            if (def.inclusive)\n                bag.maximum = def.value;\n            else\n                bag.exclusiveMaximum = def.value;\n        }\n    });\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,\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.onattach.push((inst) => {\n        const bag = inst._zod.bag;\n        const curr = (def.inclusive ? bag.minimum : bag.exclusiveMinimum) ?? Number.NEGATIVE_INFINITY;\n        if (def.value > curr) {\n            if (def.inclusive)\n                bag.minimum = def.value;\n            else\n                bag.exclusiveMinimum = def.value;\n        }\n    });\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,\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.onattach.push((inst) => {\n        var _a;\n        (_a = inst._zod.bag).multipleOf ?? (_a.multipleOf = def.value);\n    });\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            ? 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.onattach.push((inst) => {\n        const bag = inst._zod.bag;\n        bag.format = def.format;\n        bag.minimum = minimum;\n        bag.maximum = maximum;\n        if (isInt)\n            bag.pattern = regexes.integer;\n    });\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.onattach.push((inst) => {\n        const bag = inst._zod.bag;\n        bag.format = def.format;\n        bag.minimum = minimum;\n        bag.maximum = maximum;\n    });\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 = (payload) => {\n        const val = payload.value;\n        return !util.nullish(val) && val.size !== undefined;\n    });\n    inst._zod.onattach.push((inst) => {\n        const curr = (inst._zod.bag.maximum ?? Number.POSITIVE_INFINITY);\n        if (def.maximum < curr)\n            inst._zod.bag.maximum = def.maximum;\n    });\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 = (payload) => {\n        const val = payload.value;\n        return !util.nullish(val) && val.size !== undefined;\n    });\n    inst._zod.onattach.push((inst) => {\n        const curr = (inst._zod.bag.minimum ?? Number.NEGATIVE_INFINITY);\n        if (def.minimum > curr)\n            inst._zod.bag.minimum = def.minimum;\n    });\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 = (payload) => {\n        const val = payload.value;\n        return !util.nullish(val) && val.size !== undefined;\n    });\n    inst._zod.onattach.push((inst) => {\n        const bag = inst._zod.bag;\n        bag.minimum = def.size;\n        bag.maximum = def.size;\n        bag.size = def.size;\n    });\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 = (payload) => {\n        const val = payload.value;\n        return !util.nullish(val) && val.length !== undefined;\n    });\n    inst._zod.onattach.push((inst) => {\n        const curr = (inst._zod.bag.maximum ?? Number.POSITIVE_INFINITY);\n        if (def.maximum < curr)\n            inst._zod.bag.maximum = def.maximum;\n    });\n    inst._zod.check = (payload) => {\n        const input = payload.value;\n        const length = input.length;\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 = (payload) => {\n        const val = payload.value;\n        return !util.nullish(val) && val.length !== undefined;\n    });\n    inst._zod.onattach.push((inst) => {\n        const curr = (inst._zod.bag.minimum ?? Number.NEGATIVE_INFINITY);\n        if (def.minimum > curr)\n            inst._zod.bag.minimum = def.minimum;\n    });\n    inst._zod.check = (payload) => {\n        const input = payload.value;\n        const length = input.length;\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 = (payload) => {\n        const val = payload.value;\n        return !util.nullish(val) && val.length !== undefined;\n    });\n    inst._zod.onattach.push((inst) => {\n        const bag = inst._zod.bag;\n        bag.minimum = def.length;\n        bag.maximum = def.length;\n        bag.length = def.length;\n    });\n    inst._zod.check = (payload) => {\n        const input = payload.value;\n        const length = input.length;\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    inst._zod.onattach.push((inst) => {\n        const bag = inst._zod.bag;\n        bag.format = def.format;\n        if (def.pattern) {\n            bag.patterns ?? (bag.patterns = new Set());\n            bag.patterns.add(def.pattern);\n        }\n    });\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    const pattern = new RegExp(typeof def.position === \"number\" ? `^.{${def.position}}${escapedRegex}` : escapedRegex);\n    def.pattern = pattern;\n    inst._zod.onattach.push((inst) => {\n        const bag = inst._zod.bag;\n        bag.patterns ?? (bag.patterns = new Set());\n        bag.patterns.add(pattern);\n    });\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.onattach.push((inst) => {\n        const bag = inst._zod.bag;\n        bag.patterns ?? (bag.patterns = new Set());\n        bag.patterns.add(pattern);\n    });\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.onattach.push((inst) => {\n        const bag = inst._zod.bag;\n        bag.patterns ?? (bag.patterns = new Set());\n        bag.patterns.add(pattern);\n    });\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 $ZodCheckMimeType = /*@__PURE__*/ core.$constructor(\"$ZodCheckMimeType\", (inst, def) => {\n    $ZodCheck.init(inst, def);\n    const mimeSet = new Set(def.mime);\n    inst._zod.onattach.push((inst) => {\n        inst._zod.bag.mime = def.mime;\n    });\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 = []) {\n        this.content = [];\n        this.indent = 0;\n        if (this)\n            this.args = args;\n    }\n    indented(fn) {\n        this.indent += 1;\n        fn(this);\n        this.indent -= 1;\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 args = this?.args;\n        const content = this?.content ?? [``];\n        const lines = [...content.map((x) => `  ${x}`)];\n        // console.log(lines.join(\"\\n\"));\n        return new F(...args, lines.join(\"\\n\"));\n    }\n}\n","export const version = {\n    major: 4,\n    minor: 4,\n    patch: 3,\n};\n","import * as checks from \"./checks.js\";\nimport * as core from \"./core.js\";\nimport { Doc } from \"./doc.js\";\nimport { parse, parseAsync, safeParse, safeParseAsync } 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 checks = [...(inst._zod.def.checks ?? [])];\n    // if inst is itself a checks.$ZodCheck, run it as a check\n    if (inst._zod.traits.has(\"$ZodCheck\")) {\n        checks.unshift(inst);\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\n        // 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            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                        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                    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\n                // 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    // Lazy initialize ~standard to avoid creating objects for every schema\n    util.defineLazy(inst, \"~standard\", () => ({\n        validate: (value) => {\n            try {\n                const r = safeParse(inst, value);\n                return r.success ? { value: r.data } : { issues: r.error?.issues };\n            }\n            catch (_) {\n                return safeParseAsync(inst, value).then((r) => (r.success ? { value: r.data } : { issues: r.error?.issues }));\n            }\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    inst._zod.pattern = [...(inst?._zod.bag?.patterns ?? [])].pop() ?? regexes.string(inst._zod.bag);\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});\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            // When normalize is off, require :// for http/https URLs\n            // This prevents strings like \"http:example.com\" or \"https:/path\" from being silently accepted\n            if (!def.normalize && def.protocol?.source === regexes.httpProtocol.source) {\n                if (!/^https?:\\/\\//i.test(trimmed)) {\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            }\n            // @ts-ignore\n            const url = new URL(trimmed);\n            if (def.hostname) {\n                def.hostname.lastIndex = 0;\n                if (!def.hostname.test(url.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            }\n            if (def.protocol) {\n                def.protocol.lastIndex = 0;\n                if (!def.protocol.test(url.protocol.endsWith(\":\") ? url.protocol.slice(0, -1) : url.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            }\n            // Set the output value based on normalize flag\n            if (def.normalize) {\n                // Use normalized URL\n                payload.value = url.href;\n            }\n            else {\n                // Preserve the original input (trimmed)\n                payload.value = trimmed;\n            }\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    def.pattern ?? (def.pattern = regexes.nanoid);\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    inst._zod.bag.format = `ipv4`;\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.bag.format = `ipv6`;\n    inst._zod.check = (payload) => {\n        try {\n            // @ts-ignore\n            new URL(`http://[${payload.value}]`);\n            // return;\n        }\n        catch {\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    inst._zod.bag.format = `mac`;\n});\nexport const $ZodCIDRv4 = /*@__PURE__*/ core.$constructor(\"$ZodCIDRv4\", (inst, def) => {\n    def.pattern ?? (def.pattern = regexes.cidrv4);\n    $ZodStringFormat.init(inst, def);\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        const parts = payload.value.split(\"/\");\n        try {\n            if (parts.length !== 2)\n                throw new Error();\n            const [address, prefix] = parts;\n            if (!prefix)\n                throw new Error();\n            const prefixNum = Number(prefix);\n            if (`${prefixNum}` !== prefix)\n                throw new Error();\n            if (prefixNum < 0 || prefixNum > 128)\n                throw new Error();\n            // @ts-ignore\n            new URL(`http://[${address}]`);\n        }\n        catch {\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}\nexport const $ZodBase64 = /*@__PURE__*/ core.$constructor(\"$ZodBase64\", (inst, def) => {\n    def.pattern ?? (def.pattern = regexes.base64);\n    $ZodStringFormat.init(inst, def);\n    inst._zod.bag.contentEncoding = \"base64\";\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//////////////////////////////   ZodBase64   //////////////////////////////\nexport function isValidBase64URL(data) {\n    if (!regexes.base64url.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 = regexes.base64url);\n    $ZodStringFormat.init(inst, def);\n    inst._zod.bag.contentEncoding = \"base64url\";\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//////////////////////////////   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 = inst._zod.bag.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                    ? \"Infinity\"\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});\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    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 = Array(input.length);\n        const proms = [];\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            }\n        }\n        if (proms.length) {\n            return Promise.all(proms).then(() => payload);\n        }\n        return payload; //handleArrayResultsAsync(parseResults, final);\n    };\n});\nfunction handlePropertyResult(result, final, key, input, isOptionalIn, isOptionalOut) {\n    const isPresent = key in input;\n    if (result.issues.length) {\n        // For optional-in/out schemas, ignore errors on absent keys.\n        if (isOptionalIn && isOptionalOut && !isPresent) {\n            return;\n        }\n        final.issues.push(...util.prefixIssues(key, result.issues));\n    }\n    if (!isPresent && !isOptionalIn) {\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) {\n            final.value[key] = undefined;\n        }\n    }\n    else {\n        final.value[key] = result.value;\n    }\n}\nfunction normalizeDef(def) {\n    const keys = Object.keys(def.shape);\n    for (const k of keys) {\n        if (!def.shape?.[k]?._zod?.traits?.has(\"$ZodType\")) {\n            throw new Error(`Invalid element at key \"${k}\": expected a Zod schema`);\n        }\n    }\n    const okeys = util.optionalKeys(def.shape);\n    return {\n        ...def,\n        keys,\n        keySet: new Set(keys),\n        numKeys: keys.length,\n        optionalKeys: new Set(okeys),\n    };\n}\nfunction handleCatchall(proms, input, payload, ctx, def, inst) {\n    const unrecognized = [];\n    const keySet = def.keySet;\n    const _catchall = def.catchall._zod;\n    const t = _catchall.def.type;\n    const isOptionalIn = _catchall.optin === \"optional\";\n    const isOptionalOut = _catchall.optout === \"optional\";\n    for (const key in input) {\n        // skip __proto__ so it can't replace the result prototype via the\n        // assignment setter on the plain {} we build into\n        if (key === \"__proto__\")\n            continue;\n        if (keySet.has(key))\n            continue;\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, isOptionalIn, isOptionalOut)));\n        }\n        else {\n            handlePropertyResult(r, payload, key, input, isOptionalIn, isOptionalOut);\n        }\n    }\n    if (unrecognized.length) {\n        payload.issues.push({\n            code: \"unrecognized_keys\",\n            keys: unrecognized,\n            input,\n            inst,\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 sh = def.shape;\n    const desc = Object.getOwnPropertyDescriptor(def, \"shape\");\n    if (!desc?.get) {\n        const sh = def.shape;\n        Object.defineProperty(def, \"shape\", {\n            get: () => {\n                const newSh = { ...sh };\n                Object.defineProperty(def, \"shape\", {\n                    value: newSh,\n                });\n                return newSh;\n            },\n        });\n    }\n    const _normalized = util.cached(() => normalizeDef(def));\n    util.defineLazy(inst._zod, \"propValues\", () => {\n        const shape = def.shape;\n        const propValues = {};\n        for (const key in shape) {\n            const field = shape[key]._zod;\n            if (field.values) {\n                propValues[key] ?? (propValues[key] = new Set());\n                for (const v of field.values)\n                    propValues[key].add(v);\n            }\n        }\n        return propValues;\n    });\n    const isObject = util.isObject;\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        payload.value = {};\n        const proms = [];\n        const shape = value.shape;\n        for (const key of value.keys) {\n            const el = shape[key];\n            const isOptionalIn = el._zod.optin === \"optional\";\n            const isOptionalOut = el._zod.optout === \"optional\";\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, isOptionalIn, isOptionalOut)));\n            }\n            else {\n                handlePropertyResult(r, payload, key, input, isOptionalIn, isOptionalOut);\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);\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 generateFastpass = (shape) => {\n        const doc = new Doc([\"shape\", \"payload\", \"ctx\"]);\n        const normalized = _normalized.value;\n        const parseStr = (key) => {\n            const k = util.esc(key);\n            return `shape[${k}]._zod.run({ value: input[${k}], issues: [] }, ctx)`;\n        };\n        doc.write(`const input = payload.value;`);\n        const ids = Object.create(null);\n        let counter = 0;\n        for (const key of normalized.keys) {\n            ids[key] = `key_${counter++}`;\n        }\n        // A: preserve key order {\n        doc.write(`const newResult = {};`);\n        for (const key of normalized.keys) {\n            const id = ids[key];\n            const k = util.esc(key);\n            const schema = shape[key];\n            const isOptionalIn = schema?._zod?.optin === \"optional\";\n            const isOptionalOut = schema?._zod?.optout === \"optional\";\n            doc.write(`const ${id} = ${parseStr(key)};`);\n            if (isOptionalIn && isOptionalOut) {\n                // For optional-in/out schemas, ignore errors on absent keys\n                doc.write(`\n        if (${id}.issues.length) {\n          if (${k} in input) {\n            payload.issues = payload.issues.concat(${id}.issues.map(iss => ({\n              ...iss,\n              path: iss.path ? [${k}, ...iss.path] : [${k}]\n            })));\n          }\n        }\n        \n        if (${id}.value === undefined) {\n          if (${k} in input) {\n            newResult[${k}] = undefined;\n          }\n        } else {\n          newResult[${k}] = ${id}.value;\n        }\n        \n      `);\n            }\n            else if (!isOptionalIn) {\n                doc.write(`\n        const ${id}_present = ${k} in input;\n        if (${id}.issues.length) {\n          payload.issues = payload.issues.concat(${id}.issues.map(iss => ({\n            ...iss,\n            path: iss.path ? [${k}, ...iss.path] : [${k}]\n          })));\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        }\n\n        if (${id}_present) {\n          if (${id}.value === undefined) {\n            newResult[${k}] = undefined;\n          } else {\n            newResult[${k}] = ${id}.value;\n          }\n        }\n\n      `);\n            }\n            else {\n                doc.write(`\n        if (${id}.issues.length) {\n          payload.issues = payload.issues.concat(${id}.issues.map(iss => ({\n            ...iss,\n            path: iss.path ? [${k}, ...iss.path] : [${k}]\n          })));\n        }\n        \n        if (${id}.value === undefined) {\n          if (${k} in input) {\n            newResult[${k}] = undefined;\n          }\n        } else {\n          newResult[${k}] = ${id}.value;\n        }\n        \n      `);\n            }\n        }\n        doc.write(`payload.value = newResult;`);\n        doc.write(`return payload;`);\n        const fn = doc.compile();\n        return (payload, ctx) => fn(shape, payload, ctx);\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);\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.defineLazy(inst._zod, \"optin\", () => def.options.some((o) => o._zod.optin === \"optional\") ? \"optional\" : undefined);\n    util.defineLazy(inst._zod, \"optout\", () => def.options.some((o) => o._zod.optout === \"optional\") ? \"optional\" : undefined);\n    util.defineLazy(inst._zod, \"values\", () => {\n        if (def.options.every((o) => o._zod.values)) {\n            return new Set(def.options.flatMap((option) => Array.from(option._zod.values)));\n        }\n        return undefined;\n    });\n    util.defineLazy(inst._zod, \"pattern\", () => {\n        if (def.options.every((o) => o._zod.pattern)) {\n            const patterns = 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 successes = results.filter((r) => r.issues.length === 0);\n    if (successes.length === 1) {\n        final.value = successes[0].value;\n        return final;\n    }\n    if (successes.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        });\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});\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.defineLazy(inst._zod, \"propValues\", () => {\n        const propValues = {};\n        for (const option of 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 \"${def.options.indexOf(option)}\"`);\n            for (const [k, v] of Object.entries(pv)) {\n                if (!propValues[k])\n                    propValues[k] = new Set();\n                for (const val of v) {\n                    propValues[k].add(val);\n                }\n            }\n        }\n        return propValues;\n    });\n    const disc = util.cached(() => {\n        const opts = def.options;\n        const map = new Map();\n        for (const o of opts) {\n            const values = o._zod.propValues?.[def.discriminator];\n            if (!values || values.size === 0)\n                throw new Error(`Invalid discriminated union option at index \"${def.options.indexOf(o)}\"`);\n            for (const v of values) {\n                if (map.has(v)) {\n                    throw new Error(`Duplicate discriminator value \"${String(v)}\"`);\n                }\n                map.set(v, o);\n            }\n        }\n        return map;\n    });\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 opt = disc.value.get(input?.[def.discriminator]);\n        if (opt) {\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\n        //   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()),\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});\nfunction 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        for (const key of sharedKeys) {\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) report each key as unrecognized\n    const unrecKeys = new Map();\n    let unrecIssue;\n    for (const iss of left.issues) {\n        if (iss.code === \"unrecognized_keys\") {\n            unrecIssue ?? (unrecIssue = iss);\n            for (const k of iss.keys) {\n                if (!unrecKeys.has(k))\n                    unrecKeys.set(k, {});\n                unrecKeys.get(k).l = true;\n            }\n        }\n        else {\n            result.issues.push(iss);\n        }\n    }\n    for (const iss of right.issues) {\n        if (iss.code === \"unrecognized_keys\") {\n            for (const k of iss.keys) {\n                if (!unrecKeys.has(k))\n                    unrecKeys.set(k, {});\n                unrecKeys.get(k).r = true;\n            }\n        }\n        else {\n            result.issues.push(iss);\n        }\n    }\n    // Report only keys unrecognized by BOTH sides\n    const bothKeys = [...unrecKeys].filter(([, f]) => f.l && f.r).map(([k]) => k);\n    if (bothKeys.length && unrecIssue) {\n        result.issues.push({ ...unrecIssue, keys: bothKeys });\n    }\n    if (util.aborted(result))\n        return result;\n    const merged = mergeValues(left.value, right.value);\n    if (!merged.valid) {\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    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 = [];\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\n        // array. The post-processing in `handleTupleResults` walks them in\n        // order so it can decide whether an absent optional-output error can\n        // truncate the tail or must be reported to preserve required output.\n        const itemResults = new Array(items.length);\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            }\n        }\n        if (def.rest) {\n            let i = items.length - 1;\n            const rest = input.slice(items.length);\n            for (const el of rest) {\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        if (items[i]._zod[key] !== \"optional\")\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\n    // rule, but only after `optoutStart`: the first index where the output\n    // 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        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    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        const proms = [];\n        const values = def.keyType._zod.values;\n        if (values) {\n            payload.value = {};\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                    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                    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                    unrecognized = unrecognized ?? [];\n                    unrecognized.push(key);\n                }\n            }\n            if (unrecognized && unrecognized.length > 0) {\n                payload.issues.push({\n                    code: \"unrecognized_keys\",\n                    input,\n                    inst,\n                    keys: unrecognized,\n                });\n            }\n        }\n        else {\n            payload.value = {};\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)\n                // 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 {\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                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[keyResult.value] = result.value;\n                    }));\n                }\n                else {\n                    if (result.issues.length) {\n                        payload.issues.push(...util.prefixIssues(key, result.issues));\n                    }\n                    payload.value[keyResult.value] = result.value;\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    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 = new Map();\n        for (const [key, value] of input) {\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});\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    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 = new Set();\n        for (const item of input) {\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});\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    inst._zod.pattern = new RegExp(`^(${values\n        .filter((k) => util.propertyKeyTypes.has(typeof k))\n        .map((o) => (typeof o === \"string\" ? util.escapeRegex(o) : o.toString()))\n        .join(\"|\")})$`);\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    if (def.values.length === 0) {\n        throw new Error(\"Cannot create literal schema with no valid values\");\n    }\n    const values = new Set(def.values);\n    inst._zod.values = values;\n    inst._zod.pattern = new RegExp(`^(${def.values\n        .map((o) => (typeof o === \"string\" ? util.escapeRegex(o) : o ? util.escapeRegex(o.toString()) : String(o)))\n        .join(\"|\")})$`);\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    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                payload.fallback = true;\n                return payload;\n            });\n        }\n        if (_out instanceof Promise) {\n            throw new core.$ZodAsyncError();\n        }\n        payload.value = _out;\n        payload.fallback = true;\n        return payload;\n    };\n});\nfunction handleOptionalResult(result, input) {\n    if (input === undefined && (result.issues.length || result.fallback)) {\n        return { issues: [], value: undefined };\n    }\n    return result;\n}\nexport const $ZodOptional = /*@__PURE__*/ core.$constructor(\"$ZodOptional\", (inst, def) => {\n    $ZodType.init(inst, def);\n    inst._zod.optin = \"optional\";\n    inst._zod.optout = \"optional\";\n    util.defineLazy(inst._zod, \"values\", () => {\n        return def.innerType._zod.values ? new Set([...def.innerType._zod.values, undefined]) : undefined;\n    });\n    util.defineLazy(inst._zod, \"pattern\", () => {\n        const pattern = def.innerType._zod.pattern;\n        return pattern ? new RegExp(`^(${util.cleanRegex(pattern.source)})?$`) : undefined;\n    });\n    inst._zod.parse = (payload, ctx) => {\n        if (def.innerType._zod.optin === \"optional\") {\n            const input = payload.value;\n            const result = def.innerType._zod.run(payload, ctx);\n            if (result instanceof Promise)\n                return result.then((r) => handleOptionalResult(r, input));\n            return handleOptionalResult(result, input);\n        }\n        if (payload.value === undefined) {\n            return payload;\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.defineLazy(inst._zod, \"values\", () => def.innerType._zod.values);\n    util.defineLazy(inst._zod, \"pattern\", () => 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.defineLazy(inst._zod, \"optin\", () => def.innerType._zod.optin);\n    util.defineLazy(inst._zod, \"optout\", () => def.innerType._zod.optout);\n    util.defineLazy(inst._zod, \"pattern\", () => {\n        const pattern = def.innerType._zod.pattern;\n        return pattern ? new RegExp(`^(${util.cleanRegex(pattern.source)}|null)$`) : undefined;\n    });\n    util.defineLazy(inst._zod, \"values\", () => {\n        return def.innerType._zod.values ? new Set([...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 = \"optional\";\n    util.defineLazy(inst._zod, \"values\", () => 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 = \"optional\";\n    util.defineLazy(inst._zod, \"values\", () => 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.defineLazy(inst._zod, \"values\", () => {\n        const v = 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});\nexport const $ZodCatch = /*@__PURE__*/ core.$constructor(\"$ZodCatch\", (inst, def) => {\n    $ZodType.init(inst, def);\n    inst._zod.optin = \"optional\";\n    util.defineLazy(inst._zod, \"optout\", () => def.innerType._zod.optout);\n    util.defineLazy(inst._zod, \"values\", () => 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(payload, ctx);\n        if (result instanceof Promise) {\n            return result.then((result) => {\n                payload.value = result.value;\n                if (result.issues.length) {\n                    payload.value = def.catchValue({\n                        ...payload,\n                        error: {\n                            issues: result.issues.map((iss) => util.finalizeIssue(iss, ctx, core.config())),\n                        },\n                        input: payload.value,\n                    });\n                    payload.issues = [];\n                    payload.fallback = true;\n                }\n                return payload;\n            });\n        }\n        payload.value = result.value;\n        if (result.issues.length) {\n            payload.value = def.catchValue({\n                ...payload,\n                error: {\n                    issues: result.issues.map((iss) => util.finalizeIssue(iss, ctx, core.config())),\n                },\n                input: payload.value,\n            });\n            payload.issues = [];\n            payload.fallback = true;\n        }\n        return payload;\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.defineLazy(inst._zod, \"values\", () => def.in._zod.values);\n    util.defineLazy(inst._zod, \"optin\", () => def.in._zod.optin);\n    util.defineLazy(inst._zod, \"optout\", () => def.out._zod.optout);\n    util.defineLazy(inst._zod, \"propValues\", () => 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    if (left.issues.length) {\n        // prevent further checks\n        left.aborted = true;\n        return left;\n    }\n    return next._zod.run({ value: left.value, issues: left.issues, fallback: left.fallback }, ctx);\n}\nexport const $ZodCodec = /*@__PURE__*/ core.$constructor(\"$ZodCodec\", (inst, def) => {\n    $ZodType.init(inst, def);\n    util.defineLazy(inst._zod, \"values\", () => def.in._zod.values);\n    util.defineLazy(inst._zod, \"optin\", () => def.in._zod.optin);\n    util.defineLazy(inst._zod, \"optout\", () => def.out._zod.optout);\n    util.defineLazy(inst._zod, \"propValues\", () => 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.defineLazy(inst._zod, \"propValues\", () => def.innerType._zod.propValues);\n    util.defineLazy(inst._zod, \"values\", () => def.innerType._zod.values);\n    util.defineLazy(inst._zod, \"optin\", () => def.innerType?._zod?.optin);\n    util.defineLazy(inst._zod, \"optout\", () => 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    payload.value = Object.freeze(payload.value);\n    return payload;\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            if (!part._zod.pattern) {\n                // if (!source)\n                throw new Error(`Invalid template literal part, no pattern found: ${[...part._zod.traits].shift()}`);\n            }\n            const source = part._zod.pattern instanceof RegExp ? part._zod.pattern.source : part._zod.pattern;\n            if (!source)\n                throw new Error(`Invalid template literal part: ${part._zod.traits}`);\n            const start = source.startsWith(\"^\") ? 1 : 0;\n            const end = source.endsWith(\"$\") ? source.length - 1 : source.length;\n            regexParts.push(source.slice(start, end));\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    inst._def = 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        return 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        };\n    };\n    inst.implementAsync = (func) => {\n        if (typeof func !== \"function\") {\n            throw new Error(\"implementAsync() must be called with a function\");\n        }\n        return 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        };\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\n    // lazy (e.g. via `.describe()`/`.meta()`) share the same inner instance,\n    // 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.defineLazy(inst._zod, \"pattern\", () => inst._zod.innerType?._zod?.pattern);\n    util.defineLazy(inst._zod, \"propValues\", () => inst._zod.innerType?._zod?.propValues);\n    util.defineLazy(inst._zod, \"optin\", () => inst._zod.innerType?._zod?.optin ?? undefined);\n    util.defineLazy(inst._zod, \"optout\", () => inst._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 \"../core/util.js\";\nconst error = () => {\n    const Sizable = {\n        string: { unit: \"حرف\", verb: \"أن يحوي\" },\n        file: { unit: \"بايت\", verb: \"أن يحوي\" },\n        array: { unit: \"عنصر\", verb: \"أن يحوي\" },\n        set: { unit: \"عنصر\", verb: \"أن يحوي\" },\n    };\n    function getSizing(origin) {\n        return Sizable[origin] ?? null;\n    }\n    const FormatDictionary = {\n        regex: \"مدخل\",\n        email: \"بريد إلكتروني\",\n        url: \"رابط\",\n        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\",\n        date: \"تاريخ بمعيار ISO\",\n        time: \"وقت بمعيار ISO\",\n        duration: \"مدة بمعيار ISO\",\n        ipv4: \"عنوان IPv4\",\n        ipv6: \"عنوان IPv6\",\n        cidrv4: \"مدى عناوين بصيغة IPv4\",\n        cidrv6: \"مدى عناوين بصيغة IPv6\",\n        base64: \"نَص بترميز base64-encoded\",\n        base64url: \"نَص بترميز base64url-encoded\",\n        json_string: \"نَص على هيئة JSON\",\n        e164: \"رقم هاتف بمعيار E.164\",\n        jwt: \"JWT\",\n        template_literal: \"مدخل\",\n    };\n    const TypeDictionary = {\n        nan: \"NaN\",\n    };\n    return (issue) => {\n        switch (issue.code) {\n            case \"invalid_type\": {\n                const expected = TypeDictionary[issue.expected] ?? issue.expected;\n                const receivedType = util.parsedType(issue.input);\n                const received = TypeDictionary[receivedType] ?? receivedType;\n                if (/^[A-Z]/.test(issue.expected)) {\n                    return `مدخلات غير مقبولة: يفترض إدخال instanceof ${issue.expected}، ولكن تم إدخال ${received}`;\n                }\n                return `مدخلات غير مقبولة: يفترض إدخال ${expected}، ولكن تم إدخال ${received}`;\n            }\n            case \"invalid_value\":\n                if (issue.values.length === 1)\n                    return `مدخلات غير مقبولة: يفترض إدخال ${util.stringifyPrimitive(issue.values[0])}`;\n                return `اختيار غير مقبول: يتوقع انتقاء أحد هذه الخيارات: ${util.joinValues(issue.values, \"|\")}`;\n            case \"too_big\": {\n                const adj = issue.inclusive ? \"<=\" : \"<\";\n                const sizing = getSizing(issue.origin);\n                if (sizing)\n                    return ` أكبر من اللازم: يفترض أن تكون ${issue.origin ?? \"القيمة\"} ${adj} ${issue.maximum.toString()} ${sizing.unit ?? \"عنصر\"}`;\n                return `أكبر من اللازم: يفترض أن تكون ${issue.origin ?? \"القيمة\"} ${adj} ${issue.maximum.toString()}`;\n            }\n            case \"too_small\": {\n                const adj = issue.inclusive ? \">=\" : \">\";\n                const sizing = getSizing(issue.origin);\n                if (sizing) {\n                    return `أصغر من اللازم: يفترض لـ ${issue.origin} أن يكون ${adj} ${issue.minimum.toString()} ${sizing.unit}`;\n                }\n                return `أصغر من اللازم: يفترض لـ ${issue.origin} أن يكون ${adj} ${issue.minimum.toString()}`;\n            }\n            case \"invalid_format\": {\n                const _issue = issue;\n                if (_issue.format === \"starts_with\")\n                    return `نَص غير مقبول: يجب أن يبدأ بـ \"${issue.prefix}\"`;\n                if (_issue.format === \"ends_with\")\n                    return `نَص غير مقبول: يجب أن ينتهي بـ \"${_issue.suffix}\"`;\n                if (_issue.format === \"includes\")\n                    return `نَص غير مقبول: يجب أن يتضمَّن \"${_issue.includes}\"`;\n                if (_issue.format === \"regex\")\n                    return `نَص غير مقبول: يجب أن يطابق النمط ${_issue.pattern}`;\n                return `${FormatDictionary[_issue.format] ?? issue.format} غير مقبول`;\n            }\n            case \"not_multiple_of\":\n                return `رقم غير مقبول: يجب أن يكون من مضاعفات ${issue.divisor}`;\n            case \"unrecognized_keys\":\n                return `معرف${issue.keys.length > 1 ? \"ات\" : \"\"} غريب${issue.keys.length > 1 ? \"ة\" : \"\"}: ${util.joinValues(issue.keys, \"، \")}`;\n            case \"invalid_key\":\n                return `معرف غير مقبول في ${issue.origin}`;\n            case \"invalid_union\":\n                return \"مدخل غير مقبول\";\n            case \"invalid_element\":\n                return `مدخل غير مقبول في ${issue.origin}`;\n            default:\n                return \"مدخل غير مقبول\";\n        }\n    };\n};\nexport default function () {\n    return {\n        localeError: error(),\n    };\n}\n","import * as util from \"../core/util.js\";\nconst error = () => {\n    const Sizable = {\n        string: { unit: \"simvol\", verb: \"olmalıdır\" },\n        file: { unit: \"bayt\", verb: \"olmalıdır\" },\n        array: { unit: \"element\", verb: \"olmalıdır\" },\n        set: { unit: \"element\", verb: \"olmalıdır\" },\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        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        jwt: \"JWT\",\n        template_literal: \"input\",\n    };\n    const TypeDictionary = {\n        nan: \"NaN\",\n    };\n    return (issue) => {\n        switch (issue.code) {\n            case \"invalid_type\": {\n                const expected = TypeDictionary[issue.expected] ?? issue.expected;\n                const receivedType = util.parsedType(issue.input);\n                const received = TypeDictionary[receivedType] ?? receivedType;\n                if (/^[A-Z]/.test(issue.expected)) {\n                    return `Yanlış dəyər: gözlənilən instanceof ${issue.expected}, daxil olan ${received}`;\n                }\n                return `Yanlış dəyər: gözlənilən ${expected}, daxil olan ${received}`;\n            }\n            case \"invalid_value\":\n                if (issue.values.length === 1)\n                    return `Yanlış dəyər: gözlənilən ${util.stringifyPrimitive(issue.values[0])}`;\n                return `Yanlış seçim: aşağıdakılardan biri olmalıdır: ${util.joinValues(issue.values, \"|\")}`;\n            case \"too_big\": {\n                const adj = issue.inclusive ? \"<=\" : \"<\";\n                const sizing = getSizing(issue.origin);\n                if (sizing)\n                    return `Çox böyük: gözlənilən ${issue.origin ?? \"dəyər\"} ${adj}${issue.maximum.toString()} ${sizing.unit ?? \"element\"}`;\n                return `Çox böyük: gözlənilən ${issue.origin ?? \"dəyər\"} ${adj}${issue.maximum.toString()}`;\n            }\n            case \"too_small\": {\n                const adj = issue.inclusive ? \">=\" : \">\";\n                const sizing = getSizing(issue.origin);\n                if (sizing)\n                    return `Çox kiçik: gözlənilən ${issue.origin} ${adj}${issue.minimum.toString()} ${sizing.unit}`;\n                return `Çox kiçik: gözlənilən ${issue.origin} ${adj}${issue.minimum.toString()}`;\n            }\n            case \"invalid_format\": {\n                const _issue = issue;\n                if (_issue.format === \"starts_with\")\n                    return `Yanlış mətn: \"${_issue.prefix}\" ilə başlamalıdır`;\n                if (_issue.format === \"ends_with\")\n                    return `Yanlış mətn: \"${_issue.suffix}\" ilə bitməlidir`;\n                if (_issue.format === \"includes\")\n                    return `Yanlış mətn: \"${_issue.includes}\" daxil olmalıdır`;\n                if (_issue.format === \"regex\")\n                    return `Yanlış mətn: ${_issue.pattern} şablonuna uyğun olmalıdır`;\n                return `Yanlış ${FormatDictionary[_issue.format] ?? issue.format}`;\n            }\n            case \"not_multiple_of\":\n                return `Yanlış ədəd: ${issue.divisor} ilə bölünə bilən olmalıdır`;\n            case \"unrecognized_keys\":\n                return `Tanınmayan açar${issue.keys.length > 1 ? \"lar\" : \"\"}: ${util.joinValues(issue.keys, \", \")}`;\n            case \"invalid_key\":\n                return `${issue.origin} daxilində yanlış açar`;\n            case \"invalid_union\":\n                return \"Yanlış dəyər\";\n            case \"invalid_element\":\n                return `${issue.origin} daxilində yanlış dəyər`;\n            default:\n                return `Yanlış dəyər`;\n        }\n    };\n};\nexport default function () {\n    return {\n        localeError: error(),\n    };\n}\n","import * as util from \"../core/util.js\";\nfunction getBelarusianPlural(count, one, few, many) {\n    const absCount = Math.abs(count);\n    const lastDigit = absCount % 10;\n    const lastTwoDigits = absCount % 100;\n    if (lastTwoDigits >= 11 && lastTwoDigits <= 19) {\n        return many;\n    }\n    if (lastDigit === 1) {\n        return one;\n    }\n    if (lastDigit >= 2 && lastDigit <= 4) {\n        return few;\n    }\n    return many;\n}\nconst error = () => {\n    const Sizable = {\n        string: {\n            unit: {\n                one: \"сімвал\",\n                few: \"сімвалы\",\n                many: \"сімвалаў\",\n            },\n            verb: \"мець\",\n        },\n        array: {\n            unit: {\n                one: \"элемент\",\n                few: \"элементы\",\n                many: \"элементаў\",\n            },\n            verb: \"мець\",\n        },\n        set: {\n            unit: {\n                one: \"элемент\",\n                few: \"элементы\",\n                many: \"элементаў\",\n            },\n            verb: \"мець\",\n        },\n        file: {\n            unit: {\n                one: \"байт\",\n                few: \"байты\",\n                many: \"байтаў\",\n            },\n            verb: \"мець\",\n        },\n    };\n    function getSizing(origin) {\n        return Sizable[origin] ?? null;\n    }\n    const FormatDictionary = {\n        regex: \"увод\",\n        email: \"email адрас\",\n        url: \"URL\",\n        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 дата і час\",\n        date: \"ISO дата\",\n        time: \"ISO час\",\n        duration: \"ISO працягласць\",\n        ipv4: \"IPv4 адрас\",\n        ipv6: \"IPv6 адрас\",\n        cidrv4: \"IPv4 дыяпазон\",\n        cidrv6: \"IPv6 дыяпазон\",\n        base64: \"радок у фармаце base64\",\n        base64url: \"радок у фармаце base64url\",\n        json_string: \"JSON радок\",\n        e164: \"нумар E.164\",\n        jwt: \"JWT\",\n        template_literal: \"увод\",\n    };\n    const TypeDictionary = {\n        nan: \"NaN\",\n        number: \"лік\",\n        array: \"масіў\",\n    };\n    return (issue) => {\n        switch (issue.code) {\n            case \"invalid_type\": {\n                const expected = TypeDictionary[issue.expected] ?? issue.expected;\n                const receivedType = util.parsedType(issue.input);\n                const received = TypeDictionary[receivedType] ?? receivedType;\n                if (/^[A-Z]/.test(issue.expected)) {\n                    return `Няправільны ўвод: чакаўся instanceof ${issue.expected}, атрымана ${received}`;\n                }\n                return `Няправільны ўвод: чакаўся ${expected}, атрымана ${received}`;\n            }\n            case \"invalid_value\":\n                if (issue.values.length === 1)\n                    return `Няправільны ўвод: чакалася ${util.stringifyPrimitive(issue.values[0])}`;\n                return `Няправільны варыянт: чакаўся адзін з ${util.joinValues(issue.values, \"|\")}`;\n            case \"too_big\": {\n                const adj = issue.inclusive ? \"<=\" : \"<\";\n                const sizing = getSizing(issue.origin);\n                if (sizing) {\n                    const maxValue = Number(issue.maximum);\n                    const unit = getBelarusianPlural(maxValue, sizing.unit.one, sizing.unit.few, sizing.unit.many);\n                    return `Занадта вялікі: чакалася, што ${issue.origin ?? \"значэнне\"} павінна ${sizing.verb} ${adj}${issue.maximum.toString()} ${unit}`;\n                }\n                return `Занадта вялікі: чакалася, што ${issue.origin ?? \"значэнне\"} павінна быць ${adj}${issue.maximum.toString()}`;\n            }\n            case \"too_small\": {\n                const adj = issue.inclusive ? \">=\" : \">\";\n                const sizing = getSizing(issue.origin);\n                if (sizing) {\n                    const minValue = Number(issue.minimum);\n                    const unit = getBelarusianPlural(minValue, sizing.unit.one, sizing.unit.few, sizing.unit.many);\n                    return `Занадта малы: чакалася, што ${issue.origin} павінна ${sizing.verb} ${adj}${issue.minimum.toString()} ${unit}`;\n                }\n                return `Занадта малы: чакалася, што ${issue.origin} павінна быць ${adj}${issue.minimum.toString()}`;\n            }\n            case \"invalid_format\": {\n                const _issue = issue;\n                if (_issue.format === \"starts_with\")\n                    return `Няправільны радок: павінен пачынацца з \"${_issue.prefix}\"`;\n                if (_issue.format === \"ends_with\")\n                    return `Няправільны радок: павінен заканчвацца на \"${_issue.suffix}\"`;\n                if (_issue.format === \"includes\")\n                    return `Няправільны радок: павінен змяшчаць \"${_issue.includes}\"`;\n                if (_issue.format === \"regex\")\n                    return `Няправільны радок: павінен адпавядаць шаблону ${_issue.pattern}`;\n                return `Няправільны ${FormatDictionary[_issue.format] ?? issue.format}`;\n            }\n            case \"not_multiple_of\":\n                return `Няправільны лік: павінен быць кратным ${issue.divisor}`;\n            case \"unrecognized_keys\":\n                return `Нераспазнаны ${issue.keys.length > 1 ? \"ключы\" : \"ключ\"}: ${util.joinValues(issue.keys, \", \")}`;\n            case \"invalid_key\":\n                return `Няправільны ключ у ${issue.origin}`;\n            case \"invalid_union\":\n                return \"Няправільны ўвод\";\n            case \"invalid_element\":\n                return `Няправільнае значэнне ў ${issue.origin}`;\n            default:\n                return `Няправільны ўвод`;\n        }\n    };\n};\nexport default function () {\n    return {\n        localeError: error(),\n    };\n}\n","import * as util from \"../core/util.js\";\nconst error = () => {\n    const Sizable = {\n        string: { unit: \"символа\", verb: \"да съдържа\" },\n        file: { unit: \"байта\", verb: \"да съдържа\" },\n        array: { unit: \"елемента\", verb: \"да съдържа\" },\n        set: { unit: \"елемента\", verb: \"да съдържа\" },\n    };\n    function getSizing(origin) {\n        return Sizable[origin] ?? null;\n    }\n    const FormatDictionary = {\n        regex: \"вход\",\n        email: \"имейл адрес\",\n        url: \"URL\",\n        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 време\",\n        date: \"ISO дата\",\n        time: \"ISO време\",\n        duration: \"ISO продължителност\",\n        ipv4: \"IPv4 адрес\",\n        ipv6: \"IPv6 адрес\",\n        cidrv4: \"IPv4 диапазон\",\n        cidrv6: \"IPv6 диапазон\",\n        base64: \"base64-кодиран низ\",\n        base64url: \"base64url-кодиран низ\",\n        json_string: \"JSON низ\",\n        e164: \"E.164 номер\",\n        jwt: \"JWT\",\n        template_literal: \"вход\",\n    };\n    const TypeDictionary = {\n        nan: \"NaN\",\n        number: \"число\",\n        array: \"масив\",\n    };\n    return (issue) => {\n        switch (issue.code) {\n            case \"invalid_type\": {\n                const expected = TypeDictionary[issue.expected] ?? issue.expected;\n                const receivedType = util.parsedType(issue.input);\n                const received = TypeDictionary[receivedType] ?? receivedType;\n                if (/^[A-Z]/.test(issue.expected)) {\n                    return `Невалиден вход: очакван instanceof ${issue.expected}, получен ${received}`;\n                }\n                return `Невалиден вход: очакван ${expected}, получен ${received}`;\n            }\n            case \"invalid_value\":\n                if (issue.values.length === 1)\n                    return `Невалиден вход: очакван ${util.stringifyPrimitive(issue.values[0])}`;\n                return `Невалидна опция: очаквано едно от ${util.joinValues(issue.values, \"|\")}`;\n            case \"too_big\": {\n                const adj = issue.inclusive ? \"<=\" : \"<\";\n                const sizing = getSizing(issue.origin);\n                if (sizing)\n                    return `Твърде голямо: очаква се ${issue.origin ?? \"стойност\"} да съдържа ${adj}${issue.maximum.toString()} ${sizing.unit ?? \"елемента\"}`;\n                return `Твърде голямо: очаква се ${issue.origin ?? \"стойност\"} да бъде ${adj}${issue.maximum.toString()}`;\n            }\n            case \"too_small\": {\n                const adj = issue.inclusive ? \">=\" : \">\";\n                const sizing = getSizing(issue.origin);\n                if (sizing) {\n                    return `Твърде малко: очаква се ${issue.origin} да съдържа ${adj}${issue.minimum.toString()} ${sizing.unit}`;\n                }\n                return `Твърде малко: очаква се ${issue.origin} да бъде ${adj}${issue.minimum.toString()}`;\n            }\n            case \"invalid_format\": {\n                const _issue = issue;\n                if (_issue.format === \"starts_with\") {\n                    return `Невалиден низ: трябва да започва с \"${_issue.prefix}\"`;\n                }\n                if (_issue.format === \"ends_with\")\n                    return `Невалиден низ: трябва да завършва с \"${_issue.suffix}\"`;\n                if (_issue.format === \"includes\")\n                    return `Невалиден низ: трябва да включва \"${_issue.includes}\"`;\n                if (_issue.format === \"regex\")\n                    return `Невалиден низ: трябва да съвпада с ${_issue.pattern}`;\n                let invalid_adj = \"Невалиден\";\n                if (_issue.format === \"emoji\")\n                    invalid_adj = \"Невалидно\";\n                if (_issue.format === \"datetime\")\n                    invalid_adj = \"Невалидно\";\n                if (_issue.format === \"date\")\n                    invalid_adj = \"Невалидна\";\n                if (_issue.format === \"time\")\n                    invalid_adj = \"Невалидно\";\n                if (_issue.format === \"duration\")\n                    invalid_adj = \"Невалидна\";\n                return `${invalid_adj} ${FormatDictionary[_issue.format] ?? issue.format}`;\n            }\n            case \"not_multiple_of\":\n                return `Невалидно число: трябва да бъде кратно на ${issue.divisor}`;\n            case \"unrecognized_keys\":\n                return `Неразпознат${issue.keys.length > 1 ? \"и\" : \"\"} ключ${issue.keys.length > 1 ? \"ове\" : \"\"}: ${util.joinValues(issue.keys, \", \")}`;\n            case \"invalid_key\":\n                return `Невалиден ключ в ${issue.origin}`;\n            case \"invalid_union\":\n                return \"Невалиден вход\";\n            case \"invalid_element\":\n                return `Невалидна стойност в ${issue.origin}`;\n            default:\n                return `Невалиден вход`;\n        }\n    };\n};\nexport default function () {\n    return {\n        localeError: error(),\n    };\n}\n","import * as util from \"../core/util.js\";\nconst error = () => {\n    const Sizable = {\n        string: { unit: \"caràcters\", verb: \"contenir\" },\n        file: { unit: \"bytes\", verb: \"contenir\" },\n        array: { unit: \"elements\", verb: \"contenir\" },\n        set: { unit: \"elements\", verb: \"contenir\" },\n    };\n    function getSizing(origin) {\n        return Sizable[origin] ?? null;\n    }\n    const FormatDictionary = {\n        regex: \"entrada\",\n        email: \"adreça electrònica\",\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: \"data i hora ISO\",\n        date: \"data ISO\",\n        time: \"hora ISO\",\n        duration: \"durada ISO\",\n        ipv4: \"adreça IPv4\",\n        ipv6: \"adreça IPv6\",\n        cidrv4: \"rang IPv4\",\n        cidrv6: \"rang IPv6\",\n        base64: \"cadena codificada en base64\",\n        base64url: \"cadena codificada en base64url\",\n        json_string: \"cadena JSON\",\n        e164: \"número E.164\",\n        jwt: \"JWT\",\n        template_literal: \"entrada\",\n    };\n    const TypeDictionary = {\n        nan: \"NaN\",\n    };\n    return (issue) => {\n        switch (issue.code) {\n            case \"invalid_type\": {\n                const expected = TypeDictionary[issue.expected] ?? issue.expected;\n                const receivedType = util.parsedType(issue.input);\n                const received = TypeDictionary[receivedType] ?? receivedType;\n                if (/^[A-Z]/.test(issue.expected)) {\n                    return `Tipus invàlid: s'esperava instanceof ${issue.expected}, s'ha rebut ${received}`;\n                }\n                return `Tipus invàlid: s'esperava ${expected}, s'ha rebut ${received}`;\n            }\n            case \"invalid_value\":\n                if (issue.values.length === 1)\n                    return `Valor invàlid: s'esperava ${util.stringifyPrimitive(issue.values[0])}`;\n                return `Opció invàlida: s'esperava una de ${util.joinValues(issue.values, \" o \")}`;\n            case \"too_big\": {\n                const adj = issue.inclusive ? \"com a màxim\" : \"menys de\";\n                const sizing = getSizing(issue.origin);\n                if (sizing)\n                    return `Massa gran: s'esperava que ${issue.origin ?? \"el valor\"} contingués ${adj} ${issue.maximum.toString()} ${sizing.unit ?? \"elements\"}`;\n                return `Massa gran: s'esperava que ${issue.origin ?? \"el valor\"} fos ${adj} ${issue.maximum.toString()}`;\n            }\n            case \"too_small\": {\n                const adj = issue.inclusive ? \"com a mínim\" : \"més de\";\n                const sizing = getSizing(issue.origin);\n                if (sizing) {\n                    return `Massa petit: s'esperava que ${issue.origin} contingués ${adj} ${issue.minimum.toString()} ${sizing.unit}`;\n                }\n                return `Massa petit: s'esperava que ${issue.origin} fos ${adj} ${issue.minimum.toString()}`;\n            }\n            case \"invalid_format\": {\n                const _issue = issue;\n                if (_issue.format === \"starts_with\") {\n                    return `Format invàlid: ha de començar amb \"${_issue.prefix}\"`;\n                }\n                if (_issue.format === \"ends_with\")\n                    return `Format invàlid: ha d'acabar amb \"${_issue.suffix}\"`;\n                if (_issue.format === \"includes\")\n                    return `Format invàlid: ha d'incloure \"${_issue.includes}\"`;\n                if (_issue.format === \"regex\")\n                    return `Format invàlid: ha de coincidir amb el patró ${_issue.pattern}`;\n                return `Format invàlid per a ${FormatDictionary[_issue.format] ?? issue.format}`;\n            }\n            case \"not_multiple_of\":\n                return `Número invàlid: ha de ser múltiple de ${issue.divisor}`;\n            case \"unrecognized_keys\":\n                return `Clau${issue.keys.length > 1 ? \"s\" : \"\"} no reconeguda${issue.keys.length > 1 ? \"s\" : \"\"}: ${util.joinValues(issue.keys, \", \")}`;\n            case \"invalid_key\":\n                return `Clau invàlida a ${issue.origin}`;\n            case \"invalid_union\":\n                return \"Entrada invàlida\"; // Could also be \"Tipus d'unió invàlid\" but \"Entrada invàlida\" is more general\n            case \"invalid_element\":\n                return `Element invàlid a ${issue.origin}`;\n            default:\n                return `Entrada invàlida`;\n        }\n    };\n};\nexport default function () {\n    return {\n        localeError: error(),\n    };\n}\n","import * as util from \"../core/util.js\";\nconst error = () => {\n    const Sizable = {\n        string: { unit: \"znaků\", verb: \"mít\" },\n        file: { unit: \"bajtů\", verb: \"mít\" },\n        array: { unit: \"prvků\", verb: \"mít\" },\n        set: { unit: \"prvků\", verb: \"mít\" },\n    };\n    function getSizing(origin) {\n        return Sizable[origin] ?? null;\n    }\n    const FormatDictionary = {\n        regex: \"regulární výraz\",\n        email: \"e-mailová adresa\",\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: \"datum a čas ve formátu ISO\",\n        date: \"datum ve formátu ISO\",\n        time: \"čas ve formátu ISO\",\n        duration: \"doba trvání ISO\",\n        ipv4: \"IPv4 adresa\",\n        ipv6: \"IPv6 adresa\",\n        cidrv4: \"rozsah IPv4\",\n        cidrv6: \"rozsah IPv6\",\n        base64: \"řetězec zakódovaný ve formátu base64\",\n        base64url: \"řetězec zakódovaný ve formátu base64url\",\n        json_string: \"řetězec ve formátu JSON\",\n        e164: \"číslo E.164\",\n        jwt: \"JWT\",\n        template_literal: \"vstup\",\n    };\n    const TypeDictionary = {\n        nan: \"NaN\",\n        number: \"číslo\",\n        string: \"řetězec\",\n        function: \"funkce\",\n        array: \"pole\",\n    };\n    return (issue) => {\n        switch (issue.code) {\n            case \"invalid_type\": {\n                const expected = TypeDictionary[issue.expected] ?? issue.expected;\n                const receivedType = util.parsedType(issue.input);\n                const received = TypeDictionary[receivedType] ?? receivedType;\n                if (/^[A-Z]/.test(issue.expected)) {\n                    return `Neplatný vstup: očekáváno instanceof ${issue.expected}, obdrženo ${received}`;\n                }\n                return `Neplatný vstup: očekáváno ${expected}, obdrženo ${received}`;\n            }\n            case \"invalid_value\":\n                if (issue.values.length === 1)\n                    return `Neplatný vstup: očekáváno ${util.stringifyPrimitive(issue.values[0])}`;\n                return `Neplatná možnost: očekávána jedna z hodnot ${util.joinValues(issue.values, \"|\")}`;\n            case \"too_big\": {\n                const adj = issue.inclusive ? \"<=\" : \"<\";\n                const sizing = getSizing(issue.origin);\n                if (sizing) {\n                    return `Hodnota je příliš velká: ${issue.origin ?? \"hodnota\"} musí mít ${adj}${issue.maximum.toString()} ${sizing.unit ?? \"prvků\"}`;\n                }\n                return `Hodnota je příliš velká: ${issue.origin ?? \"hodnota\"} musí být ${adj}${issue.maximum.toString()}`;\n            }\n            case \"too_small\": {\n                const adj = issue.inclusive ? \">=\" : \">\";\n                const sizing = getSizing(issue.origin);\n                if (sizing) {\n                    return `Hodnota je příliš malá: ${issue.origin ?? \"hodnota\"} musí mít ${adj}${issue.minimum.toString()} ${sizing.unit ?? \"prvků\"}`;\n                }\n                return `Hodnota je příliš malá: ${issue.origin ?? \"hodnota\"} musí být ${adj}${issue.minimum.toString()}`;\n            }\n            case \"invalid_format\": {\n                const _issue = issue;\n                if (_issue.format === \"starts_with\")\n                    return `Neplatný řetězec: musí začínat na \"${_issue.prefix}\"`;\n                if (_issue.format === \"ends_with\")\n                    return `Neplatný řetězec: musí končit na \"${_issue.suffix}\"`;\n                if (_issue.format === \"includes\")\n                    return `Neplatný řetězec: musí obsahovat \"${_issue.includes}\"`;\n                if (_issue.format === \"regex\")\n                    return `Neplatný řetězec: musí odpovídat vzoru ${_issue.pattern}`;\n                return `Neplatný formát ${FormatDictionary[_issue.format] ?? issue.format}`;\n            }\n            case \"not_multiple_of\":\n                return `Neplatné číslo: musí být násobkem ${issue.divisor}`;\n            case \"unrecognized_keys\":\n                return `Neznámé klíče: ${util.joinValues(issue.keys, \", \")}`;\n            case \"invalid_key\":\n                return `Neplatný klíč v ${issue.origin}`;\n            case \"invalid_union\":\n                return \"Neplatný vstup\";\n            case \"invalid_element\":\n                return `Neplatná hodnota v ${issue.origin}`;\n            default:\n                return `Neplatný vstup`;\n        }\n    };\n};\nexport default function () {\n    return {\n        localeError: error(),\n    };\n}\n","import * as util from \"../core/util.js\";\nconst error = () => {\n    const Sizable = {\n        string: { unit: \"tegn\", verb: \"havde\" },\n        file: { unit: \"bytes\", verb: \"havde\" },\n        array: { unit: \"elementer\", verb: \"indeholdt\" },\n        set: { unit: \"elementer\", verb: \"indeholdt\" },\n    };\n    function getSizing(origin) {\n        return Sizable[origin] ?? null;\n    }\n    const FormatDictionary = {\n        regex: \"input\",\n        email: \"e-mailadresse\",\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 dato- og klokkeslæt\",\n        date: \"ISO-dato\",\n        time: \"ISO-klokkeslæt\",\n        duration: \"ISO-varighed\",\n        ipv4: \"IPv4-område\",\n        ipv6: \"IPv6-område\",\n        cidrv4: \"IPv4-spektrum\",\n        cidrv6: \"IPv6-spektrum\",\n        base64: \"base64-kodet streng\",\n        base64url: \"base64url-kodet streng\",\n        json_string: \"JSON-streng\",\n        e164: \"E.164-nummer\",\n        jwt: \"JWT\",\n        template_literal: \"input\",\n    };\n    const TypeDictionary = {\n        nan: \"NaN\",\n        string: \"streng\",\n        number: \"tal\",\n        boolean: \"boolean\",\n        array: \"liste\",\n        object: \"objekt\",\n        set: \"sæt\",\n        file: \"fil\",\n    };\n    return (issue) => {\n        switch (issue.code) {\n            case \"invalid_type\": {\n                const expected = TypeDictionary[issue.expected] ?? issue.expected;\n                const receivedType = util.parsedType(issue.input);\n                const received = TypeDictionary[receivedType] ?? receivedType;\n                if (/^[A-Z]/.test(issue.expected)) {\n                    return `Ugyldigt input: forventede instanceof ${issue.expected}, fik ${received}`;\n                }\n                return `Ugyldigt input: forventede ${expected}, fik ${received}`;\n            }\n            case \"invalid_value\":\n                if (issue.values.length === 1)\n                    return `Ugyldig værdi: forventede ${util.stringifyPrimitive(issue.values[0])}`;\n                return `Ugyldigt valg: forventede en af følgende ${util.joinValues(issue.values, \"|\")}`;\n            case \"too_big\": {\n                const adj = issue.inclusive ? \"<=\" : \"<\";\n                const sizing = getSizing(issue.origin);\n                const origin = TypeDictionary[issue.origin] ?? issue.origin;\n                if (sizing)\n                    return `For stor: forventede ${origin ?? \"value\"} ${sizing.verb} ${adj} ${issue.maximum.toString()} ${sizing.unit ?? \"elementer\"}`;\n                return `For stor: forventede ${origin ?? \"value\"} havde ${adj} ${issue.maximum.toString()}`;\n            }\n            case \"too_small\": {\n                const adj = issue.inclusive ? \">=\" : \">\";\n                const sizing = getSizing(issue.origin);\n                const origin = TypeDictionary[issue.origin] ?? issue.origin;\n                if (sizing) {\n                    return `For lille: forventede ${origin} ${sizing.verb} ${adj} ${issue.minimum.toString()} ${sizing.unit}`;\n                }\n                return `For lille: forventede ${origin} havde ${adj} ${issue.minimum.toString()}`;\n            }\n            case \"invalid_format\": {\n                const _issue = issue;\n                if (_issue.format === \"starts_with\")\n                    return `Ugyldig streng: skal starte med \"${_issue.prefix}\"`;\n                if (_issue.format === \"ends_with\")\n                    return `Ugyldig streng: skal ende med \"${_issue.suffix}\"`;\n                if (_issue.format === \"includes\")\n                    return `Ugyldig streng: skal indeholde \"${_issue.includes}\"`;\n                if (_issue.format === \"regex\")\n                    return `Ugyldig streng: skal matche mønsteret ${_issue.pattern}`;\n                return `Ugyldig ${FormatDictionary[_issue.format] ?? issue.format}`;\n            }\n            case \"not_multiple_of\":\n                return `Ugyldigt tal: skal være deleligt med ${issue.divisor}`;\n            case \"unrecognized_keys\":\n                return `${issue.keys.length > 1 ? \"Ukendte nøgler\" : \"Ukendt nøgle\"}: ${util.joinValues(issue.keys, \", \")}`;\n            case \"invalid_key\":\n                return `Ugyldig nøgle i ${issue.origin}`;\n            case \"invalid_union\":\n                return \"Ugyldigt input: matcher ingen af de tilladte typer\";\n            case \"invalid_element\":\n                return `Ugyldig værdi i ${issue.origin}`;\n            default:\n                return `Ugyldigt input`;\n        }\n    };\n};\nexport default function () {\n    return {\n        localeError: error(),\n    };\n}\n","import * as util from \"../core/util.js\";\nconst error = () => {\n    const Sizable = {\n        string: { unit: \"Zeichen\", verb: \"zu haben\" },\n        file: { unit: \"Bytes\", verb: \"zu haben\" },\n        array: { unit: \"Elemente\", verb: \"zu haben\" },\n        set: { unit: \"Elemente\", verb: \"zu haben\" },\n    };\n    function getSizing(origin) {\n        return Sizable[origin] ?? null;\n    }\n    const FormatDictionary = {\n        regex: \"Eingabe\",\n        email: \"E-Mail-Adresse\",\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-Datum und -Uhrzeit\",\n        date: \"ISO-Datum\",\n        time: \"ISO-Uhrzeit\",\n        duration: \"ISO-Dauer\",\n        ipv4: \"IPv4-Adresse\",\n        ipv6: \"IPv6-Adresse\",\n        cidrv4: \"IPv4-Bereich\",\n        cidrv6: \"IPv6-Bereich\",\n        base64: \"Base64-codierter String\",\n        base64url: \"Base64-URL-codierter String\",\n        json_string: \"JSON-String\",\n        e164: \"E.164-Nummer\",\n        jwt: \"JWT\",\n        template_literal: \"Eingabe\",\n    };\n    const TypeDictionary = {\n        nan: \"NaN\",\n        number: \"Zahl\",\n        array: \"Array\",\n    };\n    return (issue) => {\n        switch (issue.code) {\n            case \"invalid_type\": {\n                const expected = TypeDictionary[issue.expected] ?? issue.expected;\n                const receivedType = util.parsedType(issue.input);\n                const received = TypeDictionary[receivedType] ?? receivedType;\n                if (/^[A-Z]/.test(issue.expected)) {\n                    return `Ungültige Eingabe: erwartet instanceof ${issue.expected}, erhalten ${received}`;\n                }\n                return `Ungültige Eingabe: erwartet ${expected}, erhalten ${received}`;\n            }\n            case \"invalid_value\":\n                if (issue.values.length === 1)\n                    return `Ungültige Eingabe: erwartet ${util.stringifyPrimitive(issue.values[0])}`;\n                return `Ungültige Option: erwartet eine von ${util.joinValues(issue.values, \"|\")}`;\n            case \"too_big\": {\n                const adj = issue.inclusive ? \"<=\" : \"<\";\n                const sizing = getSizing(issue.origin);\n                if (sizing)\n                    return `Zu groß: erwartet, dass ${issue.origin ?? \"Wert\"} ${adj}${issue.maximum.toString()} ${sizing.unit ?? \"Elemente\"} hat`;\n                return `Zu groß: erwartet, dass ${issue.origin ?? \"Wert\"} ${adj}${issue.maximum.toString()} ist`;\n            }\n            case \"too_small\": {\n                const adj = issue.inclusive ? \">=\" : \">\";\n                const sizing = getSizing(issue.origin);\n                if (sizing) {\n                    return `Zu klein: erwartet, dass ${issue.origin} ${adj}${issue.minimum.toString()} ${sizing.unit} hat`;\n                }\n                return `Zu klein: erwartet, dass ${issue.origin} ${adj}${issue.minimum.toString()} ist`;\n            }\n            case \"invalid_format\": {\n                const _issue = issue;\n                if (_issue.format === \"starts_with\")\n                    return `Ungültiger String: muss mit \"${_issue.prefix}\" beginnen`;\n                if (_issue.format === \"ends_with\")\n                    return `Ungültiger String: muss mit \"${_issue.suffix}\" enden`;\n                if (_issue.format === \"includes\")\n                    return `Ungültiger String: muss \"${_issue.includes}\" enthalten`;\n                if (_issue.format === \"regex\")\n                    return `Ungültiger String: muss dem Muster ${_issue.pattern} entsprechen`;\n                return `Ungültig: ${FormatDictionary[_issue.format] ?? issue.format}`;\n            }\n            case \"not_multiple_of\":\n                return `Ungültige Zahl: muss ein Vielfaches von ${issue.divisor} sein`;\n            case \"unrecognized_keys\":\n                return `${issue.keys.length > 1 ? \"Unbekannte Schlüssel\" : \"Unbekannter Schlüssel\"}: ${util.joinValues(issue.keys, \", \")}`;\n            case \"invalid_key\":\n                return `Ungültiger Schlüssel in ${issue.origin}`;\n            case \"invalid_union\":\n                return \"Ungültige Eingabe\";\n            case \"invalid_element\":\n                return `Ungültiger Wert in ${issue.origin}`;\n            default:\n                return `Ungültige Eingabe`;\n        }\n    };\n};\nexport default function () {\n    return {\n        localeError: error(),\n    };\n}\n","import * as util from \"../core/util.js\";\nconst error = () => {\n    const Sizable = {\n        string: { unit: \"χαρακτήρες\", verb: \"να έχει\" },\n        file: { unit: \"bytes\", verb: \"να έχει\" },\n        array: { unit: \"στοιχεία\", verb: \"να έχει\" },\n        set: { unit: \"στοιχεία\", verb: \"να έχει\" },\n        map: { unit: \"καταχωρήσεις\", verb: \"να έχει\" },\n    };\n    function getSizing(origin) {\n        return Sizable[origin] ?? null;\n    }\n    const FormatDictionary = {\n        regex: \"είσοδος\",\n        email: \"διεύθυνση email\",\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 ημερομηνία και ώρα\",\n        date: \"ISO ημερομηνία\",\n        time: \"ISO ώρα\",\n        duration: \"ISO διάρκεια\",\n        ipv4: \"διεύθυνση IPv4\",\n        ipv6: \"διεύθυνση IPv6\",\n        mac: \"διεύθυνση MAC\",\n        cidrv4: \"εύρος IPv4\",\n        cidrv6: \"εύρος IPv6\",\n        base64: \"συμβολοσειρά κωδικοποιημένη σε base64\",\n        base64url: \"συμβολοσειρά κωδικοποιημένη σε base64url\",\n        json_string: \"συμβολοσειρά JSON\",\n        e164: \"αριθμός E.164\",\n        jwt: \"JWT\",\n        template_literal: \"είσοδος\",\n    };\n    const TypeDictionary = {\n        nan: \"NaN\",\n    };\n    return (issue) => {\n        switch (issue.code) {\n            case \"invalid_type\": {\n                const expected = TypeDictionary[issue.expected] ?? issue.expected;\n                const receivedType = util.parsedType(issue.input);\n                const received = TypeDictionary[receivedType] ?? receivedType;\n                if (typeof issue.expected === \"string\" && /^[A-Z]/.test(issue.expected)) {\n                    return `Μη έγκυρη είσοδος: αναμενόταν instanceof ${issue.expected}, λήφθηκε ${received}`;\n                }\n                return `Μη έγκυρη είσοδος: αναμενόταν ${expected}, λήφθηκε ${received}`;\n            }\n            case \"invalid_value\":\n                if (issue.values.length === 1)\n                    return `Μη έγκυρη είσοδος: αναμενόταν ${util.stringifyPrimitive(issue.values[0])}`;\n                return `Μη έγκυρη επιλογή: αναμενόταν ένα από ${util.joinValues(issue.values, \"|\")}`;\n            case \"too_big\": {\n                const adj = issue.inclusive ? \"<=\" : \"<\";\n                const sizing = getSizing(issue.origin);\n                if (sizing)\n                    return `Πολύ μεγάλο: αναμενόταν ${issue.origin ?? \"τιμή\"} να έχει ${adj}${issue.maximum.toString()} ${sizing.unit ?? \"στοιχεία\"}`;\n                return `Πολύ μεγάλο: αναμενόταν ${issue.origin ?? \"τιμή\"} να είναι ${adj}${issue.maximum.toString()}`;\n            }\n            case \"too_small\": {\n                const adj = issue.inclusive ? \">=\" : \">\";\n                const sizing = getSizing(issue.origin);\n                if (sizing) {\n                    return `Πολύ μικρό: αναμενόταν ${issue.origin} να έχει ${adj}${issue.minimum.toString()} ${sizing.unit}`;\n                }\n                return `Πολύ μικρό: αναμενόταν ${issue.origin} να είναι ${adj}${issue.minimum.toString()}`;\n            }\n            case \"invalid_format\": {\n                const _issue = issue;\n                if (_issue.format === \"starts_with\") {\n                    return `Μη έγκυρη συμβολοσειρά: πρέπει να ξεκινά με \"${_issue.prefix}\"`;\n                }\n                if (_issue.format === \"ends_with\")\n                    return `Μη έγκυρη συμβολοσειρά: πρέπει να τελειώνει με \"${_issue.suffix}\"`;\n                if (_issue.format === \"includes\")\n                    return `Μη έγκυρη συμβολοσειρά: πρέπει να περιέχει \"${_issue.includes}\"`;\n                if (_issue.format === \"regex\")\n                    return `Μη έγκυρη συμβολοσειρά: πρέπει να ταιριάζει με το μοτίβο ${_issue.pattern}`;\n                return `Μη έγκυρο: ${FormatDictionary[_issue.format] ?? issue.format}`;\n            }\n            case \"not_multiple_of\":\n                return `Μη έγκυρος αριθμός: πρέπει να είναι πολλαπλάσιο του ${issue.divisor}`;\n            case \"unrecognized_keys\":\n                return `Άγνωστ${issue.keys.length > 1 ? \"α\" : \"ο\"} κλειδ${issue.keys.length > 1 ? \"ιά\" : \"ί\"}: ${util.joinValues(issue.keys, \", \")}`;\n            case \"invalid_key\":\n                return `Μη έγκυρο κλειδί στο ${issue.origin}`;\n            case \"invalid_union\":\n                return \"Μη έγκυρη είσοδος\";\n            case \"invalid_element\":\n                return `Μη έγκυρη τιμή στο ${issue.origin}`;\n            default:\n                return `Μη έγκυρη είσοδος`;\n        }\n    };\n};\nexport default function () {\n    return {\n        localeError: error(),\n    };\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        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    return (issue) => {\n        switch (issue.code) {\n            case \"invalid_type\": {\n                const expected = TypeDictionary[issue.expected] ?? issue.expected;\n                const receivedType = util.parsedType(issue.input);\n                const received = TypeDictionary[receivedType] ?? receivedType;\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.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.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                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","import * as util from \"../core/util.js\";\nconst error = () => {\n    const Sizable = {\n        string: { unit: \"karaktrojn\", verb: \"havi\" },\n        file: { unit: \"bajtojn\", verb: \"havi\" },\n        array: { unit: \"elementojn\", verb: \"havi\" },\n        set: { unit: \"elementojn\", verb: \"havi\" },\n    };\n    function getSizing(origin) {\n        return Sizable[origin] ?? null;\n    }\n    const FormatDictionary = {\n        regex: \"enigo\",\n        email: \"retadreso\",\n        url: \"URL\",\n        emoji: \"emoĝio\",\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-datotempo\",\n        date: \"ISO-dato\",\n        time: \"ISO-tempo\",\n        duration: \"ISO-daŭro\",\n        ipv4: \"IPv4-adreso\",\n        ipv6: \"IPv6-adreso\",\n        cidrv4: \"IPv4-rango\",\n        cidrv6: \"IPv6-rango\",\n        base64: \"64-ume kodita karaktraro\",\n        base64url: \"URL-64-ume kodita karaktraro\",\n        json_string: \"JSON-karaktraro\",\n        e164: \"E.164-nombro\",\n        jwt: \"JWT\",\n        template_literal: \"enigo\",\n    };\n    const TypeDictionary = {\n        nan: \"NaN\",\n        number: \"nombro\",\n        array: \"tabelo\",\n        null: \"senvalora\",\n    };\n    return (issue) => {\n        switch (issue.code) {\n            case \"invalid_type\": {\n                const expected = TypeDictionary[issue.expected] ?? issue.expected;\n                const receivedType = util.parsedType(issue.input);\n                const received = TypeDictionary[receivedType] ?? receivedType;\n                if (/^[A-Z]/.test(issue.expected)) {\n                    return `Nevalida enigo: atendiĝis instanceof ${issue.expected}, riceviĝis ${received}`;\n                }\n                return `Nevalida enigo: atendiĝis ${expected}, riceviĝis ${received}`;\n            }\n            case \"invalid_value\":\n                if (issue.values.length === 1)\n                    return `Nevalida enigo: atendiĝis ${util.stringifyPrimitive(issue.values[0])}`;\n                return `Nevalida opcio: atendiĝis unu el ${util.joinValues(issue.values, \"|\")}`;\n            case \"too_big\": {\n                const adj = issue.inclusive ? \"<=\" : \"<\";\n                const sizing = getSizing(issue.origin);\n                if (sizing)\n                    return `Tro granda: atendiĝis ke ${issue.origin ?? \"valoro\"} havu ${adj}${issue.maximum.toString()} ${sizing.unit ?? \"elementojn\"}`;\n                return `Tro granda: atendiĝis ke ${issue.origin ?? \"valoro\"} havu ${adj}${issue.maximum.toString()}`;\n            }\n            case \"too_small\": {\n                const adj = issue.inclusive ? \">=\" : \">\";\n                const sizing = getSizing(issue.origin);\n                if (sizing) {\n                    return `Tro malgranda: atendiĝis ke ${issue.origin} havu ${adj}${issue.minimum.toString()} ${sizing.unit}`;\n                }\n                return `Tro malgranda: atendiĝis ke ${issue.origin} estu ${adj}${issue.minimum.toString()}`;\n            }\n            case \"invalid_format\": {\n                const _issue = issue;\n                if (_issue.format === \"starts_with\")\n                    return `Nevalida karaktraro: devas komenciĝi per \"${_issue.prefix}\"`;\n                if (_issue.format === \"ends_with\")\n                    return `Nevalida karaktraro: devas finiĝi per \"${_issue.suffix}\"`;\n                if (_issue.format === \"includes\")\n                    return `Nevalida karaktraro: devas inkluzivi \"${_issue.includes}\"`;\n                if (_issue.format === \"regex\")\n                    return `Nevalida karaktraro: devas kongrui kun la modelo ${_issue.pattern}`;\n                return `Nevalida ${FormatDictionary[_issue.format] ?? issue.format}`;\n            }\n            case \"not_multiple_of\":\n                return `Nevalida nombro: devas esti oblo de ${issue.divisor}`;\n            case \"unrecognized_keys\":\n                return `Nekonata${issue.keys.length > 1 ? \"j\" : \"\"} ŝlosilo${issue.keys.length > 1 ? \"j\" : \"\"}: ${util.joinValues(issue.keys, \", \")}`;\n            case \"invalid_key\":\n                return `Nevalida ŝlosilo en ${issue.origin}`;\n            case \"invalid_union\":\n                return \"Nevalida enigo\";\n            case \"invalid_element\":\n                return `Nevalida valoro en ${issue.origin}`;\n            default:\n                return `Nevalida enigo`;\n        }\n    };\n};\nexport default function () {\n    return {\n        localeError: error(),\n    };\n}\n","import * as util from \"../core/util.js\";\nconst error = () => {\n    const Sizable = {\n        string: { unit: \"caracteres\", verb: \"tener\" },\n        file: { unit: \"bytes\", verb: \"tener\" },\n        array: { unit: \"elementos\", verb: \"tener\" },\n        set: { unit: \"elementos\", verb: \"tener\" },\n    };\n    function getSizing(origin) {\n        return Sizable[origin] ?? null;\n    }\n    const FormatDictionary = {\n        regex: \"entrada\",\n        email: \"dirección de correo electrónico\",\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: \"fecha y hora ISO\",\n        date: \"fecha ISO\",\n        time: \"hora ISO\",\n        duration: \"duración ISO\",\n        ipv4: \"dirección IPv4\",\n        ipv6: \"dirección IPv6\",\n        cidrv4: \"rango IPv4\",\n        cidrv6: \"rango IPv6\",\n        base64: \"cadena codificada en base64\",\n        base64url: \"URL codificada en base64\",\n        json_string: \"cadena JSON\",\n        e164: \"número E.164\",\n        jwt: \"JWT\",\n        template_literal: \"entrada\",\n    };\n    const TypeDictionary = {\n        nan: \"NaN\",\n        string: \"texto\",\n        number: \"número\",\n        boolean: \"booleano\",\n        array: \"arreglo\",\n        object: \"objeto\",\n        set: \"conjunto\",\n        file: \"archivo\",\n        date: \"fecha\",\n        bigint: \"número grande\",\n        symbol: \"símbolo\",\n        undefined: \"indefinido\",\n        null: \"nulo\",\n        function: \"función\",\n        map: \"mapa\",\n        record: \"registro\",\n        tuple: \"tupla\",\n        enum: \"enumeración\",\n        union: \"unión\",\n        literal: \"literal\",\n        promise: \"promesa\",\n        void: \"vacío\",\n        never: \"nunca\",\n        unknown: \"desconocido\",\n        any: \"cualquiera\",\n    };\n    return (issue) => {\n        switch (issue.code) {\n            case \"invalid_type\": {\n                const expected = TypeDictionary[issue.expected] ?? issue.expected;\n                const receivedType = util.parsedType(issue.input);\n                const received = TypeDictionary[receivedType] ?? receivedType;\n                if (/^[A-Z]/.test(issue.expected)) {\n                    return `Entrada inválida: se esperaba instanceof ${issue.expected}, recibido ${received}`;\n                }\n                return `Entrada inválida: se esperaba ${expected}, recibido ${received}`;\n            }\n            case \"invalid_value\":\n                if (issue.values.length === 1)\n                    return `Entrada inválida: se esperaba ${util.stringifyPrimitive(issue.values[0])}`;\n                return `Opción inválida: se esperaba una de ${util.joinValues(issue.values, \"|\")}`;\n            case \"too_big\": {\n                const adj = issue.inclusive ? \"<=\" : \"<\";\n                const sizing = getSizing(issue.origin);\n                const origin = TypeDictionary[issue.origin] ?? issue.origin;\n                if (sizing)\n                    return `Demasiado grande: se esperaba que ${origin ?? \"valor\"} tuviera ${adj}${issue.maximum.toString()} ${sizing.unit ?? \"elementos\"}`;\n                return `Demasiado grande: se esperaba que ${origin ?? \"valor\"} fuera ${adj}${issue.maximum.toString()}`;\n            }\n            case \"too_small\": {\n                const adj = issue.inclusive ? \">=\" : \">\";\n                const sizing = getSizing(issue.origin);\n                const origin = TypeDictionary[issue.origin] ?? issue.origin;\n                if (sizing) {\n                    return `Demasiado pequeño: se esperaba que ${origin} tuviera ${adj}${issue.minimum.toString()} ${sizing.unit}`;\n                }\n                return `Demasiado pequeño: se esperaba que ${origin} fuera ${adj}${issue.minimum.toString()}`;\n            }\n            case \"invalid_format\": {\n                const _issue = issue;\n                if (_issue.format === \"starts_with\")\n                    return `Cadena inválida: debe comenzar con \"${_issue.prefix}\"`;\n                if (_issue.format === \"ends_with\")\n                    return `Cadena inválida: debe terminar en \"${_issue.suffix}\"`;\n                if (_issue.format === \"includes\")\n                    return `Cadena inválida: debe incluir \"${_issue.includes}\"`;\n                if (_issue.format === \"regex\")\n                    return `Cadena inválida: debe coincidir con el patrón ${_issue.pattern}`;\n                return `Inválido ${FormatDictionary[_issue.format] ?? issue.format}`;\n            }\n            case \"not_multiple_of\":\n                return `Número inválido: debe ser múltiplo de ${issue.divisor}`;\n            case \"unrecognized_keys\":\n                return `Llave${issue.keys.length > 1 ? \"s\" : \"\"} desconocida${issue.keys.length > 1 ? \"s\" : \"\"}: ${util.joinValues(issue.keys, \", \")}`;\n            case \"invalid_key\":\n                return `Llave inválida en ${TypeDictionary[issue.origin] ?? issue.origin}`;\n            case \"invalid_union\":\n                return \"Entrada inválida\";\n            case \"invalid_element\":\n                return `Valor inválido en ${TypeDictionary[issue.origin] ?? issue.origin}`;\n            default:\n                return `Entrada inválida`;\n        }\n    };\n};\nexport default function () {\n    return {\n        localeError: error(),\n    };\n}\n","import * as util from \"../core/util.js\";\nconst error = () => {\n    const Sizable = {\n        string: { unit: \"کاراکتر\", verb: \"داشته باشد\" },\n        file: { unit: \"بایت\", verb: \"داشته باشد\" },\n        array: { unit: \"آیتم\", verb: \"داشته باشد\" },\n        set: { unit: \"آیتم\", verb: \"داشته باشد\" },\n    };\n    function getSizing(origin) {\n        return Sizable[origin] ?? null;\n    }\n    const FormatDictionary = {\n        regex: \"ورودی\",\n        email: \"آدرس ایمیل\",\n        url: \"URL\",\n        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: \"تاریخ و زمان ایزو\",\n        date: \"تاریخ ایزو\",\n        time: \"زمان ایزو\",\n        duration: \"مدت زمان ایزو\",\n        ipv4: \"IPv4 آدرس\",\n        ipv6: \"IPv6 آدرس\",\n        cidrv4: \"IPv4 دامنه\",\n        cidrv6: \"IPv6 دامنه\",\n        base64: \"base64-encoded رشته\",\n        base64url: \"base64url-encoded رشته\",\n        json_string: \"JSON رشته\",\n        e164: \"E.164 عدد\",\n        jwt: \"JWT\",\n        template_literal: \"ورودی\",\n    };\n    const TypeDictionary = {\n        nan: \"NaN\",\n        number: \"عدد\",\n        array: \"آرایه\",\n    };\n    return (issue) => {\n        switch (issue.code) {\n            case \"invalid_type\": {\n                const expected = TypeDictionary[issue.expected] ?? issue.expected;\n                const receivedType = util.parsedType(issue.input);\n                const received = TypeDictionary[receivedType] ?? receivedType;\n                if (/^[A-Z]/.test(issue.expected)) {\n                    return `ورودی نامعتبر: می‌بایست instanceof ${issue.expected} می‌بود، ${received} دریافت شد`;\n                }\n                return `ورودی نامعتبر: می‌بایست ${expected} می‌بود، ${received} دریافت شد`;\n            }\n            case \"invalid_value\":\n                if (issue.values.length === 1) {\n                    return `ورودی نامعتبر: می‌بایست ${util.stringifyPrimitive(issue.values[0])} می‌بود`;\n                }\n                return `گزینه نامعتبر: می‌بایست یکی از ${util.joinValues(issue.values, \"|\")} می‌بود`;\n            case \"too_big\": {\n                const adj = issue.inclusive ? \"<=\" : \"<\";\n                const sizing = getSizing(issue.origin);\n                if (sizing) {\n                    return `خیلی بزرگ: ${issue.origin ?? \"مقدار\"} باید ${adj}${issue.maximum.toString()} ${sizing.unit ?? \"عنصر\"} باشد`;\n                }\n                return `خیلی بزرگ: ${issue.origin ?? \"مقدار\"} باید ${adj}${issue.maximum.toString()} باشد`;\n            }\n            case \"too_small\": {\n                const adj = issue.inclusive ? \">=\" : \">\";\n                const sizing = getSizing(issue.origin);\n                if (sizing) {\n                    return `خیلی کوچک: ${issue.origin} باید ${adj}${issue.minimum.toString()} ${sizing.unit} باشد`;\n                }\n                return `خیلی کوچک: ${issue.origin} باید ${adj}${issue.minimum.toString()} باشد`;\n            }\n            case \"invalid_format\": {\n                const _issue = issue;\n                if (_issue.format === \"starts_with\") {\n                    return `رشته نامعتبر: باید با \"${_issue.prefix}\" شروع شود`;\n                }\n                if (_issue.format === \"ends_with\") {\n                    return `رشته نامعتبر: باید با \"${_issue.suffix}\" تمام شود`;\n                }\n                if (_issue.format === \"includes\") {\n                    return `رشته نامعتبر: باید شامل \"${_issue.includes}\" باشد`;\n                }\n                if (_issue.format === \"regex\") {\n                    return `رشته نامعتبر: باید با الگوی ${_issue.pattern} مطابقت داشته باشد`;\n                }\n                return `${FormatDictionary[_issue.format] ?? issue.format} نامعتبر`;\n            }\n            case \"not_multiple_of\":\n                return `عدد نامعتبر: باید مضرب ${issue.divisor} باشد`;\n            case \"unrecognized_keys\":\n                return `کلید${issue.keys.length > 1 ? \"های\" : \"\"} ناشناس: ${util.joinValues(issue.keys, \", \")}`;\n            case \"invalid_key\":\n                return `کلید ناشناس در ${issue.origin}`;\n            case \"invalid_union\":\n                return `ورودی نامعتبر`;\n            case \"invalid_element\":\n                return `مقدار نامعتبر در ${issue.origin}`;\n            default:\n                return `ورودی نامعتبر`;\n        }\n    };\n};\nexport default function () {\n    return {\n        localeError: error(),\n    };\n}\n","import * as util from \"../core/util.js\";\nconst error = () => {\n    const Sizable = {\n        string: { unit: \"merkkiä\", subject: \"merkkijonon\" },\n        file: { unit: \"tavua\", subject: \"tiedoston\" },\n        array: { unit: \"alkiota\", subject: \"listan\" },\n        set: { unit: \"alkiota\", subject: \"joukon\" },\n        number: { unit: \"\", subject: \"luvun\" },\n        bigint: { unit: \"\", subject: \"suuren kokonaisluvun\" },\n        int: { unit: \"\", subject: \"kokonaisluvun\" },\n        date: { unit: \"\", subject: \"päivämäärän\" },\n    };\n    function getSizing(origin) {\n        return Sizable[origin] ?? null;\n    }\n    const FormatDictionary = {\n        regex: \"säännöllinen lauseke\",\n        email: \"sähköpostiosoite\",\n        url: \"URL-osoite\",\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-aikaleima\",\n        date: \"ISO-päivämäärä\",\n        time: \"ISO-aika\",\n        duration: \"ISO-kesto\",\n        ipv4: \"IPv4-osoite\",\n        ipv6: \"IPv6-osoite\",\n        cidrv4: \"IPv4-alue\",\n        cidrv6: \"IPv6-alue\",\n        base64: \"base64-koodattu merkkijono\",\n        base64url: \"base64url-koodattu merkkijono\",\n        json_string: \"JSON-merkkijono\",\n        e164: \"E.164-luku\",\n        jwt: \"JWT\",\n        template_literal: \"templaattimerkkijono\",\n    };\n    const TypeDictionary = {\n        nan: \"NaN\",\n    };\n    return (issue) => {\n        switch (issue.code) {\n            case \"invalid_type\": {\n                const expected = TypeDictionary[issue.expected] ?? issue.expected;\n                const receivedType = util.parsedType(issue.input);\n                const received = TypeDictionary[receivedType] ?? receivedType;\n                if (/^[A-Z]/.test(issue.expected)) {\n                    return `Virheellinen tyyppi: odotettiin instanceof ${issue.expected}, oli ${received}`;\n                }\n                return `Virheellinen tyyppi: odotettiin ${expected}, oli ${received}`;\n            }\n            case \"invalid_value\":\n                if (issue.values.length === 1)\n                    return `Virheellinen syöte: täytyy olla ${util.stringifyPrimitive(issue.values[0])}`;\n                return `Virheellinen valinta: täytyy olla yksi seuraavista: ${util.joinValues(issue.values, \"|\")}`;\n            case \"too_big\": {\n                const adj = issue.inclusive ? \"<=\" : \"<\";\n                const sizing = getSizing(issue.origin);\n                if (sizing) {\n                    return `Liian suuri: ${sizing.subject} täytyy olla ${adj}${issue.maximum.toString()} ${sizing.unit}`.trim();\n                }\n                return `Liian suuri: arvon täytyy olla ${adj}${issue.maximum.toString()}`;\n            }\n            case \"too_small\": {\n                const adj = issue.inclusive ? \">=\" : \">\";\n                const sizing = getSizing(issue.origin);\n                if (sizing) {\n                    return `Liian pieni: ${sizing.subject} täytyy olla ${adj}${issue.minimum.toString()} ${sizing.unit}`.trim();\n                }\n                return `Liian pieni: arvon täytyy olla ${adj}${issue.minimum.toString()}`;\n            }\n            case \"invalid_format\": {\n                const _issue = issue;\n                if (_issue.format === \"starts_with\")\n                    return `Virheellinen syöte: täytyy alkaa \"${_issue.prefix}\"`;\n                if (_issue.format === \"ends_with\")\n                    return `Virheellinen syöte: täytyy loppua \"${_issue.suffix}\"`;\n                if (_issue.format === \"includes\")\n                    return `Virheellinen syöte: täytyy sisältää \"${_issue.includes}\"`;\n                if (_issue.format === \"regex\") {\n                    return `Virheellinen syöte: täytyy vastata säännöllistä lauseketta ${_issue.pattern}`;\n                }\n                return `Virheellinen ${FormatDictionary[_issue.format] ?? issue.format}`;\n            }\n            case \"not_multiple_of\":\n                return `Virheellinen luku: täytyy olla luvun ${issue.divisor} monikerta`;\n            case \"unrecognized_keys\":\n                return `${issue.keys.length > 1 ? \"Tuntemattomat avaimet\" : \"Tuntematon avain\"}: ${util.joinValues(issue.keys, \", \")}`;\n            case \"invalid_key\":\n                return \"Virheellinen avain tietueessa\";\n            case \"invalid_union\":\n                return \"Virheellinen unioni\";\n            case \"invalid_element\":\n                return \"Virheellinen arvo joukossa\";\n            default:\n                return `Virheellinen syöte`;\n        }\n    };\n};\nexport default function () {\n    return {\n        localeError: error(),\n    };\n}\n","import * as util from \"../core/util.js\";\nconst error = () => {\n    const Sizable = {\n        string: { unit: \"caractères\", verb: \"avoir\" },\n        file: { unit: \"octets\", verb: \"avoir\" },\n        array: { unit: \"éléments\", verb: \"avoir\" },\n        set: { unit: \"éléments\", verb: \"avoir\" },\n    };\n    function getSizing(origin) {\n        return Sizable[origin] ?? null;\n    }\n    const FormatDictionary = {\n        regex: \"entrée\",\n        email: \"adresse e-mail\",\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: \"date et heure ISO\",\n        date: \"date ISO\",\n        time: \"heure ISO\",\n        duration: \"durée ISO\",\n        ipv4: \"adresse IPv4\",\n        ipv6: \"adresse IPv6\",\n        cidrv4: \"plage IPv4\",\n        cidrv6: \"plage IPv6\",\n        base64: \"chaîne encodée en base64\",\n        base64url: \"chaîne encodée en base64url\",\n        json_string: \"chaîne JSON\",\n        e164: \"numéro E.164\",\n        jwt: \"JWT\",\n        template_literal: \"entrée\",\n    };\n    const TypeDictionary = {\n        string: \"chaîne\",\n        number: \"nombre\",\n        int: \"entier\",\n        boolean: \"booléen\",\n        bigint: \"grand entier\",\n        symbol: \"symbole\",\n        undefined: \"indéfini\",\n        null: \"null\",\n        never: \"jamais\",\n        void: \"vide\",\n        date: \"date\",\n        array: \"tableau\",\n        object: \"objet\",\n        tuple: \"tuple\",\n        record: \"enregistrement\",\n        map: \"carte\",\n        set: \"ensemble\",\n        file: \"fichier\",\n        nonoptional: \"non-optionnel\",\n        nan: \"NaN\",\n        function: \"fonction\",\n    };\n    return (issue) => {\n        switch (issue.code) {\n            case \"invalid_type\": {\n                const expected = TypeDictionary[issue.expected] ?? issue.expected;\n                const receivedType = util.parsedType(issue.input);\n                const received = TypeDictionary[receivedType] ?? receivedType;\n                if (/^[A-Z]/.test(issue.expected)) {\n                    return `Entrée invalide : instanceof ${issue.expected} attendu, ${received} reçu`;\n                }\n                return `Entrée invalide : ${expected} attendu, ${received} reçu`;\n            }\n            case \"invalid_value\":\n                if (issue.values.length === 1)\n                    return `Entrée invalide : ${util.stringifyPrimitive(issue.values[0])} attendu`;\n                return `Option invalide : une valeur parmi ${util.joinValues(issue.values, \"|\")} attendue`;\n            case \"too_big\": {\n                const adj = issue.inclusive ? \"<=\" : \"<\";\n                const sizing = getSizing(issue.origin);\n                if (sizing)\n                    return `Trop grand : ${TypeDictionary[issue.origin] ?? \"valeur\"} doit ${sizing.verb} ${adj}${issue.maximum.toString()} ${sizing.unit ?? \"élément(s)\"}`;\n                return `Trop grand : ${TypeDictionary[issue.origin] ?? \"valeur\"} doit être ${adj}${issue.maximum.toString()}`;\n            }\n            case \"too_small\": {\n                const adj = issue.inclusive ? \">=\" : \">\";\n                const sizing = getSizing(issue.origin);\n                if (sizing)\n                    return `Trop petit : ${TypeDictionary[issue.origin] ?? \"valeur\"} doit ${sizing.verb} ${adj}${issue.minimum.toString()} ${sizing.unit}`;\n                return `Trop petit : ${TypeDictionary[issue.origin] ?? \"valeur\"} doit être ${adj}${issue.minimum.toString()}`;\n            }\n            case \"invalid_format\": {\n                const _issue = issue;\n                if (_issue.format === \"starts_with\")\n                    return `Chaîne invalide : doit commencer par \"${_issue.prefix}\"`;\n                if (_issue.format === \"ends_with\")\n                    return `Chaîne invalide : doit se terminer par \"${_issue.suffix}\"`;\n                if (_issue.format === \"includes\")\n                    return `Chaîne invalide : doit inclure \"${_issue.includes}\"`;\n                if (_issue.format === \"regex\")\n                    return `Chaîne invalide : doit correspondre au modèle ${_issue.pattern}`;\n                return `${FormatDictionary[_issue.format] ?? issue.format} invalide`;\n            }\n            case \"not_multiple_of\":\n                return `Nombre invalide : doit être un multiple de ${issue.divisor}`;\n            case \"unrecognized_keys\":\n                return `Clé${issue.keys.length > 1 ? \"s\" : \"\"} non reconnue${issue.keys.length > 1 ? \"s\" : \"\"} : ${util.joinValues(issue.keys, \", \")}`;\n            case \"invalid_key\":\n                return `Clé invalide dans ${issue.origin}`;\n            case \"invalid_union\":\n                return \"Entrée invalide\";\n            case \"invalid_element\":\n                return `Valeur invalide dans ${issue.origin}`;\n            default:\n                return `Entrée invalide`;\n        }\n    };\n};\nexport default function () {\n    return {\n        localeError: error(),\n    };\n}\n","import * as util from \"../core/util.js\";\nconst error = () => {\n    const Sizable = {\n        string: { unit: \"caractères\", verb: \"avoir\" },\n        file: { unit: \"octets\", verb: \"avoir\" },\n        array: { unit: \"éléments\", verb: \"avoir\" },\n        set: { unit: \"éléments\", verb: \"avoir\" },\n    };\n    function getSizing(origin) {\n        return Sizable[origin] ?? null;\n    }\n    const FormatDictionary = {\n        regex: \"entrée\",\n        email: \"adresse courriel\",\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: \"date-heure ISO\",\n        date: \"date ISO\",\n        time: \"heure ISO\",\n        duration: \"durée ISO\",\n        ipv4: \"adresse IPv4\",\n        ipv6: \"adresse IPv6\",\n        cidrv4: \"plage IPv4\",\n        cidrv6: \"plage IPv6\",\n        base64: \"chaîne encodée en base64\",\n        base64url: \"chaîne encodée en base64url\",\n        json_string: \"chaîne JSON\",\n        e164: \"numéro E.164\",\n        jwt: \"JWT\",\n        template_literal: \"entrée\",\n    };\n    const TypeDictionary = {\n        nan: \"NaN\",\n    };\n    return (issue) => {\n        switch (issue.code) {\n            case \"invalid_type\": {\n                const expected = TypeDictionary[issue.expected] ?? issue.expected;\n                const receivedType = util.parsedType(issue.input);\n                const received = TypeDictionary[receivedType] ?? receivedType;\n                if (/^[A-Z]/.test(issue.expected)) {\n                    return `Entrée invalide : attendu instanceof ${issue.expected}, reçu ${received}`;\n                }\n                return `Entrée invalide : attendu ${expected}, reçu ${received}`;\n            }\n            case \"invalid_value\":\n                if (issue.values.length === 1)\n                    return `Entrée invalide : attendu ${util.stringifyPrimitive(issue.values[0])}`;\n                return `Option invalide : attendu l'une des valeurs suivantes ${util.joinValues(issue.values, \"|\")}`;\n            case \"too_big\": {\n                const adj = issue.inclusive ? \"≤\" : \"<\";\n                const sizing = getSizing(issue.origin);\n                if (sizing)\n                    return `Trop grand : attendu que ${issue.origin ?? \"la valeur\"} ait ${adj}${issue.maximum.toString()} ${sizing.unit}`;\n                return `Trop grand : attendu que ${issue.origin ?? \"la valeur\"} soit ${adj}${issue.maximum.toString()}`;\n            }\n            case \"too_small\": {\n                const adj = issue.inclusive ? \"≥\" : \">\";\n                const sizing = getSizing(issue.origin);\n                if (sizing) {\n                    return `Trop petit : attendu que ${issue.origin} ait ${adj}${issue.minimum.toString()} ${sizing.unit}`;\n                }\n                return `Trop petit : attendu que ${issue.origin} soit ${adj}${issue.minimum.toString()}`;\n            }\n            case \"invalid_format\": {\n                const _issue = issue;\n                if (_issue.format === \"starts_with\") {\n                    return `Chaîne invalide : doit commencer par \"${_issue.prefix}\"`;\n                }\n                if (_issue.format === \"ends_with\")\n                    return `Chaîne invalide : doit se terminer par \"${_issue.suffix}\"`;\n                if (_issue.format === \"includes\")\n                    return `Chaîne invalide : doit inclure \"${_issue.includes}\"`;\n                if (_issue.format === \"regex\")\n                    return `Chaîne invalide : doit correspondre au motif ${_issue.pattern}`;\n                return `${FormatDictionary[_issue.format] ?? issue.format} invalide`;\n            }\n            case \"not_multiple_of\":\n                return `Nombre invalide : doit être un multiple de ${issue.divisor}`;\n            case \"unrecognized_keys\":\n                return `Clé${issue.keys.length > 1 ? \"s\" : \"\"} non reconnue${issue.keys.length > 1 ? \"s\" : \"\"} : ${util.joinValues(issue.keys, \", \")}`;\n            case \"invalid_key\":\n                return `Clé invalide dans ${issue.origin}`;\n            case \"invalid_union\":\n                return \"Entrée invalide\";\n            case \"invalid_element\":\n                return `Valeur invalide dans ${issue.origin}`;\n            default:\n                return `Entrée invalide`;\n        }\n    };\n};\nexport default function () {\n    return {\n        localeError: error(),\n    };\n}\n","import * as util from \"../core/util.js\";\nconst error = () => {\n    // Hebrew labels + grammatical gender\n    const TypeNames = {\n        string: { label: \"מחרוזת\", gender: \"f\" },\n        number: { label: \"מספר\", gender: \"m\" },\n        boolean: { label: \"ערך בוליאני\", gender: \"m\" },\n        bigint: { label: \"BigInt\", gender: \"m\" },\n        date: { label: \"תאריך\", gender: \"m\" },\n        array: { label: \"מערך\", gender: \"m\" },\n        object: { label: \"אובייקט\", gender: \"m\" },\n        null: { label: \"ערך ריק (null)\", gender: \"m\" },\n        undefined: { label: \"ערך לא מוגדר (undefined)\", gender: \"m\" },\n        symbol: { label: \"סימבול (Symbol)\", gender: \"m\" },\n        function: { label: \"פונקציה\", gender: \"f\" },\n        map: { label: \"מפה (Map)\", gender: \"f\" },\n        set: { label: \"קבוצה (Set)\", gender: \"f\" },\n        file: { label: \"קובץ\", gender: \"m\" },\n        promise: { label: \"Promise\", gender: \"m\" },\n        NaN: { label: \"NaN\", gender: \"m\" },\n        unknown: { label: \"ערך לא ידוע\", gender: \"m\" },\n        value: { label: \"ערך\", gender: \"m\" },\n    };\n    // Sizing units for size-related messages + localized origin labels\n    const Sizable = {\n        string: { unit: \"תווים\", shortLabel: \"קצר\", longLabel: \"ארוך\" },\n        file: { unit: \"בייטים\", shortLabel: \"קטן\", longLabel: \"גדול\" },\n        array: { unit: \"פריטים\", shortLabel: \"קטן\", longLabel: \"גדול\" },\n        set: { unit: \"פריטים\", shortLabel: \"קטן\", longLabel: \"גדול\" },\n        number: { unit: \"\", shortLabel: \"קטן\", longLabel: \"גדול\" }, // no unit\n    };\n    // Helpers — labels, articles, and verbs\n    const typeEntry = (t) => (t ? TypeNames[t] : undefined);\n    const typeLabel = (t) => {\n        const e = typeEntry(t);\n        if (e)\n            return e.label;\n        // fallback: show raw string if unknown\n        return t ?? TypeNames.unknown.label;\n    };\n    const withDefinite = (t) => `ה${typeLabel(t)}`;\n    const verbFor = (t) => {\n        const e = typeEntry(t);\n        const gender = e?.gender ?? \"m\";\n        return gender === \"f\" ? \"צריכה להיות\" : \"צריך להיות\";\n    };\n    const getSizing = (origin) => {\n        if (!origin)\n            return null;\n        return Sizable[origin] ?? null;\n    };\n    const FormatDictionary = {\n        regex: { label: \"קלט\", gender: \"m\" },\n        email: { label: \"כתובת אימייל\", gender: \"f\" },\n        url: { label: \"כתובת רשת\", gender: \"f\" },\n        emoji: { label: \"אימוג'י\", gender: \"m\" },\n        uuid: { label: \"UUID\", gender: \"m\" },\n        nanoid: { label: \"nanoid\", gender: \"m\" },\n        guid: { label: \"GUID\", gender: \"m\" },\n        cuid: { label: \"cuid\", gender: \"m\" },\n        cuid2: { label: \"cuid2\", gender: \"m\" },\n        ulid: { label: \"ULID\", gender: \"m\" },\n        xid: { label: \"XID\", gender: \"m\" },\n        ksuid: { label: \"KSUID\", gender: \"m\" },\n        datetime: { label: \"תאריך וזמן ISO\", gender: \"m\" },\n        date: { label: \"תאריך ISO\", gender: \"m\" },\n        time: { label: \"זמן ISO\", gender: \"m\" },\n        duration: { label: \"משך זמן ISO\", gender: \"m\" },\n        ipv4: { label: \"כתובת IPv4\", gender: \"f\" },\n        ipv6: { label: \"כתובת IPv6\", gender: \"f\" },\n        cidrv4: { label: \"טווח IPv4\", gender: \"m\" },\n        cidrv6: { label: \"טווח IPv6\", gender: \"m\" },\n        base64: { label: \"מחרוזת בבסיס 64\", gender: \"f\" },\n        base64url: { label: \"מחרוזת בבסיס 64 לכתובות רשת\", gender: \"f\" },\n        json_string: { label: \"מחרוזת JSON\", gender: \"f\" },\n        e164: { label: \"מספר E.164\", gender: \"m\" },\n        jwt: { label: \"JWT\", gender: \"m\" },\n        ends_with: { label: \"קלט\", gender: \"m\" },\n        includes: { label: \"קלט\", gender: \"m\" },\n        lowercase: { label: \"קלט\", gender: \"m\" },\n        starts_with: { label: \"קלט\", gender: \"m\" },\n        uppercase: { label: \"קלט\", gender: \"m\" },\n    };\n    const TypeDictionary = {\n        nan: \"NaN\",\n    };\n    return (issue) => {\n        switch (issue.code) {\n            case \"invalid_type\": {\n                // Expected type: show without definite article for clearer Hebrew\n                const expectedKey = issue.expected;\n                const expected = TypeDictionary[expectedKey ?? \"\"] ?? typeLabel(expectedKey);\n                // Received: show localized label if known, otherwise constructor/raw\n                const receivedType = util.parsedType(issue.input);\n                const received = TypeDictionary[receivedType] ?? TypeNames[receivedType]?.label ?? receivedType;\n                if (/^[A-Z]/.test(issue.expected)) {\n                    return `קלט לא תקין: צריך להיות instanceof ${issue.expected}, התקבל ${received}`;\n                }\n                return `קלט לא תקין: צריך להיות ${expected}, התקבל ${received}`;\n            }\n            case \"invalid_value\": {\n                if (issue.values.length === 1) {\n                    return `ערך לא תקין: הערך חייב להיות ${util.stringifyPrimitive(issue.values[0])}`;\n                }\n                // Join values with proper Hebrew formatting\n                const stringified = issue.values.map((v) => util.stringifyPrimitive(v));\n                if (issue.values.length === 2) {\n                    return `ערך לא תקין: האפשרויות המתאימות הן ${stringified[0]} או ${stringified[1]}`;\n                }\n                // For 3+ values: \"a\", \"b\" או \"c\"\n                const lastValue = stringified[stringified.length - 1];\n                const restValues = stringified.slice(0, -1).join(\", \");\n                return `ערך לא תקין: האפשרויות המתאימות הן ${restValues} או ${lastValue}`;\n            }\n            case \"too_big\": {\n                const sizing = getSizing(issue.origin);\n                const subject = withDefinite(issue.origin ?? \"value\");\n                if (issue.origin === \"string\") {\n                    // Special handling for strings - more natural Hebrew\n                    return `${sizing?.longLabel ?? \"ארוך\"} מדי: ${subject} צריכה להכיל ${issue.maximum.toString()} ${sizing?.unit ?? \"\"} ${issue.inclusive ? \"או פחות\" : \"לכל היותר\"}`.trim();\n                }\n                if (issue.origin === \"number\") {\n                    // Natural Hebrew for numbers\n                    const comparison = issue.inclusive ? `קטן או שווה ל-${issue.maximum}` : `קטן מ-${issue.maximum}`;\n                    return `גדול מדי: ${subject} צריך להיות ${comparison}`;\n                }\n                if (issue.origin === \"array\" || issue.origin === \"set\") {\n                    // Natural Hebrew for arrays and sets\n                    const verb = issue.origin === \"set\" ? \"צריכה\" : \"צריך\";\n                    const comparison = issue.inclusive\n                        ? `${issue.maximum} ${sizing?.unit ?? \"\"} או פחות`\n                        : `פחות מ-${issue.maximum} ${sizing?.unit ?? \"\"}`;\n                    return `גדול מדי: ${subject} ${verb} להכיל ${comparison}`.trim();\n                }\n                const adj = issue.inclusive ? \"<=\" : \"<\";\n                const be = verbFor(issue.origin ?? \"value\");\n                if (sizing?.unit) {\n                    return `${sizing.longLabel} מדי: ${subject} ${be} ${adj}${issue.maximum.toString()} ${sizing.unit}`;\n                }\n                return `${sizing?.longLabel ?? \"גדול\"} מדי: ${subject} ${be} ${adj}${issue.maximum.toString()}`;\n            }\n            case \"too_small\": {\n                const sizing = getSizing(issue.origin);\n                const subject = withDefinite(issue.origin ?? \"value\");\n                if (issue.origin === \"string\") {\n                    // Special handling for strings - more natural Hebrew\n                    return `${sizing?.shortLabel ?? \"קצר\"} מדי: ${subject} צריכה להכיל ${issue.minimum.toString()} ${sizing?.unit ?? \"\"} ${issue.inclusive ? \"או יותר\" : \"לפחות\"}`.trim();\n                }\n                if (issue.origin === \"number\") {\n                    // Natural Hebrew for numbers\n                    const comparison = issue.inclusive ? `גדול או שווה ל-${issue.minimum}` : `גדול מ-${issue.minimum}`;\n                    return `קטן מדי: ${subject} צריך להיות ${comparison}`;\n                }\n                if (issue.origin === \"array\" || issue.origin === \"set\") {\n                    // Natural Hebrew for arrays and sets\n                    const verb = issue.origin === \"set\" ? \"צריכה\" : \"צריך\";\n                    // Special case for singular (minimum === 1)\n                    if (issue.minimum === 1 && issue.inclusive) {\n                        const singularPhrase = issue.origin === \"set\" ? \"לפחות פריט אחד\" : \"לפחות פריט אחד\";\n                        return `קטן מדי: ${subject} ${verb} להכיל ${singularPhrase}`;\n                    }\n                    const comparison = issue.inclusive\n                        ? `${issue.minimum} ${sizing?.unit ?? \"\"} או יותר`\n                        : `יותר מ-${issue.minimum} ${sizing?.unit ?? \"\"}`;\n                    return `קטן מדי: ${subject} ${verb} להכיל ${comparison}`.trim();\n                }\n                const adj = issue.inclusive ? \">=\" : \">\";\n                const be = verbFor(issue.origin ?? \"value\");\n                if (sizing?.unit) {\n                    return `${sizing.shortLabel} מדי: ${subject} ${be} ${adj}${issue.minimum.toString()} ${sizing.unit}`;\n                }\n                return `${sizing?.shortLabel ?? \"קטן\"} מדי: ${subject} ${be} ${adj}${issue.minimum.toString()}`;\n            }\n            case \"invalid_format\": {\n                const _issue = issue;\n                // These apply to strings — use feminine grammar + ה׳ הידיעה\n                if (_issue.format === \"starts_with\")\n                    return `המחרוזת חייבת להתחיל ב \"${_issue.prefix}\"`;\n                if (_issue.format === \"ends_with\")\n                    return `המחרוזת חייבת להסתיים ב \"${_issue.suffix}\"`;\n                if (_issue.format === \"includes\")\n                    return `המחרוזת חייבת לכלול \"${_issue.includes}\"`;\n                if (_issue.format === \"regex\")\n                    return `המחרוזת חייבת להתאים לתבנית ${_issue.pattern}`;\n                // Handle gender agreement for formats\n                const nounEntry = FormatDictionary[_issue.format];\n                const noun = nounEntry?.label ?? _issue.format;\n                const gender = nounEntry?.gender ?? \"m\";\n                const adjective = gender === \"f\" ? \"תקינה\" : \"תקין\";\n                return `${noun} לא ${adjective}`;\n            }\n            case \"not_multiple_of\":\n                return `מספר לא תקין: חייב להיות מכפלה של ${issue.divisor}`;\n            case \"unrecognized_keys\":\n                return `מפתח${issue.keys.length > 1 ? \"ות\" : \"\"} לא מזוה${issue.keys.length > 1 ? \"ים\" : \"ה\"}: ${util.joinValues(issue.keys, \", \")}`;\n            case \"invalid_key\": {\n                return `שדה לא תקין באובייקט`;\n            }\n            case \"invalid_union\":\n                return \"קלט לא תקין\";\n            case \"invalid_element\": {\n                const place = withDefinite(issue.origin ?? \"array\");\n                return `ערך לא תקין ב${place}`;\n            }\n            default:\n                return `קלט לא תקין`;\n        }\n    };\n};\nexport default function () {\n    return {\n        localeError: error(),\n    };\n}\n","import * as util from \"../core/util.js\";\nconst error = () => {\n    const Sizable = {\n        string: { unit: \"znakova\", verb: \"imati\" },\n        file: { unit: \"bajtova\", verb: \"imati\" },\n        array: { unit: \"stavki\", verb: \"imati\" },\n        set: { unit: \"stavki\", verb: \"imati\" },\n    };\n    function getSizing(origin) {\n        return Sizable[origin] ?? null;\n    }\n    const FormatDictionary = {\n        regex: \"unos\",\n        email: \"email adresa\",\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 datum i vrijeme\",\n        date: \"ISO datum\",\n        time: \"ISO vrijeme\",\n        duration: \"ISO trajanje\",\n        ipv4: \"IPv4 adresa\",\n        ipv6: \"IPv6 adresa\",\n        cidrv4: \"IPv4 raspon\",\n        cidrv6: \"IPv6 raspon\",\n        base64: \"base64 kodirani tekst\",\n        base64url: \"base64url kodirani tekst\",\n        json_string: \"JSON tekst\",\n        e164: \"E.164 broj\",\n        jwt: \"JWT\",\n        template_literal: \"unos\",\n    };\n    const TypeDictionary = {\n        nan: \"NaN\",\n        string: \"tekst\",\n        number: \"broj\",\n        boolean: \"boolean\",\n        array: \"niz\",\n        object: \"objekt\",\n        set: \"skup\",\n        file: \"datoteka\",\n        date: \"datum\",\n        bigint: \"bigint\",\n        symbol: \"simbol\",\n        undefined: \"undefined\",\n        null: \"null\",\n        function: \"funkcija\",\n        map: \"mapa\",\n    };\n    return (issue) => {\n        switch (issue.code) {\n            case \"invalid_type\": {\n                const expected = TypeDictionary[issue.expected] ?? issue.expected;\n                const receivedType = util.parsedType(issue.input);\n                const received = TypeDictionary[receivedType] ?? receivedType;\n                if (/^[A-Z]/.test(issue.expected)) {\n                    return `Neispravan unos: očekuje se instanceof ${issue.expected}, a primljeno je ${received}`;\n                }\n                return `Neispravan unos: očekuje se ${expected}, a primljeno je ${received}`;\n            }\n            case \"invalid_value\":\n                if (issue.values.length === 1)\n                    return `Neispravna vrijednost: očekivano ${util.stringifyPrimitive(issue.values[0])}`;\n                return `Neispravna opcija: očekivano jedno od ${util.joinValues(issue.values, \"|\")}`;\n            case \"too_big\": {\n                const adj = issue.inclusive ? \"<=\" : \"<\";\n                const sizing = getSizing(issue.origin);\n                const origin = TypeDictionary[issue.origin] ?? issue.origin;\n                if (sizing)\n                    return `Preveliko: očekivano da ${origin ?? \"vrijednost\"} ima ${adj}${issue.maximum.toString()} ${sizing.unit ?? \"elemenata\"}`;\n                return `Preveliko: očekivano da ${origin ?? \"vrijednost\"} bude ${adj}${issue.maximum.toString()}`;\n            }\n            case \"too_small\": {\n                const adj = issue.inclusive ? \">=\" : \">\";\n                const sizing = getSizing(issue.origin);\n                const origin = TypeDictionary[issue.origin] ?? issue.origin;\n                if (sizing) {\n                    return `Premalo: očekivano da ${origin} ima ${adj}${issue.minimum.toString()} ${sizing.unit}`;\n                }\n                return `Premalo: očekivano da ${origin} bude ${adj}${issue.minimum.toString()}`;\n            }\n            case \"invalid_format\": {\n                const _issue = issue;\n                if (_issue.format === \"starts_with\")\n                    return `Neispravan tekst: mora započinjati s \"${_issue.prefix}\"`;\n                if (_issue.format === \"ends_with\")\n                    return `Neispravan tekst: mora završavati s \"${_issue.suffix}\"`;\n                if (_issue.format === \"includes\")\n                    return `Neispravan tekst: mora sadržavati \"${_issue.includes}\"`;\n                if (_issue.format === \"regex\")\n                    return `Neispravan tekst: mora odgovarati uzorku ${_issue.pattern}`;\n                return `Neispravna ${FormatDictionary[_issue.format] ?? issue.format}`;\n            }\n            case \"not_multiple_of\":\n                return `Neispravan broj: mora biti višekratnik od ${issue.divisor}`;\n            case \"unrecognized_keys\":\n                return `Neprepoznat${issue.keys.length > 1 ? \"i ključevi\" : \" ključ\"}: ${util.joinValues(issue.keys, \", \")}`;\n            case \"invalid_key\":\n                return `Neispravan ključ u ${TypeDictionary[issue.origin] ?? issue.origin}`;\n            case \"invalid_union\":\n                return \"Neispravan unos\";\n            case \"invalid_element\":\n                return `Neispravna vrijednost u ${TypeDictionary[issue.origin] ?? issue.origin}`;\n            default:\n                return `Neispravan unos`;\n        }\n    };\n};\nexport default function () {\n    return {\n        localeError: error(),\n    };\n}\n","import * as util from \"../core/util.js\";\nconst error = () => {\n    const Sizable = {\n        string: { unit: \"karakter\", verb: \"legyen\" },\n        file: { unit: \"byte\", verb: \"legyen\" },\n        array: { unit: \"elem\", verb: \"legyen\" },\n        set: { unit: \"elem\", verb: \"legyen\" },\n    };\n    function getSizing(origin) {\n        return Sizable[origin] ?? null;\n    }\n    const FormatDictionary = {\n        regex: \"bemenet\",\n        email: \"email cím\",\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 időbélyeg\",\n        date: \"ISO dátum\",\n        time: \"ISO idő\",\n        duration: \"ISO időintervallum\",\n        ipv4: \"IPv4 cím\",\n        ipv6: \"IPv6 cím\",\n        cidrv4: \"IPv4 tartomány\",\n        cidrv6: \"IPv6 tartomány\",\n        base64: \"base64-kódolt string\",\n        base64url: \"base64url-kódolt string\",\n        json_string: \"JSON string\",\n        e164: \"E.164 szám\",\n        jwt: \"JWT\",\n        template_literal: \"bemenet\",\n    };\n    const TypeDictionary = {\n        nan: \"NaN\",\n        number: \"szám\",\n        array: \"tömb\",\n    };\n    return (issue) => {\n        switch (issue.code) {\n            case \"invalid_type\": {\n                const expected = TypeDictionary[issue.expected] ?? issue.expected;\n                const receivedType = util.parsedType(issue.input);\n                const received = TypeDictionary[receivedType] ?? receivedType;\n                if (/^[A-Z]/.test(issue.expected)) {\n                    return `Érvénytelen bemenet: a várt érték instanceof ${issue.expected}, a kapott érték ${received}`;\n                }\n                return `Érvénytelen bemenet: a várt érték ${expected}, a kapott érték ${received}`;\n            }\n            case \"invalid_value\":\n                if (issue.values.length === 1)\n                    return `Érvénytelen bemenet: a várt érték ${util.stringifyPrimitive(issue.values[0])}`;\n                return `Érvénytelen opció: valamelyik érték várt ${util.joinValues(issue.values, \"|\")}`;\n            case \"too_big\": {\n                const adj = issue.inclusive ? \"<=\" : \"<\";\n                const sizing = getSizing(issue.origin);\n                if (sizing)\n                    return `Túl nagy: ${issue.origin ?? \"érték\"} mérete túl nagy ${adj}${issue.maximum.toString()} ${sizing.unit ?? \"elem\"}`;\n                return `Túl nagy: a bemeneti érték ${issue.origin ?? \"érték\"} túl nagy: ${adj}${issue.maximum.toString()}`;\n            }\n            case \"too_small\": {\n                const adj = issue.inclusive ? \">=\" : \">\";\n                const sizing = getSizing(issue.origin);\n                if (sizing) {\n                    return `Túl kicsi: a bemeneti érték ${issue.origin} mérete túl kicsi ${adj}${issue.minimum.toString()} ${sizing.unit}`;\n                }\n                return `Túl kicsi: a bemeneti érték ${issue.origin} túl kicsi ${adj}${issue.minimum.toString()}`;\n            }\n            case \"invalid_format\": {\n                const _issue = issue;\n                if (_issue.format === \"starts_with\")\n                    return `Érvénytelen string: \"${_issue.prefix}\" értékkel kell kezdődnie`;\n                if (_issue.format === \"ends_with\")\n                    return `Érvénytelen string: \"${_issue.suffix}\" értékkel kell végződnie`;\n                if (_issue.format === \"includes\")\n                    return `Érvénytelen string: \"${_issue.includes}\" értéket kell tartalmaznia`;\n                if (_issue.format === \"regex\")\n                    return `Érvénytelen string: ${_issue.pattern} mintának kell megfelelnie`;\n                return `Érvénytelen ${FormatDictionary[_issue.format] ?? issue.format}`;\n            }\n            case \"not_multiple_of\":\n                return `Érvénytelen szám: ${issue.divisor} többszörösének kell lennie`;\n            case \"unrecognized_keys\":\n                return `Ismeretlen kulcs${issue.keys.length > 1 ? \"s\" : \"\"}: ${util.joinValues(issue.keys, \", \")}`;\n            case \"invalid_key\":\n                return `Érvénytelen kulcs ${issue.origin}`;\n            case \"invalid_union\":\n                return \"Érvénytelen bemenet\";\n            case \"invalid_element\":\n                return `Érvénytelen érték: ${issue.origin}`;\n            default:\n                return `Érvénytelen bemenet`;\n        }\n    };\n};\nexport default function () {\n    return {\n        localeError: error(),\n    };\n}\n","import * as util from \"../core/util.js\";\nfunction getArmenianPlural(count, one, many) {\n    return Math.abs(count) === 1 ? one : many;\n}\nfunction withDefiniteArticle(word) {\n    if (!word)\n        return \"\";\n    const vowels = [\"ա\", \"ե\", \"ը\", \"ի\", \"ո\", \"ու\", \"օ\"];\n    const lastChar = word[word.length - 1];\n    return word + (vowels.includes(lastChar) ? \"ն\" : \"ը\");\n}\nconst error = () => {\n    const Sizable = {\n        string: {\n            unit: {\n                one: \"նշան\",\n                many: \"նշաններ\",\n            },\n            verb: \"ունենալ\",\n        },\n        file: {\n            unit: {\n                one: \"բայթ\",\n                many: \"բայթեր\",\n            },\n            verb: \"ունենալ\",\n        },\n        array: {\n            unit: {\n                one: \"տարր\",\n                many: \"տարրեր\",\n            },\n            verb: \"ունենալ\",\n        },\n        set: {\n            unit: {\n                one: \"տարր\",\n                many: \"տարրեր\",\n            },\n            verb: \"ունենալ\",\n        },\n    };\n    function getSizing(origin) {\n        return Sizable[origin] ?? null;\n    }\n    const FormatDictionary = {\n        regex: \"մուտք\",\n        email: \"էլ. հասցե\",\n        url: \"URL\",\n        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 ամսաթիվ և ժամ\",\n        date: \"ISO ամսաթիվ\",\n        time: \"ISO ժամ\",\n        duration: \"ISO տևողություն\",\n        ipv4: \"IPv4 հասցե\",\n        ipv6: \"IPv6 հասցե\",\n        cidrv4: \"IPv4 միջակայք\",\n        cidrv6: \"IPv6 միջակայք\",\n        base64: \"base64 ձևաչափով տող\",\n        base64url: \"base64url ձևաչափով տող\",\n        json_string: \"JSON տող\",\n        e164: \"E.164 համար\",\n        jwt: \"JWT\",\n        template_literal: \"մուտք\",\n    };\n    const TypeDictionary = {\n        nan: \"NaN\",\n        number: \"թիվ\",\n        array: \"զանգված\",\n    };\n    return (issue) => {\n        switch (issue.code) {\n            case \"invalid_type\": {\n                const expected = TypeDictionary[issue.expected] ?? issue.expected;\n                const receivedType = util.parsedType(issue.input);\n                const received = TypeDictionary[receivedType] ?? receivedType;\n                if (/^[A-Z]/.test(issue.expected)) {\n                    return `Սխալ մուտքագրում․ սպասվում էր instanceof ${issue.expected}, ստացվել է ${received}`;\n                }\n                return `Սխալ մուտքագրում․ սպասվում էր ${expected}, ստացվել է ${received}`;\n            }\n            case \"invalid_value\":\n                if (issue.values.length === 1)\n                    return `Սխալ մուտքագրում․ սպասվում էր ${util.stringifyPrimitive(issue.values[1])}`;\n                return `Սխալ տարբերակ․ սպասվում էր հետևյալներից մեկը՝ ${util.joinValues(issue.values, \"|\")}`;\n            case \"too_big\": {\n                const adj = issue.inclusive ? \"<=\" : \"<\";\n                const sizing = getSizing(issue.origin);\n                if (sizing) {\n                    const maxValue = Number(issue.maximum);\n                    const unit = getArmenianPlural(maxValue, sizing.unit.one, sizing.unit.many);\n                    return `Չափազանց մեծ արժեք․ սպասվում է, որ ${withDefiniteArticle(issue.origin ?? \"արժեք\")} կունենա ${adj}${issue.maximum.toString()} ${unit}`;\n                }\n                return `Չափազանց մեծ արժեք․ սպասվում է, որ ${withDefiniteArticle(issue.origin ?? \"արժեք\")} լինի ${adj}${issue.maximum.toString()}`;\n            }\n            case \"too_small\": {\n                const adj = issue.inclusive ? \">=\" : \">\";\n                const sizing = getSizing(issue.origin);\n                if (sizing) {\n                    const minValue = Number(issue.minimum);\n                    const unit = getArmenianPlural(minValue, sizing.unit.one, sizing.unit.many);\n                    return `Չափազանց փոքր արժեք․ սպասվում է, որ ${withDefiniteArticle(issue.origin)} կունենա ${adj}${issue.minimum.toString()} ${unit}`;\n                }\n                return `Չափազանց փոքր արժեք․ սպասվում է, որ ${withDefiniteArticle(issue.origin)} լինի ${adj}${issue.minimum.toString()}`;\n            }\n            case \"invalid_format\": {\n                const _issue = issue;\n                if (_issue.format === \"starts_with\")\n                    return `Սխալ տող․ պետք է սկսվի \"${_issue.prefix}\"-ով`;\n                if (_issue.format === \"ends_with\")\n                    return `Սխալ տող․ պետք է ավարտվի \"${_issue.suffix}\"-ով`;\n                if (_issue.format === \"includes\")\n                    return `Սխալ տող․ պետք է պարունակի \"${_issue.includes}\"`;\n                if (_issue.format === \"regex\")\n                    return `Սխալ տող․ պետք է համապատասխանի ${_issue.pattern} ձևաչափին`;\n                return `Սխալ ${FormatDictionary[_issue.format] ?? issue.format}`;\n            }\n            case \"not_multiple_of\":\n                return `Սխալ թիվ․ պետք է բազմապատիկ լինի ${issue.divisor}-ի`;\n            case \"unrecognized_keys\":\n                return `Չճանաչված բանալի${issue.keys.length > 1 ? \"ներ\" : \"\"}. ${util.joinValues(issue.keys, \", \")}`;\n            case \"invalid_key\":\n                return `Սխալ բանալի ${withDefiniteArticle(issue.origin)}-ում`;\n            case \"invalid_union\":\n                return \"Սխալ մուտքագրում\";\n            case \"invalid_element\":\n                return `Սխալ արժեք ${withDefiniteArticle(issue.origin)}-ում`;\n            default:\n                return `Սխալ մուտքագրում`;\n        }\n    };\n};\nexport default function () {\n    return {\n        localeError: error(),\n    };\n}\n","import * as util from \"../core/util.js\";\nconst error = () => {\n    const Sizable = {\n        string: { unit: \"karakter\", verb: \"memiliki\" },\n        file: { unit: \"byte\", verb: \"memiliki\" },\n        array: { unit: \"item\", verb: \"memiliki\" },\n        set: { unit: \"item\", verb: \"memiliki\" },\n    };\n    function getSizing(origin) {\n        return Sizable[origin] ?? null;\n    }\n    const FormatDictionary = {\n        regex: \"input\",\n        email: \"alamat email\",\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: \"tanggal dan waktu format ISO\",\n        date: \"tanggal format ISO\",\n        time: \"jam format ISO\",\n        duration: \"durasi format ISO\",\n        ipv4: \"alamat IPv4\",\n        ipv6: \"alamat IPv6\",\n        cidrv4: \"rentang alamat IPv4\",\n        cidrv6: \"rentang alamat IPv6\",\n        base64: \"string dengan enkode base64\",\n        base64url: \"string dengan enkode base64url\",\n        json_string: \"string JSON\",\n        e164: \"angka E.164\",\n        jwt: \"JWT\",\n        template_literal: \"input\",\n    };\n    const TypeDictionary = {\n        nan: \"NaN\",\n    };\n    return (issue) => {\n        switch (issue.code) {\n            case \"invalid_type\": {\n                const expected = TypeDictionary[issue.expected] ?? issue.expected;\n                const receivedType = util.parsedType(issue.input);\n                const received = TypeDictionary[receivedType] ?? receivedType;\n                if (/^[A-Z]/.test(issue.expected)) {\n                    return `Input tidak valid: diharapkan instanceof ${issue.expected}, diterima ${received}`;\n                }\n                return `Input tidak valid: diharapkan ${expected}, diterima ${received}`;\n            }\n            case \"invalid_value\":\n                if (issue.values.length === 1)\n                    return `Input tidak valid: diharapkan ${util.stringifyPrimitive(issue.values[0])}`;\n                return `Pilihan tidak valid: diharapkan salah satu dari ${util.joinValues(issue.values, \"|\")}`;\n            case \"too_big\": {\n                const adj = issue.inclusive ? \"<=\" : \"<\";\n                const sizing = getSizing(issue.origin);\n                if (sizing)\n                    return `Terlalu besar: diharapkan ${issue.origin ?? \"value\"} memiliki ${adj}${issue.maximum.toString()} ${sizing.unit ?? \"elemen\"}`;\n                return `Terlalu besar: diharapkan ${issue.origin ?? \"value\"} menjadi ${adj}${issue.maximum.toString()}`;\n            }\n            case \"too_small\": {\n                const adj = issue.inclusive ? \">=\" : \">\";\n                const sizing = getSizing(issue.origin);\n                if (sizing) {\n                    return `Terlalu kecil: diharapkan ${issue.origin} memiliki ${adj}${issue.minimum.toString()} ${sizing.unit}`;\n                }\n                return `Terlalu kecil: diharapkan ${issue.origin} menjadi ${adj}${issue.minimum.toString()}`;\n            }\n            case \"invalid_format\": {\n                const _issue = issue;\n                if (_issue.format === \"starts_with\")\n                    return `String tidak valid: harus dimulai dengan \"${_issue.prefix}\"`;\n                if (_issue.format === \"ends_with\")\n                    return `String tidak valid: harus berakhir dengan \"${_issue.suffix}\"`;\n                if (_issue.format === \"includes\")\n                    return `String tidak valid: harus menyertakan \"${_issue.includes}\"`;\n                if (_issue.format === \"regex\")\n                    return `String tidak valid: harus sesuai pola ${_issue.pattern}`;\n                return `${FormatDictionary[_issue.format] ?? issue.format} tidak valid`;\n            }\n            case \"not_multiple_of\":\n                return `Angka tidak valid: harus kelipatan dari ${issue.divisor}`;\n            case \"unrecognized_keys\":\n                return `Kunci tidak dikenali ${issue.keys.length > 1 ? \"s\" : \"\"}: ${util.joinValues(issue.keys, \", \")}`;\n            case \"invalid_key\":\n                return `Kunci tidak valid di ${issue.origin}`;\n            case \"invalid_union\":\n                return \"Input tidak valid\";\n            case \"invalid_element\":\n                return `Nilai tidak valid di ${issue.origin}`;\n            default:\n                return `Input tidak valid`;\n        }\n    };\n};\nexport default function () {\n    return {\n        localeError: error(),\n    };\n}\n","import * as util from \"../core/util.js\";\nconst error = () => {\n    const Sizable = {\n        string: { unit: \"stafi\", verb: \"að hafa\" },\n        file: { unit: \"bæti\", verb: \"að hafa\" },\n        array: { unit: \"hluti\", verb: \"að hafa\" },\n        set: { unit: \"hluti\", verb: \"að hafa\" },\n    };\n    function getSizing(origin) {\n        return Sizable[origin] ?? null;\n    }\n    const FormatDictionary = {\n        regex: \"gildi\",\n        email: \"netfang\",\n        url: \"vefslóð\",\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 dagsetning og tími\",\n        date: \"ISO dagsetning\",\n        time: \"ISO tími\",\n        duration: \"ISO tímalengd\",\n        ipv4: \"IPv4 address\",\n        ipv6: \"IPv6 address\",\n        cidrv4: \"IPv4 range\",\n        cidrv6: \"IPv6 range\",\n        base64: \"base64-encoded strengur\",\n        base64url: \"base64url-encoded strengur\",\n        json_string: \"JSON strengur\",\n        e164: \"E.164 tölugildi\",\n        jwt: \"JWT\",\n        template_literal: \"gildi\",\n    };\n    const TypeDictionary = {\n        nan: \"NaN\",\n        number: \"númer\",\n        array: \"fylki\",\n    };\n    return (issue) => {\n        switch (issue.code) {\n            case \"invalid_type\": {\n                const expected = TypeDictionary[issue.expected] ?? issue.expected;\n                const receivedType = util.parsedType(issue.input);\n                const received = TypeDictionary[receivedType] ?? receivedType;\n                if (/^[A-Z]/.test(issue.expected)) {\n                    return `Rangt gildi: Þú slóst inn ${received} þar sem á að vera instanceof ${issue.expected}`;\n                }\n                return `Rangt gildi: Þú slóst inn ${received} þar sem á að vera ${expected}`;\n            }\n            case \"invalid_value\":\n                if (issue.values.length === 1)\n                    return `Rangt gildi: gert ráð fyrir ${util.stringifyPrimitive(issue.values[0])}`;\n                return `Ógilt val: má vera eitt af eftirfarandi ${util.joinValues(issue.values, \"|\")}`;\n            case \"too_big\": {\n                const adj = issue.inclusive ? \"<=\" : \"<\";\n                const sizing = getSizing(issue.origin);\n                if (sizing)\n                    return `Of stórt: gert er ráð fyrir að ${issue.origin ?? \"gildi\"} hafi ${adj}${issue.maximum.toString()} ${sizing.unit ?? \"hluti\"}`;\n                return `Of stórt: gert er ráð fyrir að ${issue.origin ?? \"gildi\"} sé ${adj}${issue.maximum.toString()}`;\n            }\n            case \"too_small\": {\n                const adj = issue.inclusive ? \">=\" : \">\";\n                const sizing = getSizing(issue.origin);\n                if (sizing) {\n                    return `Of lítið: gert er ráð fyrir að ${issue.origin} hafi ${adj}${issue.minimum.toString()} ${sizing.unit}`;\n                }\n                return `Of lítið: gert er ráð fyrir að ${issue.origin} sé ${adj}${issue.minimum.toString()}`;\n            }\n            case \"invalid_format\": {\n                const _issue = issue;\n                if (_issue.format === \"starts_with\") {\n                    return `Ógildur strengur: verður að byrja á \"${_issue.prefix}\"`;\n                }\n                if (_issue.format === \"ends_with\")\n                    return `Ógildur strengur: verður að enda á \"${_issue.suffix}\"`;\n                if (_issue.format === \"includes\")\n                    return `Ógildur strengur: verður að innihalda \"${_issue.includes}\"`;\n                if (_issue.format === \"regex\")\n                    return `Ógildur strengur: verður að fylgja mynstri ${_issue.pattern}`;\n                return `Rangt ${FormatDictionary[_issue.format] ?? issue.format}`;\n            }\n            case \"not_multiple_of\":\n                return `Röng tala: verður að vera margfeldi af ${issue.divisor}`;\n            case \"unrecognized_keys\":\n                return `Óþekkt ${issue.keys.length > 1 ? \"ir lyklar\" : \"ur lykill\"}: ${util.joinValues(issue.keys, \", \")}`;\n            case \"invalid_key\":\n                return `Rangur lykill í ${issue.origin}`;\n            case \"invalid_union\":\n                return \"Rangt gildi\";\n            case \"invalid_element\":\n                return `Rangt gildi í ${issue.origin}`;\n            default:\n                return `Rangt gildi`;\n        }\n    };\n};\nexport default function () {\n    return {\n        localeError: error(),\n    };\n}\n","import * as util from \"../core/util.js\";\nconst error = () => {\n    const Sizable = {\n        string: { unit: \"caratteri\", verb: \"avere\" },\n        file: { unit: \"byte\", verb: \"avere\" },\n        array: { unit: \"elementi\", verb: \"avere\" },\n        set: { unit: \"elementi\", verb: \"avere\" },\n    };\n    function getSizing(origin) {\n        return Sizable[origin] ?? null;\n    }\n    const FormatDictionary = {\n        regex: \"input\",\n        email: \"indirizzo email\",\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: \"data e ora ISO\",\n        date: \"data ISO\",\n        time: \"ora ISO\",\n        duration: \"durata ISO\",\n        ipv4: \"indirizzo IPv4\",\n        ipv6: \"indirizzo IPv6\",\n        cidrv4: \"intervallo IPv4\",\n        cidrv6: \"intervallo IPv6\",\n        base64: \"stringa codificata in base64\",\n        base64url: \"URL codificata in base64\",\n        json_string: \"stringa JSON\",\n        e164: \"numero E.164\",\n        jwt: \"JWT\",\n        template_literal: \"input\",\n    };\n    const TypeDictionary = {\n        nan: \"NaN\",\n        number: \"numero\",\n        array: \"vettore\",\n    };\n    return (issue) => {\n        switch (issue.code) {\n            case \"invalid_type\": {\n                const expected = TypeDictionary[issue.expected] ?? issue.expected;\n                const receivedType = util.parsedType(issue.input);\n                const received = TypeDictionary[receivedType] ?? receivedType;\n                if (/^[A-Z]/.test(issue.expected)) {\n                    return `Input non valido: atteso instanceof ${issue.expected}, ricevuto ${received}`;\n                }\n                return `Input non valido: atteso ${expected}, ricevuto ${received}`;\n            }\n            case \"invalid_value\":\n                if (issue.values.length === 1)\n                    return `Input non valido: atteso ${util.stringifyPrimitive(issue.values[0])}`;\n                return `Opzione non valida: atteso uno tra ${util.joinValues(issue.values, \"|\")}`;\n            case \"too_big\": {\n                const adj = issue.inclusive ? \"<=\" : \"<\";\n                const sizing = getSizing(issue.origin);\n                if (sizing)\n                    return `Troppo grande: ${issue.origin ?? \"valore\"} deve avere ${adj}${issue.maximum.toString()} ${sizing.unit ?? \"elementi\"}`;\n                return `Troppo grande: ${issue.origin ?? \"valore\"} deve essere ${adj}${issue.maximum.toString()}`;\n            }\n            case \"too_small\": {\n                const adj = issue.inclusive ? \">=\" : \">\";\n                const sizing = getSizing(issue.origin);\n                if (sizing) {\n                    return `Troppo piccolo: ${issue.origin} deve avere ${adj}${issue.minimum.toString()} ${sizing.unit}`;\n                }\n                return `Troppo piccolo: ${issue.origin} deve essere ${adj}${issue.minimum.toString()}`;\n            }\n            case \"invalid_format\": {\n                const _issue = issue;\n                if (_issue.format === \"starts_with\")\n                    return `Stringa non valida: deve iniziare con \"${_issue.prefix}\"`;\n                if (_issue.format === \"ends_with\")\n                    return `Stringa non valida: deve terminare con \"${_issue.suffix}\"`;\n                if (_issue.format === \"includes\")\n                    return `Stringa non valida: deve includere \"${_issue.includes}\"`;\n                if (_issue.format === \"regex\")\n                    return `Stringa non valida: deve corrispondere al pattern ${_issue.pattern}`;\n                return `Input non valido: ${FormatDictionary[_issue.format] ?? issue.format}`;\n            }\n            case \"not_multiple_of\":\n                return `Numero non valido: deve essere un multiplo di ${issue.divisor}`;\n            case \"unrecognized_keys\":\n                return `Chiav${issue.keys.length > 1 ? \"i\" : \"e\"} non riconosciut${issue.keys.length > 1 ? \"e\" : \"a\"}: ${util.joinValues(issue.keys, \", \")}`;\n            case \"invalid_key\":\n                return `Chiave non valida in ${issue.origin}`;\n            case \"invalid_union\":\n                return \"Input non valido\";\n            case \"invalid_element\":\n                return `Valore non valido in ${issue.origin}`;\n            default:\n                return `Input non valido`;\n        }\n    };\n};\nexport default function () {\n    return {\n        localeError: error(),\n    };\n}\n","import * as util from \"../core/util.js\";\nconst error = () => {\n    const Sizable = {\n        string: { unit: \"文字\", verb: \"である\" },\n        file: { unit: \"バイト\", verb: \"である\" },\n        array: { unit: \"要素\", verb: \"である\" },\n        set: { unit: \"要素\", verb: \"である\" },\n    };\n    function getSizing(origin) {\n        return Sizable[origin] ?? null;\n    }\n    const FormatDictionary = {\n        regex: \"入力値\",\n        email: \"メールアドレス\",\n        url: \"URL\",\n        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日時\",\n        date: \"ISO日付\",\n        time: \"ISO時刻\",\n        duration: \"ISO期間\",\n        ipv4: \"IPv4アドレス\",\n        ipv6: \"IPv6アドレス\",\n        cidrv4: \"IPv4範囲\",\n        cidrv6: \"IPv6範囲\",\n        base64: \"base64エンコード文字列\",\n        base64url: \"base64urlエンコード文字列\",\n        json_string: \"JSON文字列\",\n        e164: \"E.164番号\",\n        jwt: \"JWT\",\n        template_literal: \"入力値\",\n    };\n    const TypeDictionary = {\n        nan: \"NaN\",\n        number: \"数値\",\n        array: \"配列\",\n    };\n    return (issue) => {\n        switch (issue.code) {\n            case \"invalid_type\": {\n                const expected = TypeDictionary[issue.expected] ?? issue.expected;\n                const receivedType = util.parsedType(issue.input);\n                const received = TypeDictionary[receivedType] ?? receivedType;\n                if (/^[A-Z]/.test(issue.expected)) {\n                    return `無効な入力: instanceof ${issue.expected}が期待されましたが、${received}が入力されました`;\n                }\n                return `無効な入力: ${expected}が期待されましたが、${received}が入力されました`;\n            }\n            case \"invalid_value\":\n                if (issue.values.length === 1)\n                    return `無効な入力: ${util.stringifyPrimitive(issue.values[0])}が期待されました`;\n                return `無効な選択: ${util.joinValues(issue.values, \"、\")}のいずれかである必要があります`;\n            case \"too_big\": {\n                const adj = issue.inclusive ? \"以下である\" : \"より小さい\";\n                const sizing = getSizing(issue.origin);\n                if (sizing)\n                    return `大きすぎる値: ${issue.origin ?? \"値\"}は${issue.maximum.toString()}${sizing.unit ?? \"要素\"}${adj}必要があります`;\n                return `大きすぎる値: ${issue.origin ?? \"値\"}は${issue.maximum.toString()}${adj}必要があります`;\n            }\n            case \"too_small\": {\n                const adj = issue.inclusive ? \"以上である\" : \"より大きい\";\n                const sizing = getSizing(issue.origin);\n                if (sizing)\n                    return `小さすぎる値: ${issue.origin}は${issue.minimum.toString()}${sizing.unit}${adj}必要があります`;\n                return `小さすぎる値: ${issue.origin}は${issue.minimum.toString()}${adj}必要があります`;\n            }\n            case \"invalid_format\": {\n                const _issue = issue;\n                if (_issue.format === \"starts_with\")\n                    return `無効な文字列: \"${_issue.prefix}\"で始まる必要があります`;\n                if (_issue.format === \"ends_with\")\n                    return `無効な文字列: \"${_issue.suffix}\"で終わる必要があります`;\n                if (_issue.format === \"includes\")\n                    return `無効な文字列: \"${_issue.includes}\"を含む必要があります`;\n                if (_issue.format === \"regex\")\n                    return `無効な文字列: パターン${_issue.pattern}に一致する必要があります`;\n                return `無効な${FormatDictionary[_issue.format] ?? issue.format}`;\n            }\n            case \"not_multiple_of\":\n                return `無効な数値: ${issue.divisor}の倍数である必要があります`;\n            case \"unrecognized_keys\":\n                return `認識されていないキー${issue.keys.length > 1 ? \"群\" : \"\"}: ${util.joinValues(issue.keys, \"、\")}`;\n            case \"invalid_key\":\n                return `${issue.origin}内の無効なキー`;\n            case \"invalid_union\":\n                return \"無効な入力\";\n            case \"invalid_element\":\n                return `${issue.origin}内の無効な値`;\n            default:\n                return `無効な入力`;\n        }\n    };\n};\nexport default function () {\n    return {\n        localeError: error(),\n    };\n}\n","import * as util from \"../core/util.js\";\nconst error = () => {\n    const Sizable = {\n        string: { unit: \"სიმბოლო\", verb: \"უნდა შეიცავდეს\" },\n        file: { unit: \"ბაიტი\", verb: \"უნდა შეიცავდეს\" },\n        array: { unit: \"ელემენტი\", verb: \"უნდა შეიცავდეს\" },\n        set: { unit: \"ელემენტი\", verb: \"უნდა შეიცავდეს\" },\n    };\n    function getSizing(origin) {\n        return Sizable[origin] ?? null;\n    }\n    const FormatDictionary = {\n        regex: \"შეყვანა\",\n        email: \"ელ-ფოსტის მისამართი\",\n        url: \"URL\",\n        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: \"თარიღი-დრო\",\n        date: \"თარიღი\",\n        time: \"დრო\",\n        duration: \"ხანგრძლივობა\",\n        ipv4: \"IPv4 მისამართი\",\n        ipv6: \"IPv6 მისამართი\",\n        cidrv4: \"IPv4 დიაპაზონი\",\n        cidrv6: \"IPv6 დიაპაზონი\",\n        base64: \"base64-კოდირებული ველი\",\n        base64url: \"base64url-კოდირებული ველი\",\n        json_string: \"JSON ველი\",\n        e164: \"E.164 ნომერი\",\n        jwt: \"JWT\",\n        template_literal: \"შეყვანა\",\n    };\n    const TypeDictionary = {\n        nan: \"NaN\",\n        number: \"რიცხვი\",\n        string: \"ველი\",\n        boolean: \"ბულეანი\",\n        function: \"ფუნქცია\",\n        array: \"მასივი\",\n    };\n    return (issue) => {\n        switch (issue.code) {\n            case \"invalid_type\": {\n                const expected = TypeDictionary[issue.expected] ?? issue.expected;\n                const receivedType = util.parsedType(issue.input);\n                const received = TypeDictionary[receivedType] ?? receivedType;\n                if (/^[A-Z]/.test(issue.expected)) {\n                    return `არასწორი შეყვანა: მოსალოდნელი instanceof ${issue.expected}, მიღებული ${received}`;\n                }\n                return `არასწორი შეყვანა: მოსალოდნელი ${expected}, მიღებული ${received}`;\n            }\n            case \"invalid_value\":\n                if (issue.values.length === 1)\n                    return `არასწორი შეყვანა: მოსალოდნელი ${util.stringifyPrimitive(issue.values[0])}`;\n                return `არასწორი ვარიანტი: მოსალოდნელია ერთ-ერთი ${util.joinValues(issue.values, \"|\")}-დან`;\n            case \"too_big\": {\n                const adj = issue.inclusive ? \"<=\" : \"<\";\n                const sizing = getSizing(issue.origin);\n                if (sizing)\n                    return `ზედმეტად დიდი: მოსალოდნელი ${issue.origin ?? \"მნიშვნელობა\"} ${sizing.verb} ${adj}${issue.maximum.toString()} ${sizing.unit}`;\n                return `ზედმეტად დიდი: მოსალოდნელი ${issue.origin ?? \"მნიშვნელობა\"} იყოს ${adj}${issue.maximum.toString()}`;\n            }\n            case \"too_small\": {\n                const adj = issue.inclusive ? \">=\" : \">\";\n                const sizing = getSizing(issue.origin);\n                if (sizing) {\n                    return `ზედმეტად პატარა: მოსალოდნელი ${issue.origin} ${sizing.verb} ${adj}${issue.minimum.toString()} ${sizing.unit}`;\n                }\n                return `ზედმეტად პატარა: მოსალოდნელი ${issue.origin} იყოს ${adj}${issue.minimum.toString()}`;\n            }\n            case \"invalid_format\": {\n                const _issue = issue;\n                if (_issue.format === \"starts_with\") {\n                    return `არასწორი ველი: უნდა იწყებოდეს \"${_issue.prefix}\"-ით`;\n                }\n                if (_issue.format === \"ends_with\")\n                    return `არასწორი ველი: უნდა მთავრდებოდეს \"${_issue.suffix}\"-ით`;\n                if (_issue.format === \"includes\")\n                    return `არასწორი ველი: უნდა შეიცავდეს \"${_issue.includes}\"-ს`;\n                if (_issue.format === \"regex\")\n                    return `არასწორი ველი: უნდა შეესაბამებოდეს შაბლონს ${_issue.pattern}`;\n                return `არასწორი ${FormatDictionary[_issue.format] ?? issue.format}`;\n            }\n            case \"not_multiple_of\":\n                return `არასწორი რიცხვი: უნდა იყოს ${issue.divisor}-ის ჯერადი`;\n            case \"unrecognized_keys\":\n                return `უცნობი გასაღებ${issue.keys.length > 1 ? \"ები\" : \"ი\"}: ${util.joinValues(issue.keys, \", \")}`;\n            case \"invalid_key\":\n                return `არასწორი გასაღები ${issue.origin}-ში`;\n            case \"invalid_union\":\n                return \"არასწორი შეყვანა\";\n            case \"invalid_element\":\n                return `არასწორი მნიშვნელობა ${issue.origin}-ში`;\n            default:\n                return `არასწორი შეყვანა`;\n        }\n    };\n};\nexport default function () {\n    return {\n        localeError: error(),\n    };\n}\n","import * as util from \"../core/util.js\";\nconst error = () => {\n    const Sizable = {\n        string: { unit: \"តួអក្សរ\", verb: \"គួរមាន\" },\n        file: { unit: \"បៃ\", verb: \"គួរមាន\" },\n        array: { unit: \"ធាតុ\", verb: \"គួរមាន\" },\n        set: { unit: \"ធាតុ\", verb: \"គួរមាន\" },\n    };\n    function getSizing(origin) {\n        return Sizable[origin] ?? null;\n    }\n    const FormatDictionary = {\n        regex: \"ទិន្នន័យបញ្ចូល\",\n        email: \"អាសយដ្ឋានអ៊ីមែល\",\n        url: \"URL\",\n        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\",\n        date: \"កាលបរិច្ឆេទ ISO\",\n        time: \"ម៉ោង ISO\",\n        duration: \"រយៈពេល ISO\",\n        ipv4: \"អាសយដ្ឋាន IPv4\",\n        ipv6: \"អាសយដ្ឋាន IPv6\",\n        cidrv4: \"ដែនអាសយដ្ឋាន IPv4\",\n        cidrv6: \"ដែនអាសយដ្ឋាន IPv6\",\n        base64: \"ខ្សែអក្សរអ៊ិកូដ base64\",\n        base64url: \"ខ្សែអក្សរអ៊ិកូដ base64url\",\n        json_string: \"ខ្សែអក្សរ JSON\",\n        e164: \"លេខ E.164\",\n        jwt: \"JWT\",\n        template_literal: \"ទិន្នន័យបញ្ចូល\",\n    };\n    const TypeDictionary = {\n        nan: \"NaN\",\n        number: \"លេខ\",\n        array: \"អារេ (Array)\",\n        null: \"គ្មានតម្លៃ (null)\",\n    };\n    return (issue) => {\n        switch (issue.code) {\n            case \"invalid_type\": {\n                const expected = TypeDictionary[issue.expected] ?? issue.expected;\n                const receivedType = util.parsedType(issue.input);\n                const received = TypeDictionary[receivedType] ?? receivedType;\n                if (/^[A-Z]/.test(issue.expected)) {\n                    return `ទិន្នន័យបញ្ចូលមិនត្រឹមត្រូវ៖ ត្រូវការ instanceof ${issue.expected} ប៉ុន្តែទទួលបាន ${received}`;\n                }\n                return `ទិន្នន័យបញ្ចូលមិនត្រឹមត្រូវ៖ ត្រូវការ ${expected} ប៉ុន្តែទទួលបាន ${received}`;\n            }\n            case \"invalid_value\":\n                if (issue.values.length === 1)\n                    return `ទិន្នន័យបញ្ចូលមិនត្រឹមត្រូវ៖ ត្រូវការ ${util.stringifyPrimitive(issue.values[0])}`;\n                return `ជម្រើសមិនត្រឹមត្រូវ៖ ត្រូវជាមួយក្នុងចំណោម ${util.joinValues(issue.values, \"|\")}`;\n            case \"too_big\": {\n                const adj = issue.inclusive ? \"<=\" : \"<\";\n                const sizing = getSizing(issue.origin);\n                if (sizing)\n                    return `ធំពេក៖ ត្រូវការ ${issue.origin ?? \"តម្លៃ\"} ${adj} ${issue.maximum.toString()} ${sizing.unit ?? \"ធាតុ\"}`;\n                return `ធំពេក៖ ត្រូវការ ${issue.origin ?? \"តម្លៃ\"} ${adj} ${issue.maximum.toString()}`;\n            }\n            case \"too_small\": {\n                const adj = issue.inclusive ? \">=\" : \">\";\n                const sizing = getSizing(issue.origin);\n                if (sizing) {\n                    return `តូចពេក៖ ត្រូវការ ${issue.origin} ${adj} ${issue.minimum.toString()} ${sizing.unit}`;\n                }\n                return `តូចពេក៖ ត្រូវការ ${issue.origin} ${adj} ${issue.minimum.toString()}`;\n            }\n            case \"invalid_format\": {\n                const _issue = issue;\n                if (_issue.format === \"starts_with\") {\n                    return `ខ្សែអក្សរមិនត្រឹមត្រូវ៖ ត្រូវចាប់ផ្តើមដោយ \"${_issue.prefix}\"`;\n                }\n                if (_issue.format === \"ends_with\")\n                    return `ខ្សែអក្សរមិនត្រឹមត្រូវ៖ ត្រូវបញ្ចប់ដោយ \"${_issue.suffix}\"`;\n                if (_issue.format === \"includes\")\n                    return `ខ្សែអក្សរមិនត្រឹមត្រូវ៖ ត្រូវមាន \"${_issue.includes}\"`;\n                if (_issue.format === \"regex\")\n                    return `ខ្សែអក្សរមិនត្រឹមត្រូវ៖ ត្រូវតែផ្គូផ្គងនឹងទម្រង់ដែលបានកំណត់ ${_issue.pattern}`;\n                return `មិនត្រឹមត្រូវ៖ ${FormatDictionary[_issue.format] ?? issue.format}`;\n            }\n            case \"not_multiple_of\":\n                return `លេខមិនត្រឹមត្រូវ៖ ត្រូវតែជាពហុគុណនៃ ${issue.divisor}`;\n            case \"unrecognized_keys\":\n                return `រកឃើញសោមិនស្គាល់៖ ${util.joinValues(issue.keys, \", \")}`;\n            case \"invalid_key\":\n                return `សោមិនត្រឹមត្រូវនៅក្នុង ${issue.origin}`;\n            case \"invalid_union\":\n                return `ទិន្នន័យមិនត្រឹមត្រូវ`;\n            case \"invalid_element\":\n                return `ទិន្នន័យមិនត្រឹមត្រូវនៅក្នុង ${issue.origin}`;\n            default:\n                return `ទិន្នន័យមិនត្រឹមត្រូវ`;\n        }\n    };\n};\nexport default function () {\n    return {\n        localeError: error(),\n    };\n}\n","import km from \"./km.js\";\n/** @deprecated Use `km` instead. */\nexport default function () {\n    return km();\n}\n","import * as util from \"../core/util.js\";\nconst error = () => {\n    const Sizable = {\n        string: { unit: \"문자\", verb: \"to have\" },\n        file: { unit: \"바이트\", verb: \"to have\" },\n        array: { unit: \"개\", verb: \"to have\" },\n        set: { unit: \"개\", verb: \"to have\" },\n    };\n    function getSizing(origin) {\n        return Sizable[origin] ?? null;\n    }\n    const FormatDictionary = {\n        regex: \"입력\",\n        email: \"이메일 주소\",\n        url: \"URL\",\n        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 날짜시간\",\n        date: \"ISO 날짜\",\n        time: \"ISO 시간\",\n        duration: \"ISO 기간\",\n        ipv4: \"IPv4 주소\",\n        ipv6: \"IPv6 주소\",\n        cidrv4: \"IPv4 범위\",\n        cidrv6: \"IPv6 범위\",\n        base64: \"base64 인코딩 문자열\",\n        base64url: \"base64url 인코딩 문자열\",\n        json_string: \"JSON 문자열\",\n        e164: \"E.164 번호\",\n        jwt: \"JWT\",\n        template_literal: \"입력\",\n    };\n    const TypeDictionary = {\n        nan: \"NaN\",\n    };\n    return (issue) => {\n        switch (issue.code) {\n            case \"invalid_type\": {\n                const expected = TypeDictionary[issue.expected] ?? issue.expected;\n                const receivedType = util.parsedType(issue.input);\n                const received = TypeDictionary[receivedType] ?? receivedType;\n                if (/^[A-Z]/.test(issue.expected)) {\n                    return `잘못된 입력: 예상 타입은 instanceof ${issue.expected}, 받은 타입은 ${received}입니다`;\n                }\n                return `잘못된 입력: 예상 타입은 ${expected}, 받은 타입은 ${received}입니다`;\n            }\n            case \"invalid_value\":\n                if (issue.values.length === 1)\n                    return `잘못된 입력: 값은 ${util.stringifyPrimitive(issue.values[0])} 이어야 합니다`;\n                return `잘못된 옵션: ${util.joinValues(issue.values, \"또는 \")} 중 하나여야 합니다`;\n            case \"too_big\": {\n                const adj = issue.inclusive ? \"이하\" : \"미만\";\n                const suffix = adj === \"미만\" ? \"이어야 합니다\" : \"여야 합니다\";\n                const sizing = getSizing(issue.origin);\n                const unit = sizing?.unit ?? \"요소\";\n                if (sizing)\n                    return `${issue.origin ?? \"값\"}이 너무 큽니다: ${issue.maximum.toString()}${unit} ${adj}${suffix}`;\n                return `${issue.origin ?? \"값\"}이 너무 큽니다: ${issue.maximum.toString()} ${adj}${suffix}`;\n            }\n            case \"too_small\": {\n                const adj = issue.inclusive ? \"이상\" : \"초과\";\n                const suffix = adj === \"이상\" ? \"이어야 합니다\" : \"여야 합니다\";\n                const sizing = getSizing(issue.origin);\n                const unit = sizing?.unit ?? \"요소\";\n                if (sizing) {\n                    return `${issue.origin ?? \"값\"}이 너무 작습니다: ${issue.minimum.toString()}${unit} ${adj}${suffix}`;\n                }\n                return `${issue.origin ?? \"값\"}이 너무 작습니다: ${issue.minimum.toString()} ${adj}${suffix}`;\n            }\n            case \"invalid_format\": {\n                const _issue = issue;\n                if (_issue.format === \"starts_with\") {\n                    return `잘못된 문자열: \"${_issue.prefix}\"(으)로 시작해야 합니다`;\n                }\n                if (_issue.format === \"ends_with\")\n                    return `잘못된 문자열: \"${_issue.suffix}\"(으)로 끝나야 합니다`;\n                if (_issue.format === \"includes\")\n                    return `잘못된 문자열: \"${_issue.includes}\"을(를) 포함해야 합니다`;\n                if (_issue.format === \"regex\")\n                    return `잘못된 문자열: 정규식 ${_issue.pattern} 패턴과 일치해야 합니다`;\n                return `잘못된 ${FormatDictionary[_issue.format] ?? issue.format}`;\n            }\n            case \"not_multiple_of\":\n                return `잘못된 숫자: ${issue.divisor}의 배수여야 합니다`;\n            case \"unrecognized_keys\":\n                return `인식할 수 없는 키: ${util.joinValues(issue.keys, \", \")}`;\n            case \"invalid_key\":\n                return `잘못된 키: ${issue.origin}`;\n            case \"invalid_union\":\n                return `잘못된 입력`;\n            case \"invalid_element\":\n                return `잘못된 값: ${issue.origin}`;\n            default:\n                return `잘못된 입력`;\n        }\n    };\n};\nexport default function () {\n    return {\n        localeError: error(),\n    };\n}\n","import * as util from \"../core/util.js\";\nconst capitalizeFirstCharacter = (text) => {\n    return text.charAt(0).toUpperCase() + text.slice(1);\n};\nfunction getUnitTypeFromNumber(number) {\n    const abs = Math.abs(number);\n    const last = abs % 10;\n    const last2 = abs % 100;\n    if ((last2 >= 11 && last2 <= 19) || last === 0)\n        return \"many\";\n    if (last === 1)\n        return \"one\";\n    return \"few\";\n}\nconst error = () => {\n    const Sizable = {\n        string: {\n            unit: {\n                one: \"simbolis\",\n                few: \"simboliai\",\n                many: \"simbolių\",\n            },\n            verb: {\n                smaller: {\n                    inclusive: \"turi būti ne ilgesnė kaip\",\n                    notInclusive: \"turi būti trumpesnė kaip\",\n                },\n                bigger: {\n                    inclusive: \"turi būti ne trumpesnė kaip\",\n                    notInclusive: \"turi būti ilgesnė kaip\",\n                },\n            },\n        },\n        file: {\n            unit: {\n                one: \"baitas\",\n                few: \"baitai\",\n                many: \"baitų\",\n            },\n            verb: {\n                smaller: {\n                    inclusive: \"turi būti ne didesnis kaip\",\n                    notInclusive: \"turi būti mažesnis kaip\",\n                },\n                bigger: {\n                    inclusive: \"turi būti ne mažesnis kaip\",\n                    notInclusive: \"turi būti didesnis kaip\",\n                },\n            },\n        },\n        array: {\n            unit: {\n                one: \"elementą\",\n                few: \"elementus\",\n                many: \"elementų\",\n            },\n            verb: {\n                smaller: {\n                    inclusive: \"turi turėti ne daugiau kaip\",\n                    notInclusive: \"turi turėti mažiau kaip\",\n                },\n                bigger: {\n                    inclusive: \"turi turėti ne mažiau kaip\",\n                    notInclusive: \"turi turėti daugiau kaip\",\n                },\n            },\n        },\n        set: {\n            unit: {\n                one: \"elementą\",\n                few: \"elementus\",\n                many: \"elementų\",\n            },\n            verb: {\n                smaller: {\n                    inclusive: \"turi turėti ne daugiau kaip\",\n                    notInclusive: \"turi turėti mažiau kaip\",\n                },\n                bigger: {\n                    inclusive: \"turi turėti ne mažiau kaip\",\n                    notInclusive: \"turi turėti daugiau kaip\",\n                },\n            },\n        },\n    };\n    function getSizing(origin, unitType, inclusive, targetShouldBe) {\n        const result = Sizable[origin] ?? null;\n        if (result === null)\n            return result;\n        return {\n            unit: result.unit[unitType],\n            verb: result.verb[targetShouldBe][inclusive ? \"inclusive\" : \"notInclusive\"],\n        };\n    }\n    const FormatDictionary = {\n        regex: \"įvestis\",\n        email: \"el. pašto adresas\",\n        url: \"URL\",\n        emoji: \"jaustukas\",\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 data ir laikas\",\n        date: \"ISO data\",\n        time: \"ISO laikas\",\n        duration: \"ISO trukmė\",\n        ipv4: \"IPv4 adresas\",\n        ipv6: \"IPv6 adresas\",\n        cidrv4: \"IPv4 tinklo prefiksas (CIDR)\",\n        cidrv6: \"IPv6 tinklo prefiksas (CIDR)\",\n        base64: \"base64 užkoduota eilutė\",\n        base64url: \"base64url užkoduota eilutė\",\n        json_string: \"JSON eilutė\",\n        e164: \"E.164 numeris\",\n        jwt: \"JWT\",\n        template_literal: \"įvestis\",\n    };\n    const TypeDictionary = {\n        nan: \"NaN\",\n        number: \"skaičius\",\n        bigint: \"sveikasis skaičius\",\n        string: \"eilutė\",\n        boolean: \"loginė reikšmė\",\n        undefined: \"neapibrėžta reikšmė\",\n        function: \"funkcija\",\n        symbol: \"simbolis\",\n        array: \"masyvas\",\n        object: \"objektas\",\n        null: \"nulinė reikšmė\",\n    };\n    return (issue) => {\n        switch (issue.code) {\n            case \"invalid_type\": {\n                const expected = TypeDictionary[issue.expected] ?? issue.expected;\n                const receivedType = util.parsedType(issue.input);\n                const received = TypeDictionary[receivedType] ?? receivedType;\n                if (/^[A-Z]/.test(issue.expected)) {\n                    return `Gautas tipas ${received}, o tikėtasi - instanceof ${issue.expected}`;\n                }\n                return `Gautas tipas ${received}, o tikėtasi - ${expected}`;\n            }\n            case \"invalid_value\":\n                if (issue.values.length === 1)\n                    return `Privalo būti ${util.stringifyPrimitive(issue.values[0])}`;\n                return `Privalo būti vienas iš ${util.joinValues(issue.values, \"|\")} pasirinkimų`;\n            case \"too_big\": {\n                const origin = TypeDictionary[issue.origin] ?? issue.origin;\n                const sizing = getSizing(issue.origin, getUnitTypeFromNumber(Number(issue.maximum)), issue.inclusive ?? false, \"smaller\");\n                if (sizing?.verb)\n                    return `${capitalizeFirstCharacter(origin ?? issue.origin ?? \"reikšmė\")} ${sizing.verb} ${issue.maximum.toString()} ${sizing.unit ?? \"elementų\"}`;\n                const adj = issue.inclusive ? \"ne didesnis kaip\" : \"mažesnis kaip\";\n                return `${capitalizeFirstCharacter(origin ?? issue.origin ?? \"reikšmė\")} turi būti ${adj} ${issue.maximum.toString()} ${sizing?.unit}`;\n            }\n            case \"too_small\": {\n                const origin = TypeDictionary[issue.origin] ?? issue.origin;\n                const sizing = getSizing(issue.origin, getUnitTypeFromNumber(Number(issue.minimum)), issue.inclusive ?? false, \"bigger\");\n                if (sizing?.verb)\n                    return `${capitalizeFirstCharacter(origin ?? issue.origin ?? \"reikšmė\")} ${sizing.verb} ${issue.minimum.toString()} ${sizing.unit ?? \"elementų\"}`;\n                const adj = issue.inclusive ? \"ne mažesnis kaip\" : \"didesnis kaip\";\n                return `${capitalizeFirstCharacter(origin ?? issue.origin ?? \"reikšmė\")} turi būti ${adj} ${issue.minimum.toString()} ${sizing?.unit}`;\n            }\n            case \"invalid_format\": {\n                const _issue = issue;\n                if (_issue.format === \"starts_with\") {\n                    return `Eilutė privalo prasidėti \"${_issue.prefix}\"`;\n                }\n                if (_issue.format === \"ends_with\")\n                    return `Eilutė privalo pasibaigti \"${_issue.suffix}\"`;\n                if (_issue.format === \"includes\")\n                    return `Eilutė privalo įtraukti \"${_issue.includes}\"`;\n                if (_issue.format === \"regex\")\n                    return `Eilutė privalo atitikti ${_issue.pattern}`;\n                return `Neteisingas ${FormatDictionary[_issue.format] ?? issue.format}`;\n            }\n            case \"not_multiple_of\":\n                return `Skaičius privalo būti ${issue.divisor} kartotinis.`;\n            case \"unrecognized_keys\":\n                return `Neatpažint${issue.keys.length > 1 ? \"i\" : \"as\"} rakt${issue.keys.length > 1 ? \"ai\" : \"as\"}: ${util.joinValues(issue.keys, \", \")}`;\n            case \"invalid_key\":\n                return \"Rastas klaidingas raktas\";\n            case \"invalid_union\":\n                return \"Klaidinga įvestis\";\n            case \"invalid_element\": {\n                const origin = TypeDictionary[issue.origin] ?? issue.origin;\n                return `${capitalizeFirstCharacter(origin ?? issue.origin ?? \"reikšmė\")} turi klaidingą įvestį`;\n            }\n            default:\n                return \"Klaidinga įvestis\";\n        }\n    };\n};\nexport default function () {\n    return {\n        localeError: error(),\n    };\n}\n","import * as util from \"../core/util.js\";\nconst error = () => {\n    const Sizable = {\n        string: { unit: \"знаци\", verb: \"да имаат\" },\n        file: { unit: \"бајти\", verb: \"да имаат\" },\n        array: { unit: \"ставки\", verb: \"да имаат\" },\n        set: { unit: \"ставки\", verb: \"да имаат\" },\n    };\n    function getSizing(origin) {\n        return Sizable[origin] ?? null;\n    }\n    const FormatDictionary = {\n        regex: \"внес\",\n        email: \"адреса на е-пошта\",\n        url: \"URL\",\n        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 датум и време\",\n        date: \"ISO датум\",\n        time: \"ISO време\",\n        duration: \"ISO времетраење\",\n        ipv4: \"IPv4 адреса\",\n        ipv6: \"IPv6 адреса\",\n        cidrv4: \"IPv4 опсег\",\n        cidrv6: \"IPv6 опсег\",\n        base64: \"base64-енкодирана низа\",\n        base64url: \"base64url-енкодирана низа\",\n        json_string: \"JSON низа\",\n        e164: \"E.164 број\",\n        jwt: \"JWT\",\n        template_literal: \"внес\",\n    };\n    const TypeDictionary = {\n        nan: \"NaN\",\n        number: \"број\",\n        array: \"низа\",\n    };\n    return (issue) => {\n        switch (issue.code) {\n            case \"invalid_type\": {\n                const expected = TypeDictionary[issue.expected] ?? issue.expected;\n                const receivedType = util.parsedType(issue.input);\n                const received = TypeDictionary[receivedType] ?? receivedType;\n                if (/^[A-Z]/.test(issue.expected)) {\n                    return `Грешен внес: се очекува instanceof ${issue.expected}, примено ${received}`;\n                }\n                return `Грешен внес: се очекува ${expected}, примено ${received}`;\n            }\n            case \"invalid_value\":\n                if (issue.values.length === 1)\n                    return `Invalid input: expected ${util.stringifyPrimitive(issue.values[0])}`;\n                return `Грешана опција: се очекува една ${util.joinValues(issue.values, \"|\")}`;\n            case \"too_big\": {\n                const adj = issue.inclusive ? \"<=\" : \"<\";\n                const sizing = getSizing(issue.origin);\n                if (sizing)\n                    return `Премногу голем: се очекува ${issue.origin ?? \"вредноста\"} да има ${adj}${issue.maximum.toString()} ${sizing.unit ?? \"елементи\"}`;\n                return `Премногу голем: се очекува ${issue.origin ?? \"вредноста\"} да биде ${adj}${issue.maximum.toString()}`;\n            }\n            case \"too_small\": {\n                const adj = issue.inclusive ? \">=\" : \">\";\n                const sizing = getSizing(issue.origin);\n                if (sizing) {\n                    return `Премногу мал: се очекува ${issue.origin} да има ${adj}${issue.minimum.toString()} ${sizing.unit}`;\n                }\n                return `Премногу мал: се очекува ${issue.origin} да биде ${adj}${issue.minimum.toString()}`;\n            }\n            case \"invalid_format\": {\n                const _issue = issue;\n                if (_issue.format === \"starts_with\") {\n                    return `Неважечка низа: мора да започнува со \"${_issue.prefix}\"`;\n                }\n                if (_issue.format === \"ends_with\")\n                    return `Неважечка низа: мора да завршува со \"${_issue.suffix}\"`;\n                if (_issue.format === \"includes\")\n                    return `Неважечка низа: мора да вклучува \"${_issue.includes}\"`;\n                if (_issue.format === \"regex\")\n                    return `Неважечка низа: мора да одгоара на патернот ${_issue.pattern}`;\n                return `Invalid ${FormatDictionary[_issue.format] ?? issue.format}`;\n            }\n            case \"not_multiple_of\":\n                return `Грешен број: мора да биде делив со ${issue.divisor}`;\n            case \"unrecognized_keys\":\n                return `${issue.keys.length > 1 ? \"Непрепознаени клучеви\" : \"Непрепознаен клуч\"}: ${util.joinValues(issue.keys, \", \")}`;\n            case \"invalid_key\":\n                return `Грешен клуч во ${issue.origin}`;\n            case \"invalid_union\":\n                return \"Грешен внес\";\n            case \"invalid_element\":\n                return `Грешна вредност во ${issue.origin}`;\n            default:\n                return `Грешен внес`;\n        }\n    };\n};\nexport default function () {\n    return {\n        localeError: error(),\n    };\n}\n","import * as util from \"../core/util.js\";\nconst error = () => {\n    const Sizable = {\n        string: { unit: \"aksara\", verb: \"mempunyai\" },\n        file: { unit: \"bait\", verb: \"mempunyai\" },\n        array: { unit: \"elemen\", verb: \"mempunyai\" },\n        set: { unit: \"elemen\", verb: \"mempunyai\" },\n    };\n    function getSizing(origin) {\n        return Sizable[origin] ?? null;\n    }\n    const FormatDictionary = {\n        regex: \"input\",\n        email: \"alamat e-mel\",\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: \"tarikh masa ISO\",\n        date: \"tarikh ISO\",\n        time: \"masa ISO\",\n        duration: \"tempoh ISO\",\n        ipv4: \"alamat IPv4\",\n        ipv6: \"alamat IPv6\",\n        cidrv4: \"julat IPv4\",\n        cidrv6: \"julat IPv6\",\n        base64: \"string dikodkan base64\",\n        base64url: \"string dikodkan base64url\",\n        json_string: \"string JSON\",\n        e164: \"nombor E.164\",\n        jwt: \"JWT\",\n        template_literal: \"input\",\n    };\n    const TypeDictionary = {\n        nan: \"NaN\",\n        number: \"nombor\",\n    };\n    return (issue) => {\n        switch (issue.code) {\n            case \"invalid_type\": {\n                const expected = TypeDictionary[issue.expected] ?? issue.expected;\n                const receivedType = util.parsedType(issue.input);\n                const received = TypeDictionary[receivedType] ?? receivedType;\n                if (/^[A-Z]/.test(issue.expected)) {\n                    return `Input tidak sah: dijangka instanceof ${issue.expected}, diterima ${received}`;\n                }\n                return `Input tidak sah: dijangka ${expected}, diterima ${received}`;\n            }\n            case \"invalid_value\":\n                if (issue.values.length === 1)\n                    return `Input tidak sah: dijangka ${util.stringifyPrimitive(issue.values[0])}`;\n                return `Pilihan tidak sah: dijangka salah satu daripada ${util.joinValues(issue.values, \"|\")}`;\n            case \"too_big\": {\n                const adj = issue.inclusive ? \"<=\" : \"<\";\n                const sizing = getSizing(issue.origin);\n                if (sizing)\n                    return `Terlalu besar: dijangka ${issue.origin ?? \"nilai\"} ${sizing.verb} ${adj}${issue.maximum.toString()} ${sizing.unit ?? \"elemen\"}`;\n                return `Terlalu besar: dijangka ${issue.origin ?? \"nilai\"} adalah ${adj}${issue.maximum.toString()}`;\n            }\n            case \"too_small\": {\n                const adj = issue.inclusive ? \">=\" : \">\";\n                const sizing = getSizing(issue.origin);\n                if (sizing) {\n                    return `Terlalu kecil: dijangka ${issue.origin} ${sizing.verb} ${adj}${issue.minimum.toString()} ${sizing.unit}`;\n                }\n                return `Terlalu kecil: dijangka ${issue.origin} adalah ${adj}${issue.minimum.toString()}`;\n            }\n            case \"invalid_format\": {\n                const _issue = issue;\n                if (_issue.format === \"starts_with\")\n                    return `String tidak sah: mesti bermula dengan \"${_issue.prefix}\"`;\n                if (_issue.format === \"ends_with\")\n                    return `String tidak sah: mesti berakhir dengan \"${_issue.suffix}\"`;\n                if (_issue.format === \"includes\")\n                    return `String tidak sah: mesti mengandungi \"${_issue.includes}\"`;\n                if (_issue.format === \"regex\")\n                    return `String tidak sah: mesti sepadan dengan corak ${_issue.pattern}`;\n                return `${FormatDictionary[_issue.format] ?? issue.format} tidak sah`;\n            }\n            case \"not_multiple_of\":\n                return `Nombor tidak sah: perlu gandaan ${issue.divisor}`;\n            case \"unrecognized_keys\":\n                return `Kunci tidak dikenali: ${util.joinValues(issue.keys, \", \")}`;\n            case \"invalid_key\":\n                return `Kunci tidak sah dalam ${issue.origin}`;\n            case \"invalid_union\":\n                return \"Input tidak sah\";\n            case \"invalid_element\":\n                return `Nilai tidak sah dalam ${issue.origin}`;\n            default:\n                return `Input tidak sah`;\n        }\n    };\n};\nexport default function () {\n    return {\n        localeError: error(),\n    };\n}\n","import * as util from \"../core/util.js\";\nconst error = () => {\n    const Sizable = {\n        string: { unit: \"tekens\", verb: \"heeft\" },\n        file: { unit: \"bytes\", verb: \"heeft\" },\n        array: { unit: \"elementen\", verb: \"heeft\" },\n        set: { unit: \"elementen\", verb: \"heeft\" },\n    };\n    function getSizing(origin) {\n        return Sizable[origin] ?? null;\n    }\n    const FormatDictionary = {\n        regex: \"invoer\",\n        email: \"emailadres\",\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 datum en tijd\",\n        date: \"ISO datum\",\n        time: \"ISO tijd\",\n        duration: \"ISO duur\",\n        ipv4: \"IPv4-adres\",\n        ipv6: \"IPv6-adres\",\n        cidrv4: \"IPv4-bereik\",\n        cidrv6: \"IPv6-bereik\",\n        base64: \"base64-gecodeerde tekst\",\n        base64url: \"base64 URL-gecodeerde tekst\",\n        json_string: \"JSON string\",\n        e164: \"E.164-nummer\",\n        jwt: \"JWT\",\n        template_literal: \"invoer\",\n    };\n    const TypeDictionary = {\n        nan: \"NaN\",\n        number: \"getal\",\n    };\n    return (issue) => {\n        switch (issue.code) {\n            case \"invalid_type\": {\n                const expected = TypeDictionary[issue.expected] ?? issue.expected;\n                const receivedType = util.parsedType(issue.input);\n                const received = TypeDictionary[receivedType] ?? receivedType;\n                if (/^[A-Z]/.test(issue.expected)) {\n                    return `Ongeldige invoer: verwacht instanceof ${issue.expected}, ontving ${received}`;\n                }\n                return `Ongeldige invoer: verwacht ${expected}, ontving ${received}`;\n            }\n            case \"invalid_value\":\n                if (issue.values.length === 1)\n                    return `Ongeldige invoer: verwacht ${util.stringifyPrimitive(issue.values[0])}`;\n                return `Ongeldige optie: verwacht één van ${util.joinValues(issue.values, \"|\")}`;\n            case \"too_big\": {\n                const adj = issue.inclusive ? \"<=\" : \"<\";\n                const sizing = getSizing(issue.origin);\n                const longName = issue.origin === \"date\" ? \"laat\" : issue.origin === \"string\" ? \"lang\" : \"groot\";\n                if (sizing)\n                    return `Te ${longName}: verwacht dat ${issue.origin ?? \"waarde\"} ${adj}${issue.maximum.toString()} ${sizing.unit ?? \"elementen\"} ${sizing.verb}`;\n                return `Te ${longName}: verwacht dat ${issue.origin ?? \"waarde\"} ${adj}${issue.maximum.toString()} is`;\n            }\n            case \"too_small\": {\n                const adj = issue.inclusive ? \">=\" : \">\";\n                const sizing = getSizing(issue.origin);\n                const shortName = issue.origin === \"date\" ? \"vroeg\" : issue.origin === \"string\" ? \"kort\" : \"klein\";\n                if (sizing) {\n                    return `Te ${shortName}: verwacht dat ${issue.origin} ${adj}${issue.minimum.toString()} ${sizing.unit} ${sizing.verb}`;\n                }\n                return `Te ${shortName}: verwacht dat ${issue.origin} ${adj}${issue.minimum.toString()} is`;\n            }\n            case \"invalid_format\": {\n                const _issue = issue;\n                if (_issue.format === \"starts_with\") {\n                    return `Ongeldige tekst: moet met \"${_issue.prefix}\" beginnen`;\n                }\n                if (_issue.format === \"ends_with\")\n                    return `Ongeldige tekst: moet op \"${_issue.suffix}\" eindigen`;\n                if (_issue.format === \"includes\")\n                    return `Ongeldige tekst: moet \"${_issue.includes}\" bevatten`;\n                if (_issue.format === \"regex\")\n                    return `Ongeldige tekst: moet overeenkomen met patroon ${_issue.pattern}`;\n                return `Ongeldig: ${FormatDictionary[_issue.format] ?? issue.format}`;\n            }\n            case \"not_multiple_of\":\n                return `Ongeldig getal: moet een veelvoud van ${issue.divisor} zijn`;\n            case \"unrecognized_keys\":\n                return `Onbekende key${issue.keys.length > 1 ? \"s\" : \"\"}: ${util.joinValues(issue.keys, \", \")}`;\n            case \"invalid_key\":\n                return `Ongeldige key in ${issue.origin}`;\n            case \"invalid_union\":\n                return \"Ongeldige invoer\";\n            case \"invalid_element\":\n                return `Ongeldige waarde in ${issue.origin}`;\n            default:\n                return `Ongeldige invoer`;\n        }\n    };\n};\nexport default function () {\n    return {\n        localeError: error(),\n    };\n}\n","import * as util from \"../core/util.js\";\nconst error = () => {\n    const Sizable = {\n        string: { unit: \"tegn\", verb: \"å ha\" },\n        file: { unit: \"bytes\", verb: \"å ha\" },\n        array: { unit: \"elementer\", verb: \"å inneholde\" },\n        set: { unit: \"elementer\", verb: \"å inneholde\" },\n    };\n    function getSizing(origin) {\n        return Sizable[origin] ?? null;\n    }\n    const FormatDictionary = {\n        regex: \"input\",\n        email: \"e-postadresse\",\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 dato- og klokkeslett\",\n        date: \"ISO-dato\",\n        time: \"ISO-klokkeslett\",\n        duration: \"ISO-varighet\",\n        ipv4: \"IPv4-område\",\n        ipv6: \"IPv6-område\",\n        cidrv4: \"IPv4-spekter\",\n        cidrv6: \"IPv6-spekter\",\n        base64: \"base64-enkodet streng\",\n        base64url: \"base64url-enkodet streng\",\n        json_string: \"JSON-streng\",\n        e164: \"E.164-nummer\",\n        jwt: \"JWT\",\n        template_literal: \"input\",\n    };\n    const TypeDictionary = {\n        nan: \"NaN\",\n        number: \"tall\",\n        array: \"liste\",\n    };\n    return (issue) => {\n        switch (issue.code) {\n            case \"invalid_type\": {\n                const expected = TypeDictionary[issue.expected] ?? issue.expected;\n                const receivedType = util.parsedType(issue.input);\n                const received = TypeDictionary[receivedType] ?? receivedType;\n                if (/^[A-Z]/.test(issue.expected)) {\n                    return `Ugyldig input: forventet instanceof ${issue.expected}, fikk ${received}`;\n                }\n                return `Ugyldig input: forventet ${expected}, fikk ${received}`;\n            }\n            case \"invalid_value\":\n                if (issue.values.length === 1)\n                    return `Ugyldig verdi: forventet ${util.stringifyPrimitive(issue.values[0])}`;\n                return `Ugyldig valg: forventet en av ${util.joinValues(issue.values, \"|\")}`;\n            case \"too_big\": {\n                const adj = issue.inclusive ? \"<=\" : \"<\";\n                const sizing = getSizing(issue.origin);\n                if (sizing)\n                    return `For stor(t): forventet ${issue.origin ?? \"value\"} til å ha ${adj}${issue.maximum.toString()} ${sizing.unit ?? \"elementer\"}`;\n                return `For stor(t): forventet ${issue.origin ?? \"value\"} til å ha ${adj}${issue.maximum.toString()}`;\n            }\n            case \"too_small\": {\n                const adj = issue.inclusive ? \">=\" : \">\";\n                const sizing = getSizing(issue.origin);\n                if (sizing) {\n                    return `For lite(n): forventet ${issue.origin} til å ha ${adj}${issue.minimum.toString()} ${sizing.unit}`;\n                }\n                return `For lite(n): forventet ${issue.origin} til å ha ${adj}${issue.minimum.toString()}`;\n            }\n            case \"invalid_format\": {\n                const _issue = issue;\n                if (_issue.format === \"starts_with\")\n                    return `Ugyldig streng: må starte med \"${_issue.prefix}\"`;\n                if (_issue.format === \"ends_with\")\n                    return `Ugyldig streng: må ende med \"${_issue.suffix}\"`;\n                if (_issue.format === \"includes\")\n                    return `Ugyldig streng: må inneholde \"${_issue.includes}\"`;\n                if (_issue.format === \"regex\")\n                    return `Ugyldig streng: må matche mønsteret ${_issue.pattern}`;\n                return `Ugyldig ${FormatDictionary[_issue.format] ?? issue.format}`;\n            }\n            case \"not_multiple_of\":\n                return `Ugyldig tall: må være et multiplum av ${issue.divisor}`;\n            case \"unrecognized_keys\":\n                return `${issue.keys.length > 1 ? \"Ukjente nøkler\" : \"Ukjent nøkkel\"}: ${util.joinValues(issue.keys, \", \")}`;\n            case \"invalid_key\":\n                return `Ugyldig nøkkel i ${issue.origin}`;\n            case \"invalid_union\":\n                return \"Ugyldig input\";\n            case \"invalid_element\":\n                return `Ugyldig verdi i ${issue.origin}`;\n            default:\n                return `Ugyldig input`;\n        }\n    };\n};\nexport default function () {\n    return {\n        localeError: error(),\n    };\n}\n","import * as util from \"../core/util.js\";\nconst error = () => {\n    const Sizable = {\n        string: { unit: \"harf\", verb: \"olmalıdır\" },\n        file: { unit: \"bayt\", verb: \"olmalıdır\" },\n        array: { unit: \"unsur\", verb: \"olmalıdır\" },\n        set: { unit: \"unsur\", verb: \"olmalıdır\" },\n    };\n    function getSizing(origin) {\n        return Sizable[origin] ?? null;\n    }\n    const FormatDictionary = {\n        regex: \"giren\",\n        email: \"epostagâh\",\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 hengâmı\",\n        date: \"ISO tarihi\",\n        time: \"ISO zamanı\",\n        duration: \"ISO müddeti\",\n        ipv4: \"IPv4 nişânı\",\n        ipv6: \"IPv6 nişânı\",\n        cidrv4: \"IPv4 menzili\",\n        cidrv6: \"IPv6 menzili\",\n        base64: \"base64-şifreli metin\",\n        base64url: \"base64url-şifreli metin\",\n        json_string: \"JSON metin\",\n        e164: \"E.164 sayısı\",\n        jwt: \"JWT\",\n        template_literal: \"giren\",\n    };\n    const TypeDictionary = {\n        nan: \"NaN\",\n        number: \"numara\",\n        array: \"saf\",\n        null: \"gayb\",\n    };\n    return (issue) => {\n        switch (issue.code) {\n            case \"invalid_type\": {\n                const expected = TypeDictionary[issue.expected] ?? issue.expected;\n                const receivedType = util.parsedType(issue.input);\n                const received = TypeDictionary[receivedType] ?? receivedType;\n                if (/^[A-Z]/.test(issue.expected)) {\n                    return `Fâsit giren: umulan instanceof ${issue.expected}, alınan ${received}`;\n                }\n                return `Fâsit giren: umulan ${expected}, alınan ${received}`;\n            }\n            case \"invalid_value\":\n                if (issue.values.length === 1)\n                    return `Fâsit giren: umulan ${util.stringifyPrimitive(issue.values[0])}`;\n                return `Fâsit tercih: mûteberler ${util.joinValues(issue.values, \"|\")}`;\n            case \"too_big\": {\n                const adj = issue.inclusive ? \"<=\" : \"<\";\n                const sizing = getSizing(issue.origin);\n                if (sizing)\n                    return `Fazla büyük: ${issue.origin ?? \"value\"}, ${adj}${issue.maximum.toString()} ${sizing.unit ?? \"elements\"} sahip olmalıydı.`;\n                return `Fazla büyük: ${issue.origin ?? \"value\"}, ${adj}${issue.maximum.toString()} olmalıydı.`;\n            }\n            case \"too_small\": {\n                const adj = issue.inclusive ? \">=\" : \">\";\n                const sizing = getSizing(issue.origin);\n                if (sizing) {\n                    return `Fazla küçük: ${issue.origin}, ${adj}${issue.minimum.toString()} ${sizing.unit} sahip olmalıydı.`;\n                }\n                return `Fazla küçük: ${issue.origin}, ${adj}${issue.minimum.toString()} olmalıydı.`;\n            }\n            case \"invalid_format\": {\n                const _issue = issue;\n                if (_issue.format === \"starts_with\")\n                    return `Fâsit metin: \"${_issue.prefix}\" ile başlamalı.`;\n                if (_issue.format === \"ends_with\")\n                    return `Fâsit metin: \"${_issue.suffix}\" ile bitmeli.`;\n                if (_issue.format === \"includes\")\n                    return `Fâsit metin: \"${_issue.includes}\" ihtivâ etmeli.`;\n                if (_issue.format === \"regex\")\n                    return `Fâsit metin: ${_issue.pattern} nakşına uymalı.`;\n                return `Fâsit ${FormatDictionary[_issue.format] ?? issue.format}`;\n            }\n            case \"not_multiple_of\":\n                return `Fâsit sayı: ${issue.divisor} katı olmalıydı.`;\n            case \"unrecognized_keys\":\n                return `Tanınmayan anahtar ${issue.keys.length > 1 ? \"s\" : \"\"}: ${util.joinValues(issue.keys, \", \")}`;\n            case \"invalid_key\":\n                return `${issue.origin} için tanınmayan anahtar var.`;\n            case \"invalid_union\":\n                return \"Giren tanınamadı.\";\n            case \"invalid_element\":\n                return `${issue.origin} için tanınmayan kıymet var.`;\n            default:\n                return `Kıymet tanınamadı.`;\n        }\n    };\n};\nexport default function () {\n    return {\n        localeError: error(),\n    };\n}\n","import * as util from \"../core/util.js\";\nconst error = () => {\n    const Sizable = {\n        string: { unit: \"توکي\", verb: \"ولري\" },\n        file: { unit: \"بایټس\", verb: \"ولري\" },\n        array: { unit: \"توکي\", verb: \"ولري\" },\n        set: { unit: \"توکي\", verb: \"ولري\" },\n    };\n    function getSizing(origin) {\n        return Sizable[origin] ?? null;\n    }\n    const FormatDictionary = {\n        regex: \"ورودي\",\n        email: \"بریښنالیک\",\n        url: \"یو آر ال\",\n        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: \"نیټه او وخت\",\n        date: \"نېټه\",\n        time: \"وخت\",\n        duration: \"موده\",\n        ipv4: \"د IPv4 پته\",\n        ipv6: \"د IPv6 پته\",\n        cidrv4: \"د IPv4 ساحه\",\n        cidrv6: \"د IPv6 ساحه\",\n        base64: \"base64-encoded متن\",\n        base64url: \"base64url-encoded متن\",\n        json_string: \"JSON متن\",\n        e164: \"د E.164 شمېره\",\n        jwt: \"JWT\",\n        template_literal: \"ورودي\",\n    };\n    const TypeDictionary = {\n        nan: \"NaN\",\n        number: \"عدد\",\n        array: \"ارې\",\n    };\n    return (issue) => {\n        switch (issue.code) {\n            case \"invalid_type\": {\n                const expected = TypeDictionary[issue.expected] ?? issue.expected;\n                const receivedType = util.parsedType(issue.input);\n                const received = TypeDictionary[receivedType] ?? receivedType;\n                if (/^[A-Z]/.test(issue.expected)) {\n                    return `ناسم ورودي: باید instanceof ${issue.expected} وای, مګر ${received} ترلاسه شو`;\n                }\n                return `ناسم ورودي: باید ${expected} وای, مګر ${received} ترلاسه شو`;\n            }\n            case \"invalid_value\":\n                if (issue.values.length === 1) {\n                    return `ناسم ورودي: باید ${util.stringifyPrimitive(issue.values[0])} وای`;\n                }\n                return `ناسم انتخاب: باید یو له ${util.joinValues(issue.values, \"|\")} څخه وای`;\n            case \"too_big\": {\n                const adj = issue.inclusive ? \"<=\" : \"<\";\n                const sizing = getSizing(issue.origin);\n                if (sizing) {\n                    return `ډیر لوی: ${issue.origin ?? \"ارزښت\"} باید ${adj}${issue.maximum.toString()} ${sizing.unit ?? \"عنصرونه\"} ولري`;\n                }\n                return `ډیر لوی: ${issue.origin ?? \"ارزښت\"} باید ${adj}${issue.maximum.toString()} وي`;\n            }\n            case \"too_small\": {\n                const adj = issue.inclusive ? \">=\" : \">\";\n                const sizing = getSizing(issue.origin);\n                if (sizing) {\n                    return `ډیر کوچنی: ${issue.origin} باید ${adj}${issue.minimum.toString()} ${sizing.unit} ولري`;\n                }\n                return `ډیر کوچنی: ${issue.origin} باید ${adj}${issue.minimum.toString()} وي`;\n            }\n            case \"invalid_format\": {\n                const _issue = issue;\n                if (_issue.format === \"starts_with\") {\n                    return `ناسم متن: باید د \"${_issue.prefix}\" سره پیل شي`;\n                }\n                if (_issue.format === \"ends_with\") {\n                    return `ناسم متن: باید د \"${_issue.suffix}\" سره پای ته ورسيږي`;\n                }\n                if (_issue.format === \"includes\") {\n                    return `ناسم متن: باید \"${_issue.includes}\" ولري`;\n                }\n                if (_issue.format === \"regex\") {\n                    return `ناسم متن: باید د ${_issue.pattern} سره مطابقت ولري`;\n                }\n                return `${FormatDictionary[_issue.format] ?? issue.format} ناسم دی`;\n            }\n            case \"not_multiple_of\":\n                return `ناسم عدد: باید د ${issue.divisor} مضرب وي`;\n            case \"unrecognized_keys\":\n                return `ناسم ${issue.keys.length > 1 ? \"کلیډونه\" : \"کلیډ\"}: ${util.joinValues(issue.keys, \", \")}`;\n            case \"invalid_key\":\n                return `ناسم کلیډ په ${issue.origin} کې`;\n            case \"invalid_union\":\n                return `ناسمه ورودي`;\n            case \"invalid_element\":\n                return `ناسم عنصر په ${issue.origin} کې`;\n            default:\n                return `ناسمه ورودي`;\n        }\n    };\n};\nexport default function () {\n    return {\n        localeError: error(),\n    };\n}\n","import * as util from \"../core/util.js\";\nconst error = () => {\n    const Sizable = {\n        string: { unit: \"znaków\", verb: \"mieć\" },\n        file: { unit: \"bajtów\", verb: \"mieć\" },\n        array: { unit: \"elementów\", verb: \"mieć\" },\n        set: { unit: \"elementów\", verb: \"mieć\" },\n    };\n    function getSizing(origin) {\n        return Sizable[origin] ?? null;\n    }\n    const FormatDictionary = {\n        regex: \"wyrażenie\",\n        email: \"adres email\",\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: \"data i godzina w formacie ISO\",\n        date: \"data w formacie ISO\",\n        time: \"godzina w formacie ISO\",\n        duration: \"czas trwania ISO\",\n        ipv4: \"adres IPv4\",\n        ipv6: \"adres IPv6\",\n        cidrv4: \"zakres IPv4\",\n        cidrv6: \"zakres IPv6\",\n        base64: \"ciąg znaków zakodowany w formacie base64\",\n        base64url: \"ciąg znaków zakodowany w formacie base64url\",\n        json_string: \"ciąg znaków w formacie JSON\",\n        e164: \"liczba E.164\",\n        jwt: \"JWT\",\n        template_literal: \"wejście\",\n    };\n    const TypeDictionary = {\n        nan: \"NaN\",\n        number: \"liczba\",\n        array: \"tablica\",\n    };\n    return (issue) => {\n        switch (issue.code) {\n            case \"invalid_type\": {\n                const expected = TypeDictionary[issue.expected] ?? issue.expected;\n                const receivedType = util.parsedType(issue.input);\n                const received = TypeDictionary[receivedType] ?? receivedType;\n                if (/^[A-Z]/.test(issue.expected)) {\n                    return `Nieprawidłowe dane wejściowe: oczekiwano instanceof ${issue.expected}, otrzymano ${received}`;\n                }\n                return `Nieprawidłowe dane wejściowe: oczekiwano ${expected}, otrzymano ${received}`;\n            }\n            case \"invalid_value\":\n                if (issue.values.length === 1)\n                    return `Nieprawidłowe dane wejściowe: oczekiwano ${util.stringifyPrimitive(issue.values[0])}`;\n                return `Nieprawidłowa opcja: oczekiwano jednej z wartości ${util.joinValues(issue.values, \"|\")}`;\n            case \"too_big\": {\n                const adj = issue.inclusive ? \"<=\" : \"<\";\n                const sizing = getSizing(issue.origin);\n                if (sizing) {\n                    return `Za duża wartość: oczekiwano, że ${issue.origin ?? \"wartość\"} będzie mieć ${adj}${issue.maximum.toString()} ${sizing.unit ?? \"elementów\"}`;\n                }\n                return `Zbyt duż(y/a/e): oczekiwano, że ${issue.origin ?? \"wartość\"} będzie wynosić ${adj}${issue.maximum.toString()}`;\n            }\n            case \"too_small\": {\n                const adj = issue.inclusive ? \">=\" : \">\";\n                const sizing = getSizing(issue.origin);\n                if (sizing) {\n                    return `Za mała wartość: oczekiwano, że ${issue.origin ?? \"wartość\"} będzie mieć ${adj}${issue.minimum.toString()} ${sizing.unit ?? \"elementów\"}`;\n                }\n                return `Zbyt mał(y/a/e): oczekiwano, że ${issue.origin ?? \"wartość\"} będzie wynosić ${adj}${issue.minimum.toString()}`;\n            }\n            case \"invalid_format\": {\n                const _issue = issue;\n                if (_issue.format === \"starts_with\")\n                    return `Nieprawidłowy ciąg znaków: musi zaczynać się od \"${_issue.prefix}\"`;\n                if (_issue.format === \"ends_with\")\n                    return `Nieprawidłowy ciąg znaków: musi kończyć się na \"${_issue.suffix}\"`;\n                if (_issue.format === \"includes\")\n                    return `Nieprawidłowy ciąg znaków: musi zawierać \"${_issue.includes}\"`;\n                if (_issue.format === \"regex\")\n                    return `Nieprawidłowy ciąg znaków: musi odpowiadać wzorcowi ${_issue.pattern}`;\n                return `Nieprawidłow(y/a/e) ${FormatDictionary[_issue.format] ?? issue.format}`;\n            }\n            case \"not_multiple_of\":\n                return `Nieprawidłowa liczba: musi być wielokrotnością ${issue.divisor}`;\n            case \"unrecognized_keys\":\n                return `Nierozpoznane klucze${issue.keys.length > 1 ? \"s\" : \"\"}: ${util.joinValues(issue.keys, \", \")}`;\n            case \"invalid_key\":\n                return `Nieprawidłowy klucz w ${issue.origin}`;\n            case \"invalid_union\":\n                return \"Nieprawidłowe dane wejściowe\";\n            case \"invalid_element\":\n                return `Nieprawidłowa wartość w ${issue.origin}`;\n            default:\n                return `Nieprawidłowe dane wejściowe`;\n        }\n    };\n};\nexport default function () {\n    return {\n        localeError: error(),\n    };\n}\n","import * as util from \"../core/util.js\";\nconst error = () => {\n    const Sizable = {\n        string: { unit: \"caracteres\", verb: \"ter\" },\n        file: { unit: \"bytes\", verb: \"ter\" },\n        array: { unit: \"itens\", verb: \"ter\" },\n        set: { unit: \"itens\", verb: \"ter\" },\n    };\n    function getSizing(origin) {\n        return Sizable[origin] ?? null;\n    }\n    const FormatDictionary = {\n        regex: \"padrão\",\n        email: \"endereço de e-mail\",\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: \"data e hora ISO\",\n        date: \"data ISO\",\n        time: \"hora ISO\",\n        duration: \"duração ISO\",\n        ipv4: \"endereço IPv4\",\n        ipv6: \"endereço IPv6\",\n        cidrv4: \"faixa de IPv4\",\n        cidrv6: \"faixa de IPv6\",\n        base64: \"texto codificado em base64\",\n        base64url: \"URL codificada em base64\",\n        json_string: \"texto JSON\",\n        e164: \"número E.164\",\n        jwt: \"JWT\",\n        template_literal: \"entrada\",\n    };\n    const TypeDictionary = {\n        nan: \"NaN\",\n        number: \"número\",\n        null: \"nulo\",\n    };\n    return (issue) => {\n        switch (issue.code) {\n            case \"invalid_type\": {\n                const expected = TypeDictionary[issue.expected] ?? issue.expected;\n                const receivedType = util.parsedType(issue.input);\n                const received = TypeDictionary[receivedType] ?? receivedType;\n                if (/^[A-Z]/.test(issue.expected)) {\n                    return `Tipo inválido: esperado instanceof ${issue.expected}, recebido ${received}`;\n                }\n                return `Tipo inválido: esperado ${expected}, recebido ${received}`;\n            }\n            case \"invalid_value\":\n                if (issue.values.length === 1)\n                    return `Entrada inválida: esperado ${util.stringifyPrimitive(issue.values[0])}`;\n                return `Opção inválida: esperada uma das ${util.joinValues(issue.values, \"|\")}`;\n            case \"too_big\": {\n                const adj = issue.inclusive ? \"<=\" : \"<\";\n                const sizing = getSizing(issue.origin);\n                if (sizing)\n                    return `Muito grande: esperado que ${issue.origin ?? \"valor\"} tivesse ${adj}${issue.maximum.toString()} ${sizing.unit ?? \"elementos\"}`;\n                return `Muito grande: esperado que ${issue.origin ?? \"valor\"} fosse ${adj}${issue.maximum.toString()}`;\n            }\n            case \"too_small\": {\n                const adj = issue.inclusive ? \">=\" : \">\";\n                const sizing = getSizing(issue.origin);\n                if (sizing) {\n                    return `Muito pequeno: esperado que ${issue.origin} tivesse ${adj}${issue.minimum.toString()} ${sizing.unit}`;\n                }\n                return `Muito pequeno: esperado que ${issue.origin} fosse ${adj}${issue.minimum.toString()}`;\n            }\n            case \"invalid_format\": {\n                const _issue = issue;\n                if (_issue.format === \"starts_with\")\n                    return `Texto inválido: deve começar com \"${_issue.prefix}\"`;\n                if (_issue.format === \"ends_with\")\n                    return `Texto inválido: deve terminar com \"${_issue.suffix}\"`;\n                if (_issue.format === \"includes\")\n                    return `Texto inválido: deve incluir \"${_issue.includes}\"`;\n                if (_issue.format === \"regex\")\n                    return `Texto inválido: deve corresponder ao padrão ${_issue.pattern}`;\n                return `${FormatDictionary[_issue.format] ?? issue.format} inválido`;\n            }\n            case \"not_multiple_of\":\n                return `Número inválido: deve ser múltiplo de ${issue.divisor}`;\n            case \"unrecognized_keys\":\n                return `Chave${issue.keys.length > 1 ? \"s\" : \"\"} desconhecida${issue.keys.length > 1 ? \"s\" : \"\"}: ${util.joinValues(issue.keys, \", \")}`;\n            case \"invalid_key\":\n                return `Chave inválida em ${issue.origin}`;\n            case \"invalid_union\":\n                return \"Entrada inválida\";\n            case \"invalid_element\":\n                return `Valor inválido em ${issue.origin}`;\n            default:\n                return `Campo inválido`;\n        }\n    };\n};\nexport default function () {\n    return {\n        localeError: error(),\n    };\n}\n","import * as util from \"../core/util.js\";\nconst error = () => {\n    const Sizable = {\n        string: { unit: \"caractere\", verb: \"să aibă\" },\n        file: { unit: \"octeți\", verb: \"să aibă\" },\n        array: { unit: \"elemente\", verb: \"să aibă\" },\n        set: { unit: \"elemente\", verb: \"să aibă\" },\n        map: { unit: \"intrări\", verb: \"să aibă\" },\n    };\n    function getSizing(origin) {\n        return Sizable[origin] ?? null;\n    }\n    const FormatDictionary = {\n        regex: \"intrare\",\n        email: \"adresă de email\",\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: \"dată și oră ISO\",\n        date: \"dată ISO\",\n        time: \"oră ISO\",\n        duration: \"durată ISO\",\n        ipv4: \"adresă IPv4\",\n        ipv6: \"adresă IPv6\",\n        mac: \"adresă MAC\",\n        cidrv4: \"interval IPv4\",\n        cidrv6: \"interval IPv6\",\n        base64: \"șir codat base64\",\n        base64url: \"șir codat base64url\",\n        json_string: \"șir JSON\",\n        e164: \"număr E.164\",\n        jwt: \"JWT\",\n        template_literal: \"intrare\",\n    };\n    const TypeDictionary = {\n        nan: \"NaN\",\n        string: \"șir\",\n        number: \"număr\",\n        boolean: \"boolean\",\n        function: \"funcție\",\n        array: \"matrice\",\n        object: \"obiect\",\n        undefined: \"nedefinit\",\n        symbol: \"simbol\",\n        bigint: \"număr mare\",\n        void: \"void\",\n        never: \"never\",\n        map: \"hartă\",\n        set: \"set\",\n    };\n    return (issue) => {\n        switch (issue.code) {\n            case \"invalid_type\": {\n                const expected = TypeDictionary[issue.expected] ?? issue.expected;\n                const receivedType = util.parsedType(issue.input);\n                const received = TypeDictionary[receivedType] ?? receivedType;\n                return `Intrare invalidă: așteptat ${expected}, primit ${received}`;\n            }\n            case \"invalid_value\":\n                if (issue.values.length === 1)\n                    return `Intrare invalidă: așteptat ${util.stringifyPrimitive(issue.values[0])}`;\n                return `Opțiune invalidă: așteptat una dintre ${util.joinValues(issue.values, \"|\")}`;\n            case \"too_big\": {\n                const adj = issue.inclusive ? \"<=\" : \"<\";\n                const sizing = getSizing(issue.origin);\n                if (sizing)\n                    return `Prea mare: așteptat ca ${issue.origin ?? \"valoarea\"} ${sizing.verb} ${adj}${issue.maximum.toString()} ${sizing.unit ?? \"elemente\"}`;\n                return `Prea mare: așteptat ca ${issue.origin ?? \"valoarea\"} să fie ${adj}${issue.maximum.toString()}`;\n            }\n            case \"too_small\": {\n                const adj = issue.inclusive ? \">=\" : \">\";\n                const sizing = getSizing(issue.origin);\n                if (sizing) {\n                    return `Prea mic: așteptat ca ${issue.origin} ${sizing.verb} ${adj}${issue.minimum.toString()} ${sizing.unit}`;\n                }\n                return `Prea mic: așteptat ca ${issue.origin} să fie ${adj}${issue.minimum.toString()}`;\n            }\n            case \"invalid_format\": {\n                const _issue = issue;\n                if (_issue.format === \"starts_with\") {\n                    return `Șir invalid: trebuie să înceapă cu \"${_issue.prefix}\"`;\n                }\n                if (_issue.format === \"ends_with\")\n                    return `Șir invalid: trebuie să se termine cu \"${_issue.suffix}\"`;\n                if (_issue.format === \"includes\")\n                    return `Șir invalid: trebuie să includă \"${_issue.includes}\"`;\n                if (_issue.format === \"regex\")\n                    return `Șir invalid: trebuie să se potrivească cu modelul ${_issue.pattern}`;\n                return `Format invalid: ${FormatDictionary[_issue.format] ?? issue.format}`;\n            }\n            case \"not_multiple_of\":\n                return `Număr invalid: trebuie să fie multiplu de ${issue.divisor}`;\n            case \"unrecognized_keys\":\n                return `Chei nerecunoscute: ${util.joinValues(issue.keys, \", \")}`;\n            case \"invalid_key\":\n                return `Cheie invalidă în ${issue.origin}`;\n            case \"invalid_union\":\n                return \"Intrare invalidă\";\n            case \"invalid_element\":\n                return `Valoare invalidă în ${issue.origin}`;\n            default:\n                return `Intrare invalidă`;\n        }\n    };\n};\nexport default function () {\n    return {\n        localeError: error(),\n    };\n}\n","import * as util from \"../core/util.js\";\nfunction getRussianPlural(count, one, few, many) {\n    const absCount = Math.abs(count);\n    const lastDigit = absCount % 10;\n    const lastTwoDigits = absCount % 100;\n    if (lastTwoDigits >= 11 && lastTwoDigits <= 19) {\n        return many;\n    }\n    if (lastDigit === 1) {\n        return one;\n    }\n    if (lastDigit >= 2 && lastDigit <= 4) {\n        return few;\n    }\n    return many;\n}\nconst error = () => {\n    const Sizable = {\n        string: {\n            unit: {\n                one: \"символ\",\n                few: \"символа\",\n                many: \"символов\",\n            },\n            verb: \"иметь\",\n        },\n        file: {\n            unit: {\n                one: \"байт\",\n                few: \"байта\",\n                many: \"байт\",\n            },\n            verb: \"иметь\",\n        },\n        array: {\n            unit: {\n                one: \"элемент\",\n                few: \"элемента\",\n                many: \"элементов\",\n            },\n            verb: \"иметь\",\n        },\n        set: {\n            unit: {\n                one: \"элемент\",\n                few: \"элемента\",\n                many: \"элементов\",\n            },\n            verb: \"иметь\",\n        },\n    };\n    function getSizing(origin) {\n        return Sizable[origin] ?? null;\n    }\n    const FormatDictionary = {\n        regex: \"ввод\",\n        email: \"email адрес\",\n        url: \"URL\",\n        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 дата и время\",\n        date: \"ISO дата\",\n        time: \"ISO время\",\n        duration: \"ISO длительность\",\n        ipv4: \"IPv4 адрес\",\n        ipv6: \"IPv6 адрес\",\n        cidrv4: \"IPv4 диапазон\",\n        cidrv6: \"IPv6 диапазон\",\n        base64: \"строка в формате base64\",\n        base64url: \"строка в формате base64url\",\n        json_string: \"JSON строка\",\n        e164: \"номер E.164\",\n        jwt: \"JWT\",\n        template_literal: \"ввод\",\n    };\n    const TypeDictionary = {\n        nan: \"NaN\",\n        number: \"число\",\n        array: \"массив\",\n    };\n    return (issue) => {\n        switch (issue.code) {\n            case \"invalid_type\": {\n                const expected = TypeDictionary[issue.expected] ?? issue.expected;\n                const receivedType = util.parsedType(issue.input);\n                const received = TypeDictionary[receivedType] ?? receivedType;\n                if (/^[A-Z]/.test(issue.expected)) {\n                    return `Неверный ввод: ожидалось instanceof ${issue.expected}, получено ${received}`;\n                }\n                return `Неверный ввод: ожидалось ${expected}, получено ${received}`;\n            }\n            case \"invalid_value\":\n                if (issue.values.length === 1)\n                    return `Неверный ввод: ожидалось ${util.stringifyPrimitive(issue.values[0])}`;\n                return `Неверный вариант: ожидалось одно из ${util.joinValues(issue.values, \"|\")}`;\n            case \"too_big\": {\n                const adj = issue.inclusive ? \"<=\" : \"<\";\n                const sizing = getSizing(issue.origin);\n                if (sizing) {\n                    const maxValue = Number(issue.maximum);\n                    const unit = getRussianPlural(maxValue, sizing.unit.one, sizing.unit.few, sizing.unit.many);\n                    return `Слишком большое значение: ожидалось, что ${issue.origin ?? \"значение\"} будет иметь ${adj}${issue.maximum.toString()} ${unit}`;\n                }\n                return `Слишком большое значение: ожидалось, что ${issue.origin ?? \"значение\"} будет ${adj}${issue.maximum.toString()}`;\n            }\n            case \"too_small\": {\n                const adj = issue.inclusive ? \">=\" : \">\";\n                const sizing = getSizing(issue.origin);\n                if (sizing) {\n                    const minValue = Number(issue.minimum);\n                    const unit = getRussianPlural(minValue, sizing.unit.one, sizing.unit.few, sizing.unit.many);\n                    return `Слишком маленькое значение: ожидалось, что ${issue.origin} будет иметь ${adj}${issue.minimum.toString()} ${unit}`;\n                }\n                return `Слишком маленькое значение: ожидалось, что ${issue.origin} будет ${adj}${issue.minimum.toString()}`;\n            }\n            case \"invalid_format\": {\n                const _issue = issue;\n                if (_issue.format === \"starts_with\")\n                    return `Неверная строка: должна начинаться с \"${_issue.prefix}\"`;\n                if (_issue.format === \"ends_with\")\n                    return `Неверная строка: должна заканчиваться на \"${_issue.suffix}\"`;\n                if (_issue.format === \"includes\")\n                    return `Неверная строка: должна содержать \"${_issue.includes}\"`;\n                if (_issue.format === \"regex\")\n                    return `Неверная строка: должна соответствовать шаблону ${_issue.pattern}`;\n                return `Неверный ${FormatDictionary[_issue.format] ?? issue.format}`;\n            }\n            case \"not_multiple_of\":\n                return `Неверное число: должно быть кратным ${issue.divisor}`;\n            case \"unrecognized_keys\":\n                return `Нераспознанн${issue.keys.length > 1 ? \"ые\" : \"ый\"} ключ${issue.keys.length > 1 ? \"и\" : \"\"}: ${util.joinValues(issue.keys, \", \")}`;\n            case \"invalid_key\":\n                return `Неверный ключ в ${issue.origin}`;\n            case \"invalid_union\":\n                return \"Неверные входные данные\";\n            case \"invalid_element\":\n                return `Неверное значение в ${issue.origin}`;\n            default:\n                return `Неверные входные данные`;\n        }\n    };\n};\nexport default function () {\n    return {\n        localeError: error(),\n    };\n}\n","import * as util from \"../core/util.js\";\nconst error = () => {\n    const Sizable = {\n        string: { unit: \"znakov\", verb: \"imeti\" },\n        file: { unit: \"bajtov\", verb: \"imeti\" },\n        array: { unit: \"elementov\", verb: \"imeti\" },\n        set: { unit: \"elementov\", verb: \"imeti\" },\n    };\n    function getSizing(origin) {\n        return Sizable[origin] ?? null;\n    }\n    const FormatDictionary = {\n        regex: \"vnos\",\n        email: \"e-poštni naslov\",\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 datum in čas\",\n        date: \"ISO datum\",\n        time: \"ISO čas\",\n        duration: \"ISO trajanje\",\n        ipv4: \"IPv4 naslov\",\n        ipv6: \"IPv6 naslov\",\n        cidrv4: \"obseg IPv4\",\n        cidrv6: \"obseg IPv6\",\n        base64: \"base64 kodiran niz\",\n        base64url: \"base64url kodiran niz\",\n        json_string: \"JSON niz\",\n        e164: \"E.164 številka\",\n        jwt: \"JWT\",\n        template_literal: \"vnos\",\n    };\n    const TypeDictionary = {\n        nan: \"NaN\",\n        number: \"število\",\n        array: \"tabela\",\n    };\n    return (issue) => {\n        switch (issue.code) {\n            case \"invalid_type\": {\n                const expected = TypeDictionary[issue.expected] ?? issue.expected;\n                const receivedType = util.parsedType(issue.input);\n                const received = TypeDictionary[receivedType] ?? receivedType;\n                if (/^[A-Z]/.test(issue.expected)) {\n                    return `Neveljaven vnos: pričakovano instanceof ${issue.expected}, prejeto ${received}`;\n                }\n                return `Neveljaven vnos: pričakovano ${expected}, prejeto ${received}`;\n            }\n            case \"invalid_value\":\n                if (issue.values.length === 1)\n                    return `Neveljaven vnos: pričakovano ${util.stringifyPrimitive(issue.values[0])}`;\n                return `Neveljavna možnost: pričakovano eno izmed ${util.joinValues(issue.values, \"|\")}`;\n            case \"too_big\": {\n                const adj = issue.inclusive ? \"<=\" : \"<\";\n                const sizing = getSizing(issue.origin);\n                if (sizing)\n                    return `Preveliko: pričakovano, da bo ${issue.origin ?? \"vrednost\"} imelo ${adj}${issue.maximum.toString()} ${sizing.unit ?? \"elementov\"}`;\n                return `Preveliko: pričakovano, da bo ${issue.origin ?? \"vrednost\"} ${adj}${issue.maximum.toString()}`;\n            }\n            case \"too_small\": {\n                const adj = issue.inclusive ? \">=\" : \">\";\n                const sizing = getSizing(issue.origin);\n                if (sizing) {\n                    return `Premajhno: pričakovano, da bo ${issue.origin} imelo ${adj}${issue.minimum.toString()} ${sizing.unit}`;\n                }\n                return `Premajhno: pričakovano, da bo ${issue.origin} ${adj}${issue.minimum.toString()}`;\n            }\n            case \"invalid_format\": {\n                const _issue = issue;\n                if (_issue.format === \"starts_with\") {\n                    return `Neveljaven niz: mora se začeti z \"${_issue.prefix}\"`;\n                }\n                if (_issue.format === \"ends_with\")\n                    return `Neveljaven niz: mora se končati z \"${_issue.suffix}\"`;\n                if (_issue.format === \"includes\")\n                    return `Neveljaven niz: mora vsebovati \"${_issue.includes}\"`;\n                if (_issue.format === \"regex\")\n                    return `Neveljaven niz: mora ustrezati vzorcu ${_issue.pattern}`;\n                return `Neveljaven ${FormatDictionary[_issue.format] ?? issue.format}`;\n            }\n            case \"not_multiple_of\":\n                return `Neveljavno število: mora biti večkratnik ${issue.divisor}`;\n            case \"unrecognized_keys\":\n                return `Neprepoznan${issue.keys.length > 1 ? \"i ključi\" : \" ključ\"}: ${util.joinValues(issue.keys, \", \")}`;\n            case \"invalid_key\":\n                return `Neveljaven ključ v ${issue.origin}`;\n            case \"invalid_union\":\n                return \"Neveljaven vnos\";\n            case \"invalid_element\":\n                return `Neveljavna vrednost v ${issue.origin}`;\n            default:\n                return \"Neveljaven vnos\";\n        }\n    };\n};\nexport default function () {\n    return {\n        localeError: error(),\n    };\n}\n","import * as util from \"../core/util.js\";\nconst error = () => {\n    const Sizable = {\n        string: { unit: \"tecken\", verb: \"att ha\" },\n        file: { unit: \"bytes\", verb: \"att ha\" },\n        array: { unit: \"objekt\", verb: \"att innehålla\" },\n        set: { unit: \"objekt\", verb: \"att innehålla\" },\n    };\n    function getSizing(origin) {\n        return Sizable[origin] ?? null;\n    }\n    const FormatDictionary = {\n        regex: \"reguljärt uttryck\",\n        email: \"e-postadress\",\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-datum och tid\",\n        date: \"ISO-datum\",\n        time: \"ISO-tid\",\n        duration: \"ISO-varaktighet\",\n        ipv4: \"IPv4-intervall\",\n        ipv6: \"IPv6-intervall\",\n        cidrv4: \"IPv4-spektrum\",\n        cidrv6: \"IPv6-spektrum\",\n        base64: \"base64-kodad sträng\",\n        base64url: \"base64url-kodad sträng\",\n        json_string: \"JSON-sträng\",\n        e164: \"E.164-nummer\",\n        jwt: \"JWT\",\n        template_literal: \"mall-literal\",\n    };\n    const TypeDictionary = {\n        nan: \"NaN\",\n        number: \"antal\",\n        array: \"lista\",\n    };\n    return (issue) => {\n        switch (issue.code) {\n            case \"invalid_type\": {\n                const expected = TypeDictionary[issue.expected] ?? issue.expected;\n                const receivedType = util.parsedType(issue.input);\n                const received = TypeDictionary[receivedType] ?? receivedType;\n                if (/^[A-Z]/.test(issue.expected)) {\n                    return `Ogiltig inmatning: förväntat instanceof ${issue.expected}, fick ${received}`;\n                }\n                return `Ogiltig inmatning: förväntat ${expected}, fick ${received}`;\n            }\n            case \"invalid_value\":\n                if (issue.values.length === 1)\n                    return `Ogiltig inmatning: förväntat ${util.stringifyPrimitive(issue.values[0])}`;\n                return `Ogiltigt val: förväntade en av ${util.joinValues(issue.values, \"|\")}`;\n            case \"too_big\": {\n                const adj = issue.inclusive ? \"<=\" : \"<\";\n                const sizing = getSizing(issue.origin);\n                if (sizing) {\n                    return `För stor(t): förväntade ${issue.origin ?? \"värdet\"} att ha ${adj}${issue.maximum.toString()} ${sizing.unit ?? \"element\"}`;\n                }\n                return `För stor(t): förväntat ${issue.origin ?? \"värdet\"} att ha ${adj}${issue.maximum.toString()}`;\n            }\n            case \"too_small\": {\n                const adj = issue.inclusive ? \">=\" : \">\";\n                const sizing = getSizing(issue.origin);\n                if (sizing) {\n                    return `För lite(t): förväntade ${issue.origin ?? \"värdet\"} att ha ${adj}${issue.minimum.toString()} ${sizing.unit}`;\n                }\n                return `För lite(t): förväntade ${issue.origin ?? \"värdet\"} att ha ${adj}${issue.minimum.toString()}`;\n            }\n            case \"invalid_format\": {\n                const _issue = issue;\n                if (_issue.format === \"starts_with\") {\n                    return `Ogiltig sträng: måste börja med \"${_issue.prefix}\"`;\n                }\n                if (_issue.format === \"ends_with\")\n                    return `Ogiltig sträng: måste sluta med \"${_issue.suffix}\"`;\n                if (_issue.format === \"includes\")\n                    return `Ogiltig sträng: måste innehålla \"${_issue.includes}\"`;\n                if (_issue.format === \"regex\")\n                    return `Ogiltig sträng: måste matcha mönstret \"${_issue.pattern}\"`;\n                return `Ogiltig(t) ${FormatDictionary[_issue.format] ?? issue.format}`;\n            }\n            case \"not_multiple_of\":\n                return `Ogiltigt tal: måste vara en multipel av ${issue.divisor}`;\n            case \"unrecognized_keys\":\n                return `${issue.keys.length > 1 ? \"Okända nycklar\" : \"Okänd nyckel\"}: ${util.joinValues(issue.keys, \", \")}`;\n            case \"invalid_key\":\n                return `Ogiltig nyckel i ${issue.origin ?? \"värdet\"}`;\n            case \"invalid_union\":\n                return \"Ogiltig input\";\n            case \"invalid_element\":\n                return `Ogiltigt värde i ${issue.origin ?? \"värdet\"}`;\n            default:\n                return `Ogiltig input`;\n        }\n    };\n};\nexport default function () {\n    return {\n        localeError: error(),\n    };\n}\n","import * as util from \"../core/util.js\";\nconst error = () => {\n    const Sizable = {\n        string: { unit: \"எழுத்துக்கள்\", verb: \"கொண்டிருக்க வேண்டும்\" },\n        file: { unit: \"பைட்டுகள்\", verb: \"கொண்டிருக்க வேண்டும்\" },\n        array: { unit: \"உறுப்புகள்\", verb: \"கொண்டிருக்க வேண்டும்\" },\n        set: { unit: \"உறுப்புகள்\", verb: \"கொண்டிருக்க வேண்டும்\" },\n    };\n    function getSizing(origin) {\n        return Sizable[origin] ?? null;\n    }\n    const FormatDictionary = {\n        regex: \"உள்ளீடு\",\n        email: \"மின்னஞ்சல் முகவரி\",\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 தேதி நேரம்\",\n        date: \"ISO தேதி\",\n        time: \"ISO நேரம்\",\n        duration: \"ISO கால அளவு\",\n        ipv4: \"IPv4 முகவரி\",\n        ipv6: \"IPv6 முகவரி\",\n        cidrv4: \"IPv4 வரம்பு\",\n        cidrv6: \"IPv6 வரம்பு\",\n        base64: \"base64-encoded சரம்\",\n        base64url: \"base64url-encoded சரம்\",\n        json_string: \"JSON சரம்\",\n        e164: \"E.164 எண்\",\n        jwt: \"JWT\",\n        template_literal: \"input\",\n    };\n    const TypeDictionary = {\n        nan: \"NaN\",\n        number: \"எண்\",\n        array: \"அணி\",\n        null: \"வெறுமை\",\n    };\n    return (issue) => {\n        switch (issue.code) {\n            case \"invalid_type\": {\n                const expected = TypeDictionary[issue.expected] ?? issue.expected;\n                const receivedType = util.parsedType(issue.input);\n                const received = TypeDictionary[receivedType] ?? receivedType;\n                if (/^[A-Z]/.test(issue.expected)) {\n                    return `தவறான உள்ளீடு: எதிர்பார்க்கப்பட்டது instanceof ${issue.expected}, பெறப்பட்டது ${received}`;\n                }\n                return `தவறான உள்ளீடு: எதிர்பார்க்கப்பட்டது ${expected}, பெறப்பட்டது ${received}`;\n            }\n            case \"invalid_value\":\n                if (issue.values.length === 1)\n                    return `தவறான உள்ளீடு: எதிர்பார்க்கப்பட்டது ${util.stringifyPrimitive(issue.values[0])}`;\n                return `தவறான விருப்பம்: எதிர்பார்க்கப்பட்டது ${util.joinValues(issue.values, \"|\")} இல் ஒன்று`;\n            case \"too_big\": {\n                const adj = issue.inclusive ? \"<=\" : \"<\";\n                const sizing = getSizing(issue.origin);\n                if (sizing) {\n                    return `மிக பெரியது: எதிர்பார்க்கப்பட்டது ${issue.origin ?? \"மதிப்பு\"} ${adj}${issue.maximum.toString()} ${sizing.unit ?? \"உறுப்புகள்\"} ஆக இருக்க வேண்டும்`;\n                }\n                return `மிக பெரியது: எதிர்பார்க்கப்பட்டது ${issue.origin ?? \"மதிப்பு\"} ${adj}${issue.maximum.toString()} ஆக இருக்க வேண்டும்`;\n            }\n            case \"too_small\": {\n                const adj = issue.inclusive ? \">=\" : \">\";\n                const sizing = getSizing(issue.origin);\n                if (sizing) {\n                    return `மிகச் சிறியது: எதிர்பார்க்கப்பட்டது ${issue.origin} ${adj}${issue.minimum.toString()} ${sizing.unit} ஆக இருக்க வேண்டும்`; //\n                }\n                return `மிகச் சிறியது: எதிர்பார்க்கப்பட்டது ${issue.origin} ${adj}${issue.minimum.toString()} ஆக இருக்க வேண்டும்`;\n            }\n            case \"invalid_format\": {\n                const _issue = issue;\n                if (_issue.format === \"starts_with\")\n                    return `தவறான சரம்: \"${_issue.prefix}\" இல் தொடங்க வேண்டும்`;\n                if (_issue.format === \"ends_with\")\n                    return `தவறான சரம்: \"${_issue.suffix}\" இல் முடிவடைய வேண்டும்`;\n                if (_issue.format === \"includes\")\n                    return `தவறான சரம்: \"${_issue.includes}\" ஐ உள்ளடக்க வேண்டும்`;\n                if (_issue.format === \"regex\")\n                    return `தவறான சரம்: ${_issue.pattern} முறைபாட்டுடன் பொருந்த வேண்டும்`;\n                return `தவறான ${FormatDictionary[_issue.format] ?? issue.format}`;\n            }\n            case \"not_multiple_of\":\n                return `தவறான எண்: ${issue.divisor} இன் பலமாக இருக்க வேண்டும்`;\n            case \"unrecognized_keys\":\n                return `அடையாளம் தெரியாத விசை${issue.keys.length > 1 ? \"கள்\" : \"\"}: ${util.joinValues(issue.keys, \", \")}`;\n            case \"invalid_key\":\n                return `${issue.origin} இல் தவறான விசை`;\n            case \"invalid_union\":\n                return \"தவறான உள்ளீடு\";\n            case \"invalid_element\":\n                return `${issue.origin} இல் தவறான மதிப்பு`;\n            default:\n                return `தவறான உள்ளீடு`;\n        }\n    };\n};\nexport default function () {\n    return {\n        localeError: error(),\n    };\n}\n","import * as util from \"../core/util.js\";\nconst error = () => {\n    const Sizable = {\n        string: { unit: \"ตัวอักษร\", verb: \"ควรมี\" },\n        file: { unit: \"ไบต์\", verb: \"ควรมี\" },\n        array: { unit: \"รายการ\", verb: \"ควรมี\" },\n        set: { unit: \"รายการ\", verb: \"ควรมี\" },\n    };\n    function getSizing(origin) {\n        return Sizable[origin] ?? null;\n    }\n    const FormatDictionary = {\n        regex: \"ข้อมูลที่ป้อน\",\n        email: \"ที่อยู่อีเมล\",\n        url: \"URL\",\n        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\",\n        date: \"วันที่แบบ ISO\",\n        time: \"เวลาแบบ ISO\",\n        duration: \"ช่วงเวลาแบบ ISO\",\n        ipv4: \"ที่อยู่ IPv4\",\n        ipv6: \"ที่อยู่ IPv6\",\n        cidrv4: \"ช่วง IP แบบ IPv4\",\n        cidrv6: \"ช่วง IP แบบ IPv6\",\n        base64: \"ข้อความแบบ Base64\",\n        base64url: \"ข้อความแบบ Base64 สำหรับ URL\",\n        json_string: \"ข้อความแบบ JSON\",\n        e164: \"เบอร์โทรศัพท์ระหว่างประเทศ (E.164)\",\n        jwt: \"โทเคน JWT\",\n        template_literal: \"ข้อมูลที่ป้อน\",\n    };\n    const TypeDictionary = {\n        nan: \"NaN\",\n        number: \"ตัวเลข\",\n        array: \"อาร์เรย์ (Array)\",\n        null: \"ไม่มีค่า (null)\",\n    };\n    return (issue) => {\n        switch (issue.code) {\n            case \"invalid_type\": {\n                const expected = TypeDictionary[issue.expected] ?? issue.expected;\n                const receivedType = util.parsedType(issue.input);\n                const received = TypeDictionary[receivedType] ?? receivedType;\n                if (/^[A-Z]/.test(issue.expected)) {\n                    return `ประเภทข้อมูลไม่ถูกต้อง: ควรเป็น instanceof ${issue.expected} แต่ได้รับ ${received}`;\n                }\n                return `ประเภทข้อมูลไม่ถูกต้อง: ควรเป็น ${expected} แต่ได้รับ ${received}`;\n            }\n            case \"invalid_value\":\n                if (issue.values.length === 1)\n                    return `ค่าไม่ถูกต้อง: ควรเป็น ${util.stringifyPrimitive(issue.values[0])}`;\n                return `ตัวเลือกไม่ถูกต้อง: ควรเป็นหนึ่งใน ${util.joinValues(issue.values, \"|\")}`;\n            case \"too_big\": {\n                const adj = issue.inclusive ? \"ไม่เกิน\" : \"น้อยกว่า\";\n                const sizing = getSizing(issue.origin);\n                if (sizing)\n                    return `เกินกำหนด: ${issue.origin ?? \"ค่า\"} ควรมี${adj} ${issue.maximum.toString()} ${sizing.unit ?? \"รายการ\"}`;\n                return `เกินกำหนด: ${issue.origin ?? \"ค่า\"} ควรมี${adj} ${issue.maximum.toString()}`;\n            }\n            case \"too_small\": {\n                const adj = issue.inclusive ? \"อย่างน้อย\" : \"มากกว่า\";\n                const sizing = getSizing(issue.origin);\n                if (sizing) {\n                    return `น้อยกว่ากำหนด: ${issue.origin} ควรมี${adj} ${issue.minimum.toString()} ${sizing.unit}`;\n                }\n                return `น้อยกว่ากำหนด: ${issue.origin} ควรมี${adj} ${issue.minimum.toString()}`;\n            }\n            case \"invalid_format\": {\n                const _issue = issue;\n                if (_issue.format === \"starts_with\") {\n                    return `รูปแบบไม่ถูกต้อง: ข้อความต้องขึ้นต้นด้วย \"${_issue.prefix}\"`;\n                }\n                if (_issue.format === \"ends_with\")\n                    return `รูปแบบไม่ถูกต้อง: ข้อความต้องลงท้ายด้วย \"${_issue.suffix}\"`;\n                if (_issue.format === \"includes\")\n                    return `รูปแบบไม่ถูกต้อง: ข้อความต้องมี \"${_issue.includes}\" อยู่ในข้อความ`;\n                if (_issue.format === \"regex\")\n                    return `รูปแบบไม่ถูกต้อง: ต้องตรงกับรูปแบบที่กำหนด ${_issue.pattern}`;\n                return `รูปแบบไม่ถูกต้อง: ${FormatDictionary[_issue.format] ?? issue.format}`;\n            }\n            case \"not_multiple_of\":\n                return `ตัวเลขไม่ถูกต้อง: ต้องเป็นจำนวนที่หารด้วย ${issue.divisor} ได้ลงตัว`;\n            case \"unrecognized_keys\":\n                return `พบคีย์ที่ไม่รู้จัก: ${util.joinValues(issue.keys, \", \")}`;\n            case \"invalid_key\":\n                return `คีย์ไม่ถูกต้องใน ${issue.origin}`;\n            case \"invalid_union\":\n                return \"ข้อมูลไม่ถูกต้อง: ไม่ตรงกับรูปแบบยูเนียนที่กำหนดไว้\";\n            case \"invalid_element\":\n                return `ข้อมูลไม่ถูกต้องใน ${issue.origin}`;\n            default:\n                return `ข้อมูลไม่ถูกต้อง`;\n        }\n    };\n};\nexport default function () {\n    return {\n        localeError: error(),\n    };\n}\n","import * as util from \"../core/util.js\";\nconst error = () => {\n    const Sizable = {\n        string: { unit: \"karakter\", verb: \"olmalı\" },\n        file: { unit: \"bayt\", verb: \"olmalı\" },\n        array: { unit: \"öğe\", verb: \"olmalı\" },\n        set: { unit: \"öğe\", verb: \"olmalı\" },\n    };\n    function getSizing(origin) {\n        return Sizable[origin] ?? null;\n    }\n    const FormatDictionary = {\n        regex: \"girdi\",\n        email: \"e-posta adresi\",\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 tarih ve saat\",\n        date: \"ISO tarih\",\n        time: \"ISO saat\",\n        duration: \"ISO süre\",\n        ipv4: \"IPv4 adresi\",\n        ipv6: \"IPv6 adresi\",\n        cidrv4: \"IPv4 aralığı\",\n        cidrv6: \"IPv6 aralığı\",\n        base64: \"base64 ile şifrelenmiş metin\",\n        base64url: \"base64url ile şifrelenmiş metin\",\n        json_string: \"JSON dizesi\",\n        e164: \"E.164 sayısı\",\n        jwt: \"JWT\",\n        template_literal: \"Şablon dizesi\",\n    };\n    const TypeDictionary = {\n        nan: \"NaN\",\n    };\n    return (issue) => {\n        switch (issue.code) {\n            case \"invalid_type\": {\n                const expected = TypeDictionary[issue.expected] ?? issue.expected;\n                const receivedType = util.parsedType(issue.input);\n                const received = TypeDictionary[receivedType] ?? receivedType;\n                if (/^[A-Z]/.test(issue.expected)) {\n                    return `Geçersiz değer: beklenen instanceof ${issue.expected}, alınan ${received}`;\n                }\n                return `Geçersiz değer: beklenen ${expected}, alınan ${received}`;\n            }\n            case \"invalid_value\":\n                if (issue.values.length === 1)\n                    return `Geçersiz değer: beklenen ${util.stringifyPrimitive(issue.values[0])}`;\n                return `Geçersiz seçenek: aşağıdakilerden biri olmalı: ${util.joinValues(issue.values, \"|\")}`;\n            case \"too_big\": {\n                const adj = issue.inclusive ? \"<=\" : \"<\";\n                const sizing = getSizing(issue.origin);\n                if (sizing)\n                    return `Çok büyük: beklenen ${issue.origin ?? \"değer\"} ${adj}${issue.maximum.toString()} ${sizing.unit ?? \"öğe\"}`;\n                return `Çok büyük: beklenen ${issue.origin ?? \"değer\"} ${adj}${issue.maximum.toString()}`;\n            }\n            case \"too_small\": {\n                const adj = issue.inclusive ? \">=\" : \">\";\n                const sizing = getSizing(issue.origin);\n                if (sizing)\n                    return `Çok küçük: beklenen ${issue.origin} ${adj}${issue.minimum.toString()} ${sizing.unit}`;\n                return `Çok küçük: beklenen ${issue.origin} ${adj}${issue.minimum.toString()}`;\n            }\n            case \"invalid_format\": {\n                const _issue = issue;\n                if (_issue.format === \"starts_with\")\n                    return `Geçersiz metin: \"${_issue.prefix}\" ile başlamalı`;\n                if (_issue.format === \"ends_with\")\n                    return `Geçersiz metin: \"${_issue.suffix}\" ile bitmeli`;\n                if (_issue.format === \"includes\")\n                    return `Geçersiz metin: \"${_issue.includes}\" içermeli`;\n                if (_issue.format === \"regex\")\n                    return `Geçersiz metin: ${_issue.pattern} desenine uymalı`;\n                return `Geçersiz ${FormatDictionary[_issue.format] ?? issue.format}`;\n            }\n            case \"not_multiple_of\":\n                return `Geçersiz sayı: ${issue.divisor} ile tam bölünebilmeli`;\n            case \"unrecognized_keys\":\n                return `Tanınmayan anahtar${issue.keys.length > 1 ? \"lar\" : \"\"}: ${util.joinValues(issue.keys, \", \")}`;\n            case \"invalid_key\":\n                return `${issue.origin} içinde geçersiz anahtar`;\n            case \"invalid_union\":\n                return \"Geçersiz değer\";\n            case \"invalid_element\":\n                return `${issue.origin} içinde geçersiz değer`;\n            default:\n                return `Geçersiz değer`;\n        }\n    };\n};\nexport default function () {\n    return {\n        localeError: error(),\n    };\n}\n","import * as util from \"../core/util.js\";\nconst error = () => {\n    const Sizable = {\n        string: { unit: \"символів\", verb: \"матиме\" },\n        file: { unit: \"байтів\", verb: \"матиме\" },\n        array: { unit: \"елементів\", verb: \"матиме\" },\n        set: { unit: \"елементів\", verb: \"матиме\" },\n    };\n    function getSizing(origin) {\n        return Sizable[origin] ?? null;\n    }\n    const FormatDictionary = {\n        regex: \"вхідні дані\",\n        email: \"адреса електронної пошти\",\n        url: \"URL\",\n        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\",\n        date: \"дата ISO\",\n        time: \"час ISO\",\n        duration: \"тривалість ISO\",\n        ipv4: \"адреса IPv4\",\n        ipv6: \"адреса IPv6\",\n        cidrv4: \"діапазон IPv4\",\n        cidrv6: \"діапазон IPv6\",\n        base64: \"рядок у кодуванні base64\",\n        base64url: \"рядок у кодуванні base64url\",\n        json_string: \"рядок JSON\",\n        e164: \"номер E.164\",\n        jwt: \"JWT\",\n        template_literal: \"вхідні дані\",\n    };\n    const TypeDictionary = {\n        nan: \"NaN\",\n        number: \"число\",\n        array: \"масив\",\n    };\n    return (issue) => {\n        switch (issue.code) {\n            case \"invalid_type\": {\n                const expected = TypeDictionary[issue.expected] ?? issue.expected;\n                const receivedType = util.parsedType(issue.input);\n                const received = TypeDictionary[receivedType] ?? receivedType;\n                if (/^[A-Z]/.test(issue.expected)) {\n                    return `Неправильні вхідні дані: очікується instanceof ${issue.expected}, отримано ${received}`;\n                }\n                return `Неправильні вхідні дані: очікується ${expected}, отримано ${received}`;\n            }\n            case \"invalid_value\":\n                if (issue.values.length === 1)\n                    return `Неправильні вхідні дані: очікується ${util.stringifyPrimitive(issue.values[0])}`;\n                return `Неправильна опція: очікується одне з ${util.joinValues(issue.values, \"|\")}`;\n            case \"too_big\": {\n                const adj = issue.inclusive ? \"<=\" : \"<\";\n                const sizing = getSizing(issue.origin);\n                if (sizing)\n                    return `Занадто велике: очікується, що ${issue.origin ?? \"значення\"} ${sizing.verb} ${adj}${issue.maximum.toString()} ${sizing.unit ?? \"елементів\"}`;\n                return `Занадто велике: очікується, що ${issue.origin ?? \"значення\"} буде ${adj}${issue.maximum.toString()}`;\n            }\n            case \"too_small\": {\n                const adj = issue.inclusive ? \">=\" : \">\";\n                const sizing = getSizing(issue.origin);\n                if (sizing) {\n                    return `Занадто мале: очікується, що ${issue.origin} ${sizing.verb} ${adj}${issue.minimum.toString()} ${sizing.unit}`;\n                }\n                return `Занадто мале: очікується, що ${issue.origin} буде ${adj}${issue.minimum.toString()}`;\n            }\n            case \"invalid_format\": {\n                const _issue = issue;\n                if (_issue.format === \"starts_with\")\n                    return `Неправильний рядок: повинен починатися з \"${_issue.prefix}\"`;\n                if (_issue.format === \"ends_with\")\n                    return `Неправильний рядок: повинен закінчуватися на \"${_issue.suffix}\"`;\n                if (_issue.format === \"includes\")\n                    return `Неправильний рядок: повинен містити \"${_issue.includes}\"`;\n                if (_issue.format === \"regex\")\n                    return `Неправильний рядок: повинен відповідати шаблону ${_issue.pattern}`;\n                return `Неправильний ${FormatDictionary[_issue.format] ?? issue.format}`;\n            }\n            case \"not_multiple_of\":\n                return `Неправильне число: повинно бути кратним ${issue.divisor}`;\n            case \"unrecognized_keys\":\n                return `Нерозпізнаний ключ${issue.keys.length > 1 ? \"і\" : \"\"}: ${util.joinValues(issue.keys, \", \")}`;\n            case \"invalid_key\":\n                return `Неправильний ключ у ${issue.origin}`;\n            case \"invalid_union\":\n                return \"Неправильні вхідні дані\";\n            case \"invalid_element\":\n                return `Неправильне значення у ${issue.origin}`;\n            default:\n                return `Неправильні вхідні дані`;\n        }\n    };\n};\nexport default function () {\n    return {\n        localeError: error(),\n    };\n}\n","import uk from \"./uk.js\";\n/** @deprecated Use `uk` instead. */\nexport default function () {\n    return uk();\n}\n","import * as util from \"../core/util.js\";\nconst error = () => {\n    const Sizable = {\n        string: { unit: \"حروف\", verb: \"ہونا\" },\n        file: { unit: \"بائٹس\", verb: \"ہونا\" },\n        array: { unit: \"آئٹمز\", verb: \"ہونا\" },\n        set: { unit: \"آئٹمز\", verb: \"ہونا\" },\n    };\n    function getSizing(origin) {\n        return Sizable[origin] ?? null;\n    }\n    const FormatDictionary = {\n        regex: \"ان پٹ\",\n        email: \"ای میل ایڈریس\",\n        url: \"یو آر ایل\",\n        emoji: \"ایموجی\",\n        uuid: \"یو یو آئی ڈی\",\n        uuidv4: \"یو یو آئی ڈی وی 4\",\n        uuidv6: \"یو یو آئی ڈی وی 6\",\n        nanoid: \"نینو آئی ڈی\",\n        guid: \"جی یو آئی ڈی\",\n        cuid: \"سی یو آئی ڈی\",\n        cuid2: \"سی یو آئی ڈی 2\",\n        ulid: \"یو ایل آئی ڈی\",\n        xid: \"ایکس آئی ڈی\",\n        ksuid: \"کے ایس یو آئی ڈی\",\n        datetime: \"آئی ایس او ڈیٹ ٹائم\",\n        date: \"آئی ایس او تاریخ\",\n        time: \"آئی ایس او وقت\",\n        duration: \"آئی ایس او مدت\",\n        ipv4: \"آئی پی وی 4 ایڈریس\",\n        ipv6: \"آئی پی وی 6 ایڈریس\",\n        cidrv4: \"آئی پی وی 4 رینج\",\n        cidrv6: \"آئی پی وی 6 رینج\",\n        base64: \"بیس 64 ان کوڈڈ سٹرنگ\",\n        base64url: \"بیس 64 یو آر ایل ان کوڈڈ سٹرنگ\",\n        json_string: \"جے ایس او این سٹرنگ\",\n        e164: \"ای 164 نمبر\",\n        jwt: \"جے ڈبلیو ٹی\",\n        template_literal: \"ان پٹ\",\n    };\n    const TypeDictionary = {\n        nan: \"NaN\",\n        number: \"نمبر\",\n        array: \"آرے\",\n        null: \"نل\",\n    };\n    return (issue) => {\n        switch (issue.code) {\n            case \"invalid_type\": {\n                const expected = TypeDictionary[issue.expected] ?? issue.expected;\n                const receivedType = util.parsedType(issue.input);\n                const received = TypeDictionary[receivedType] ?? receivedType;\n                if (/^[A-Z]/.test(issue.expected)) {\n                    return `غلط ان پٹ: instanceof ${issue.expected} متوقع تھا، ${received} موصول ہوا`;\n                }\n                return `غلط ان پٹ: ${expected} متوقع تھا، ${received} موصول ہوا`;\n            }\n            case \"invalid_value\":\n                if (issue.values.length === 1)\n                    return `غلط ان پٹ: ${util.stringifyPrimitive(issue.values[0])} متوقع تھا`;\n                return `غلط آپشن: ${util.joinValues(issue.values, \"|\")} میں سے ایک متوقع تھا`;\n            case \"too_big\": {\n                const adj = issue.inclusive ? \"<=\" : \"<\";\n                const sizing = getSizing(issue.origin);\n                if (sizing)\n                    return `بہت بڑا: ${issue.origin ?? \"ویلیو\"} کے ${adj}${issue.maximum.toString()} ${sizing.unit ?? \"عناصر\"} ہونے متوقع تھے`;\n                return `بہت بڑا: ${issue.origin ?? \"ویلیو\"} کا ${adj}${issue.maximum.toString()} ہونا متوقع تھا`;\n            }\n            case \"too_small\": {\n                const adj = issue.inclusive ? \">=\" : \">\";\n                const sizing = getSizing(issue.origin);\n                if (sizing) {\n                    return `بہت چھوٹا: ${issue.origin} کے ${adj}${issue.minimum.toString()} ${sizing.unit} ہونے متوقع تھے`;\n                }\n                return `بہت چھوٹا: ${issue.origin} کا ${adj}${issue.minimum.toString()} ہونا متوقع تھا`;\n            }\n            case \"invalid_format\": {\n                const _issue = issue;\n                if (_issue.format === \"starts_with\") {\n                    return `غلط سٹرنگ: \"${_issue.prefix}\" سے شروع ہونا چاہیے`;\n                }\n                if (_issue.format === \"ends_with\")\n                    return `غلط سٹرنگ: \"${_issue.suffix}\" پر ختم ہونا چاہیے`;\n                if (_issue.format === \"includes\")\n                    return `غلط سٹرنگ: \"${_issue.includes}\" شامل ہونا چاہیے`;\n                if (_issue.format === \"regex\")\n                    return `غلط سٹرنگ: پیٹرن ${_issue.pattern} سے میچ ہونا چاہیے`;\n                return `غلط ${FormatDictionary[_issue.format] ?? issue.format}`;\n            }\n            case \"not_multiple_of\":\n                return `غلط نمبر: ${issue.divisor} کا مضاعف ہونا چاہیے`;\n            case \"unrecognized_keys\":\n                return `غیر تسلیم شدہ کی${issue.keys.length > 1 ? \"ز\" : \"\"}: ${util.joinValues(issue.keys, \"، \")}`;\n            case \"invalid_key\":\n                return `${issue.origin} میں غلط کی`;\n            case \"invalid_union\":\n                return \"غلط ان پٹ\";\n            case \"invalid_element\":\n                return `${issue.origin} میں غلط ویلیو`;\n            default:\n                return `غلط ان پٹ`;\n        }\n    };\n};\nexport default function () {\n    return {\n        localeError: error(),\n    };\n}\n","import * as util from \"../core/util.js\";\nconst error = () => {\n    const Sizable = {\n        string: { unit: \"belgi\", verb: \"bo‘lishi kerak\" },\n        file: { unit: \"bayt\", verb: \"bo‘lishi kerak\" },\n        array: { unit: \"element\", verb: \"bo‘lishi kerak\" },\n        set: { unit: \"element\", verb: \"bo‘lishi kerak\" },\n        map: { unit: \"yozuv\", verb: \"bo‘lishi kerak\" },\n    };\n    function getSizing(origin) {\n        return Sizable[origin] ?? null;\n    }\n    const FormatDictionary = {\n        regex: \"kirish\",\n        email: \"elektron pochta manzili\",\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 sana va vaqti\",\n        date: \"ISO sana\",\n        time: \"ISO vaqt\",\n        duration: \"ISO davomiylik\",\n        ipv4: \"IPv4 manzil\",\n        ipv6: \"IPv6 manzil\",\n        mac: \"MAC manzil\",\n        cidrv4: \"IPv4 diapazon\",\n        cidrv6: \"IPv6 diapazon\",\n        base64: \"base64 kodlangan satr\",\n        base64url: \"base64url kodlangan satr\",\n        json_string: \"JSON satr\",\n        e164: \"E.164 raqam\",\n        jwt: \"JWT\",\n        template_literal: \"kirish\",\n    };\n    const TypeDictionary = {\n        nan: \"NaN\",\n        number: \"raqam\",\n        array: \"massiv\",\n    };\n    return (issue) => {\n        switch (issue.code) {\n            case \"invalid_type\": {\n                const expected = TypeDictionary[issue.expected] ?? issue.expected;\n                const receivedType = util.parsedType(issue.input);\n                const received = TypeDictionary[receivedType] ?? receivedType;\n                if (/^[A-Z]/.test(issue.expected)) {\n                    return `Noto‘g‘ri kirish: kutilgan instanceof ${issue.expected}, qabul qilingan ${received}`;\n                }\n                return `Noto‘g‘ri kirish: kutilgan ${expected}, qabul qilingan ${received}`;\n            }\n            case \"invalid_value\":\n                if (issue.values.length === 1)\n                    return `Noto‘g‘ri kirish: kutilgan ${util.stringifyPrimitive(issue.values[0])}`;\n                return `Noto‘g‘ri variant: quyidagilardan biri kutilgan ${util.joinValues(issue.values, \"|\")}`;\n            case \"too_big\": {\n                const adj = issue.inclusive ? \"<=\" : \"<\";\n                const sizing = getSizing(issue.origin);\n                if (sizing)\n                    return `Juda katta: kutilgan ${issue.origin ?? \"qiymat\"} ${adj}${issue.maximum.toString()} ${sizing.unit} ${sizing.verb}`;\n                return `Juda katta: kutilgan ${issue.origin ?? \"qiymat\"} ${adj}${issue.maximum.toString()}`;\n            }\n            case \"too_small\": {\n                const adj = issue.inclusive ? \">=\" : \">\";\n                const sizing = getSizing(issue.origin);\n                if (sizing) {\n                    return `Juda kichik: kutilgan ${issue.origin} ${adj}${issue.minimum.toString()} ${sizing.unit} ${sizing.verb}`;\n                }\n                return `Juda kichik: kutilgan ${issue.origin} ${adj}${issue.minimum.toString()}`;\n            }\n            case \"invalid_format\": {\n                const _issue = issue;\n                if (_issue.format === \"starts_with\")\n                    return `Noto‘g‘ri satr: \"${_issue.prefix}\" bilan boshlanishi kerak`;\n                if (_issue.format === \"ends_with\")\n                    return `Noto‘g‘ri satr: \"${_issue.suffix}\" bilan tugashi kerak`;\n                if (_issue.format === \"includes\")\n                    return `Noto‘g‘ri satr: \"${_issue.includes}\" ni o‘z ichiga olishi kerak`;\n                if (_issue.format === \"regex\")\n                    return `Noto‘g‘ri satr: ${_issue.pattern} shabloniga mos kelishi kerak`;\n                return `Noto‘g‘ri ${FormatDictionary[_issue.format] ?? issue.format}`;\n            }\n            case \"not_multiple_of\":\n                return `Noto‘g‘ri raqam: ${issue.divisor} ning karralisi bo‘lishi kerak`;\n            case \"unrecognized_keys\":\n                return `Noma’lum kalit${issue.keys.length > 1 ? \"lar\" : \"\"}: ${util.joinValues(issue.keys, \", \")}`;\n            case \"invalid_key\":\n                return `${issue.origin} dagi kalit noto‘g‘ri`;\n            case \"invalid_union\":\n                return \"Noto‘g‘ri kirish\";\n            case \"invalid_element\":\n                return `${issue.origin} da noto‘g‘ri qiymat`;\n            default:\n                return `Noto‘g‘ri kirish`;\n        }\n    };\n};\nexport default function () {\n    return {\n        localeError: error(),\n    };\n}\n","import * as util from \"../core/util.js\";\nconst error = () => {\n    const Sizable = {\n        string: { unit: \"ký tự\", verb: \"có\" },\n        file: { unit: \"byte\", verb: \"có\" },\n        array: { unit: \"phần tử\", verb: \"có\" },\n        set: { unit: \"phần tử\", verb: \"có\" },\n    };\n    function getSizing(origin) {\n        return Sizable[origin] ?? null;\n    }\n    const FormatDictionary = {\n        regex: \"đầu vào\",\n        email: \"địa chỉ email\",\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: \"ngày giờ ISO\",\n        date: \"ngày ISO\",\n        time: \"giờ ISO\",\n        duration: \"khoảng thời gian ISO\",\n        ipv4: \"địa chỉ IPv4\",\n        ipv6: \"địa chỉ IPv6\",\n        cidrv4: \"dải IPv4\",\n        cidrv6: \"dải IPv6\",\n        base64: \"chuỗi mã hóa base64\",\n        base64url: \"chuỗi mã hóa base64url\",\n        json_string: \"chuỗi JSON\",\n        e164: \"số E.164\",\n        jwt: \"JWT\",\n        template_literal: \"đầu vào\",\n    };\n    const TypeDictionary = {\n        nan: \"NaN\",\n        number: \"số\",\n        array: \"mảng\",\n    };\n    return (issue) => {\n        switch (issue.code) {\n            case \"invalid_type\": {\n                const expected = TypeDictionary[issue.expected] ?? issue.expected;\n                const receivedType = util.parsedType(issue.input);\n                const received = TypeDictionary[receivedType] ?? receivedType;\n                if (/^[A-Z]/.test(issue.expected)) {\n                    return `Đầu vào không hợp lệ: mong đợi instanceof ${issue.expected}, nhận được ${received}`;\n                }\n                return `Đầu vào không hợp lệ: mong đợi ${expected}, nhận được ${received}`;\n            }\n            case \"invalid_value\":\n                if (issue.values.length === 1)\n                    return `Đầu vào không hợp lệ: mong đợi ${util.stringifyPrimitive(issue.values[0])}`;\n                return `Tùy chọn không hợp lệ: mong đợi một trong các giá trị ${util.joinValues(issue.values, \"|\")}`;\n            case \"too_big\": {\n                const adj = issue.inclusive ? \"<=\" : \"<\";\n                const sizing = getSizing(issue.origin);\n                if (sizing)\n                    return `Quá lớn: mong đợi ${issue.origin ?? \"giá trị\"} ${sizing.verb} ${adj}${issue.maximum.toString()} ${sizing.unit ?? \"phần tử\"}`;\n                return `Quá lớn: mong đợi ${issue.origin ?? \"giá trị\"} ${adj}${issue.maximum.toString()}`;\n            }\n            case \"too_small\": {\n                const adj = issue.inclusive ? \">=\" : \">\";\n                const sizing = getSizing(issue.origin);\n                if (sizing) {\n                    return `Quá nhỏ: mong đợi ${issue.origin} ${sizing.verb} ${adj}${issue.minimum.toString()} ${sizing.unit}`;\n                }\n                return `Quá nhỏ: mong đợi ${issue.origin} ${adj}${issue.minimum.toString()}`;\n            }\n            case \"invalid_format\": {\n                const _issue = issue;\n                if (_issue.format === \"starts_with\")\n                    return `Chuỗi không hợp lệ: phải bắt đầu bằng \"${_issue.prefix}\"`;\n                if (_issue.format === \"ends_with\")\n                    return `Chuỗi không hợp lệ: phải kết thúc bằng \"${_issue.suffix}\"`;\n                if (_issue.format === \"includes\")\n                    return `Chuỗi không hợp lệ: phải bao gồm \"${_issue.includes}\"`;\n                if (_issue.format === \"regex\")\n                    return `Chuỗi không hợp lệ: phải khớp với mẫu ${_issue.pattern}`;\n                return `${FormatDictionary[_issue.format] ?? issue.format} không hợp lệ`;\n            }\n            case \"not_multiple_of\":\n                return `Số không hợp lệ: phải là bội số của ${issue.divisor}`;\n            case \"unrecognized_keys\":\n                return `Khóa không được nhận dạng: ${util.joinValues(issue.keys, \", \")}`;\n            case \"invalid_key\":\n                return `Khóa không hợp lệ trong ${issue.origin}`;\n            case \"invalid_union\":\n                return \"Đầu vào không hợp lệ\";\n            case \"invalid_element\":\n                return `Giá trị không hợp lệ trong ${issue.origin}`;\n            default:\n                return `Đầu vào không hợp lệ`;\n        }\n    };\n};\nexport default function () {\n    return {\n        localeError: error(),\n    };\n}\n","import * as util from \"../core/util.js\";\nconst error = () => {\n    const Sizable = {\n        string: { unit: \"字符\", verb: \"包含\" },\n        file: { unit: \"字节\", verb: \"包含\" },\n        array: { unit: \"项\", verb: \"包含\" },\n        set: { unit: \"项\", verb: \"包含\" },\n    };\n    function getSizing(origin) {\n        return Sizable[origin] ?? null;\n    }\n    const FormatDictionary = {\n        regex: \"输入\",\n        email: \"电子邮件\",\n        url: \"URL\",\n        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日期时间\",\n        date: \"ISO日期\",\n        time: \"ISO时间\",\n        duration: \"ISO时长\",\n        ipv4: \"IPv4地址\",\n        ipv6: \"IPv6地址\",\n        cidrv4: \"IPv4网段\",\n        cidrv6: \"IPv6网段\",\n        base64: \"base64编码字符串\",\n        base64url: \"base64url编码字符串\",\n        json_string: \"JSON字符串\",\n        e164: \"E.164号码\",\n        jwt: \"JWT\",\n        template_literal: \"输入\",\n    };\n    const TypeDictionary = {\n        nan: \"NaN\",\n        number: \"数字\",\n        array: \"数组\",\n        null: \"空值(null)\",\n    };\n    return (issue) => {\n        switch (issue.code) {\n            case \"invalid_type\": {\n                const expected = TypeDictionary[issue.expected] ?? issue.expected;\n                const receivedType = util.parsedType(issue.input);\n                const received = TypeDictionary[receivedType] ?? receivedType;\n                if (/^[A-Z]/.test(issue.expected)) {\n                    return `无效输入：期望 instanceof ${issue.expected}，实际接收 ${received}`;\n                }\n                return `无效输入：期望 ${expected}，实际接收 ${received}`;\n            }\n            case \"invalid_value\":\n                if (issue.values.length === 1)\n                    return `无效输入：期望 ${util.stringifyPrimitive(issue.values[0])}`;\n                return `无效选项：期望以下之一 ${util.joinValues(issue.values, \"|\")}`;\n            case \"too_big\": {\n                const adj = issue.inclusive ? \"<=\" : \"<\";\n                const sizing = getSizing(issue.origin);\n                if (sizing)\n                    return `数值过大：期望 ${issue.origin ?? \"值\"} ${adj}${issue.maximum.toString()} ${sizing.unit ?? \"个元素\"}`;\n                return `数值过大：期望 ${issue.origin ?? \"值\"} ${adj}${issue.maximum.toString()}`;\n            }\n            case \"too_small\": {\n                const adj = issue.inclusive ? \">=\" : \">\";\n                const sizing = getSizing(issue.origin);\n                if (sizing) {\n                    return `数值过小：期望 ${issue.origin} ${adj}${issue.minimum.toString()} ${sizing.unit}`;\n                }\n                return `数值过小：期望 ${issue.origin} ${adj}${issue.minimum.toString()}`;\n            }\n            case \"invalid_format\": {\n                const _issue = issue;\n                if (_issue.format === \"starts_with\")\n                    return `无效字符串：必须以 \"${_issue.prefix}\" 开头`;\n                if (_issue.format === \"ends_with\")\n                    return `无效字符串：必须以 \"${_issue.suffix}\" 结尾`;\n                if (_issue.format === \"includes\")\n                    return `无效字符串：必须包含 \"${_issue.includes}\"`;\n                if (_issue.format === \"regex\")\n                    return `无效字符串：必须满足正则表达式 ${_issue.pattern}`;\n                return `无效${FormatDictionary[_issue.format] ?? issue.format}`;\n            }\n            case \"not_multiple_of\":\n                return `无效数字：必须是 ${issue.divisor} 的倍数`;\n            case \"unrecognized_keys\":\n                return `出现未知的键(key): ${util.joinValues(issue.keys, \", \")}`;\n            case \"invalid_key\":\n                return `${issue.origin} 中的键(key)无效`;\n            case \"invalid_union\":\n                return \"无效输入\";\n            case \"invalid_element\":\n                return `${issue.origin} 中包含无效值(value)`;\n            default:\n                return `无效输入`;\n        }\n    };\n};\nexport default function () {\n    return {\n        localeError: error(),\n    };\n}\n","import * as util from \"../core/util.js\";\nconst error = () => {\n    const Sizable = {\n        string: { unit: \"字元\", verb: \"擁有\" },\n        file: { unit: \"位元組\", verb: \"擁有\" },\n        array: { unit: \"項目\", verb: \"擁有\" },\n        set: { unit: \"項目\", verb: \"擁有\" },\n    };\n    function getSizing(origin) {\n        return Sizable[origin] ?? null;\n    }\n    const FormatDictionary = {\n        regex: \"輸入\",\n        email: \"郵件地址\",\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 日期時間\",\n        date: \"ISO 日期\",\n        time: \"ISO 時間\",\n        duration: \"ISO 期間\",\n        ipv4: \"IPv4 位址\",\n        ipv6: \"IPv6 位址\",\n        cidrv4: \"IPv4 範圍\",\n        cidrv6: \"IPv6 範圍\",\n        base64: \"base64 編碼字串\",\n        base64url: \"base64url 編碼字串\",\n        json_string: \"JSON 字串\",\n        e164: \"E.164 數值\",\n        jwt: \"JWT\",\n        template_literal: \"輸入\",\n    };\n    const TypeDictionary = {\n        nan: \"NaN\",\n    };\n    return (issue) => {\n        switch (issue.code) {\n            case \"invalid_type\": {\n                const expected = TypeDictionary[issue.expected] ?? issue.expected;\n                const receivedType = util.parsedType(issue.input);\n                const received = TypeDictionary[receivedType] ?? receivedType;\n                if (/^[A-Z]/.test(issue.expected)) {\n                    return `無效的輸入值：預期為 instanceof ${issue.expected}，但收到 ${received}`;\n                }\n                return `無效的輸入值：預期為 ${expected}，但收到 ${received}`;\n            }\n            case \"invalid_value\":\n                if (issue.values.length === 1)\n                    return `無效的輸入值：預期為 ${util.stringifyPrimitive(issue.values[0])}`;\n                return `無效的選項：預期為以下其中之一 ${util.joinValues(issue.values, \"|\")}`;\n            case \"too_big\": {\n                const adj = issue.inclusive ? \"<=\" : \"<\";\n                const sizing = getSizing(issue.origin);\n                if (sizing)\n                    return `數值過大：預期 ${issue.origin ?? \"值\"} 應為 ${adj}${issue.maximum.toString()} ${sizing.unit ?? \"個元素\"}`;\n                return `數值過大：預期 ${issue.origin ?? \"值\"} 應為 ${adj}${issue.maximum.toString()}`;\n            }\n            case \"too_small\": {\n                const adj = issue.inclusive ? \">=\" : \">\";\n                const sizing = getSizing(issue.origin);\n                if (sizing) {\n                    return `數值過小：預期 ${issue.origin} 應為 ${adj}${issue.minimum.toString()} ${sizing.unit}`;\n                }\n                return `數值過小：預期 ${issue.origin} 應為 ${adj}${issue.minimum.toString()}`;\n            }\n            case \"invalid_format\": {\n                const _issue = issue;\n                if (_issue.format === \"starts_with\") {\n                    return `無效的字串：必須以 \"${_issue.prefix}\" 開頭`;\n                }\n                if (_issue.format === \"ends_with\")\n                    return `無效的字串：必須以 \"${_issue.suffix}\" 結尾`;\n                if (_issue.format === \"includes\")\n                    return `無效的字串：必須包含 \"${_issue.includes}\"`;\n                if (_issue.format === \"regex\")\n                    return `無效的字串：必須符合格式 ${_issue.pattern}`;\n                return `無效的 ${FormatDictionary[_issue.format] ?? issue.format}`;\n            }\n            case \"not_multiple_of\":\n                return `無效的數字：必須為 ${issue.divisor} 的倍數`;\n            case \"unrecognized_keys\":\n                return `無法識別的鍵值${issue.keys.length > 1 ? \"們\" : \"\"}：${util.joinValues(issue.keys, \"、\")}`;\n            case \"invalid_key\":\n                return `${issue.origin} 中有無效的鍵值`;\n            case \"invalid_union\":\n                return \"無效的輸入值\";\n            case \"invalid_element\":\n                return `${issue.origin} 中有無效的值`;\n            default:\n                return `無效的輸入值`;\n        }\n    };\n};\nexport default function () {\n    return {\n        localeError: error(),\n    };\n}\n","import * as util from \"../core/util.js\";\nconst error = () => {\n    const Sizable = {\n        string: { unit: \"àmi\", verb: \"ní\" },\n        file: { unit: \"bytes\", verb: \"ní\" },\n        array: { unit: \"nkan\", verb: \"ní\" },\n        set: { unit: \"nkan\", verb: \"ní\" },\n    };\n    function getSizing(origin) {\n        return Sizable[origin] ?? null;\n    }\n    const FormatDictionary = {\n        regex: \"ẹ̀rọ ìbáwọlé\",\n        email: \"àdírẹ́sì ìmẹ́lì\",\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: \"àkókò ISO\",\n        date: \"ọjọ́ ISO\",\n        time: \"àkókò ISO\",\n        duration: \"àkókò tó pé ISO\",\n        ipv4: \"àdírẹ́sì IPv4\",\n        ipv6: \"àdírẹ́sì IPv6\",\n        cidrv4: \"àgbègbè IPv4\",\n        cidrv6: \"àgbègbè IPv6\",\n        base64: \"ọ̀rọ̀ tí a kọ́ ní base64\",\n        base64url: \"ọ̀rọ̀ base64url\",\n        json_string: \"ọ̀rọ̀ JSON\",\n        e164: \"nọ́mbà E.164\",\n        jwt: \"JWT\",\n        template_literal: \"ẹ̀rọ ìbáwọlé\",\n    };\n    const TypeDictionary = {\n        nan: \"NaN\",\n        number: \"nọ́mbà\",\n        array: \"akopọ\",\n    };\n    return (issue) => {\n        switch (issue.code) {\n            case \"invalid_type\": {\n                const expected = TypeDictionary[issue.expected] ?? issue.expected;\n                const receivedType = util.parsedType(issue.input);\n                const received = TypeDictionary[receivedType] ?? receivedType;\n                if (/^[A-Z]/.test(issue.expected)) {\n                    return `Ìbáwọlé aṣìṣe: a ní láti fi instanceof ${issue.expected}, àmọ̀ a rí ${received}`;\n                }\n                return `Ìbáwọlé aṣìṣe: a ní láti fi ${expected}, àmọ̀ a rí ${received}`;\n            }\n            case \"invalid_value\":\n                if (issue.values.length === 1)\n                    return `Ìbáwọlé aṣìṣe: a ní láti fi ${util.stringifyPrimitive(issue.values[0])}`;\n                return `Àṣàyàn aṣìṣe: yan ọ̀kan lára ${util.joinValues(issue.values, \"|\")}`;\n            case \"too_big\": {\n                const adj = issue.inclusive ? \"<=\" : \"<\";\n                const sizing = getSizing(issue.origin);\n                if (sizing)\n                    return `Tó pọ̀ jù: a ní láti jẹ́ pé ${issue.origin ?? \"iye\"} ${sizing.verb} ${adj}${issue.maximum} ${sizing.unit}`;\n                return `Tó pọ̀ jù: a ní láti jẹ́ ${adj}${issue.maximum}`;\n            }\n            case \"too_small\": {\n                const adj = issue.inclusive ? \">=\" : \">\";\n                const sizing = getSizing(issue.origin);\n                if (sizing)\n                    return `Kéré ju: a ní láti jẹ́ pé ${issue.origin} ${sizing.verb} ${adj}${issue.minimum} ${sizing.unit}`;\n                return `Kéré ju: a ní láti jẹ́ ${adj}${issue.minimum}`;\n            }\n            case \"invalid_format\": {\n                const _issue = issue;\n                if (_issue.format === \"starts_with\")\n                    return `Ọ̀rọ̀ aṣìṣe: gbọ́dọ̀ bẹ̀rẹ̀ pẹ̀lú \"${_issue.prefix}\"`;\n                if (_issue.format === \"ends_with\")\n                    return `Ọ̀rọ̀ aṣìṣe: gbọ́dọ̀ parí pẹ̀lú \"${_issue.suffix}\"`;\n                if (_issue.format === \"includes\")\n                    return `Ọ̀rọ̀ aṣìṣe: gbọ́dọ̀ ní \"${_issue.includes}\"`;\n                if (_issue.format === \"regex\")\n                    return `Ọ̀rọ̀ aṣìṣe: gbọ́dọ̀ bá àpẹẹrẹ mu ${_issue.pattern}`;\n                return `Aṣìṣe: ${FormatDictionary[_issue.format] ?? issue.format}`;\n            }\n            case \"not_multiple_of\":\n                return `Nọ́mbà aṣìṣe: gbọ́dọ̀ jẹ́ èyà pípín ti ${issue.divisor}`;\n            case \"unrecognized_keys\":\n                return `Bọtìnì àìmọ̀: ${util.joinValues(issue.keys, \", \")}`;\n            case \"invalid_key\":\n                return `Bọtìnì aṣìṣe nínú ${issue.origin}`;\n            case \"invalid_union\":\n                return \"Ìbáwọlé aṣìṣe\";\n            case \"invalid_element\":\n                return `Iye aṣìṣe nínú ${issue.origin}`;\n            default:\n                return \"Ìbáwọlé aṣìṣe\";\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 ca } from \"./ca.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 he } from \"./he.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 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 nl } from \"./nl.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 ro } from \"./ro.js\";\nexport { default as ru } from \"./ru.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 th } from \"./th.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 = Symbol(\"ZodOutput\");\nexport const $input = 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 * as checks from \"./checks.js\";\nimport * as registries from \"./registries.js\";\nimport * as schemas from \"./schemas.js\";\nimport * as util from \"./util.js\";\n// @__NO_SIDE_EFFECTS__\nexport function _string(Class, params) {\n    return new Class({\n        type: \"string\",\n        ...util.normalizeParams(params),\n    });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _coercedString(Class, params) {\n    return new Class({\n        type: \"string\",\n        coerce: true,\n        ...util.normalizeParams(params),\n    });\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 _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({\n        type: \"number\",\n        checks: [],\n        ...util.normalizeParams(params),\n    });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _coercedNumber(Class, params) {\n    return new Class({\n        type: \"number\",\n        coerce: true,\n        checks: [],\n        ...util.normalizeParams(params),\n    });\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 _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,\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 : () => 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                _issue.input ?? (_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    return codec;\n}\n// @__NO_SIDE_EFFECTS__\nexport function _stringFormat(Class, format, fnOrRegex, _params = {}) {\n    const params = util.normalizeParams(_params);\n    const def = {\n        ...util.normalizeParams(_params),\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\";\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        cycles: params?.cycles ?? \"ref\",\n        reused: params?.reused ?? \"inline\",\n        external: params?.external ?? undefined,\n    };\n}\nexport function process(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    // 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            process(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        Object.assign(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}\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    // 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\n    // defId will be empty if the ref points to an external schema (or #)\n    const makeURI = (entry) => {\n        // comparing the seen objects because sometimes\n        // multiple schemas map to the same seen object.\n        // 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}/${id}` };\n        }\n        if (entry[1] === root) {\n            return { ref: \"#\" };\n        }\n        // self-contained schema\n        const uriPrefix = `#`;\n        const defUriPrefix = `${uriPrefix}/${defsSegment}/`;\n        const defId = entry[1].schema.id ?? `__schema${ctx.counter++}`;\n        return { defId, ref: defUriPrefix + defId };\n    };\n    // stored cached version in `def` property\n    // 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\n        // 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                // biome-ignore lint:\n                continue;\n            }\n        }\n    }\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                Object.assign(schema, refSchema);\n            }\n            // restore child's own properties (child wins)\n            Object.assign(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\n        // This handles cases like: readonly().meta({id}).describe()\n        // 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    for (const entry of [...ctx.seen.entries()].reverse()) {\n        flattenRef(entry[0]);\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    Object.assign(result, root.def ?? root.schema);\n    // The `id` in `.meta()` is a Zod-specific registration tag used to extract\n    // schemas into $defs — it is not user-facing JSON Schema metadata. Strip it\n    // from the output body where it would otherwise leak. The id is preserved\n    // 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\n    const defs = ctx.external?.defs ?? {};\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            defs[seen.defId] = seen.def;\n        }\n    }\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\n        // each call to finalize() is functionally independent\n        // 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        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    process(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    process(schema, ctx);\n    extractDefs(ctx, schema);\n    return finalize(ctx, schema);\n};\n","import { extractDefs, finalize, initializeContext, process, } from \"./to-json-schema.js\";\nimport { getEnumValues } from \"./util.js\";\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 ====================\nexport const stringProcessor = (schema, ctx, _json, _params) => {\n    const json = _json;\n    json.type = \"string\";\n    const { minimum, maximum, format, patterns, contentEncoding } = schema._zod\n        .bag;\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        // JSON Schema format: \"time\" requires a full time with offset or Z\n        // z.iso.time() does not include timezone information, so format: \"time\" should never be used\n        if (format === \"time\") {\n            delete json.format;\n        }\n    }\n    if (contentEncoding)\n        json.contentEncoding = contentEncoding;\n    if (patterns && patterns.size > 0) {\n        const regexes = [...patterns];\n        if (regexes.length === 1)\n            json.pattern = regexes[0].source;\n        else if (regexes.length > 1) {\n            json.allOf = [\n                ...regexes.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, format, multipleOf, exclusiveMaximum, exclusiveMinimum } = schema._zod.bag;\n    if (typeof format === \"string\" && format.includes(\"int\"))\n        json.type = \"integer\";\n    else\n        json.type = \"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 (typeof multipleOf === \"number\")\n        json.multipleOf = multipleOf;\n};\nexport const booleanProcessor = (_schema, _ctx, json, _params) => {\n    json.type = \"boolean\";\n};\nexport const bigintProcessor = (_schema, ctx, _json, _params) => {\n    if (ctx.unrepresentable === \"throw\") {\n        throw new Error(\"BigInt cannot be represented in JSON Schema\");\n    }\n};\nexport const symbolProcessor = (_schema, ctx, _json, _params) => {\n    if (ctx.unrepresentable === \"throw\") {\n        throw new Error(\"Symbols cannot be represented in JSON Schema\");\n    }\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    if (ctx.unrepresentable === \"throw\") {\n        throw new Error(\"Undefined cannot be represented in JSON Schema\");\n    }\n};\nexport const voidProcessor = (_schema, ctx, _json, _params) => {\n    if (ctx.unrepresentable === \"throw\") {\n        throw new Error(\"Void cannot be represented in JSON Schema\");\n    }\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    if (ctx.unrepresentable === \"throw\") {\n        throw new Error(\"Date cannot be represented in JSON Schema\");\n    }\n};\nexport const enumProcessor = (schema, _ctx, json, _params) => {\n    const def = schema._zod.def;\n    const values = getEnumValues(def.entries);\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    const vals = [];\n    for (const val of def.values) {\n        if (val === undefined) {\n            if (ctx.unrepresentable === \"throw\") {\n                throw new Error(\"Literal `undefined` cannot be represented in JSON Schema\");\n            }\n            else {\n                // do not add to vals\n            }\n        }\n        else if (typeof val === \"bigint\") {\n            if (ctx.unrepresentable === \"throw\") {\n                throw new Error(\"BigInt literals cannot be represented in JSON Schema\");\n            }\n            else {\n                vals.push(Number(val));\n            }\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    if (ctx.unrepresentable === \"throw\") {\n        throw new Error(\"NaN cannot be represented in JSON Schema\");\n    }\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    const file = {\n        type: \"string\",\n        format: \"binary\",\n        contentEncoding: \"binary\",\n    };\n    const { minimum, maximum, mime } = schema._zod.bag;\n    if (minimum !== undefined)\n        file.minLength = minimum;\n    if (maximum !== undefined)\n        file.maxLength = maximum;\n    if (mime) {\n        if (mime.length === 1) {\n            file.contentMediaType = mime[0];\n            Object.assign(_json, file);\n        }\n        else {\n            Object.assign(_json, file); // shared props at root\n            _json.anyOf = mime.map((m) => ({ contentMediaType: m })); // only contentMediaType differs\n        }\n    }\n    else {\n        Object.assign(_json, file);\n    }\n};\nexport const successProcessor = (_schema, _ctx, json, _params) => {\n    json.type = \"boolean\";\n};\nexport const customProcessor = (_schema, ctx, _json, _params) => {\n    if (ctx.unrepresentable === \"throw\") {\n        throw new Error(\"Custom types cannot be represented in JSON Schema\");\n    }\n};\nexport const functionProcessor = (_schema, ctx, _json, _params) => {\n    if (ctx.unrepresentable === \"throw\") {\n        throw new Error(\"Function types cannot be represented in JSON Schema\");\n    }\n};\nexport const transformProcessor = (_schema, ctx, _json, _params) => {\n    if (ctx.unrepresentable === \"throw\") {\n        throw new Error(\"Transforms cannot be represented in JSON Schema\");\n    }\n};\nexport const mapProcessor = (_schema, ctx, _json, _params) => {\n    if (ctx.unrepresentable === \"throw\") {\n        throw new Error(\"Map cannot be represented in JSON Schema\");\n    }\n};\nexport const setProcessor = (_schema, ctx, _json, _params) => {\n    if (ctx.unrepresentable === \"throw\") {\n        throw new Error(\"Set cannot be represented in JSON Schema\");\n    }\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 } = schema._zod.bag;\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 = process(def.element, ctx, {\n        ...params,\n        path: [...params.path, \"items\"],\n    });\n};\nexport const objectProcessor = (schema, ctx, _json, params) => {\n    const json = _json;\n    const def = schema._zod.def;\n    json.type = \"object\";\n    json.properties = {};\n    const shape = def.shape;\n    for (const key in shape) {\n        json.properties[key] = process(shape[key], ctx, {\n            ...params,\n            path: [...params.path, \"properties\", key],\n        });\n    }\n    // required keys\n    const allKeys = new Set(Object.keys(shape));\n    const requiredKeys = new Set([...allKeys].filter((key) => {\n        const v = def.shape[key]._zod;\n        if (ctx.io === \"input\") {\n            return v.optin === undefined;\n        }\n        else {\n            return v.optout === undefined;\n        }\n    }));\n    if (requiredKeys.size > 0) {\n        json.required = Array.from(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 = process(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)\n    // This includes both z.xor() and discriminated unions\n    const isExclusive = def.inclusive === false;\n    const options = def.options.map((x, i) => process(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 = process(def.left, ctx, {\n        ...params,\n        path: [...params.path, \"allOf\", 0],\n    });\n    const b = process(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};\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) => process(x, ctx, {\n        ...params,\n        path: [...params.path, prefixPath, i],\n    }));\n    const rest = def.rest\n        ? process(def.rest, ctx, {\n            ...params,\n            path: [...params.path, restPath, ...(ctx.target === \"openapi-3.0\" ? [def.items.length] : [])],\n        })\n        : null;\n    if (ctx.target === \"draft-2020-12\") {\n        json.prefixItems = prefixItems;\n        if (rest) {\n            json.items = rest;\n        }\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        json.minItems = prefixItems.length;\n        if (!rest) {\n            json.maxItems = prefixItems.length;\n        }\n    }\n    else {\n        json.items = prefixItems;\n        if (rest) {\n            json.additionalItems = rest;\n        }\n    }\n    // length\n    const { minimum, maximum } = schema._zod.bag;\n    if (typeof minimum === \"number\")\n        json.minItems = minimum;\n    if (typeof maximum === \"number\")\n        json.maxItems = maximum;\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\n    // This correctly represents \"only validate keys matching the pattern\" semantics\n    // and composes well with allOf (intersections)\n    const keyType = def.keyType;\n    const keyBag = keyType._zod.bag;\n    const patterns = keyBag?.patterns;\n    if (def.mode === \"loose\" && patterns && patterns.size > 0) {\n        // Use patternProperties for looseRecord with regex patterns\n        const valueSchema = process(def.valueType, ctx, {\n            ...params,\n            path: [...params.path, \"patternProperties\", \"*\"],\n        });\n        json.patternProperties = {};\n        for (const pattern of patterns) {\n            json.patternProperties[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 = process(def.keyType, ctx, {\n                ...params,\n                path: [...params.path, \"propertyNames\"],\n            });\n        }\n        json.additionalProperties = process(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    if (keyValues) {\n        const validKeyValues = [...keyValues].filter((v) => typeof v === \"string\" || typeof v === \"number\");\n        if (validKeyValues.length > 0) {\n            json.required = validKeyValues;\n        }\n    }\n};\nexport const nullableProcessor = (schema, ctx, json, params) => {\n    const def = schema._zod.def;\n    const inner = process(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    process(def.innerType, ctx, params);\n    const seen = ctx.seen.get(schema);\n    seen.ref = def.innerType;\n};\nexport const defaultProcessor = (schema, ctx, json, params) => {\n    const def = schema._zod.def;\n    process(def.innerType, ctx, params);\n    const seen = ctx.seen.get(schema);\n    seen.ref = def.innerType;\n    json.default = JSON.parse(JSON.stringify(def.defaultValue));\n};\nexport const prefaultProcessor = (schema, ctx, json, params) => {\n    const def = schema._zod.def;\n    process(def.innerType, ctx, params);\n    const seen = ctx.seen.get(schema);\n    seen.ref = def.innerType;\n    if (ctx.io === \"input\")\n        json._prefault = JSON.parse(JSON.stringify(def.defaultValue));\n};\nexport const catchProcessor = (schema, ctx, json, params) => {\n    const def = schema._zod.def;\n    process(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        throw new Error(\"Dynamic catch values are not supported in JSON Schema\");\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    process(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    process(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    process(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    process(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    process(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            process(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            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    process(input, ctx);\n    extractDefs(ctx, input);\n    return finalize(ctx, input);\n}\n","import { allProcessors } from \"./json-schema-processors.js\";\nimport { extractDefs, finalize, initializeContext, process, } from \"./to-json-schema.js\";\n/**\n * Legacy class-based interface for JSON Schema generation.\n * This class wraps the new functional implementation to provide backward compatibility.\n *\n * @deprecated Use the `toJSONSchema` function instead for new code.\n *\n * @example\n * ```typescript\n * // Legacy usage (still supported)\n * const gen = new JSONSchemaGenerator({ target: \"draft-07\" });\n * gen.process(schema);\n * const result = gen.emit(schema);\n *\n * // Preferred modern usage\n * const result = toJSONSchema(schema, { target: \"draft-07\" });\n * ```\n */\nexport class JSONSchemaGenerator {\n    /** @deprecated Access via ctx instead */\n    get metadataRegistry() {\n        return this.ctx.metadataRegistry;\n    }\n    /** @deprecated Access via ctx instead */\n    get target() {\n        return this.ctx.target;\n    }\n    /** @deprecated Access via ctx instead */\n    get unrepresentable() {\n        return this.ctx.unrepresentable;\n    }\n    /** @deprecated Access via ctx instead */\n    get override() {\n        return this.ctx.override;\n    }\n    /** @deprecated Access via ctx instead */\n    get io() {\n        return this.ctx.io;\n    }\n    /** @deprecated Access via ctx instead */\n    get counter() {\n        return this.ctx.counter;\n    }\n    set counter(value) {\n        this.ctx.counter = value;\n    }\n    /** @deprecated Access via ctx instead */\n    get seen() {\n        return this.ctx.seen;\n    }\n    constructor(params) {\n        // Normalize target for internal context\n        let normalizedTarget = params?.target ?? \"draft-2020-12\";\n        if (normalizedTarget === \"draft-4\")\n            normalizedTarget = \"draft-04\";\n        if (normalizedTarget === \"draft-7\")\n            normalizedTarget = \"draft-07\";\n        this.ctx = initializeContext({\n            processors: allProcessors,\n            target: normalizedTarget,\n            ...(params?.metadata && { metadata: params.metadata }),\n            ...(params?.unrepresentable && { unrepresentable: params.unrepresentable }),\n            ...(params?.override && { override: params.override }),\n            ...(params?.io && { io: params.io }),\n        });\n    }\n    /**\n     * Process a schema to prepare it for JSON Schema generation.\n     * This must be called before emit().\n     */\n    process(schema, _params = { path: [], schemaPath: [] }) {\n        return process(schema, this.ctx, _params);\n    }\n    /**\n     * Emit the final JSON Schema after processing.\n     * Must call process() first.\n     */\n    emit(schema, _params) {\n        // Apply emit params to the context\n        if (_params) {\n            if (_params.cycles)\n                this.ctx.cycles = _params.cycles;\n            if (_params.reused)\n                this.ctx.reused = _params.reused;\n            if (_params.external)\n                this.ctx.external = _params.external;\n        }\n        extractDefs(this.ctx, schema);\n        const result = finalize(this.ctx, schema);\n        // Strip ~standard property to match old implementation's return type\n        const { \"~standard\": _, ...plainResult } = result;\n        return plainResult;\n    }\n}\n","export {};\n","export * from \"./core.js\";\nexport * from \"./parse.js\";\nexport * from \"./errors.js\";\nexport * from \"./schemas.js\";\nexport * from \"./checks.js\";\nexport * from \"./versions.js\";\nexport * as util 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 \"./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, _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 * as schemas from \"./schemas.js\";\nexport const ZodISODateTime = /*@__PURE__*/ core.$constructor(\"ZodISODateTime\", (inst, def) => {\n    core.$ZodISODateTime.init(inst, def);\n    schemas.ZodStringFormat.init(inst, def);\n});\nexport function datetime(params) {\n    return core._isoDateTime(ZodISODateTime, params);\n}\nexport const ZodISODate = /*@__PURE__*/ core.$constructor(\"ZodISODate\", (inst, def) => {\n    core.$ZodISODate.init(inst, def);\n    schemas.ZodStringFormat.init(inst, def);\n});\nexport function date(params) {\n    return core._isoDate(ZodISODate, params);\n}\nexport const ZodISOTime = /*@__PURE__*/ core.$constructor(\"ZodISOTime\", (inst, def) => {\n    core.$ZodISOTime.init(inst, def);\n    schemas.ZodStringFormat.init(inst, def);\n});\nexport function time(params) {\n    return core._isoTime(ZodISOTime, params);\n}\nexport const ZodISODuration = /*@__PURE__*/ core.$constructor(\"ZodISODuration\", (inst, def) => {\n    core.$ZodISODuration.init(inst, def);\n    schemas.ZodStringFormat.init(inst, def);\n});\nexport function duration(params) {\n    return core._isoDuration(ZodISODuration, params);\n}\n","import * as core from \"../core/index.js\";\nimport { $ZodError } from \"../core/index.js\";\nimport * as util from \"../core/util.js\";\nconst initializer = (inst, issues) => {\n    $ZodError.init(inst, issues);\n    inst.name = \"ZodError\";\n    Object.defineProperties(inst, {\n        format: {\n            value: (mapper) => core.formatError(inst, mapper),\n            // enumerable: false,\n        },\n        flatten: {\n            value: (mapper) => core.flattenError(inst, mapper),\n            // enumerable: false,\n        },\n        addIssue: {\n            value: (issue) => {\n                inst.issues.push(issue);\n                inst.message = JSON.stringify(inst.issues, util.jsonStringifyReplacer, 2);\n            },\n            // enumerable: false,\n        },\n        addIssues: {\n            value: (issues) => {\n                inst.issues.push(...issues);\n                inst.message = JSON.stringify(inst.issues, util.jsonStringifyReplacer, 2);\n            },\n            // enumerable: false,\n        },\n        isEmpty: {\n            get() {\n                return inst.issues.length === 0;\n            },\n            // enumerable: false,\n        },\n    });\n    // Object.defineProperty(inst, \"isEmpty\", {\n    //   get() {\n    //     return inst.issues.length === 0;\n    //   },\n    // });\n};\nexport const ZodError = /*@__PURE__*/ core.$constructor(\"ZodError\", initializer);\nexport const ZodRealError = /*@__PURE__*/ core.$constructor(\"ZodError\", initializer, {\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);\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 { createStandardJSONSchemaMethod, createToJSONSchemaMethod } from \"../core/to-json-schema.js\";\nimport * as checks from \"./checks.js\";\nimport * as iso from \"./iso.js\";\nimport * as parse from \"./parse.js\";\n// Lazy-bind builder methods.\n//\n// Builder methods (`.optional`, `.array`, `.refine`, ...) live as\n// non-enumerable getters on each concrete schema constructor's\n// prototype. On first access from an instance the getter allocates\n// `fn.bind(this)` and caches it as an own property on that instance,\n// so detached usage (`const m = schema.optional; m()`) still works\n// and the per-instance allocation only happens for methods actually\n// touched.\n//\n// One install per (prototype, group), memoized by `_installedGroups`.\nconst _installedGroups = /* @__PURE__ */ new WeakMap();\nfunction _installLazyMethods(inst, group, methods) {\n    const proto = Object.getPrototypeOf(inst);\n    let installed = _installedGroups.get(proto);\n    if (!installed) {\n        installed = new Set();\n        _installedGroups.set(proto, installed);\n    }\n    if (installed.has(group))\n        return;\n    installed.add(group);\n    for (const key in methods) {\n        const fn = methods[key];\n        Object.defineProperty(proto, key, {\n            configurable: true,\n            enumerable: false,\n            get() {\n                const bound = fn.bind(this);\n                Object.defineProperty(this, key, {\n                    configurable: true,\n                    writable: true,\n                    enumerable: true,\n                    value: bound,\n                });\n                return bound;\n            },\n            set(v) {\n                Object.defineProperty(this, key, {\n                    configurable: true,\n                    writable: true,\n                    enumerable: true,\n                    value: v,\n                });\n            },\n        });\n    }\n}\nexport const ZodType = /*@__PURE__*/ core.$constructor(\"ZodType\", (inst, def) => {\n    core.$ZodType.init(inst, def);\n    Object.assign(inst[\"~standard\"], {\n        jsonSchema: {\n            input: createStandardJSONSchemaMethod(inst, \"input\"),\n            output: createStandardJSONSchemaMethod(inst, \"output\"),\n        },\n    });\n    inst.toJSONSchema = createToJSONSchemaMethod(inst, {});\n    inst.def = def;\n    inst.type = def.type;\n    Object.defineProperty(inst, \"_def\", { value: def });\n    // Parse-family is intentionally kept as per-instance closures: these are\n    // the hot path AND the most-detached methods (`arr.map(schema.parse)`,\n    // `const { parse } = schema`, etc.). Eager closures here mean callers pay\n    // ~12 closure allocations per schema but get monomorphic call sites and\n    // detached usage that \"just works\".\n    inst.parse = (data, params) => parse.parse(inst, data, params, { callee: inst.parse });\n    inst.safeParse = (data, params) => parse.safeParse(inst, data, params);\n    inst.parseAsync = async (data, params) => parse.parseAsync(inst, data, params, { callee: inst.parseAsync });\n    inst.safeParseAsync = async (data, params) => parse.safeParseAsync(inst, data, params);\n    inst.spa = inst.safeParseAsync;\n    inst.encode = (data, params) => parse.encode(inst, data, params);\n    inst.decode = (data, params) => parse.decode(inst, data, params);\n    inst.encodeAsync = async (data, params) => parse.encodeAsync(inst, data, params);\n    inst.decodeAsync = async (data, params) => parse.decodeAsync(inst, data, params);\n    inst.safeEncode = (data, params) => parse.safeEncode(inst, data, params);\n    inst.safeDecode = (data, params) => parse.safeDecode(inst, data, params);\n    inst.safeEncodeAsync = async (data, params) => parse.safeEncodeAsync(inst, data, params);\n    inst.safeDecodeAsync = async (data, params) => parse.safeDecodeAsync(inst, data, params);\n    // All builder methods are placed on the internal prototype as lazy-bind\n    // getters. On first access per-instance, a bound thunk is allocated and\n    // cached as an own property; subsequent accesses skip the getter. This\n    // means: no per-instance allocation for unused methods, full\n    // detachability preserved (`const m = schema.optional; m()` works), and\n    // shared underlying function references across all instances.\n    _installLazyMethods(inst, \"ZodType\", {\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)\n            // returns a clone with `data` registered. The mapped type picks\n            // up the second overload, so we accept variadic any-args and\n            // 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) {\n            return fn(this);\n        },\n    });\n    Object.defineProperty(inst, \"description\", {\n        get() {\n            return core.globalRegistry.get(inst)?.description;\n        },\n        configurable: true,\n    });\n    return inst;\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    const bag = inst._zod.bag;\n    inst.format = bag.format ?? null;\n    inst.minLength = bag.minimum ?? null;\n    inst.maxLength = bag.maximum ?? null;\n    _installLazyMethods(inst, \"_ZodString\", {\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    });\n});\nexport const ZodString = /*@__PURE__*/ core.$constructor(\"ZodString\", (inst, def) => {\n    core.$ZodString.init(inst, def);\n    _ZodString.init(inst, def);\n    inst.email = (params) => inst.check(core._email(ZodEmail, params));\n    inst.url = (params) => inst.check(core._url(ZodURL, params));\n    inst.jwt = (params) => inst.check(core._jwt(ZodJWT, params));\n    inst.emoji = (params) => inst.check(core._emoji(ZodEmoji, params));\n    inst.guid = (params) => inst.check(core._guid(ZodGUID, params));\n    inst.uuid = (params) => inst.check(core._uuid(ZodUUID, params));\n    inst.uuidv4 = (params) => inst.check(core._uuidv4(ZodUUID, params));\n    inst.uuidv6 = (params) => inst.check(core._uuidv6(ZodUUID, params));\n    inst.uuidv7 = (params) => inst.check(core._uuidv7(ZodUUID, params));\n    inst.nanoid = (params) => inst.check(core._nanoid(ZodNanoID, params));\n    inst.guid = (params) => inst.check(core._guid(ZodGUID, params));\n    inst.cuid = (params) => inst.check(core._cuid(ZodCUID, params));\n    inst.cuid2 = (params) => inst.check(core._cuid2(ZodCUID2, params));\n    inst.ulid = (params) => inst.check(core._ulid(ZodULID, params));\n    inst.base64 = (params) => inst.check(core._base64(ZodBase64, params));\n    inst.base64url = (params) => inst.check(core._base64url(ZodBase64URL, params));\n    inst.xid = (params) => inst.check(core._xid(ZodXID, params));\n    inst.ksuid = (params) => inst.check(core._ksuid(ZodKSUID, params));\n    inst.ipv4 = (params) => inst.check(core._ipv4(ZodIPv4, params));\n    inst.ipv6 = (params) => inst.check(core._ipv6(ZodIPv6, params));\n    inst.cidrv4 = (params) => inst.check(core._cidrv4(ZodCIDRv4, params));\n    inst.cidrv6 = (params) => inst.check(core._cidrv6(ZodCIDRv6, params));\n    inst.e164 = (params) => inst.check(core._e164(ZodE164, params));\n    // iso\n    inst.datetime = (params) => inst.check(iso.datetime(params));\n    inst.date = (params) => inst.check(iso.date(params));\n    inst.time = (params) => inst.check(iso.time(params));\n    inst.duration = (params) => inst.check(iso.duration(params));\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 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: core.regexes.httpProtocol,\n        hostname: core.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 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\", core.regexes.hostname, _params);\n}\nexport function hex(_params) {\n    return core._stringFormat(ZodCustomStringFormat, \"hex\", core.regexes.hex, _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    _installLazyMethods(inst, \"ZodNumber\", {\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    });\n    const bag = inst._zod.bag;\n    inst.minValue =\n        Math.max(bag.minimum ?? Number.NEGATIVE_INFINITY, bag.exclusiveMinimum ?? Number.NEGATIVE_INFINITY) ?? null;\n    inst.maxValue =\n        Math.min(bag.maximum ?? Number.POSITIVE_INFINITY, bag.exclusiveMaximum ?? Number.POSITIVE_INFINITY) ?? null;\n    inst.isInt = (bag.format ?? \"\").includes(\"int\") || Number.isSafeInteger(bag.multipleOf ?? 0.5);\n    inst.isFinite = true;\n    inst.format = bag.format ?? null;\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    inst.gte = (value, params) => inst.check(checks.gte(value, params));\n    inst.min = (value, params) => inst.check(checks.gte(value, params));\n    inst.gt = (value, params) => inst.check(checks.gt(value, params));\n    inst.gte = (value, params) => inst.check(checks.gte(value, params));\n    inst.min = (value, params) => inst.check(checks.gte(value, params));\n    inst.lt = (value, params) => inst.check(checks.lt(value, params));\n    inst.lte = (value, params) => inst.check(checks.lte(value, params));\n    inst.max = (value, params) => inst.check(checks.lte(value, params));\n    inst.positive = (params) => inst.check(checks.gt(BigInt(0), params));\n    inst.negative = (params) => inst.check(checks.lt(BigInt(0), params));\n    inst.nonpositive = (params) => inst.check(checks.lte(BigInt(0), params));\n    inst.nonnegative = (params) => inst.check(checks.gte(BigInt(0), params));\n    inst.multipleOf = (value, params) => inst.check(checks.multipleOf(value, params));\n    const bag = inst._zod.bag;\n    inst.minValue = bag.minimum ?? null;\n    inst.maxValue = bag.maximum ?? null;\n    inst.format = bag.format ?? null;\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});\n// int64\nexport function int64(params) {\n    return core._int64(ZodBigIntFormat, params);\n}\n// uint64\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    const c = inst._zod.bag;\n    inst.minDate = c.minimum ? new Date(c.minimum) : null;\n    inst.maxDate = c.maximum ? new Date(c.maximum) : null;\n});\nexport function date(params) {\n    return core._date(ZodDate, params);\n}\nexport const ZodArray = /*@__PURE__*/ core.$constructor(\"ZodArray\", (inst, def) => {\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    _installLazyMethods(inst, \"ZodArray\", {\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    });\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    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.defineLazy(inst, \"shape\", () => {\n        return def.shape;\n    });\n    _installLazyMethods(inst, \"ZodObject\", {\n        keyof() {\n            return _enum(Object.keys(this._zod.def.shape));\n        },\n        catchall(catchall) {\n            return this.clone({ ...this._zod.def, catchall: catchall });\n        },\n        passthrough() {\n            return this.clone({ ...this._zod.def, catchall: unknown() });\n        },\n        loose() {\n            return this.clone({ ...this._zod.def, catchall: unknown() });\n        },\n        strict() {\n            return this.clone({ ...this._zod.def, catchall: never() });\n        },\n        strip() {\n            return this.clone({ ...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        required(...args) {\n            return util.required(ZodNonOptional, this, args[0]);\n        },\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,\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    core.$ZodTuple.init(inst, def);\n    ZodType.init(inst, def);\n    inst._zod.processJSONSchema = (ctx, json, params) => processors.tupleProcessor(inst, ctx, json, params);\n    inst.rest = (rest) => inst.clone({\n        ...inst._zod.def,\n        rest: rest,\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    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    const k = core.clone(keyType);\n    k._zod.values = undefined;\n    return new ZodRecord({\n        type: \"record\",\n        keyType: k,\n        valueType: valueType,\n        ...util.normalizeParams(params),\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    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    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    inst.options = Object.values(def.entries);\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    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                _issue.input ?? (_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                payload.fallback = true;\n                return payload;\n            });\n        }\n        payload.value = output;\n        payload.fallback = true;\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 : () => 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;\nfunction _instanceof(cls, params = {}) {\n    const inst = new ZodCustom({\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 { globalRegistry } from \"../core/registries.js\";\nimport * as _checks from \"./checks.js\";\nimport * as _iso from \"./iso.js\";\nimport * as _schemas from \"./schemas.js\";\n// Local z object to avoid circular dependency with ../index.js\nconst z = {\n    ..._schemas,\n    ..._checks,\n    iso: _iso,\n};\n// Keys that are recognized and handled by the conversion logic\nconst RECOGNIZED_KEYS = /*@__PURE__*/ new Set([\n    // Schema identification\n    \"$schema\",\n    \"$ref\",\n    \"$defs\",\n    \"definitions\",\n    // Core schema keywords\n    \"$id\",\n    \"id\",\n    \"$comment\",\n    \"$anchor\",\n    \"$vocabulary\",\n    \"$dynamicRef\",\n    \"$dynamicAnchor\",\n    // Type\n    \"type\",\n    \"enum\",\n    \"const\",\n    // Composition\n    \"anyOf\",\n    \"oneOf\",\n    \"allOf\",\n    \"not\",\n    // Object\n    \"properties\",\n    \"required\",\n    \"additionalProperties\",\n    \"patternProperties\",\n    \"propertyNames\",\n    \"minProperties\",\n    \"maxProperties\",\n    // Array\n    \"items\",\n    \"prefixItems\",\n    \"additionalItems\",\n    \"minItems\",\n    \"maxItems\",\n    \"uniqueItems\",\n    \"contains\",\n    \"minContains\",\n    \"maxContains\",\n    // String\n    \"minLength\",\n    \"maxLength\",\n    \"pattern\",\n    \"format\",\n    // Number\n    \"minimum\",\n    \"maximum\",\n    \"exclusiveMinimum\",\n    \"exclusiveMaximum\",\n    \"multipleOf\",\n    // Already handled metadata\n    \"description\",\n    \"default\",\n    // Content\n    \"contentEncoding\",\n    \"contentMediaType\",\n    \"contentSchema\",\n    // Unsupported (error-throwing)\n    \"unevaluatedItems\",\n    \"unevaluatedProperties\",\n    \"if\",\n    \"then\",\n    \"else\",\n    \"dependentSchemas\",\n    \"dependentRequired\",\n    // OpenAPI\n    \"nullable\",\n    \"readOnly\",\n]);\nfunction detectVersion(schema, defaultTarget) {\n    const $schema = schema.$schema;\n    if ($schema === \"https://json-schema.org/draft/2020-12/schema\") {\n        return \"draft-2020-12\";\n    }\n    if ($schema === \"http://json-schema.org/draft-07/schema#\") {\n        return \"draft-7\";\n    }\n    if ($schema === \"http://json-schema.org/draft-04/schema#\") {\n        return \"draft-4\";\n    }\n    // Use defaultTarget if provided, otherwise default to draft-2020-12\n    return defaultTarget ?? \"draft-2020-12\";\n}\nfunction resolveRef(ref, ctx) {\n    if (!ref.startsWith(\"#\")) {\n        throw new Error(\"External $ref is not supported, only local refs (#/...) are allowed\");\n    }\n    const path = ref.slice(1).split(\"/\").filter(Boolean);\n    // Handle root reference \"#\"\n    if (path.length === 0) {\n        return ctx.rootSchema;\n    }\n    const defsKey = ctx.version === \"draft-2020-12\" ? \"$defs\" : \"definitions\";\n    if (path[0] === defsKey) {\n        const key = path[1];\n        if (!key || !ctx.defs[key]) {\n            throw new Error(`Reference not found: ${ref}`);\n        }\n        return ctx.defs[key];\n    }\n    throw new Error(`Reference not found: ${ref}`);\n}\nfunction convertBaseSchema(schema, ctx) {\n    // Handle unsupported features\n    if (schema.not !== undefined) {\n        // Special case: { not: {} } represents never\n        if (typeof schema.not === \"object\" && Object.keys(schema.not).length === 0) {\n            return z.never();\n        }\n        throw new Error(\"not is not supported in Zod (except { not: {} } for never)\");\n    }\n    if (schema.unevaluatedItems !== undefined) {\n        throw new Error(\"unevaluatedItems is not supported\");\n    }\n    if (schema.unevaluatedProperties !== undefined) {\n        throw new Error(\"unevaluatedProperties is not supported\");\n    }\n    if (schema.if !== undefined || schema.then !== undefined || schema.else !== undefined) {\n        throw new Error(\"Conditional schemas (if/then/else) are not supported\");\n    }\n    if (schema.dependentSchemas !== undefined || schema.dependentRequired !== undefined) {\n        throw new Error(\"dependentSchemas and dependentRequired are not supported\");\n    }\n    // Handle $ref\n    if (schema.$ref) {\n        const refPath = schema.$ref;\n        if (ctx.refs.has(refPath)) {\n            return ctx.refs.get(refPath);\n        }\n        if (ctx.processing.has(refPath)) {\n            // Circular reference - use lazy\n            return z.lazy(() => {\n                if (!ctx.refs.has(refPath)) {\n                    throw new Error(`Circular reference not resolved: ${refPath}`);\n                }\n                return ctx.refs.get(refPath);\n            });\n        }\n        ctx.processing.add(refPath);\n        const resolved = resolveRef(refPath, ctx);\n        const zodSchema = convertSchema(resolved, ctx);\n        ctx.refs.set(refPath, zodSchema);\n        ctx.processing.delete(refPath);\n        return zodSchema;\n    }\n    // Handle enum\n    if (schema.enum !== undefined) {\n        const enumValues = schema.enum;\n        // Special case: OpenAPI 3.0 null representation { type: \"string\", nullable: true, enum: [null] }\n        if (ctx.version === \"openapi-3.0\" &&\n            schema.nullable === true &&\n            enumValues.length === 1 &&\n            enumValues[0] === null) {\n            return z.null();\n        }\n        if (enumValues.length === 0) {\n            return z.never();\n        }\n        if (enumValues.length === 1) {\n            return z.literal(enumValues[0]);\n        }\n        // Check if all values are strings\n        if (enumValues.every((v) => typeof v === \"string\")) {\n            return z.enum(enumValues);\n        }\n        // Mixed types - use union of literals\n        const literalSchemas = enumValues.map((v) => z.literal(v));\n        if (literalSchemas.length < 2) {\n            return literalSchemas[0];\n        }\n        return z.union([literalSchemas[0], literalSchemas[1], ...literalSchemas.slice(2)]);\n    }\n    // Handle const\n    if (schema.const !== undefined) {\n        return z.literal(schema.const);\n    }\n    // Handle type\n    const type = schema.type;\n    if (Array.isArray(type)) {\n        // Expand type array into anyOf union\n        const typeSchemas = type.map((t) => {\n            const typeSchema = { ...schema, type: t };\n            return convertBaseSchema(typeSchema, ctx);\n        });\n        if (typeSchemas.length === 0) {\n            return z.never();\n        }\n        if (typeSchemas.length === 1) {\n            return typeSchemas[0];\n        }\n        return z.union(typeSchemas);\n    }\n    if (!type) {\n        // No type specified - empty schema (any)\n        return z.any();\n    }\n    let zodSchema;\n    switch (type) {\n        case \"string\": {\n            let stringSchema = z.string();\n            // Apply format using .check() with Zod format functions\n            if (schema.format) {\n                const format = schema.format;\n                // Map common formats to Zod check functions\n                if (format === \"email\") {\n                    stringSchema = stringSchema.check(z.email());\n                }\n                else if (format === \"uri\" || format === \"uri-reference\") {\n                    stringSchema = stringSchema.check(z.url());\n                }\n                else if (format === \"uuid\" || format === \"guid\") {\n                    stringSchema = stringSchema.check(z.uuid());\n                }\n                else if (format === \"date-time\") {\n                    stringSchema = stringSchema.check(z.iso.datetime());\n                }\n                else if (format === \"date\") {\n                    stringSchema = stringSchema.check(z.iso.date());\n                }\n                else if (format === \"time\") {\n                    stringSchema = stringSchema.check(z.iso.time());\n                }\n                else if (format === \"duration\") {\n                    stringSchema = stringSchema.check(z.iso.duration());\n                }\n                else if (format === \"ipv4\") {\n                    stringSchema = stringSchema.check(z.ipv4());\n                }\n                else if (format === \"ipv6\") {\n                    stringSchema = stringSchema.check(z.ipv6());\n                }\n                else if (format === \"mac\") {\n                    stringSchema = stringSchema.check(z.mac());\n                }\n                else if (format === \"cidr\") {\n                    stringSchema = stringSchema.check(z.cidrv4());\n                }\n                else if (format === \"cidr-v6\") {\n                    stringSchema = stringSchema.check(z.cidrv6());\n                }\n                else if (format === \"base64\") {\n                    stringSchema = stringSchema.check(z.base64());\n                }\n                else if (format === \"base64url\") {\n                    stringSchema = stringSchema.check(z.base64url());\n                }\n                else if (format === \"e164\") {\n                    stringSchema = stringSchema.check(z.e164());\n                }\n                else if (format === \"jwt\") {\n                    stringSchema = stringSchema.check(z.jwt());\n                }\n                else if (format === \"emoji\") {\n                    stringSchema = stringSchema.check(z.emoji());\n                }\n                else if (format === \"nanoid\") {\n                    stringSchema = stringSchema.check(z.nanoid());\n                }\n                else if (format === \"cuid\") {\n                    stringSchema = stringSchema.check(z.cuid());\n                }\n                else if (format === \"cuid2\") {\n                    stringSchema = stringSchema.check(z.cuid2());\n                }\n                else if (format === \"ulid\") {\n                    stringSchema = stringSchema.check(z.ulid());\n                }\n                else if (format === \"xid\") {\n                    stringSchema = stringSchema.check(z.xid());\n                }\n                else if (format === \"ksuid\") {\n                    stringSchema = stringSchema.check(z.ksuid());\n                }\n                // Note: json-string format is not currently supported by Zod\n                // Custom formats are ignored - keep as plain string\n            }\n            // Apply constraints\n            if (typeof schema.minLength === \"number\") {\n                stringSchema = stringSchema.min(schema.minLength);\n            }\n            if (typeof schema.maxLength === \"number\") {\n                stringSchema = stringSchema.max(schema.maxLength);\n            }\n            if (schema.pattern) {\n                // JSON Schema patterns are not implicitly anchored (match anywhere in string)\n                stringSchema = stringSchema.regex(new RegExp(schema.pattern));\n            }\n            zodSchema = stringSchema;\n            break;\n        }\n        case \"number\":\n        case \"integer\": {\n            let numberSchema = type === \"integer\" ? z.number().int() : z.number();\n            // Apply constraints\n            if (typeof schema.minimum === \"number\") {\n                numberSchema = numberSchema.min(schema.minimum);\n            }\n            if (typeof schema.maximum === \"number\") {\n                numberSchema = numberSchema.max(schema.maximum);\n            }\n            if (typeof schema.exclusiveMinimum === \"number\") {\n                numberSchema = numberSchema.gt(schema.exclusiveMinimum);\n            }\n            else if (schema.exclusiveMinimum === true && typeof schema.minimum === \"number\") {\n                numberSchema = numberSchema.gt(schema.minimum);\n            }\n            if (typeof schema.exclusiveMaximum === \"number\") {\n                numberSchema = numberSchema.lt(schema.exclusiveMaximum);\n            }\n            else if (schema.exclusiveMaximum === true && typeof schema.maximum === \"number\") {\n                numberSchema = numberSchema.lt(schema.maximum);\n            }\n            if (typeof schema.multipleOf === \"number\") {\n                numberSchema = numberSchema.multipleOf(schema.multipleOf);\n            }\n            zodSchema = numberSchema;\n            break;\n        }\n        case \"boolean\": {\n            zodSchema = z.boolean();\n            break;\n        }\n        case \"null\": {\n            zodSchema = z.null();\n            break;\n        }\n        case \"object\": {\n            const shape = {};\n            const properties = schema.properties || {};\n            const requiredSet = new Set(schema.required || []);\n            // Convert properties - mark optional ones\n            for (const [key, propSchema] of Object.entries(properties)) {\n                const propZodSchema = convertSchema(propSchema, ctx);\n                // If not in required array, make it optional\n                shape[key] = requiredSet.has(key) ? propZodSchema : propZodSchema.optional();\n            }\n            // Handle propertyNames\n            if (schema.propertyNames) {\n                const keySchema = convertSchema(schema.propertyNames, ctx);\n                const valueSchema = schema.additionalProperties && typeof schema.additionalProperties === \"object\"\n                    ? convertSchema(schema.additionalProperties, ctx)\n                    : z.any();\n                // Case A: No properties (pure record)\n                if (Object.keys(shape).length === 0) {\n                    zodSchema = z.record(keySchema, valueSchema);\n                    break;\n                }\n                // Case B: With properties (intersection of object and looseRecord)\n                const objectSchema = z.object(shape).passthrough();\n                const recordSchema = z.looseRecord(keySchema, valueSchema);\n                zodSchema = z.intersection(objectSchema, recordSchema);\n                break;\n            }\n            // Handle patternProperties\n            if (schema.patternProperties) {\n                // patternProperties: keys matching pattern must satisfy corresponding schema\n                // Use loose records so non-matching keys pass through\n                const patternProps = schema.patternProperties;\n                const patternKeys = Object.keys(patternProps);\n                const looseRecords = [];\n                for (const pattern of patternKeys) {\n                    const patternValue = convertSchema(patternProps[pattern], ctx);\n                    const keySchema = z.string().regex(new RegExp(pattern));\n                    looseRecords.push(z.looseRecord(keySchema, patternValue));\n                }\n                // Build intersection: object schema + all pattern property records\n                const schemasToIntersect = [];\n                if (Object.keys(shape).length > 0) {\n                    // Use passthrough so patternProperties can validate additional keys\n                    schemasToIntersect.push(z.object(shape).passthrough());\n                }\n                schemasToIntersect.push(...looseRecords);\n                if (schemasToIntersect.length === 0) {\n                    zodSchema = z.object({}).passthrough();\n                }\n                else if (schemasToIntersect.length === 1) {\n                    zodSchema = schemasToIntersect[0];\n                }\n                else {\n                    // Chain intersections: (A & B) & C & D ...\n                    let result = z.intersection(schemasToIntersect[0], schemasToIntersect[1]);\n                    for (let i = 2; i < schemasToIntersect.length; i++) {\n                        result = z.intersection(result, schemasToIntersect[i]);\n                    }\n                    zodSchema = result;\n                }\n                break;\n            }\n            // Handle additionalProperties\n            // In JSON Schema, additionalProperties defaults to true (allow any extra properties)\n            // In Zod, objects strip unknown keys by default, so we need to handle this explicitly\n            const objectSchema = z.object(shape);\n            if (schema.additionalProperties === false) {\n                // Strict mode - no extra properties allowed\n                zodSchema = objectSchema.strict();\n            }\n            else if (typeof schema.additionalProperties === \"object\") {\n                // Extra properties must match the specified schema\n                zodSchema = objectSchema.catchall(convertSchema(schema.additionalProperties, ctx));\n            }\n            else {\n                // additionalProperties is true or undefined - allow any extra properties (passthrough)\n                zodSchema = objectSchema.passthrough();\n            }\n            break;\n        }\n        case \"array\": {\n            // TODO: uniqueItems is not supported\n            // TODO: contains/minContains/maxContains are not supported\n            // Check if this is a tuple (prefixItems or items as array)\n            const prefixItems = schema.prefixItems;\n            const items = schema.items;\n            if (prefixItems && Array.isArray(prefixItems)) {\n                // Tuple with prefixItems (draft-2020-12)\n                const tupleItems = prefixItems.map((item) => convertSchema(item, ctx));\n                const rest = items && typeof items === \"object\" && !Array.isArray(items)\n                    ? convertSchema(items, ctx)\n                    : undefined;\n                if (rest) {\n                    zodSchema = z.tuple(tupleItems).rest(rest);\n                }\n                else {\n                    zodSchema = z.tuple(tupleItems);\n                }\n                // Apply minItems/maxItems constraints to tuples\n                if (typeof schema.minItems === \"number\") {\n                    zodSchema = zodSchema.check(z.minLength(schema.minItems));\n                }\n                if (typeof schema.maxItems === \"number\") {\n                    zodSchema = zodSchema.check(z.maxLength(schema.maxItems));\n                }\n            }\n            else if (Array.isArray(items)) {\n                // Tuple with items array (draft-7)\n                const tupleItems = items.map((item) => convertSchema(item, ctx));\n                const rest = schema.additionalItems && typeof schema.additionalItems === \"object\"\n                    ? convertSchema(schema.additionalItems, ctx)\n                    : undefined; // additionalItems: false means no rest, handled by default tuple behavior\n                if (rest) {\n                    zodSchema = z.tuple(tupleItems).rest(rest);\n                }\n                else {\n                    zodSchema = z.tuple(tupleItems);\n                }\n                // Apply minItems/maxItems constraints to tuples\n                if (typeof schema.minItems === \"number\") {\n                    zodSchema = zodSchema.check(z.minLength(schema.minItems));\n                }\n                if (typeof schema.maxItems === \"number\") {\n                    zodSchema = zodSchema.check(z.maxLength(schema.maxItems));\n                }\n            }\n            else if (items !== undefined) {\n                // Regular array\n                const element = convertSchema(items, ctx);\n                let arraySchema = z.array(element);\n                // Apply constraints\n                if (typeof schema.minItems === \"number\") {\n                    arraySchema = arraySchema.min(schema.minItems);\n                }\n                if (typeof schema.maxItems === \"number\") {\n                    arraySchema = arraySchema.max(schema.maxItems);\n                }\n                zodSchema = arraySchema;\n            }\n            else {\n                // No items specified - array of any\n                zodSchema = z.array(z.any());\n            }\n            break;\n        }\n        default:\n            throw new Error(`Unsupported type: ${type}`);\n    }\n    return zodSchema;\n}\nfunction convertSchema(schema, ctx) {\n    if (typeof schema === \"boolean\") {\n        return schema ? z.any() : z.never();\n    }\n    // Convert base schema first (ignoring composition keywords)\n    let baseSchema = convertBaseSchema(schema, ctx);\n    const hasExplicitType = schema.type || schema.enum !== undefined || schema.const !== undefined;\n    // Process composition keywords LAST (they can appear together)\n    // Handle anyOf - wrap base schema with union\n    if (schema.anyOf && Array.isArray(schema.anyOf)) {\n        const options = schema.anyOf.map((s) => convertSchema(s, ctx));\n        const anyOfUnion = z.union(options);\n        baseSchema = hasExplicitType ? z.intersection(baseSchema, anyOfUnion) : anyOfUnion;\n    }\n    // Handle oneOf - exclusive union (exactly one must match)\n    if (schema.oneOf && Array.isArray(schema.oneOf)) {\n        const options = schema.oneOf.map((s) => convertSchema(s, ctx));\n        const oneOfUnion = z.xor(options);\n        baseSchema = hasExplicitType ? z.intersection(baseSchema, oneOfUnion) : oneOfUnion;\n    }\n    // Handle allOf - wrap base schema with intersection\n    if (schema.allOf && Array.isArray(schema.allOf)) {\n        if (schema.allOf.length === 0) {\n            baseSchema = hasExplicitType ? baseSchema : z.any();\n        }\n        else {\n            let result = hasExplicitType ? baseSchema : convertSchema(schema.allOf[0], ctx);\n            const startIdx = hasExplicitType ? 0 : 1;\n            for (let i = startIdx; i < schema.allOf.length; i++) {\n                result = z.intersection(result, convertSchema(schema.allOf[i], ctx));\n            }\n            baseSchema = result;\n        }\n    }\n    // Handle nullable (OpenAPI 3.0)\n    if (schema.nullable === true && ctx.version === \"openapi-3.0\") {\n        baseSchema = z.nullable(baseSchema);\n    }\n    // Handle readOnly\n    if (schema.readOnly === true) {\n        baseSchema = z.readonly(baseSchema);\n    }\n    // Apply `default` so it wraps the fully-composed schema. This ensures\n    // `parse(undefined) -> default` works regardless of which branch of\n    // `convertBaseSchema` produced the inner schema (enum/const/not/typed/etc.).\n    if (schema.default !== undefined) {\n        baseSchema = baseSchema.default(schema.default);\n    }\n    // Collect non-description annotation metadata into the user-supplied\n    // registry. Description is handled separately below via `.describe()` to\n    // preserve the contract that `schema.description` reads from globalRegistry.\n    const extraMeta = {};\n    const coreMetadataKeys = [\"$id\", \"id\", \"$comment\", \"$anchor\", \"$vocabulary\", \"$dynamicRef\", \"$dynamicAnchor\"];\n    for (const key of coreMetadataKeys) {\n        if (key in schema) {\n            extraMeta[key] = schema[key];\n        }\n    }\n    const contentMetadataKeys = [\"contentEncoding\", \"contentMediaType\", \"contentSchema\"];\n    for (const key of contentMetadataKeys) {\n        if (key in schema) {\n            extraMeta[key] = schema[key];\n        }\n    }\n    for (const key of Object.keys(schema)) {\n        if (!RECOGNIZED_KEYS.has(key)) {\n            extraMeta[key] = schema[key];\n        }\n    }\n    if (Object.keys(extraMeta).length > 0) {\n        ctx.registry.add(baseSchema, extraMeta);\n    }\n    // Apply description last. `.describe()` clones the schema and sets\n    // `_zod.parent` on the clone, so registry lookups on the returned reference\n    // still resolve `extraMeta` via parent inheritance.\n    if (schema.description) {\n        baseSchema = baseSchema.describe(schema.description);\n    }\n    return baseSchema;\n}\n/**\n * Converts a JSON Schema to a Zod schema. This function should be considered semi-experimental. It's behavior is liable to change. */\nexport function fromJSONSchema(schema, params) {\n    // Handle boolean schemas\n    if (typeof schema === \"boolean\") {\n        return schema ? z.any() : z.never();\n    }\n    // Normalize input via a JSON round-trip. This guarantees the converter\n    // walks a plain, finite, JSON-valid object graph: cyclic inputs fail here,\n    // getter/Proxy-based properties are materialized into static values, and\n    // class instances collapse to plain objects.\n    let normalized;\n    try {\n        normalized = JSON.parse(JSON.stringify(schema));\n    }\n    catch {\n        throw new Error(\"fromJSONSchema input is not valid JSON (possibly cyclic); use $defs/$ref for recursive schemas\");\n    }\n    const version = detectVersion(normalized, params?.defaultTarget);\n    const defs = (normalized.$defs || normalized.definitions || {});\n    const ctx = {\n        version,\n        defs,\n        refs: new Map(),\n        processing: new Set(),\n        rootSchema: normalized,\n        registry: params?.registry ?? globalRegistry,\n    };\n    return convertSchema(normalized, ctx);\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\";\n// zod-specified\nimport { config } from \"../core/index.js\";\nimport en from \"../locales/en.js\";\nconfig(en());\nexport { globalRegistry, registry, config, $output, $input, $brand, clone, regexes, treeifyError, prettifyError, formatError, flattenError, TimePrecision, util, NEVER, } from \"../core/index.js\";\nexport { toJSONSchema } from \"../core/json-schema-processors.js\";\nexport { fromJSONSchema } from \"./from-json-schema.js\";\nexport * as locales from \"../locales/index.js\";\n// iso\n// must be exported from top-level\n// 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 \"./v4/classic/external.js\";\nexport * from \"./v4/classic/external.js\";\nexport { z };\nexport default z;\n","/**\n * Branded ID types and factory functions for the Glasstrace SDK.\n *\n * These types use Zod's `.brand()` for nominal typing — a plain string\n * won't satisfy a branded type without going through the schema first.\n */\n\nimport { z } from \"zod\";\n\n/**\n * Generate a hex string from random bytes.\n *\n * Uses the Web Crypto API (globalThis.crypto) instead of Node's\n * `Buffer` or `crypto.randomBytes()` so this module works in every\n * JavaScript runtime: Node 20+, browsers, Vercel Edge, and\n * Cloudflare Workers.\n */\nfunction randomHex(byteCount: number): string {\n  const bytes = new Uint8Array(byteCount);\n  crypto.getRandomValues(bytes);\n  return Array.from(bytes, (b) => b.toString(16).padStart(2, \"0\")).join(\"\");\n}\n\n// --- Branded ID Schemas ---\n\n/**\n * Developer API key: `gt_dev_` + 48 hex chars.\n *\n * @drift-check ../glasstrace-product/docs/component-designs/sdk-architecture.md §1.2 Lens B — SDK-Facing Security Primitives (row `Dev API key gt_dev_[a-f0-9]{48}`)\n */\nexport const DevApiKeySchema = z\n  .string()\n  .regex(/^gt_dev_[a-f0-9]{48}$/)\n  .brand<\"DevApiKey\">();\nexport type DevApiKey = z.infer<typeof DevApiKeySchema>;\n\n/**\n * Anonymous API key: `gt_anon_` + 48 hex chars.\n *\n * @drift-check ../glasstrace-product/docs/component-designs/sdk-architecture.md §1.2 Lens B — SDK-Facing Security Primitives (row `Anon API key gt_anon_[a-f0-9]{48}`)\n */\nexport const AnonApiKeySchema = z\n  .string()\n  .regex(/^gt_anon_[a-f0-9]{48}$/)\n  .brand<\"AnonApiKey\">();\nexport type AnonApiKey = z.infer<typeof AnonApiKeySchema>;\n\n/**\n * Session ID: 16 hex chars (deterministic, derived from API key + time window).\n *\n * @drift-check ../glasstrace-product/docs/product-spec.md §4.5 Session Lifecycle\n */\nexport const SessionIdSchema = z\n  .string()\n  .regex(/^[a-f0-9]{16}$/)\n  .brand<\"SessionId\">();\nexport type SessionId = z.infer<typeof SessionIdSchema>;\n\n/** Build hash: 1-128 chars, alphanumeric + `.` `_` `+` `-`. */\nexport const BuildHashSchema = z\n  .string()\n  .min(1)\n  .max(128)\n  .regex(/^[a-zA-Z0-9._+-]+$/)\n  // Prevent path traversal — build hashes are used in storage paths\n  .refine((value) => value !== \".\" && value !== \"..\" && !value.includes(\"..\"), {\n    message: \"Build hash must not be '.' or '..' and must not contain '..'\",\n  })\n  .brand<\"BuildHash\">();\nexport type BuildHash = z.infer<typeof BuildHashSchema>;\n\n// --- Factory Functions ---\n\n/** Generate a new anonymous API key. */\nexport function createAnonApiKey(): AnonApiKey {\n  return AnonApiKeySchema.parse(`gt_anon_${randomHex(24)}`);\n}\n\n/** Parse and brand a build hash string. */\nexport function createBuildHash(hash: string): BuildHash {\n  return BuildHashSchema.parse(hash);\n}\n","/**\n * SDK-specific enums.\n */\n\nimport { z } from \"zod\";\n\n/** Diagnostic codes the SDK can report during health checks. */\nexport const SdkDiagnosticCodeSchema = z.enum([\n  \"ingestion_unreachable\",\n  \"ingestion_auth_failed\",\n  \"ingestion_rate_limited\",\n  \"config_sync_failed\",\n  \"source_map_upload_failed\",\n]);\nexport type SdkDiagnosticCode = z.infer<typeof SdkDiagnosticCodeSchema>;\n","/**\n * SDK configuration types.\n */\n\nimport { z } from \"zod\";\n\n/** SDK capture configuration: which events to capture. */\nexport const CaptureConfigSchema = z.object({\n  requestBodies: z.boolean(),\n  queryParamValues: z.boolean(),\n  envVarValues: z.boolean(),\n  fullConsoleOutput: z.boolean(),\n  importGraph: z.boolean(),\n  consoleErrors: z.boolean().optional().default(false),\n  errorResponseBodies: z.boolean().optional().default(false),\n  /**\n   * Account opt-in for side-effect evidence emission.\n   *\n   * When `false` (default), `recordSideEffect()` is a silent no-op:\n   * no allowlist evaluation runs and no `glasstrace.side_effect.*`\n   * attribute reaches the wire. When `true`, allowlisted side-effect\n   * metadata is attached to the active OTel span subject to the\n   * client-side allowlist enforcement layered with the product's\n   * storage-time filter as defense-in-depth.\n   */\n  sideEffectEvidence: z.boolean().optional().default(false),\n  /**\n   * Per-account value-fidelity capture posture (server-pushed).\n   *\n   * `strict` (default) is fail-closed: the SDK rejects raw wall-clock\n   * timestamps and unhashed identifiers from the `scalar.*` channel at\n   * emit time. `full` relaxes those rejections so raw magnitudes can be\n   * surfaced — but only in conjunction with an explicit producer opt-in\n   * (so a `full`-configured account still emits strict-shaped scalars\n   * unless the producer also opts in). The operator owns this flag; it\n   * is never derived from producer or request input. Absent on the wire\n   * ⇒ `strict`.\n   */\n  captureFidelity: z.enum([\"strict\", \"full\"]).optional().default(\"strict\"),\n  /**\n   * Per-account HMAC secret for pseudonymizing allowlisted identifier\n   * columns (server-pushed; never echoed back or logged).\n   *\n   * When present (and only under `captureFidelity: \"full\"`), a passive\n   * adapter projecting an `*Id` column hashes the raw identifier into a\n   * stable `gthid_<hex>` token under this key before it reaches the wire,\n   * so the raw value is never emitted. Absent (the default) ⇒ identifier\n   * capture stays off (fail-closed): the adapter emits no `*Id` scalar\n   * rather than a raw or unkeyed one. Scoped per account, so tokens do\n   * not correlate across accounts.\n   */\n  attrHmacKey: z.string().optional(),\n});\nexport type CaptureConfig = z.infer<typeof CaptureConfigSchema>;\n\n/**\n * Value-fidelity capture posture (`strict` | `full`). Exported as the\n * single source of truth so the SDK's scalar validator binds to the same\n * domain as the wire config rather than re-declaring the literal union.\n */\nexport type CaptureFidelity = CaptureConfig[\"captureFidelity\"];\n\n/**\n * Cached config returned on SDK init.\n * Stores the full SdkInitResponse payload as a generic record to avoid\n * a circular dependency (wire.ts imports from config.ts).\n * Consumers should cast via SdkInitResponseSchema.parse() when reading.\n */\nexport const SdkCachedConfigSchema = z.object({\n  response: z.record(z.string(), z.unknown()),\n  cachedAt: z.number().int().nonnegative(),\n});\nexport type SdkCachedConfig = z.infer<typeof SdkCachedConfigSchema>;\n\n/** Developer-facing config for registerGlasstrace(). */\nexport const GlasstraceOptionsSchema = z.object({\n  apiKey: z.string().optional(),\n  endpoint: z.string().url().refine(\n    (url) => url.startsWith(\"https://\") || url.startsWith(\"http://\"),\n    { message: \"Endpoint must use http:// or https://\" },\n  ).optional(),\n  forceEnable: z.boolean().optional(),\n  verbose: z.boolean().optional(),\n  /**\n   * Opt into decision tracing: the SDK logs a single, greppable\n   * `[glasstrace] decision:` line (and emits an in-process lifecycle\n   * event) at each instrumented config-decision point — which capture\n   * gate closed, which fidelity branch ran, which config tier resolved.\n   * Defaults to `false`. Also turns on when `verbose` is `true`. Purely\n   * diagnostic and off by default: behavior is byte-for-byte identical\n   * whether this is set or not.\n   */\n  decisionTrace: z.boolean().optional(),\n});\nexport type GlasstraceOptions = z.infer<typeof GlasstraceOptionsSchema>;\n\n/** All recognized SDK environment variables. */\nexport const GlasstraceEnvVarsSchema = z.object({\n  GLASSTRACE_API_KEY: z.string().optional(),\n  GLASSTRACE_FORCE_ENABLE: z.string().optional(),\n  GLASSTRACE_ENV: z.string().optional(),\n  GLASSTRACE_COVERAGE_MAP: z.string().optional(),\n  /**\n   * Env-only switch for decision tracing (`\"true\"` to enable). The\n   * environment counterpart of {@link GlasstraceOptions.decisionTrace},\n   * for turning diagnostics on without editing the `registerGlasstrace`\n   * call — for example when debugging a deployed app.\n   */\n  GLASSTRACE_DECISION_TRACE: z.string().optional(),\n  NODE_ENV: z.string().optional(),\n  VERCEL_ENV: z.string().optional(),\n});\nexport type GlasstraceEnvVars = z.infer<typeof GlasstraceEnvVarsSchema>;\n","/**\n * Wire format types for SDK ↔ backend communication.\n *\n * These schemas define the request/response shapes for:\n * - SDK initialization (POST /v1/sdk/init)\n * - SDK health diagnostics (embedded in init requests)\n * - Discovery payload (served at `/.well-known/glasstrace.json` from the\n *   project's static root — `public/` for Next.js and most frameworks,\n *   `static/` for SvelteKit; the internal `/__glasstrace/config` handler\n *   reuses this shape for backwards compatibility)\n * - Source map upload (POST /v1/source-maps)\n * - Presigned source map upload (POST /v1/source-maps/presign, POST /v1/source-maps/manifest)\n */\n\nimport { z } from \"zod\";\nimport {\n  AnonApiKeySchema,\n  BuildHashSchema,\n  DevApiKeySchema,\n  SessionIdSchema,\n} from \"./ids.js\";\nimport { CaptureConfigSchema } from \"./config.js\";\nimport {\n  MAX_SOURCE_MAP_FILE_COUNT,\n  MAX_SOURCE_MAP_FILE_PATH_LENGTH,\n  MAX_SOURCE_MAP_FILE_SIZE,\n} from \"./constants.js\";\n\n/**\n * Maximum length of `clientToken` carried on a presigned upload response,\n * in characters. Mirrors the backend canonical bound.\n */\nconst MAX_PRESIGNED_CLIENT_TOKEN_LENGTH = 2048;\n\n/**\n * Maximum length of `pathname` carried on a presigned upload response, in\n * characters. Mirrors the backend canonical bound.\n */\nconst MAX_PRESIGNED_PATHNAME_LENGTH = 1024;\n\n// --- ImportGraphPayload ---\n\n/** Test file import relationships, embedded in SDK init request. */\nexport const ImportGraphPayloadSchema = z.object({\n  buildHash: BuildHashSchema,\n  graph: z.record(z.string(), z.array(z.string())),\n});\nexport type ImportGraphPayload = z.infer<typeof ImportGraphPayloadSchema>;\n\n// --- SdkHealthReport ---\n\n/** SDK health diagnostics included in init requests. */\nexport const SdkHealthReportSchema = z.object({\n  tracesExportedSinceLastInit: z.number().int().nonnegative(),\n  tracesDropped: z.number().int().nonnegative(),\n  initFailures: z.number().int().nonnegative(),\n  configAge: z.number().int().nonnegative().describe(\"milliseconds since last config sync\"),\n  sdkVersion: z.string(),\n});\nexport type SdkHealthReport = z.infer<typeof SdkHealthReportSchema>;\n\n// --- TierLimits ---\n\n/** Rate and storage limits for the current subscription tier. */\nexport const TierLimitsSchema = z.object({\n  tracesPerMinute: z.number().int().positive(),\n  storageTtlHours: z.number().int().positive(),\n  maxTraceSizeBytes: z.number().int().positive(),\n  maxConcurrentSessions: z.number().int().positive(),\n});\nexport type TierLimits = z.infer<typeof TierLimitsSchema>;\n\n// --- SdkInitResponse ---\n\n/**\n * Response from POST /v1/sdk/init.\n *\n * Note: SdkInitRequest is intentionally NOT in the protocol package.\n * The request schema includes backend-specific types (TierLimits,\n * SubscriptionStatus) that are not part of the public contract.\n * The backend owns the request validation; the SDK only needs to\n * understand the response.\n */\nexport const SdkInitResponseSchema = z.object({\n  config: CaptureConfigSchema,\n  subscriptionStatus: z.string().max(64),\n  linkedAccountId: z.string().uuid().optional(),\n  minimumSdkVersion: z.string(),\n  apiVersion: z.string(),\n  tierLimits: TierLimitsSchema,\n  claimResult: z\n    .object({\n      newApiKey: DevApiKeySchema,\n      accountId: z.string().uuid(),\n      graceExpiresAt: z.number().int().positive(),\n    })\n    .optional(),\n});\nexport type SdkInitResponse = z.infer<typeof SdkInitResponseSchema>;\n\n// --- DiscoveryResponse ---\n\n/**\n * SDK discovery endpoint response (SDK → browser extension).\n *\n * @drift-check ../glasstrace-product/docs/component-designs/sdk-discovery-endpoint.md §5.1 Schema\n */\nexport const DiscoveryResponseSchema = z.object({\n  key: AnonApiKeySchema,\n  sessionId: SessionIdSchema,\n  claimed: z.boolean().optional(),\n  accountHint: z.string().optional(),\n});\nexport type DiscoveryResponse = z.infer<typeof DiscoveryResponseSchema>;\n\n// --- SourceMapUploadResponse ---\n\n/** Response from POST /v1/source-maps. */\nexport const SourceMapUploadResponseSchema = z.object({\n  success: z.literal(true),\n  buildHash: BuildHashSchema,\n  fileCount: z.number().int().nonnegative(),\n  totalSizeBytes: z.number().int().nonnegative(),\n});\nexport type SourceMapUploadResponse = z.infer<typeof SourceMapUploadResponseSchema>;\n\n// --- Presigned Source Map Upload ---\n\n/**\n * Request to obtain presigned upload URLs for source map files.\n *\n * Per-file `filePath` is bounded to {@link MAX_SOURCE_MAP_FILE_PATH_LENGTH}\n * characters; `sizeBytes` is bounded to {@link MAX_SOURCE_MAP_FILE_SIZE} bytes.\n * The `files` array carries between 1 and {@link MAX_SOURCE_MAP_FILE_COUNT}\n * entries. These bounds mirror the backend's canonical acceptance bounds so\n * external tooling that validates against the SDK schema observes the same\n * acceptance envelope the backend enforces at write time.\n */\nexport const PresignedUploadRequestSchema = z.object({\n  buildHash: BuildHashSchema,\n  files: z\n    .array(\n      z.object({\n        filePath: z\n          .string()\n          .min(1)\n          .max(\n            MAX_SOURCE_MAP_FILE_PATH_LENGTH,\n            `filePath length exceeds maximum of ${MAX_SOURCE_MAP_FILE_PATH_LENGTH} characters`,\n          ),\n        sizeBytes: z\n          .number()\n          .int()\n          .positive()\n          .max(\n            MAX_SOURCE_MAP_FILE_SIZE,\n            `sizeBytes exceeds maximum of ${MAX_SOURCE_MAP_FILE_SIZE} bytes (${MAX_SOURCE_MAP_FILE_SIZE / (1024 * 1024)} MiB)`,\n          ),\n      }),\n    )\n    .min(1)\n    .max(\n      MAX_SOURCE_MAP_FILE_COUNT,\n      `files array exceeds maximum of ${MAX_SOURCE_MAP_FILE_COUNT} entries`,\n    ),\n});\nexport type PresignedUploadRequest = z.infer<typeof PresignedUploadRequestSchema>;\n\n/**\n * Response containing presigned upload tokens and storage pathnames.\n *\n * Each entry in `files` carries a Vercel Blob `access` mode that pins the\n * storage visibility for the resulting blob in the wire contract.\n * The current Glasstrace SDK upload path passes a fixed `access: \"public\"`\n * to `@vercel/blob/client` `put()`; carrying the field on the response\n * keeps the protocol shape canonical so any future visibility mode is\n * negotiable without a schema change.\n *\n * `expiresAt` is a Unix timestamp in milliseconds since the epoch and uses\n * the canonical timestamp validator (`int().nonnegative()`) shared with the\n * backend wire schema.\n *\n * Per-file bounds mirror the backend's canonical acceptance bounds:\n *\n * - `filePath` ≤ {@link MAX_SOURCE_MAP_FILE_PATH_LENGTH} characters\n * - `clientToken` ≤ 2048 characters\n * - `pathname` ≤ 1024 characters\n * - `maxBytes` ≤ {@link MAX_SOURCE_MAP_FILE_SIZE} bytes (50 MiB)\n *\n * The `files` array carries between 1 and {@link MAX_SOURCE_MAP_FILE_COUNT}\n * entries. These bounds keep the SDK schema in lockstep with the backend\n * acceptance envelope; third-party tooling that validates against the SDK\n * schema sees the same upper bounds the backend enforces at write time.\n */\nexport const PresignedUploadResponseSchema = z.object({\n  uploadId: z.string().uuid(),\n  expiresAt: z.number().int().nonnegative(),\n  files: z\n    .array(\n      z.object({\n        filePath: z\n          .string()\n          .min(1)\n          .max(\n            MAX_SOURCE_MAP_FILE_PATH_LENGTH,\n            `filePath length exceeds maximum of ${MAX_SOURCE_MAP_FILE_PATH_LENGTH} characters`,\n          ),\n        clientToken: z\n          .string()\n          .min(1)\n          .max(\n            MAX_PRESIGNED_CLIENT_TOKEN_LENGTH,\n            `clientToken length exceeds maximum of ${MAX_PRESIGNED_CLIENT_TOKEN_LENGTH} characters`,\n          ),\n        pathname: z\n          .string()\n          .min(1)\n          .max(\n            MAX_PRESIGNED_PATHNAME_LENGTH,\n            `pathname length exceeds maximum of ${MAX_PRESIGNED_PATHNAME_LENGTH} characters`,\n          ),\n        maxBytes: z\n          .number()\n          .int()\n          .positive()\n          .max(\n            MAX_SOURCE_MAP_FILE_SIZE,\n            `maxBytes exceeds maximum of ${MAX_SOURCE_MAP_FILE_SIZE} bytes (${MAX_SOURCE_MAP_FILE_SIZE / (1024 * 1024)} MiB)`,\n          ),\n        /** Vercel Blob access mode — explicit in the wire contract. */\n        access: z.enum([\"public\"]),\n      }),\n    )\n    .min(1)\n    .max(\n      MAX_SOURCE_MAP_FILE_COUNT,\n      `files array exceeds maximum of ${MAX_SOURCE_MAP_FILE_COUNT} entries`,\n    ),\n});\nexport type PresignedUploadResponse = z.infer<typeof PresignedUploadResponseSchema>;\n\n/**\n * Request to finalize a presigned upload by registering the manifest.\n *\n * Per-file `filePath` is bounded to {@link MAX_SOURCE_MAP_FILE_PATH_LENGTH}\n * characters; `sizeBytes` is bounded to {@link MAX_SOURCE_MAP_FILE_SIZE}\n * bytes. The `files` array carries between 1 and\n * {@link MAX_SOURCE_MAP_FILE_COUNT} entries. These bounds mirror the\n * backend's canonical acceptance bounds.\n */\nexport const SourceMapManifestRequestSchema = z.object({\n  uploadId: z.string().uuid(),\n  buildHash: BuildHashSchema,\n  files: z\n    .array(\n      z.object({\n        filePath: z\n          .string()\n          .min(1)\n          .max(\n            MAX_SOURCE_MAP_FILE_PATH_LENGTH,\n            `filePath length exceeds maximum of ${MAX_SOURCE_MAP_FILE_PATH_LENGTH} characters`,\n          ),\n        sizeBytes: z\n          .number()\n          .int()\n          .positive()\n          .max(\n            MAX_SOURCE_MAP_FILE_SIZE,\n            `sizeBytes exceeds maximum of ${MAX_SOURCE_MAP_FILE_SIZE} bytes (${MAX_SOURCE_MAP_FILE_SIZE / (1024 * 1024)} MiB)`,\n          ),\n        blobUrl: z.string().url(),\n      }),\n    )\n    .min(1)\n    .max(\n      MAX_SOURCE_MAP_FILE_COUNT,\n      `files array exceeds maximum of ${MAX_SOURCE_MAP_FILE_COUNT} entries`,\n    ),\n});\nexport type SourceMapManifestRequest = z.infer<typeof SourceMapManifestRequestSchema>;\n\n/** Response confirming source map manifest activation. */\nexport const SourceMapManifestResponseSchema = z.object({\n  success: z.literal(true),\n  buildHash: BuildHashSchema,\n  fileCount: z.number().int().nonnegative(),\n  totalSizeBytes: z.number().int().nonnegative(),\n  activatedAt: z.number().int().positive(),\n});\nexport type SourceMapManifestResponse = z.infer<typeof SourceMapManifestResponseSchema>;\n","/**\n * SDK constants.\n */\n\nimport type { CaptureConfig } from \"./config.js\";\n\n/**\n * All glasstrace.* semantic attribute keys used by the SDK.\n *\n * @drift-check OpenTelemetry Semantic Conventions (https://opentelemetry.io/docs/specs/semconv/) + ../glasstrace-product/docs/component-designs/sdk-architecture.md §7.5 Span attributes (Tier 1)\n */\nexport const GLASSTRACE_ATTRIBUTE_NAMES = {\n  // Server-side attributes\n  TRACE_TYPE: \"glasstrace.trace.type\",\n  SESSION_ID: \"glasstrace.session.id\",\n  CORRELATION_ID: \"glasstrace.correlation.id\",\n  ENVIRONMENT: \"glasstrace.environment\",\n  ROUTE: \"glasstrace.route\",\n  HTTP_METHOD: \"glasstrace.http.method\",\n  HTTP_STATUS_CODE: \"glasstrace.http.status_code\",\n  HTTP_DURATION_MS: \"glasstrace.http.duration_ms\",\n  /**\n   * Boolean audit attribute set to `true` only when the SDK's\n   * boundary-masked-error heuristic at `enriching-exporter.ts`\n   * fires. Both same-span and descendant-aware scopes are supported;\n   * the companion {@link GLASSTRACE_ATTRIBUTE_NAMES.HTTP_BOUNDARY_MASKED_SCOPE}\n   * attribute records which scope produced the promotion.\n   *\n   * Strict additivity: backend ingestion ignores unknown attributes\n   * today; this attribute is for audit/observability. Downstream\n   * tooling MAY surface heuristic activation rates by querying for\n   * spans with this attribute set; the backend's status-handling\n   * pipeline does NOT depend on it.\n   *\n   * Absent on spans where the heuristic did not fire.\n   */\n  HTTP_BOUNDARY_MASKED: \"glasstrace.http.boundary_masked\",\n  /**\n   * Scope discriminator set alongside\n   * {@link GLASSTRACE_ATTRIBUTE_NAMES.HTTP_BOUNDARY_MASKED} whenever the\n   * boundary-masked-error heuristic promotes a span. Two values:\n   *\n   *   - `'same_span'` — the error signal (ERROR status, an `exception`\n   *     event, or an `exception.*` attribute) is on the HTTP server\n   *     span itself.\n   *   - `'descendant'` — the error signal is on a transitive child of\n   *     the HTTP server span (the page-route boundary case, where a\n   *     framework render span carries the exception while the request\n   *     renders an HTTP 200).\n   *\n   * Strict additivity: the value persists through the current\n   * ingestion pipeline untouched — no allowlist or ingestion change is\n   * required for it to be stored. Surfacing it on the read path (so a\n   * consumer can distinguish the two scopes via a query tool) is a\n   * separate downstream prerequisite, not implied by storage.\n   *\n   * Absent on spans where the heuristic did not fire.\n   */\n  HTTP_BOUNDARY_MASKED_SCOPE: \"glasstrace.http.boundary_masked_scope\",\n  ERROR_MESSAGE: \"glasstrace.error.message\",\n  ERROR_CODE: \"glasstrace.error.code\",\n  ERROR_CATEGORY: \"glasstrace.error.category\",\n  ERROR_FIELD: \"glasstrace.error.field\",\n\n  // Error evidence v1 (SDK-041 / DISC-1535).\n  // Additive to the existing `glasstrace.error.*` family. Bounded\n  // stacktrace input for the product-side StackSummary parser\n  // (SCHEMA-033); plus framework-fallback markers so the original\n  // request path is preserved when Next.js (or another framework)\n  // rewrites the route to a fallback like `/_error` or `/_not-found`;\n  // plus a source-provenance enum so product can tell which surface\n  // emitted each error fact (`exception.message` event vs span attr\n  // vs response body vs framework runtime).\n  //\n  // Wire keys remain in `glasstrace.error.*` for namespace consistency\n  // with the Tier-1 `error.message` / `error.code` / `error.category`\n  // attributes already in this registry.\n  ERROR_STACK: \"glasstrace.error.stack\",\n  ERROR_STACK_TRUNCATED: \"glasstrace.error.stack.truncated\",\n  ERROR_STACK_REDACTED: \"glasstrace.error.stack.redacted\",\n  ERROR_SOURCE: \"glasstrace.error.source\",\n  ERROR_FRAMEWORK_KIND: \"glasstrace.error.framework.kind\",\n  ERROR_ORIGINAL_PATH: \"glasstrace.error.original_path\",\n  ERROR_FALLBACK_ROUTE: \"glasstrace.error.fallback_route\",\n  ORM_PROVIDER: \"glasstrace.orm.provider\",\n  ORM_MODEL: \"glasstrace.orm.model\",\n  ORM_OPERATION: \"glasstrace.orm.operation\",\n  ORM_DURATION_MS: \"glasstrace.orm.duration_ms\",\n  FETCH_URL: \"glasstrace.fetch.url\",\n  FETCH_METHOD: \"glasstrace.fetch.method\",\n  FETCH_STATUS_CODE: \"glasstrace.fetch.status_code\",\n  FETCH_DURATION_MS: \"glasstrace.fetch.duration_ms\",\n  FETCH_TARGET: \"glasstrace.fetch.target\",\n  ENV_REFERENCED: \"glasstrace.env.referenced\",\n  BUILD_HASH: \"glasstrace.build.hash\",\n  SOURCE_FILE: \"glasstrace.source.file\",\n  SOURCE_LINE: \"glasstrace.source.line\",\n  SOURCE_MAPPED: \"glasstrace.source.mapped\",\n  TRPC_PROCEDURE: \"glasstrace.trpc.procedure\",\n  /**\n   * Zero-based positional index of the current member within a tRPC\n   * HTTP-batch dispatch. Set on\n   * member spans by `tracedMiddleware` when the SDK's\n   * `wrapBatchedHttpHandler` envelope is in scope. Numeric.\n   *\n   * Load-bearing for batches that include the same procedure name\n   * more than once — name-only matching cannot disambiguate, so the\n   * positional index is the canonical disambiguator. Absent on\n   * non-batched spans and on apps not using `wrapBatchedHttpHandler`.\n   */\n  TRPC_BATCH_MEMBER_INDEX: \"glasstrace.trpc.batch.member_index\",\n  /**\n   * Ordered list of all procedure names in the current tRPC HTTP\n   * batch. Stored as an OTel\n   * typed string array (`string[]`), NOT a JSON-encoded string —\n   * the typed-array form preserves first-class queryability in the\n   * OTel ingest pipeline.\n   *\n   * Set on each member span that `tracedMiddleware` produces when a\n   * `wrapBatchedHttpHandler` envelope is in scope. Absent on\n   * non-batched spans, on the root HTTP server span (today's\n   * release ships strict-additive scope only — per-root-span\n   * attribution is deferred to a follow-up wave because changing\n   * the root span's existing `glasstrace.trpc.procedure` shape from\n   * comma-joined to first-member representative is non-additive),\n   * and on apps not using `wrapBatchedHttpHandler`.\n   */\n  TRPC_BATCH_MEMBER_PROCEDURES:\n    \"glasstrace.trpc.batch.member_procedures\",\n  ERROR_RESPONSE_BODY: \"glasstrace.error.response_body\",\n  NEXT_ACTION_DETECTED: \"glasstrace.next.action.detected\",\n\n  // Client-side attributes\n  PLATFORM: \"glasstrace.platform\",\n  GESTURE_TYPE: \"glasstrace.gesture.type\",\n  TRIGGER_TYPE: \"glasstrace.trigger.type\",\n  ELEMENT_FINGERPRINT: \"glasstrace.element.fingerprint\",\n  ELEMENT_CONFIDENCE: \"glasstrace.element.confidence\",\n  TAB_ID: \"glasstrace.tab.id\",\n\n  // Causal evidence (SDK-046 / DISC-1537 + DISC-1539).\n  //\n  // The SDK emits `glasstrace.causal.*` attributes on spans that\n  // carry instrumentation-time evidence about a span's relationship\n  // to its owning request trace. Two families are defined here:\n  //\n  //   - `MIDDLEWARE_FOR_REQUEST` — middleware-ownership marker. Set\n  //     on a middleware-only span by `tracedRequestMiddleware()` from\n  //     `@glasstrace/sdk/middleware`. Carries the originating\n  //     request's normalized path so the product-side trace-summary\n  //     transform can link the middleware span to the owning HTTP\n  //     request trace even when the middleware runs in an edge\n  //     runtime that does not propagate AsyncLocalStorage parents.\n  //\n  //   - `POST_RESPONSE_ASYNC` — post-response async marker. Set on a\n  //     span emitted from inside `withAsyncCausality()` from\n  //     `@glasstrace/sdk/async-context`. Carries the originating\n  //     request's trace ID (32-character hex) captured at the call\n  //     site so async work scheduled via Next.js `after()`, queues,\n  //     or webhooks can be linked back to its originating request.\n  //     Companion booleans `CAUSAL_AFFECTS_HTTP_STATUS` /\n  //     `CAUSAL_AFFECTS_HTTP_DURATION` document whether the async\n  //     work participates in the root request's outcome (default\n  //     `false` — non-outcome async work).\n  //\n  // Wire keys live under the `glasstrace.causal.*` namespace so they\n  // are namespace-distinct from `glasstrace.error.*`,\n  // `glasstrace.http.*`, `glasstrace.trpc.*`, and the side-effect\n  // family below. Adding these constants is a `@glasstrace/protocol`\n  // minor bump; existing entries are untouched.\n  CAUSAL_MIDDLEWARE_FOR_REQUEST: \"glasstrace.causal.middleware_for_request\",\n  CAUSAL_POST_RESPONSE_ASYNC: \"glasstrace.causal.post_response_async\",\n  CAUSAL_AFFECTS_HTTP_STATUS: \"glasstrace.causal.affects_http_status\",\n  CAUSAL_AFFECTS_HTTP_DURATION: \"glasstrace.causal.affects_http_duration\",\n\n  // Side-effect evidence attributes.\n  // Top-level operation attributes attached to the active span when a\n  // side-effect is recorded via `recordSideEffect()`. The wire-string\n  // set aligns verbatim with the product-side filter in\n  // `packages/ingestion/src/services/trace-writer.ts`.\n  SIDE_EFFECT_KIND: \"glasstrace.side_effect.kind\",\n  SIDE_EFFECT_OPERATION: \"glasstrace.side_effect.operation\",\n  SIDE_EFFECT_STATUS: \"glasstrace.side_effect.status\",\n  SIDE_EFFECT_PHASE: \"glasstrace.side_effect.phase\",\n\n  // Allowlisted semantic field attributes — one per allowlisted key.\n  // Wire keys are camelCase to match the wire-schema enum members\n  // exactly; the SDK constant names are SCREAMING_SNAKE per the rest\n  // of GLASSTRACE_ATTRIBUTE_NAMES.\n  SIDE_EFFECT_FIELD_TEMPLATE_KEY: \"glasstrace.side_effect.field.templateKey\",\n  SIDE_EFFECT_FIELD_PROVIDER_OPERATION:\n    \"glasstrace.side_effect.field.providerOperation\",\n  SIDE_EFFECT_FIELD_ROLE: \"glasstrace.side_effect.field.role\",\n  SIDE_EFFECT_FIELD_LOCALE: \"glasstrace.side_effect.field.locale\",\n  SIDE_EFFECT_FIELD_TIMEZONE: \"glasstrace.side_effect.field.timezone\",\n  SIDE_EFFECT_FIELD_STATUS: \"glasstrace.side_effect.field.status\",\n  SIDE_EFFECT_FIELD_PHASE: \"glasstrace.side_effect.field.phase\",\n  SIDE_EFFECT_FIELD_RECIPIENT_CLASS:\n    \"glasstrace.side_effect.field.recipientClass\",\n  SIDE_EFFECT_FIELD_PARTICIPANT_COUNT:\n    \"glasstrace.side_effect.field.participantCount\",\n  SIDE_EFFECT_FIELD_ACTIVE_PARTICIPANT_COUNT:\n    \"glasstrace.side_effect.field.activeParticipantCount\",\n\n  // Omission reason attributes — one per allowlisted reason. The\n  // attribute value carries an integer count; the rejected value is\n  // never echoed.\n  SIDE_EFFECT_OMITTED_PII: \"glasstrace.side_effect.omitted.pii\",\n  SIDE_EFFECT_OMITTED_SECRET: \"glasstrace.side_effect.omitted.secret\",\n  SIDE_EFFECT_OMITTED_RAW_PAYLOAD:\n    \"glasstrace.side_effect.omitted.raw_payload\",\n  SIDE_EFFECT_OMITTED_UNSUPPORTED_KEY:\n    \"glasstrace.side_effect.omitted.unsupported_key\",\n  SIDE_EFFECT_OMITTED_VALUE_TOO_LONG:\n    \"glasstrace.side_effect.omitted.value_too_long\",\n  SIDE_EFFECT_OMITTED_NOT_EMITTED:\n    \"glasstrace.side_effect.omitted.not_emitted\",\n  SIDE_EFFECT_OMITTED_CAPTURE_DISABLED:\n    \"glasstrace.side_effect.omitted.capture_disabled\",\n\n  // Value-fidelity scalar-channel omission reasons. Counts only; the\n  // rejected raw value (timestamp, unhashed id, non-finite number) is\n  // never echoed. Mirror the product omission enum verbatim.\n  SIDE_EFFECT_OMITTED_RAW_TIMESTAMP:\n    \"glasstrace.side_effect.omitted.raw_timestamp\",\n  SIDE_EFFECT_OMITTED_UNHASHED_ID:\n    \"glasstrace.side_effect.omitted.unhashed_id\",\n  SIDE_EFFECT_OMITTED_NON_FINITE:\n    \"glasstrace.side_effect.omitted.non_finite\",\n\n  // Drop-class omission reasons that split `unsupported_key`. Counts\n  // only; the rejected value is never echoed.\n  // `scalar_cap_exceeded` = a scalar dropped because the per-operation\n  // scalar budget was already full. `allowlist_denied` = a value\n  // dropped by a default-deny allowlist gate. Mirrored verbatim by the\n  // consuming omission-reason schema. Sequencing: the consumer must\n  // accept a reason before any producer emits it, so these attribute\n  // names ship ahead of the producers that will record them.\n  SIDE_EFFECT_OMITTED_SCALAR_CAP_EXCEEDED:\n    \"glasstrace.side_effect.omitted.scalar_cap_exceeded\",\n  SIDE_EFFECT_OMITTED_ALLOWLIST_DENIED:\n    \"glasstrace.side_effect.omitted.allowlist_denied\",\n} as const;\n\n/** Default SDK capture config (conservative defaults). */\nexport const DEFAULT_CAPTURE_CONFIG: CaptureConfig = {\n  requestBodies: false,\n  queryParamValues: false,\n  envVarValues: false,\n  fullConsoleOutput: false,\n  importGraph: false,\n  consoleErrors: false,\n  errorResponseBodies: false,\n  sideEffectEvidence: false,\n  captureFidelity: \"strict\",\n};\n\n// --- Source map upload limits ---\n//\n// These constants mirror the backend canonical bounds enforced on the\n// presigned source map upload pipeline. They are exported from\n// `@glasstrace/protocol` so SDK code and external tooling that consumes\n// the wire schemas can reference the same numeric ceilings the backend\n// applies at write time, instead of duplicating literal magic numbers.\n\n/**\n * Maximum length, in characters, of a source map `filePath` carried in the\n * presigned upload wire schemas.\n *\n * Backend-canonical: applied to `PresignedUploadResponseSchema.files[].filePath`,\n * `PresignedUploadRequestSchema.files[].filePath`, and\n * `SourceMapManifestRequestSchema.files[].filePath`.\n */\nexport const MAX_SOURCE_MAP_FILE_PATH_LENGTH = 512;\n\n/**\n * Maximum size, in bytes, of an individual source map file (50 MiB).\n *\n * Backend-canonical: applied to `PresignedUploadResponseSchema.files[].maxBytes`,\n * `PresignedUploadRequestSchema.files[].sizeBytes`, and\n * `SourceMapManifestRequestSchema.files[].sizeBytes`.\n */\nexport const MAX_SOURCE_MAP_FILE_SIZE = 50 * 1024 * 1024;\n\n/**\n * Maximum number of source map files per presigned upload request or\n * manifest activation.\n *\n * Backend-canonical: applied to the top-level `files` array bound on\n * `PresignedUploadRequestSchema`, `PresignedUploadResponseSchema`, and\n * `SourceMapManifestRequestSchema`.\n */\nexport const MAX_SOURCE_MAP_FILE_COUNT = 100;\n","/**\n * Pure-JavaScript SHA-256 implementation.\n *\n * Glasstrace's session ID derivation is part of the wire contract: the\n * SDK, the browser extension, and any future tooling must produce the\n * same `SessionId` from the same inputs, regardless of runtime. A pure\n * implementation avoids runtime-branching (Node `crypto` vs Web Crypto\n * vs Edge) and the non-determinism that branching introduces — most\n * importantly, the fact that `require(\"node:crypto\")` is unavailable in\n * Node ESM and in browser bundles.\n *\n * SHA-256 is an identifier hash here, not an authentication primitive.\n * The session ID is never used for authorization.\n *\n * Implementation follows FIPS 180-4 §6.2. Tested against the standard\n * NIST test vectors and Node's built-in `crypto.createHash(\"sha256\")`.\n */\n\n/**\n * SHA-256 round constants — first 32 bits of the fractional parts of\n * the cube roots of the first 64 primes (FIPS 180-4 §4.2.2).\n */\nconst K = new Uint32Array([\n  0x428a2f98, 0x71374491, 0xb5c0fbcf, 0xe9b5dba5, 0x3956c25b, 0x59f111f1,\n  0x923f82a4, 0xab1c5ed5, 0xd807aa98, 0x12835b01, 0x243185be, 0x550c7dc3,\n  0x72be5d74, 0x80deb1fe, 0x9bdc06a7, 0xc19bf174, 0xe49b69c1, 0xefbe4786,\n  0x0fc19dc6, 0x240ca1cc, 0x2de92c6f, 0x4a7484aa, 0x5cb0a9dc, 0x76f988da,\n  0x983e5152, 0xa831c66d, 0xb00327c8, 0xbf597fc7, 0xc6e00bf3, 0xd5a79147,\n  0x06ca6351, 0x14292967, 0x27b70a85, 0x2e1b2138, 0x4d2c6dfc, 0x53380d13,\n  0x650a7354, 0x766a0abb, 0x81c2c92e, 0x92722c85, 0xa2bfe8a1, 0xa81a664b,\n  0xc24b8b70, 0xc76c51a3, 0xd192e819, 0xd6990624, 0xf40e3585, 0x106aa070,\n  0x19a4c116, 0x1e376c08, 0x2748774c, 0x34b0bcb5, 0x391c0cb3, 0x4ed8aa4a,\n  0x5b9cca4f, 0x682e6ff3, 0x748f82ee, 0x78a5636f, 0x84c87814, 0x8cc70208,\n  0x90befffa, 0xa4506ceb, 0xbef9a3f7, 0xc67178f2,\n]);\n\nfunction rotr(x: number, n: number): number {\n  return ((x >>> n) | (x << (32 - n))) >>> 0;\n}\n\n/**\n * Computes SHA-256 of a UTF-8 string and returns the digest as a\n * lowercase hexadecimal string (64 characters).\n *\n * `TextEncoder` is a web standard available in every runtime this\n * package targets: Node 20+, modern browsers, Vercel Edge, and\n * Cloudflare Workers.\n */\nexport function sha256Hex(input: string): string {\n  const message = new TextEncoder().encode(input);\n  const bitLength = message.length * 8;\n\n  // Pad per FIPS 180-4 §5.1.1: append 0x80, zero-fill, append the\n  // original length as a 64-bit big-endian integer, such that the total\n  // length is a multiple of 64 bytes (512 bits).\n  const paddedLength = Math.ceil((message.length + 9) / 64) * 64;\n  const padded = new Uint8Array(paddedLength);\n  padded.set(message);\n  padded[message.length] = 0x80;\n\n  const view = new DataView(padded.buffer);\n  // JS numbers are safe up to 2^53; for inputs up to that many bits the\n  // high 32 bits fit in a plain number. `>>> 0` yields the low 32 bits.\n  view.setUint32(paddedLength - 8, Math.floor(bitLength / 0x100000000), false);\n  view.setUint32(paddedLength - 4, bitLength >>> 0, false);\n\n  // Initial hash values — first 32 bits of fractional parts of square\n  // roots of the first 8 primes (FIPS 180-4 §5.3.3).\n  const H = new Uint32Array([\n    0x6a09e667, 0xbb67ae85, 0x3c6ef372, 0xa54ff53a,\n    0x510e527f, 0x9b05688c, 0x1f83d9ab, 0x5be0cd19,\n  ]);\n\n  const W = new Uint32Array(64);\n\n  for (let offset = 0; offset < paddedLength; offset += 64) {\n    for (let i = 0; i < 16; i++) {\n      W[i] = view.getUint32(offset + i * 4, false);\n    }\n    for (let i = 16; i < 64; i++) {\n      const s0 = rotr(W[i - 15], 7) ^ rotr(W[i - 15], 18) ^ (W[i - 15] >>> 3);\n      const s1 = rotr(W[i - 2], 17) ^ rotr(W[i - 2], 19) ^ (W[i - 2] >>> 10);\n      W[i] = (W[i - 16] + s0 + W[i - 7] + s1) >>> 0;\n    }\n\n    let a = H[0]!;\n    let b = H[1]!;\n    let c = H[2]!;\n    let d = H[3]!;\n    let e = H[4]!;\n    let f = H[5]!;\n    let g = H[6]!;\n    let h = H[7]!;\n\n    for (let i = 0; i < 64; i++) {\n      const S1 = rotr(e, 6) ^ rotr(e, 11) ^ rotr(e, 25);\n      const ch = (e & f) ^ (~e & g);\n      const temp1 = (h + S1 + ch + K[i]! + W[i]!) >>> 0;\n      const S0 = rotr(a, 2) ^ rotr(a, 13) ^ rotr(a, 22);\n      const maj = (a & b) ^ (a & c) ^ (b & c);\n      const temp2 = (S0 + maj) >>> 0;\n      h = g;\n      g = f;\n      f = e;\n      e = (d + temp1) >>> 0;\n      d = c;\n      c = b;\n      b = a;\n      a = (temp1 + temp2) >>> 0;\n    }\n\n    H[0] = (H[0]! + a) >>> 0;\n    H[1] = (H[1]! + b) >>> 0;\n    H[2] = (H[2]! + c) >>> 0;\n    H[3] = (H[3]! + d) >>> 0;\n    H[4] = (H[4]! + e) >>> 0;\n    H[5] = (H[5]! + f) >>> 0;\n    H[6] = (H[6]! + g) >>> 0;\n    H[7] = (H[7]! + h) >>> 0;\n  }\n\n  let out = \"\";\n  for (let i = 0; i < 8; i++) {\n    out += H[i]!.toString(16).padStart(8, \"0\");\n  }\n  return out;\n}\n","/**\n * Session ID derivation — part of the public Glasstrace wire contract.\n *\n * Deriving the session ID is deterministic: given the same inputs,\n * every runtime that implements this module produces the same\n * 16-character hex identifier. That determinism is the contract — it\n * lets independent clients (SDK, browser extension, server tooling)\n * agree on the same session without coordination.\n *\n * This module is pure: it has no module-level state and no\n * runtime-dependent branches. It is safe to import from Node 20+,\n * modern browsers, Vercel Edge, and Cloudflare Workers. The SHA-256\n * implementation is pure JavaScript; no `node:crypto`, no Web Crypto,\n * no bundler-specific shims.\n */\n\nimport { SessionIdSchema } from \"./ids.js\";\nimport type { SessionId } from \"./ids.js\";\nimport { sha256Hex } from \"./sha256.js\";\n\n/**\n * Derives a deterministic session ID from the inputs that define a\n * Glasstrace session. The output is a 16-character lowercase hex\n * string validated through {@link SessionIdSchema}.\n *\n * This function is part of the Glasstrace wire contract: any consumer\n * (SDK, browser extension, server tooling) that calls it with the same\n * arguments receives the same `SessionId`. That property is what lets\n * independent clients agree on a session without coordination.\n *\n * Uses a pure-JavaScript SHA-256 so the output is identical across\n * every runtime this package supports (Node 20+, modern browsers,\n * Vercel Edge, Cloudflare Workers).\n *\n * Security note: the session ID is an **identifier**, not a secret or\n * an authentication token. It is never used for authorization.\n *\n * @param apiKey - The project's API key (or anonymous placeholder).\n * @param origin - The origin string identifying the deployment\n *   environment (for example `localhost:3000` or `production`).\n * @param date - UTC date as `YYYY-MM-DD`.\n * @param windowIndex - Zero-based index of the 4-hour activity window\n *   within the day.\n * @returns A 16-character hex {@link SessionId}.\n *\n * @drift-check ../glasstrace-product/docs/product-spec.md §4.5 Session Lifecycle\n */\nexport function deriveSessionId(\n  apiKey: string,\n  origin: string,\n  date: string,\n  windowIndex: number,\n): SessionId {\n  const input = JSON.stringify([apiKey, origin, date, windowIndex]);\n  const digest = sha256Hex(input).slice(0, 16);\n  return SessionIdSchema.parse(digest);\n}\n","/**\n * Side-effect evidence value-enum constants.\n *\n * The runtime `as const` tuples are the source of truth for the\n * allowlisted value sets. TypeScript types are derived via\n * `typeof T[number]` so consumers get a literal-type union without a\n * separate string-literal-union declaration that could silently drift\n * from the runtime allowlist.\n *\n * These tuples align verbatim with the product-side wire schema in\n * `glasstrace-product/shared/types/agent-evidence.ts`. Members must\n * remain in sync across both repos; the SDK enforces these allowlists\n * client-side as defense-in-depth before any attribute reaches the\n * wire (the product's storage filter is a second defense, not the\n * primary boundary).\n *\n * @drift-check ../../glasstrace-product/docs/component-designs/side-effect-evidence-summaries.md\n */\n\n/**\n * Allowlisted side-effect operation kinds (v1).\n *\n * Each kind names a category of side effect the receiver projects in\n * MCP tool responses. New kinds require a coordinated bump across the\n * wire-schema definition, this tuple, and any downstream consumer that\n * switches on the kind.\n */\nexport const SIDE_EFFECT_OPERATION_KINDS = [\n  \"email\",\n  \"calendar_link\",\n  \"webhook\",\n  \"external_api\",\n  \"queue\",\n  \"after_callback\",\n] as const;\n\n/**\n * One of the allowlisted side-effect operation kinds.\n *\n * @see {@link SIDE_EFFECT_OPERATION_KINDS}\n */\nexport type SideEffectOperationKind =\n  (typeof SIDE_EFFECT_OPERATION_KINDS)[number];\n\n/**\n * Stable-core semantic field keys for `recordSideEffect()` evidence.\n *\n * These seven keys have specialized value validators (BCP-47 for\n * `locale`, IANA for `timezone`, compact token for the rest) and are\n * the closed set of names that can never be removed without a\n * coordinated wire-breaking change. Pattern-admitted keys (see\n * {@link SIDE_EFFECT_SEMANTIC_FIELD_OPEN_PATTERN}) live alongside\n * these and are validated by suffix routing.\n */\nexport const SIDE_EFFECT_SEMANTIC_FIELD_STABLE_CORE_KEYS = [\n  \"templateKey\",\n  \"providerOperation\",\n  \"role\",\n  \"locale\",\n  \"timezone\",\n  \"status\",\n  \"phase\",\n] as const;\n\n/**\n * One of the stable-core semantic field keys (compile-time literal\n * union). Consumers who want autocomplete for the closed stable-core\n * set import this narrower type; consumers who accept the wider\n * named-pattern admission shape use {@link SideEffectSemanticFieldKey}.\n *\n * @see {@link SIDE_EFFECT_SEMANTIC_FIELD_STABLE_CORE_KEYS}\n */\nexport type SideEffectSemanticFieldStableCoreKey =\n  (typeof SIDE_EFFECT_SEMANTIC_FIELD_STABLE_CORE_KEYS)[number];\n\n/**\n * Open-pattern semantic field key regex.\n *\n * Keys that match this regex are admitted alongside the stable-core\n * literal set. The suffix family is `*Class` / `*Count` / `*Kind` /\n * `*Role` / `*Holds`; producers normalize key names to lowerCamelCase\n * with one of the canonical suffixes. Value-shape validators route on\n * the suffix:\n *\n *   - `*Count` → digit-only string (max 16 chars)\n *   - `*Holds` → boolean string (`\"true\"` / `\"false\"`)\n *   - `*Class` / `*Kind` / `*Role` → compact-token string (max 80)\n *\n * `*Holds` carries a producer-supplied boolean relation (an asserted\n * invariant such as `timezonePreservedHolds`) inline on the categorical\n * field channel — not the scalar channel. Stable-core keys with\n * specialized validators take precedence over the default suffix\n * routing.\n */\nexport const SIDE_EFFECT_SEMANTIC_FIELD_OPEN_PATTERN =\n  /^[a-z][A-Za-z0-9]*(Class|Count|Kind|Role|Holds)$/;\n\n/**\n * Maximum length, in characters, of a semantic field KEY name.\n *\n * The pattern regex {@link SIDE_EFFECT_SEMANTIC_FIELD_OPEN_PATTERN}\n * has no length bound on its own. A producer that derived a key\n * from request/provider metadata could pass a giant string ending in\n * `Class`/`Count`/`Kind`/`Role` and inflate the emitted\n * `glasstrace.side_effect.field.<key>` OTel attribute. The closed\n * enum era bounded key-name size implicitly; pattern admission\n * needs an explicit cap. 80 mirrors the SDK's value-length cap for\n * symmetry; stable-core keys are all ≤22 chars and pattern keys\n * following the lowerCamelCase + canonical-suffix convention rarely\n * exceed ~30 chars, so 80 gives generous headroom while keeping\n * telemetry payloads bounded.\n *\n * The cap lives at the protocol layer (not just the SDK runtime)\n * because {@link isSideEffectSemanticFieldKey} is exported as the\n * public runtime guard for producer-supplied keys; consumers calling\n * the guard must see the same admission decision the SDK uses at\n * emission.\n */\nexport const MAX_SIDE_EFFECT_SEMANTIC_FIELD_KEY_LENGTH = 80;\n\n/**\n * Runtime guard for the semantic field key admission contract.\n *\n * Returns `true` when `key` is non-empty, no longer than\n * {@link MAX_SIDE_EFFECT_SEMANTIC_FIELD_KEY_LENGTH}, and either one\n * of the seven stable-core keys or matches the open-pattern regex.\n * Use this guard at any runtime call-site that needs to validate a\n * producer-supplied key before emission; for compile-time\n * autocomplete on the stable-core subset, import\n * {@link SideEffectSemanticFieldStableCoreKey}.\n *\n * Note: the length cap is part of the admission contract, not a\n * separate SDK runtime concern. Consumers using this guard see the\n * same decision the SDK uses at `recordSideEffect()` emission.\n */\nexport function isSideEffectSemanticFieldKey(key: string): boolean {\n  if (key.length > MAX_SIDE_EFFECT_SEMANTIC_FIELD_KEY_LENGTH) return false;\n  return (\n    (SIDE_EFFECT_SEMANTIC_FIELD_STABLE_CORE_KEYS as readonly string[]).includes(\n      key,\n    ) || SIDE_EFFECT_SEMANTIC_FIELD_OPEN_PATTERN.test(key)\n  );\n}\n\n/**\n * Any admissible semantic field key — the stable-core literal union\n * plus any string matching the open-pattern regex.\n *\n * Note: TypeScript collapses `<literal-union> | string` to `string`\n * at the type level (the `string` member subsumes the literal arm),\n * so compile-time narrowing is intentionally relaxed at this\n * surface. Runtime admission is enforced by\n * {@link isSideEffectSemanticFieldKey}. Consumers who want\n * compile-time stable-core autocomplete should import\n * {@link SideEffectSemanticFieldStableCoreKey} instead.\n */\nexport type SideEffectSemanticFieldKey =\n  | SideEffectSemanticFieldStableCoreKey\n  | string;\n\n/**\n * Allowlisted reasons a side-effect value may be omitted from the\n * emitted summary.\n *\n * The SDK records counts under these reasons rather than the rejected\n * values themselves so unsafe input never appears anywhere on the\n * wire. The set is fixed by the wire schema; new reasons require a\n * coordinated cross-repo bump.\n */\nexport const SIDE_EFFECT_OMISSION_REASONS = [\n  \"pii\",\n  \"secret\",\n  \"raw_payload\",\n  \"unsupported_key\",\n  \"value_too_long\",\n  \"not_emitted\",\n  \"capture_disabled\",\n  // Value-fidelity scalar channel reasons. A scalar is dropped under\n  // `raw_timestamp` when a wall-clock value (a `Date` instance, or a\n  // numeric epoch on a `*Ms` key) is rejected in favor of a bounded\n  // delta; `unhashed_id` when an `*Id` scalar is not the `gthid_<hex>`\n  // output of `hashId`; `non_finite` when a number is NaN/±Infinity.\n  // (A type-mismatched value — e.g. a date *string* on a numeric key —\n  // is dropped under `raw_payload`, not `raw_timestamp`, since the\n  // scalar channel only carries native numbers/booleans plus `gthid_`\n  // ids.) These mirror the product `SideEffectOmissionReasonSchema`\n  // tuple verbatim (hand-maintained on both sides; see @drift-check\n  // above). `non_finite` is SDK-emit-time only — JSON cannot carry\n  // NaN/Infinity to the wire.\n  \"raw_timestamp\",\n  \"unhashed_id\",\n  \"non_finite\",\n  // Drop-class reasons that split what was previously folded into\n  // `unsupported_key`. `scalar_cap_exceeded` is recorded when a scalar\n  // is dropped because the per-operation scalar budget\n  // (`MAX_SIDE_EFFECT_SCALARS_PER_OPERATION`) is already full — a\n  // cap-overflow drop, distinct from a value that is individually\n  // inadmissible. `allowlist_denied` is recorded when a value is\n  // dropped by a default-deny allowlist gate — the value was rejected\n  // because it was not explicitly permitted, distinct from a value\n  // that failed a key/shape/length check. Like the rest of this tuple\n  // these are mirrored verbatim by the consuming\n  // `SideEffectOmissionReasonSchema` (hand-maintained on both sides;\n  // see @drift-check above). The schema mirror admits these reasons\n  // before any producer emits them — see the sequencing note on\n  // `SIDE_EFFECT_OMITTED_SCALAR_CAP_EXCEEDED` in `constants.ts`.\n  \"scalar_cap_exceeded\",\n  \"allowlist_denied\",\n] as const;\n\n/**\n * One of the allowlisted side-effect omission reasons.\n *\n * @see {@link SIDE_EFFECT_OMISSION_REASONS}\n */\nexport type SideEffectOmissionReason =\n  (typeof SIDE_EFFECT_OMISSION_REASONS)[number];\n\n/**\n * Value-fidelity scalar key pattern.\n *\n * Scalars carry type-aware raw magnitudes off-summary on the\n * `glasstrace.side_effect.scalar.*` channel, distinct from the\n * categorical `*.field.*` summary channel. A scalar key is camelCase\n * ending in one of the magnitude/identity suffixes:\n *\n *   - `*Ms` / `*Amount` / `*Bytes` / `*Ratio` / `*Value` → finite number\n *   - `*Flag` → boolean\n *   - `*Id` → a `gthid_<hex>` hashed identifier (never a raw id)\n *\n * `Count` is deliberately **excluded**: count facets route to the\n * categorical summary channel via the `*Count` semantic-field validator,\n * not the scalar channel. Channel selection is by attribute **prefix**\n * (`…field.*` vs `…scalar.*`), never by key suffix — the same key may\n * legitimately exist on both channels.\n *\n * Mirrors the product `SideEffectScalarSchema` key regex verbatim\n * (`shared/types/agent-evidence.ts`); see @drift-check above.\n */\nexport const SIDE_EFFECT_SCALAR_KEY_PATTERN =\n  /^[a-z][A-Za-z0-9]*(Ms|Amount|Bytes|Ratio|Id|Value|Flag)$/;\n\n/**\n * OTel attribute-name prefix for the value-fidelity scalar channel.\n * The emitted attribute is `${SIDE_EFFECT_SCALAR_PREFIX}${key}` carrying\n * a native `number` / `boolean` / `string` value (no stringify — the\n * product validator rejects numeric- and boolean-shaped strings).\n */\nexport const SIDE_EFFECT_SCALAR_PREFIX = \"glasstrace.side_effect.scalar.\";\n\n/**\n * Maximum number of scalars recorded per side-effect operation. Scalars\n * are off-summary and do not count against the categorical\n * per-operation field budget; this is the separate scalar ceiling,\n * enforced SDK-side at emit and re-enforced product-side at ingestion.\n */\nexport const MAX_SIDE_EFFECT_SCALARS_PER_OPERATION = 16;\n\n/**\n * Runtime guard for the scalar key admission contract. Returns `true`\n * when `key` is no longer than\n * {@link MAX_SIDE_EFFECT_SEMANTIC_FIELD_KEY_LENGTH} and matches\n * {@link SIDE_EFFECT_SCALAR_KEY_PATTERN}. The length cap is shared with\n * the semantic-field key contract for symmetry with the product schema,\n * which bounds the scalar key by the same constant.\n */\nexport function isSideEffectScalarKey(key: string): boolean {\n  if (key.length > MAX_SIDE_EFFECT_SEMANTIC_FIELD_KEY_LENGTH) return false;\n  return SIDE_EFFECT_SCALAR_KEY_PATTERN.test(key);\n}\n\n/**\n * Fixed prefix of a hashed side-effect identifier produced by `hashId`.\n * The full shape is `gthid_<lowercase-hex>`; the product validator\n * accepts `/^gthid_[0-9a-f]+$/` (length-agnostic), while the SDK emits a\n * fixed-length digest so a forged `gthid_<non-hex>` fails the shape.\n */\nexport const SIDE_EFFECT_HASHED_ID_PREFIX = \"gthid_\";\n\n/**\n * Hex length of the digest in a `hashId` token (`gthid_<hex>`). The SDK\n * both emits and (under `strict`) admits exactly this length — a\n * fixed-shape `gthid_[0-9a-f]{N}` token, which is stronger than the\n * product validator's length-agnostic `^gthid_[0-9a-f]+$`. Pinning the\n * length closes a smuggling vector (arbitrary hex-encoded data behind\n * `gthid_`) and bounds the emitted attribute size. Shared by `hashId`\n * and the SDK scalar validator so the two cannot drift.\n */\nexport const SIDE_EFFECT_HASHED_ID_HEX_LENGTH = 32;\n\n/**\n * Allowlisted side-effect operation lifecycle statuses.\n */\nexport const SIDE_EFFECT_OPERATION_STATUSES = [\n  \"scheduled\",\n  \"started\",\n  \"succeeded\",\n  \"failed\",\n  \"unknown\",\n] as const;\n\n/**\n * One of the allowlisted side-effect operation statuses.\n *\n * @see {@link SIDE_EFFECT_OPERATION_STATUSES}\n */\nexport type SideEffectOperationStatus =\n  (typeof SIDE_EFFECT_OPERATION_STATUSES)[number];\n\n/**\n * Allowlisted side-effect operation execution phases.\n *\n * Distinguishes side effects that ran inside the request handler from\n * those that ran after the response was sent (e.g., `after()` hook,\n * background job).\n */\nexport const SIDE_EFFECT_OPERATION_PHASES = [\n  \"request\",\n  \"post_response\",\n  \"background\",\n  \"unknown\",\n] as const;\n\n/**\n * One of the allowlisted side-effect operation phases.\n *\n * @see {@link SIDE_EFFECT_OPERATION_PHASES}\n */\nexport type SideEffectOperationPhase =\n  (typeof SIDE_EFFECT_OPERATION_PHASES)[number];\n","/**\n * Error evidence value-enum constants.\n *\n * Companion to the new `glasstrace.error.*` attribute keys in\n * `constants.ts`. The runtime `as const` tuples are the source of\n * truth for allowlisted attribute-value sets; TypeScript types are\n * derived via `typeof T[number]` so consumers get literal unions\n * without a separate string-literal-union declaration that could\n * silently drift from the runtime allowlist.\n *\n * These tuples align with the Agent Evidence Engine SDK Attribute\n * Contract §5.5 in `glasstrace-product/docs/component-designs/agent-evidence-sdk-attribute-contract.md`.\n * Members must remain in sync across both repos; product-side\n * validators enforce these allowlists at ingestion as a second\n * defense, not the primary boundary.\n *\n * @drift-check ../../glasstrace-product/docs/component-designs/agent-evidence-sdk-attribute-contract.md §5.5\n */\n\n/**\n * Allowlisted source-provenance values for `glasstrace.error.source`.\n *\n * The SDK emits one of these to tell product consumers which surface\n * supplied each error fact. Values:\n *\n * - `otel_exception` — facts came from an OTel exception event\n *   (`recordException()` / span event with `name === \"exception\"`).\n *   This is the canonical OTel surface for exceptions and the\n *   highest-confidence source.\n * - `otel_event` — facts came from `exception.*` attributes set\n *   directly on the span (not on an event). Some real-world\n *   instrumentations populate `attrs[\"exception.message\"]` /\n *   `attrs[\"exception.type\"]` / `attrs[\"exception.stacktrace\"]`\n *   without using `recordException()`; those facts are still\n *   OTel-shape, just on the non-canonical surface. Distinct from\n *   `otel_exception` so product can tell which surface was used\n *   — the canonical event path is more authoritative when both\n *   are present.\n * - `glasstrace_attribute` — facts came from a `glasstrace.error.*`\n *   span attribute set explicitly by an adapter or user code (e.g.,\n *   the tRPC handler wrapper populating `glasstrace.error.message`).\n * - `framework_runtime` — facts came from a framework runtime fault\n *   surface (Next.js `_error` page, route-handler unhandled\n *   rejection, etc.) where the SDK observed the failure but the\n *   underlying app exception type was not directly observable.\n * - `framework_fallback` — facts came from a framework fallback\n *   route (e.g., `/_error`, `/_not-found`); the SDK preserves the\n *   originally-requested path in `glasstrace.error.original_path`\n *   and the fallback route in `glasstrace.error.fallback_route`.\n * - `response_body` — facts came from a captured response body\n *   gated on `captureConfig.errorResponseBodies`; only set when\n *   the body itself was the source of the error message/code, not\n *   when a body was captured alongside other fact sources.\n *\n * Order of preference when multiple sources provide the same fact:\n * `otel_exception` > `otel_event` > `glasstrace_attribute` >\n * `framework_runtime` > `framework_fallback` > `response_body`.\n */\nexport const ERROR_SOURCE_VALUES = [\n  \"otel_exception\",\n  \"otel_event\",\n  \"glasstrace_attribute\",\n  \"framework_runtime\",\n  \"framework_fallback\",\n  \"response_body\",\n] as const;\n\n/**\n * One of the allowlisted source-provenance values.\n *\n * @see {@link ERROR_SOURCE_VALUES}\n */\nexport type ErrorSource = (typeof ERROR_SOURCE_VALUES)[number];\n\n/**\n * Allowlisted framework-classification values for\n * `glasstrace.error.framework.kind`.\n *\n * Set when the SDK can classify the failure family beyond the\n * OTel-level `exception.type`. Values:\n *\n * - `runtime` — the framework reported the failure as a runtime\n *   fault (e.g., a Next.js route handler threw and was caught by\n *   the framework error boundary).\n * - `compile` — a compile-time diagnostic the SDK observed\n *   (Next.js dev-server module-resolution failure, etc.).\n *   Compile-diagnostic capture beyond the marker itself is gated\n *   behind a future capture policy and is NOT in the v1 contract;\n *   the SDK currently emits this kind only as a category marker\n *   when the existence of the diagnostic is observable.\n * - `fallback` — the failing request was rerouted by the framework\n *   to a fallback route (e.g., `/_error`, `/_not-found`); the SDK\n *   preserves the original request path in\n *   `glasstrace.error.original_path`.\n * - `unknown` — the SDK observed an error but could not classify\n *   the framework family. Distinct from \"no value emitted at all\"\n *   so product can tell deliberate uncertainty from missing\n *   evidence.\n */\nexport const ERROR_FRAMEWORK_KIND_VALUES = [\n  \"runtime\",\n  \"compile\",\n  \"fallback\",\n  \"unknown\",\n] as const;\n\n/**\n * One of the allowlisted framework-classification values.\n *\n * @see {@link ERROR_FRAMEWORK_KIND_VALUES}\n */\nexport type ErrorFrameworkKind =\n  (typeof ERROR_FRAMEWORK_KIND_VALUES)[number];\n","/*\n * Copyright The OpenTelemetry Authors\n * SPDX-License-Identifier: Apache-2.0\n */\n\n// this is autogenerated file, see scripts/version-update.js\nexport const VERSION = '1.9.1';\n","/*\n * Copyright The OpenTelemetry Authors\n * SPDX-License-Identifier: Apache-2.0\n */\n\nimport { VERSION } from '../version';\n\nconst re = /^(\\d+)\\.(\\d+)\\.(\\d+)(-(.+))?$/;\n\n/**\n * Create a function to test an API version to see if it is compatible with the provided ownVersion.\n *\n * The returned function has the following semantics:\n * - Exact match is always compatible\n * - Major versions must match exactly\n *    - 1.x package cannot use global 2.x package\n *    - 2.x package cannot use global 1.x package\n * - The minor version of the API module requesting access to the global API must be less than or equal to the minor version of this API\n *    - 1.3 package may use 1.4 global because the later global contains all functions 1.3 expects\n *    - 1.4 package may NOT use 1.3 global because it may try to call functions which don't exist on 1.3\n * - If the major version is 0, the minor version is treated as the major and the patch is treated as the minor\n * - Patch and build tag differences are not considered at this time\n *\n * @param ownVersion version which should be checked against\n */\nexport function _makeCompatibilityCheck(\n  ownVersion: string\n): (globalVersion: string) => boolean {\n  const acceptedVersions = new Set<string>([ownVersion]);\n  const rejectedVersions = new Set<string>();\n\n  const myVersionMatch = ownVersion.match(re);\n  if (!myVersionMatch) {\n    // we cannot guarantee compatibility so we always return noop\n    return () => false;\n  }\n\n  const ownVersionParsed = {\n    major: +myVersionMatch[1],\n    minor: +myVersionMatch[2],\n    patch: +myVersionMatch[3],\n    prerelease: myVersionMatch[4],\n  };\n\n  // if ownVersion has a prerelease tag, versions must match exactly\n  if (ownVersionParsed.prerelease != null) {\n    return function isExactmatch(globalVersion: string): boolean {\n      return globalVersion === ownVersion;\n    };\n  }\n\n  function _reject(v: string) {\n    rejectedVersions.add(v);\n    return false;\n  }\n\n  function _accept(v: string) {\n    acceptedVersions.add(v);\n    return true;\n  }\n\n  return function isCompatible(globalVersion: string): boolean {\n    if (acceptedVersions.has(globalVersion)) {\n      return true;\n    }\n\n    if (rejectedVersions.has(globalVersion)) {\n      return false;\n    }\n\n    const globalVersionMatch = globalVersion.match(re);\n    if (!globalVersionMatch) {\n      // cannot parse other version\n      // we cannot guarantee compatibility so we always noop\n      return _reject(globalVersion);\n    }\n\n    const globalVersionParsed = {\n      major: +globalVersionMatch[1],\n      minor: +globalVersionMatch[2],\n      patch: +globalVersionMatch[3],\n      prerelease: globalVersionMatch[4],\n    };\n\n    // if globalVersion has a prerelease tag, versions must match exactly\n    if (globalVersionParsed.prerelease != null) {\n      return _reject(globalVersion);\n    }\n\n    // major versions must match\n    if (ownVersionParsed.major !== globalVersionParsed.major) {\n      return _reject(globalVersion);\n    }\n\n    if (ownVersionParsed.major === 0) {\n      if (\n        ownVersionParsed.minor === globalVersionParsed.minor &&\n        ownVersionParsed.patch <= globalVersionParsed.patch\n      ) {\n        return _accept(globalVersion);\n      }\n\n      return _reject(globalVersion);\n    }\n\n    if (ownVersionParsed.minor <= globalVersionParsed.minor) {\n      return _accept(globalVersion);\n    }\n\n    return _reject(globalVersion);\n  };\n}\n\n/**\n * Test an API version to see if it is compatible with this API.\n *\n * - Exact match is always compatible\n * - Major versions must match exactly\n *    - 1.x package cannot use global 2.x package\n *    - 2.x package cannot use global 1.x package\n * - The minor version of the API module requesting access to the global API must be less than or equal to the minor version of this API\n *    - 1.3 package may use 1.4 global because the later global contains all functions 1.3 expects\n *    - 1.4 package may NOT use 1.3 global because it may try to call functions which don't exist on 1.3\n * - If the major version is 0, the minor version is treated as the major and the patch is treated as the minor\n * - Patch and build tag differences are not considered at this time\n *\n * @param version version of the API requesting an instance of the global API\n */\nexport const isCompatible = _makeCompatibilityCheck(VERSION);\n","/*\n * Copyright The OpenTelemetry Authors\n * SPDX-License-Identifier: Apache-2.0\n */\n\nimport type { MeterProvider } from '../metrics/MeterProvider';\nimport type { ContextManager } from '../context/types';\nimport type { DiagLogger } from '../diag/types';\nimport type { TextMapPropagator } from '../propagation/TextMapPropagator';\nimport type { TracerProvider } from '../trace/tracer_provider';\nimport { VERSION } from '../version';\nimport { isCompatible } from './semver';\n\nconst major = VERSION.split('.')[0];\nconst GLOBAL_OPENTELEMETRY_API_KEY = Symbol.for(\n  `opentelemetry.js.api.${major}`\n);\n\ndeclare const self: unknown;\ndeclare const window: unknown;\ndeclare const global: unknown;\n\nconst _global = (\n  typeof globalThis === 'object'\n    ? globalThis\n    : typeof self === 'object'\n      ? self\n      : typeof window === 'object'\n        ? window\n        : typeof global === 'object'\n          ? global\n          : {}\n) as OTelGlobal;\n\nexport function registerGlobal<Type extends keyof OTelGlobalAPI>(\n  type: Type,\n  instance: OTelGlobalAPI[Type],\n  diag: DiagLogger,\n  allowOverride = false\n): boolean {\n  const api = (_global[GLOBAL_OPENTELEMETRY_API_KEY] = _global[\n    GLOBAL_OPENTELEMETRY_API_KEY\n  ] ?? {\n    version: VERSION,\n  });\n\n  if (!allowOverride && api[type]) {\n    // already registered an API of this type\n    const err = new Error(\n      `@opentelemetry/api: Attempted duplicate registration of API: ${type}`\n    );\n    diag.error(err.stack || err.message);\n    return false;\n  }\n\n  if (api.version !== VERSION) {\n    // All registered APIs must be of the same version exactly\n    const err = new Error(\n      `@opentelemetry/api: Registration of version v${api.version} for ${type} does not match previously registered API v${VERSION}`\n    );\n    diag.error(err.stack || err.message);\n    return false;\n  }\n\n  api[type] = instance;\n  diag.debug(\n    `@opentelemetry/api: Registered a global for ${type} v${VERSION}.`\n  );\n\n  return true;\n}\n\nexport function getGlobal<Type extends keyof OTelGlobalAPI>(\n  type: Type\n): OTelGlobalAPI[Type] | undefined {\n  const globalVersion = _global[GLOBAL_OPENTELEMETRY_API_KEY]?.version;\n  if (!globalVersion || !isCompatible(globalVersion)) {\n    return;\n  }\n  return _global[GLOBAL_OPENTELEMETRY_API_KEY]?.[type];\n}\n\nexport function unregisterGlobal(type: keyof OTelGlobalAPI, diag: DiagLogger) {\n  diag.debug(\n    `@opentelemetry/api: Unregistering a global for ${type} v${VERSION}.`\n  );\n  const api = _global[GLOBAL_OPENTELEMETRY_API_KEY];\n\n  if (api) {\n    delete api[type];\n  }\n}\n\ntype OTelGlobal = {\n  [GLOBAL_OPENTELEMETRY_API_KEY]?: OTelGlobalAPI;\n};\n\ntype OTelGlobalAPI = {\n  version: string;\n\n  diag?: DiagLogger;\n  trace?: TracerProvider;\n  context?: ContextManager;\n  metrics?: MeterProvider;\n  propagation?: TextMapPropagator;\n};\n","/*\n * Copyright The OpenTelemetry Authors\n * SPDX-License-Identifier: Apache-2.0\n */\n\nimport { getGlobal } from '../internal/global-utils';\nimport type { ComponentLoggerOptions, DiagLogger } from './types';\n\n/**\n * Component Logger which is meant to be used as part of any component which\n * will add automatically additional namespace in front of the log message.\n * It will then forward all message to global diag logger\n * @example\n * const cLogger = diag.createComponentLogger({ namespace: '@opentelemetry/instrumentation-http' });\n * cLogger.debug('test');\n * // @opentelemetry/instrumentation-http test\n */\nexport class DiagComponentLogger implements DiagLogger {\n  private _namespace: string;\n\n  constructor(props: ComponentLoggerOptions) {\n    this._namespace = props.namespace || 'DiagComponentLogger';\n  }\n\n  public debug(...args: unknown[]): void {\n    return logProxy('debug', this._namespace, args);\n  }\n\n  public error(...args: unknown[]): void {\n    return logProxy('error', this._namespace, args);\n  }\n\n  public info(...args: unknown[]): void {\n    return logProxy('info', this._namespace, args);\n  }\n\n  public warn(...args: unknown[]): void {\n    return logProxy('warn', this._namespace, args);\n  }\n\n  public verbose(...args: unknown[]): void {\n    return logProxy('verbose', this._namespace, args);\n  }\n}\n\nfunction logProxy(\n  funcName: keyof DiagLogger,\n  namespace: string,\n  args: unknown[]\n): void {\n  const logger = getGlobal('diag');\n  // shortcut if logger not set\n  if (!logger) {\n    return;\n  }\n\n  return logger[funcName](namespace, ...args);\n}\n","/*\n * Copyright The OpenTelemetry Authors\n * SPDX-License-Identifier: Apache-2.0\n */\n\n/**\n * @since 1.0.0\n */\nexport type DiagLogFunction = (message: string, ...args: unknown[]) => void;\n\n/**\n * Defines an internal diagnostic logger interface which is used to log internal diagnostic\n * messages, you can set the default diagnostic logger via the {@link DiagAPI} setLogger function.\n * API provided implementations include :-\n * - a No-Op {@link createNoopDiagLogger}\n * - a {@link DiagLogLevel} filtering wrapper {@link createLogLevelDiagLogger}\n * - a general Console {@link DiagConsoleLogger} version.\n *\n * @since 1.0.0\n */\nexport interface DiagLogger {\n  /** Log an error scenario that was not expected and caused the requested operation to fail. */\n  error: DiagLogFunction;\n\n  /**\n   * Log a warning scenario to inform the developer of an issues that should be investigated.\n   * The requested operation may or may not have succeeded or completed.\n   */\n  warn: DiagLogFunction;\n\n  /**\n   * Log a general informational message, this should not affect functionality.\n   * This is also the default logging level so this should NOT be used for logging\n   * debugging level information.\n   */\n  info: DiagLogFunction;\n\n  /**\n   * Log a general debug message that can be useful for identifying a failure.\n   * Information logged at this level may include diagnostic details that would\n   * help identify a failure scenario.\n   * For example: Logging the order of execution of async operations.\n   */\n  debug: DiagLogFunction;\n\n  /**\n   * Log a detailed (verbose) trace level logging that can be used to identify failures\n   * where debug level logging would be insufficient, this level of tracing can include\n   * input and output parameters and as such may include PII information passing through\n   * the API. As such it is recommended that this level of tracing should not be enabled\n   * in a production environment.\n   */\n  verbose: DiagLogFunction;\n}\n\n/**\n * Defines the available internal logging levels for the diagnostic logger, the numeric values\n * of the levels are defined to match the original values from the initial LogLevel to avoid\n * compatibility/migration issues for any implementation that assume the numeric ordering.\n */\nexport enum DiagLogLevel {\n  /** Diagnostic Logging level setting to disable all logging (except and forced logs) */\n  NONE = 0,\n\n  /** Identifies an error scenario */\n  ERROR = 30,\n\n  /** Identifies a warning scenario */\n  WARN = 50,\n\n  /** General informational log message */\n  INFO = 60,\n\n  /** General debug log message */\n  DEBUG = 70,\n\n  /**\n   * Detailed trace level logging should only be used for development, should only be set\n   * in a development environment.\n   */\n  VERBOSE = 80,\n\n  /** Used to set the logging level to include all logging */\n  ALL = 9999,\n}\n\n/**\n * Defines options for ComponentLogger\n *\n * @since 1.0.0\n */\nexport interface ComponentLoggerOptions {\n  namespace: string;\n}\n\n/**\n * @since 1.4.1\n */\nexport interface DiagLoggerOptions {\n  /**\n   * The {@link DiagLogLevel} used to filter logs sent to the logger.\n   *\n   * @defaultValue DiagLogLevel.INFO\n   */\n  logLevel?: DiagLogLevel;\n\n  /**\n   * Setting this value to `true` will suppress the warning message normally emitted when registering a logger when another logger is already registered.\n   */\n  suppressOverrideMessage?: boolean;\n}\n\nexport interface DiagLoggerApi {\n  /**\n   * Set the global DiagLogger and DiagLogLevel.\n   * If a global diag logger is already set, this will override it.\n   *\n   * @param logger - The {@link DiagLogger} instance to set as the default logger.\n   * @param options - A {@link DiagLoggerOptions} object. If not provided, default values will be set.\n   * @returns `true` if the logger was successfully registered, else `false`\n   */\n  setLogger(logger: DiagLogger, options?: DiagLoggerOptions): boolean;\n\n  /**\n   *\n   * @param logger - The {@link DiagLogger} instance to set as the default logger.\n   * @param logLevel - The {@link DiagLogLevel} used to filter logs sent to the logger. If not provided it will default to {@link DiagLogLevel.INFO}.\n   * @returns `true` if the logger was successfully registered, else `false`\n   */\n  setLogger(logger: DiagLogger, logLevel?: DiagLogLevel): boolean;\n}\n","/*\n * Copyright The OpenTelemetry Authors\n * SPDX-License-Identifier: Apache-2.0\n */\n\nimport type { DiagLogFunction, DiagLogger } from '../types';\nimport { DiagLogLevel } from '../types';\n\nexport function createLogLevelDiagLogger(\n  maxLevel: DiagLogLevel,\n  logger: DiagLogger\n): DiagLogger {\n  if (maxLevel < DiagLogLevel.NONE) {\n    maxLevel = DiagLogLevel.NONE;\n  } else if (maxLevel > DiagLogLevel.ALL) {\n    maxLevel = DiagLogLevel.ALL;\n  }\n\n  // In case the logger is null or undefined\n  logger = logger || {};\n\n  function _filterFunc(\n    funcName: keyof DiagLogger,\n    theLevel: DiagLogLevel\n  ): DiagLogFunction {\n    const theFunc = logger[funcName];\n\n    if (typeof theFunc === 'function' && maxLevel >= theLevel) {\n      return theFunc.bind(logger);\n    }\n    return function () {};\n  }\n\n  return {\n    error: _filterFunc('error', DiagLogLevel.ERROR),\n    warn: _filterFunc('warn', DiagLogLevel.WARN),\n    info: _filterFunc('info', DiagLogLevel.INFO),\n    debug: _filterFunc('debug', DiagLogLevel.DEBUG),\n    verbose: _filterFunc('verbose', DiagLogLevel.VERBOSE),\n  };\n}\n","/*\n * Copyright The OpenTelemetry Authors\n * SPDX-License-Identifier: Apache-2.0\n */\n\nimport { DiagComponentLogger } from '../diag/ComponentLogger';\nimport { createLogLevelDiagLogger } from '../diag/internal/logLevelLogger';\nimport type {\n  ComponentLoggerOptions,\n  DiagLogFunction,\n  DiagLogger,\n  DiagLoggerApi,\n} from '../diag/types';\nimport { DiagLogLevel } from '../diag/types';\nimport {\n  getGlobal,\n  registerGlobal,\n  unregisterGlobal,\n} from '../internal/global-utils';\n\nconst API_NAME = 'diag';\n\n/**\n * Singleton object which represents the entry point to the OpenTelemetry internal\n * diagnostic API\n *\n * @since 1.0.0\n */\nexport class DiagAPI implements DiagLogger, DiagLoggerApi {\n  private static _instance?: DiagAPI;\n\n  /** Get the singleton instance of the DiagAPI API */\n  public static instance(): DiagAPI {\n    if (!this._instance) {\n      this._instance = new DiagAPI();\n    }\n\n    return this._instance;\n  }\n\n  /**\n   * Private internal constructor\n   * @private\n   */\n  private constructor() {\n    function _logProxy(funcName: keyof DiagLogger): DiagLogFunction {\n      return function (...args) {\n        const logger = getGlobal('diag');\n        // shortcut if logger not set\n        if (!logger) return;\n        return logger[funcName](...args);\n      };\n    }\n\n    // Using self local variable for minification purposes as 'this' cannot be minified\n    const self = this;\n\n    // DiagAPI specific functions\n\n    const setLogger: DiagLoggerApi['setLogger'] = (\n      logger,\n      optionsOrLogLevel = { logLevel: DiagLogLevel.INFO }\n    ) => {\n      if (logger === self) {\n        // There isn't much we can do here.\n        // Logging to the console might break the user application.\n        // Try to log to self. If a logger was previously registered it will receive the log.\n        const err = new Error(\n          'Cannot use diag as the logger for itself. Please use a DiagLogger implementation like ConsoleDiagLogger or a custom implementation'\n        );\n        self.error(err.stack ?? err.message);\n        return false;\n      }\n\n      if (typeof optionsOrLogLevel === 'number') {\n        optionsOrLogLevel = {\n          logLevel: optionsOrLogLevel,\n        };\n      }\n\n      const oldLogger = getGlobal('diag');\n      const newLogger = createLogLevelDiagLogger(\n        optionsOrLogLevel.logLevel ?? DiagLogLevel.INFO,\n        logger\n      );\n      // There already is an logger registered. We'll let it know before overwriting it.\n      if (oldLogger && !optionsOrLogLevel.suppressOverrideMessage) {\n        const stack = new Error().stack ?? '<failed to generate stacktrace>';\n        oldLogger.warn(`Current logger will be overwritten from ${stack}`);\n        newLogger.warn(\n          `Current logger will overwrite one already registered from ${stack}`\n        );\n      }\n\n      return registerGlobal('diag', newLogger, self, true);\n    };\n\n    self.setLogger = setLogger;\n\n    self.disable = () => {\n      unregisterGlobal(API_NAME, self);\n    };\n\n    self.createComponentLogger = (options: ComponentLoggerOptions) => {\n      return new DiagComponentLogger(options);\n    };\n\n    self.verbose = _logProxy('verbose');\n    self.debug = _logProxy('debug');\n    self.info = _logProxy('info');\n    self.warn = _logProxy('warn');\n    self.error = _logProxy('error');\n  }\n\n  public setLogger!: DiagLoggerApi['setLogger'];\n  /**\n   *\n   */\n  public createComponentLogger!: (\n    options: ComponentLoggerOptions\n  ) => DiagLogger;\n\n  // DiagLogger implementation\n  public verbose!: DiagLogFunction;\n  public debug!: DiagLogFunction;\n  public info!: DiagLogFunction;\n  public warn!: DiagLogFunction;\n  public error!: DiagLogFunction;\n\n  /**\n   * Unregister the global logger and return to Noop\n   */\n  public disable!: () => void;\n}\n","/*\n * Copyright The OpenTelemetry Authors\n * SPDX-License-Identifier: Apache-2.0\n */\n\nimport type { Baggage, BaggageEntry } from '../types';\n\nexport class BaggageImpl implements Baggage {\n  private _entries: Map<string, BaggageEntry>;\n\n  constructor(entries?: Map<string, BaggageEntry>) {\n    this._entries = entries ? new Map(entries) : new Map();\n  }\n\n  getEntry(key: string): BaggageEntry | undefined {\n    const entry = this._entries.get(key);\n    if (!entry) {\n      return undefined;\n    }\n\n    return Object.assign({}, entry);\n  }\n\n  getAllEntries(): [string, BaggageEntry][] {\n    return Array.from(this._entries.entries());\n  }\n\n  setEntry(key: string, entry: BaggageEntry): BaggageImpl {\n    const newBaggage = new BaggageImpl(this._entries);\n    newBaggage._entries.set(key, entry);\n    return newBaggage;\n  }\n\n  removeEntry(key: string): BaggageImpl {\n    const newBaggage = new BaggageImpl(this._entries);\n    newBaggage._entries.delete(key);\n    return newBaggage;\n  }\n\n  removeEntries(...keys: string[]): BaggageImpl {\n    const newBaggage = new BaggageImpl(this._entries);\n    for (const key of keys) {\n      newBaggage._entries.delete(key);\n    }\n    return newBaggage;\n  }\n\n  clear(): BaggageImpl {\n    return new BaggageImpl();\n  }\n}\n","/*\n * Copyright The OpenTelemetry Authors\n * SPDX-License-Identifier: Apache-2.0\n */\n\n/**\n * Symbol used to make BaggageEntryMetadata an opaque type\n */\nexport const baggageEntryMetadataSymbol = Symbol('BaggageEntryMetadata');\n","/*\n * Copyright The OpenTelemetry Authors\n * SPDX-License-Identifier: Apache-2.0\n */\n\nimport { DiagAPI } from '../api/diag';\nimport { BaggageImpl } from './internal/baggage-impl';\nimport { baggageEntryMetadataSymbol } from './internal/symbol';\nimport type { Baggage, BaggageEntry, BaggageEntryMetadata } from './types';\n\nconst diag = DiagAPI.instance();\n\n/**\n * Create a new Baggage with optional entries\n *\n * @param entries An array of baggage entries the new baggage should contain\n */\nexport function createBaggage(\n  entries: Record<string, BaggageEntry> = {}\n): Baggage {\n  return new BaggageImpl(new Map(Object.entries(entries)));\n}\n\n/**\n * Create a serializable BaggageEntryMetadata object from a string.\n *\n * @param str string metadata. Format is currently not defined by the spec and has no special meaning.\n *\n * @since 1.0.0\n */\nexport function baggageEntryMetadataFromString(\n  str: string\n): BaggageEntryMetadata {\n  if (typeof str !== 'string') {\n    diag.error(\n      `Cannot create baggage metadata from unknown type: ${typeof str}`\n    );\n    str = '';\n  }\n\n  return {\n    __TYPE__: baggageEntryMetadataSymbol,\n    toString() {\n      return str;\n    },\n  };\n}\n","/*\n * Copyright The OpenTelemetry Authors\n * SPDX-License-Identifier: Apache-2.0\n */\n\nimport type { Context } from './types';\n\n/**\n * Get a key to uniquely identify a context value\n *\n * @since 1.0.0\n */\nexport function createContextKey(description: string) {\n  // The specification states that for the same input, multiple calls should\n  // return different keys. Due to the nature of the JS dependency management\n  // system, this creates problems where multiple versions of some package\n  // could hold different keys for the same property.\n  //\n  // Therefore, we use Symbol.for which returns the same key for the same input.\n  return Symbol.for(description);\n}\n\nclass BaseContext implements Context {\n  private _currentContext!: Map<symbol, unknown>;\n\n  /**\n   * Construct a new context which inherits values from an optional parent context.\n   *\n   * @param parentContext a context from which to inherit values\n   */\n  constructor(parentContext?: Map<symbol, unknown>) {\n    // for minification\n    const self = this;\n\n    self._currentContext = parentContext ? new Map(parentContext) : new Map();\n\n    self.getValue = (key: symbol) => self._currentContext.get(key);\n\n    self.setValue = (key: symbol, value: unknown): Context => {\n      const context = new BaseContext(self._currentContext);\n      context._currentContext.set(key, value);\n      return context;\n    };\n\n    self.deleteValue = (key: symbol): Context => {\n      const context = new BaseContext(self._currentContext);\n      context._currentContext.delete(key);\n      return context;\n    };\n  }\n\n  /**\n   * Get a value from the context.\n   *\n   * @param key key which identifies a context value\n   */\n  public getValue!: (key: symbol) => unknown;\n\n  /**\n   * Create a new context which inherits from this context and has\n   * the given key set to the given value.\n   *\n   * @param key context key for which to set the value\n   * @param value value to set for the given key\n   */\n  public setValue!: (key: symbol, value: unknown) => Context;\n\n  /**\n   * Return a new context which inherits from this context but does\n   * not contain a value for the given key.\n   *\n   * @param key context key for which to clear a value\n   */\n  public deleteValue!: (key: symbol) => Context;\n}\n\n/**\n * The root context is used as the default parent context when there is no active context\n *\n * @since 1.0.0\n */\nexport const ROOT_CONTEXT: Context = new BaseContext();\n","/*\n * Copyright The OpenTelemetry Authors\n * SPDX-License-Identifier: Apache-2.0\n */\n\nimport type { DiagLogger, DiagLogFunction } from './types';\n\ntype ConsoleMapKeys = 'error' | 'warn' | 'info' | 'debug' | 'trace';\nconst consoleMap: { n: keyof DiagLogger; c: ConsoleMapKeys }[] = [\n  { n: 'error', c: 'error' },\n  { n: 'warn', c: 'warn' },\n  { n: 'info', c: 'info' },\n  { n: 'debug', c: 'debug' },\n  { n: 'verbose', c: 'trace' },\n];\n\n// Save original console methods at module load time, before any instrumentation\n// can wrap them. This ensures DiagConsoleLogger calls the unwrapped originals.\n// Exported for testing only — not part of the public API.\nexport const _originalConsoleMethods: Partial<\n  Record<ConsoleMapKeys | 'log', typeof console.log>\n> = {};\nif (typeof console !== 'undefined') {\n  const keys: (ConsoleMapKeys | 'log')[] = [\n    'error',\n    'warn',\n    'info',\n    'debug',\n    'trace',\n    'log',\n  ];\n  for (const key of keys) {\n    // eslint-disable-next-line no-console\n    if (typeof console[key] === 'function') {\n      // eslint-disable-next-line no-console\n      _originalConsoleMethods[key] = console[key];\n    }\n  }\n}\n\n/**\n * A simple Immutable Console based diagnostic logger which will output any messages to the Console.\n * If you want to limit the amount of logging to a specific level or lower use the\n * {@link createLogLevelDiagLogger}\n *\n * @since 1.0.0\n */\nexport class DiagConsoleLogger implements DiagLogger {\n  constructor() {\n    function _consoleFunc(funcName: ConsoleMapKeys): DiagLogFunction {\n      return function (...args) {\n        // Prefer original (pre-instrumentation) methods saved at module load time.\n        let theFunc = _originalConsoleMethods[funcName];\n        // Some environments only expose the console when the F12 developer console is open\n        if (typeof theFunc !== 'function') {\n          theFunc = _originalConsoleMethods['log'];\n        }\n        // Fall back in case console was not available at module load time but became available later.\n        if (typeof theFunc !== 'function' && console) {\n          // eslint-disable-next-line no-console\n          theFunc = console[funcName];\n          if (typeof theFunc !== 'function') {\n            // eslint-disable-next-line no-console\n            theFunc = console.log;\n          }\n        }\n        if (typeof theFunc === 'function') {\n          return theFunc.apply(console, args);\n        }\n      };\n    }\n\n    for (let i = 0; i < consoleMap.length; i++) {\n      this[consoleMap[i].n] = _consoleFunc(consoleMap[i].c);\n    }\n  }\n\n  /** Log an error scenario that was not expected and caused the requested operation to fail. */\n  public error!: DiagLogFunction;\n\n  /**\n   * Log a warning scenario to inform the developer of an issues that should be investigated.\n   * The requested operation may or may not have succeeded or completed.\n   */\n  public warn!: DiagLogFunction;\n\n  /**\n   * Log a general informational message, this should not affect functionality.\n   * This is also the default logging level so this should NOT be used for logging\n   * debugging level information.\n   */\n  public info!: DiagLogFunction;\n\n  /**\n   * Log a general debug message that can be useful for identifying a failure.\n   * Information logged at this level may include diagnostic details that would\n   * help identify a failure scenario. Useful scenarios would be to log the execution\n   * order of async operations\n   */\n  public debug!: DiagLogFunction;\n\n  /**\n   * Log a detailed (verbose) trace level logging that can be used to identify failures\n   * where debug level logging would be insufficient, this level of tracing can include\n   * input and output parameters and as such may include PII information passing through\n   * the API. As such it is recommended that this level of tracing should not be enabled\n   * in a production environment.\n   */\n  public verbose!: DiagLogFunction;\n}\n","/*\n * Copyright The OpenTelemetry Authors\n * SPDX-License-Identifier: Apache-2.0\n */\n\nimport type { Meter } from './Meter';\nimport type {\n  BatchObservableCallback,\n  Counter,\n  Gauge,\n  Histogram,\n  MetricAttributes,\n  MetricOptions,\n  Observable,\n  ObservableCallback,\n  ObservableCounter,\n  ObservableGauge,\n  ObservableUpDownCounter,\n  UpDownCounter,\n} from './Metric';\n\n/**\n * NoopMeter is a noop implementation of the {@link Meter} interface. It reuses\n * constant NoopMetrics for all of its methods.\n */\nexport class NoopMeter implements Meter {\n  constructor() {}\n\n  /**\n   * @see {@link Meter.createGauge}\n   */\n  createGauge(_name: string, _options?: MetricOptions): Gauge {\n    return NOOP_GAUGE_METRIC;\n  }\n\n  /**\n   * @see {@link Meter.createHistogram}\n   */\n  createHistogram(_name: string, _options?: MetricOptions): Histogram {\n    return NOOP_HISTOGRAM_METRIC;\n  }\n\n  /**\n   * @see {@link Meter.createCounter}\n   */\n  createCounter(_name: string, _options?: MetricOptions): Counter {\n    return NOOP_COUNTER_METRIC;\n  }\n\n  /**\n   * @see {@link Meter.createUpDownCounter}\n   */\n  createUpDownCounter(_name: string, _options?: MetricOptions): UpDownCounter {\n    return NOOP_UP_DOWN_COUNTER_METRIC;\n  }\n\n  /**\n   * @see {@link Meter.createObservableGauge}\n   */\n  createObservableGauge(\n    _name: string,\n    _options?: MetricOptions\n  ): ObservableGauge {\n    return NOOP_OBSERVABLE_GAUGE_METRIC;\n  }\n\n  /**\n   * @see {@link Meter.createObservableCounter}\n   */\n  createObservableCounter(\n    _name: string,\n    _options?: MetricOptions\n  ): ObservableCounter {\n    return NOOP_OBSERVABLE_COUNTER_METRIC;\n  }\n\n  /**\n   * @see {@link Meter.createObservableUpDownCounter}\n   */\n  createObservableUpDownCounter(\n    _name: string,\n    _options?: MetricOptions\n  ): ObservableUpDownCounter {\n    return NOOP_OBSERVABLE_UP_DOWN_COUNTER_METRIC;\n  }\n\n  /**\n   * @see {@link Meter.addBatchObservableCallback}\n   */\n  addBatchObservableCallback(\n    _callback: BatchObservableCallback,\n    _observables: Observable[]\n  ): void {}\n\n  /**\n   * @see {@link Meter.removeBatchObservableCallback}\n   */\n  removeBatchObservableCallback(_callback: BatchObservableCallback): void {}\n}\n\nexport class NoopMetric {}\n\nexport class NoopCounterMetric extends NoopMetric implements Counter {\n  add(_value: number, _attributes: MetricAttributes): void {}\n}\n\nexport class NoopUpDownCounterMetric\n  extends NoopMetric\n  implements UpDownCounter\n{\n  add(_value: number, _attributes: MetricAttributes): void {}\n}\n\nexport class NoopGaugeMetric extends NoopMetric implements Gauge {\n  record(_value: number, _attributes: MetricAttributes): void {}\n}\n\nexport class NoopHistogramMetric extends NoopMetric implements Histogram {\n  record(_value: number, _attributes: MetricAttributes): void {}\n}\n\nexport class NoopObservableMetric {\n  addCallback(_callback: ObservableCallback) {}\n\n  removeCallback(_callback: ObservableCallback) {}\n}\n\nexport class NoopObservableCounterMetric\n  extends NoopObservableMetric\n  implements ObservableCounter {}\n\nexport class NoopObservableGaugeMetric\n  extends NoopObservableMetric\n  implements ObservableGauge {}\n\nexport class NoopObservableUpDownCounterMetric\n  extends NoopObservableMetric\n  implements ObservableUpDownCounter {}\n\nexport const NOOP_METER = new NoopMeter();\n\n// Synchronous instruments\nexport const NOOP_COUNTER_METRIC = new NoopCounterMetric();\nexport const NOOP_GAUGE_METRIC = new NoopGaugeMetric();\nexport const NOOP_HISTOGRAM_METRIC = new NoopHistogramMetric();\nexport const NOOP_UP_DOWN_COUNTER_METRIC = new NoopUpDownCounterMetric();\n\n// Asynchronous instruments\nexport const NOOP_OBSERVABLE_COUNTER_METRIC = new NoopObservableCounterMetric();\nexport const NOOP_OBSERVABLE_GAUGE_METRIC = new NoopObservableGaugeMetric();\nexport const NOOP_OBSERVABLE_UP_DOWN_COUNTER_METRIC =\n  new NoopObservableUpDownCounterMetric();\n\n/**\n * Create a no-op Meter\n *\n * @since 1.3.0\n */\nexport function createNoopMeter(): Meter {\n  return NOOP_METER;\n}\n","/*\n * Copyright The OpenTelemetry Authors\n * SPDX-License-Identifier: Apache-2.0\n */\n\nimport type { Attributes, AttributeValue } from '../common/Attributes';\nimport type { Context } from '../context/types';\n\n/**\n * Advisory options influencing aggregation configuration parameters.\n *\n * @since 1.7.0\n * @experimental\n */\nexport interface MetricAdvice {\n  /**\n   * Hint the explicit bucket boundaries for SDK if the metric is been\n   * aggregated with a HistogramAggregator.\n   */\n  explicitBucketBoundaries?: number[];\n}\n\n/**\n * Options needed for metric creation\n *\n * @since 1.3.0\n */\nexport interface MetricOptions {\n  /**\n   * The description of the Metric.\n   * @default ''\n   */\n  description?: string;\n\n  /**\n   * The unit of the Metric values.\n   * @default ''\n   */\n  unit?: string;\n\n  /**\n   * Indicates the type of the recorded value.\n   * @default {@link ValueType.DOUBLE}\n   */\n  valueType?: ValueType;\n\n  /**\n   * The advice influencing aggregation configuration parameters.\n   * @experimental\n   * @since 1.7.0\n   */\n  advice?: MetricAdvice;\n}\n\n/**\n * The Type of value. It describes how the data is reported.\n *\n * @since 1.3.0\n */\nexport enum ValueType {\n  INT,\n  DOUBLE,\n}\n\n/**\n * Counter is the most common synchronous instrument. This instrument supports\n * an `Add(increment)` function for reporting a sum, and is restricted to\n * non-negative increments. The default aggregation is Sum, as for any additive\n * instrument.\n *\n * Example uses for Counter:\n * <ol>\n *   <li> count the number of bytes received. </li>\n *   <li> count the number of requests completed. </li>\n *   <li> count the number of accounts created. </li>\n *   <li> count the number of checkpoints run. </li>\n *   <li> count the number of 5xx errors. </li>\n * <ol>\n *\n * @since 1.3.0\n */\nexport interface Counter<\n  AttributesTypes extends MetricAttributes = MetricAttributes,\n> {\n  /**\n   * Increment value of counter by the input. Inputs must not be negative.\n   */\n  add(value: number, attributes?: AttributesTypes, context?: Context): void;\n}\n\n/**\n * @since 1.3.0\n */\nexport interface UpDownCounter<\n  AttributesTypes extends MetricAttributes = MetricAttributes,\n> {\n  /**\n   * Increment value of counter by the input. Inputs may be negative.\n   */\n  add(value: number, attributes?: AttributesTypes, context?: Context): void;\n}\n\n/**\n * @since 1.9.0\n */\nexport interface Gauge<\n  AttributesTypes extends MetricAttributes = MetricAttributes,\n> {\n  /**\n   * Records a measurement.\n   */\n  record(value: number, attributes?: AttributesTypes, context?: Context): void;\n}\n\n/**\n * @since 1.3.0\n */\nexport interface Histogram<\n  AttributesTypes extends MetricAttributes = MetricAttributes,\n> {\n  /**\n   * Records a measurement. Value of the measurement must not be negative.\n   */\n  record(value: number, attributes?: AttributesTypes, context?: Context): void;\n}\n\n/**\n * @deprecated please use {@link Attributes}\n * @since 1.3.0\n */\nexport type MetricAttributes = Attributes;\n\n/**\n * @deprecated please use {@link AttributeValue}\n * @since 1.3.0\n */\nexport type MetricAttributeValue = AttributeValue;\n\n/**\n * Interface that is being used in callback function for Observable Metric.\n *\n * @since 1.3.0\n */\nexport interface ObservableResult<\n  AttributesTypes extends MetricAttributes = MetricAttributes,\n> {\n  /**\n   * Observe a measurement of the value associated with the given attributes.\n   *\n   * @param value The value to be observed.\n   * @param attributes The attributes associated with the value. If more than\n   * one value is associated with the same attributes values, SDK may pick the\n   * last one or simply drop the entire observable result.\n   */\n  observe(\n    this: ObservableResult<AttributesTypes>,\n    value: number,\n    attributes?: AttributesTypes\n  ): void;\n}\n\n/**\n * Interface that is being used in batch observable callback function.\n */\nexport interface BatchObservableResult<\n  AttributesTypes extends MetricAttributes = MetricAttributes,\n> {\n  /**\n   * Observe a measurement of the value associated with the given attributes.\n   *\n   * @param metric The observable metric to be observed.\n   * @param value The value to be observed.\n   * @param attributes The attributes associated with the value. If more than\n   * one value is associated with the same attributes values, SDK may pick the\n   * last one or simply drop the entire observable result.\n   */\n  observe(\n    this: BatchObservableResult<AttributesTypes>,\n    metric: Observable<AttributesTypes>,\n    value: number,\n    attributes?: AttributesTypes\n  ): void;\n}\n\n/**\n * The observable callback for Observable instruments.\n *\n * @since 1.3.0\n */\nexport type ObservableCallback<\n  AttributesTypes extends MetricAttributes = MetricAttributes,\n> = (\n  observableResult: ObservableResult<AttributesTypes>\n) => void | Promise<void>;\n\n/**\n * The observable callback for a batch of Observable instruments.\n *\n * @since 1.3.0\n */\nexport type BatchObservableCallback<\n  AttributesTypes extends MetricAttributes = MetricAttributes,\n> = (\n  observableResult: BatchObservableResult<AttributesTypes>\n) => void | Promise<void>;\n\n/**\n * @since 1.3.0\n */\nexport interface Observable<\n  AttributesTypes extends MetricAttributes = MetricAttributes,\n> {\n  /**\n   * Sets up a function that will be called whenever a metric collection is initiated.\n   *\n   * If the function is already in the list of callbacks for this Observable, the function is not added a second time.\n   */\n  addCallback(callback: ObservableCallback<AttributesTypes>): void;\n\n  /**\n   * Removes a callback previously registered with {@link Observable.addCallback}.\n   */\n  removeCallback(callback: ObservableCallback<AttributesTypes>): void;\n}\n\n/**\n * @since 1.3.0\n */\nexport type ObservableCounter<\n  AttributesTypes extends MetricAttributes = MetricAttributes,\n> = Observable<AttributesTypes>;\n/**\n * @since 1.3.0\n */\nexport type ObservableUpDownCounter<\n  AttributesTypes extends MetricAttributes = MetricAttributes,\n> = Observable<AttributesTypes>;\n/**\n * @since 1.3.0\n */\nexport type ObservableGauge<\n  AttributesTypes extends MetricAttributes = MetricAttributes,\n> = Observable<AttributesTypes>;\n","/*\n * Copyright The OpenTelemetry Authors\n * SPDX-License-Identifier: Apache-2.0\n */\n\nimport type { Context } from '../context/types';\n\n/**\n * Injects `Context` into and extracts it from carriers that travel\n * in-band across process boundaries. Encoding is expected to conform to the\n * HTTP Header Field semantics. Values are often encoded as RPC/HTTP request\n * headers.\n *\n * The carrier of propagated data on both the client (injector) and server\n * (extractor) side is usually an object such as http headers. Propagation is\n * usually implemented via library-specific request interceptors, where the\n * client-side injects values and the server-side extracts them.\n *\n * @since 1.0.0\n */\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\nexport interface TextMapPropagator<Carrier = any> {\n  /**\n   * Injects values from a given `Context` into a carrier.\n   *\n   * OpenTelemetry defines a common set of format values (TextMapPropagator),\n   * and each has an expected `carrier` type.\n   *\n   * @param context the Context from which to extract values to transmit over\n   *     the wire.\n   * @param carrier the carrier of propagation fields, such as http request\n   *     headers.\n   * @param setter an optional {@link TextMapSetter}. If undefined, values will be\n   *     set by direct object assignment.\n   */\n  inject(\n    context: Context,\n    carrier: Carrier,\n    setter: TextMapSetter<Carrier>\n  ): void;\n\n  /**\n   * Given a `Context` and a carrier, extract context values from a\n   * carrier and return a new context, created from the old context, with the\n   * extracted values.\n   *\n   * @param context the Context from which to extract values to transmit over\n   *     the wire.\n   * @param carrier the carrier of propagation fields, such as http request\n   *     headers.\n   * @param getter an optional {@link TextMapGetter}. If undefined, keys will be all\n   *     own properties, and keys will be accessed by direct object access.\n   */\n  extract(\n    context: Context,\n    carrier: Carrier,\n    getter: TextMapGetter<Carrier>\n  ): Context;\n\n  /**\n   * Return a list of all fields which may be used by the propagator.\n   */\n  fields(): string[];\n}\n\n/**\n * A setter is specified by the caller to define a specific method\n * to set key/value pairs on the carrier within a propagator\n *\n * @since 1.0.0\n */\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\nexport interface TextMapSetter<Carrier = any> {\n  /**\n   * Callback used to set a key/value pair on an object.\n   *\n   * Should be called by the propagator each time a key/value pair\n   * should be set, and should set that key/value pair on the propagator.\n   *\n   * @param carrier object or class which carries key/value pairs\n   * @param key string key to modify\n   * @param value value to be set to the key on the carrier\n   */\n  set(carrier: Carrier, key: string, value: string): void;\n}\n\n/**\n * A getter is specified by the caller to define a specific method\n * to get the value of a key from a carrier.\n *\n * @since 1.0.0\n */\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\nexport interface TextMapGetter<Carrier = any> {\n  /**\n   * Get a list of all keys available on the carrier.\n   *\n   * @param carrier\n   */\n  keys(carrier: Carrier): string[];\n\n  /**\n   * Get the value of a specific key from the carrier.\n   *\n   * @param carrier\n   * @param key\n   */\n  get(carrier: Carrier, key: string): undefined | string | string[];\n}\n\n/**\n * @since 1.0.0\n */\nexport const defaultTextMapGetter: TextMapGetter = {\n  get(carrier, key) {\n    if (carrier == null) {\n      return undefined;\n    }\n    return carrier[key];\n  },\n\n  keys(carrier) {\n    if (carrier == null) {\n      return [];\n    }\n    return Object.keys(carrier);\n  },\n};\n\n/**\n * @since 1.0.0\n */\nexport const defaultTextMapSetter: TextMapSetter = {\n  set(carrier, key, value) {\n    if (carrier == null) {\n      return;\n    }\n\n    carrier[key] = value;\n  },\n};\n","/*\n * Copyright The OpenTelemetry Authors\n * SPDX-License-Identifier: Apache-2.0\n */\n\nimport { ROOT_CONTEXT } from './context';\nimport type * as types from './types';\n\nexport class NoopContextManager implements types.ContextManager {\n  active(): types.Context {\n    return ROOT_CONTEXT;\n  }\n\n  with<A extends unknown[], F extends (...args: A) => ReturnType<F>>(\n    _context: types.Context,\n    fn: F,\n    thisArg?: ThisParameterType<F>,\n    ...args: A\n  ): ReturnType<F> {\n    return fn.call(thisArg, ...args);\n  }\n\n  bind<T>(_context: types.Context, target: T): T {\n    return target;\n  }\n\n  enable(): this {\n    return this;\n  }\n\n  disable(): this {\n    return this;\n  }\n}\n","/*\n * Copyright The OpenTelemetry Authors\n * SPDX-License-Identifier: Apache-2.0\n */\n\nimport { NoopContextManager } from '../context/NoopContextManager';\nimport type { Context, ContextManager } from '../context/types';\nimport {\n  getGlobal,\n  registerGlobal,\n  unregisterGlobal,\n} from '../internal/global-utils';\nimport { DiagAPI } from './diag';\n\nconst API_NAME = 'context';\nconst NOOP_CONTEXT_MANAGER = new NoopContextManager();\n\n/**\n * Singleton object which represents the entry point to the OpenTelemetry Context API\n *\n * @since 1.0.0\n */\nexport class ContextAPI {\n  private static _instance?: ContextAPI;\n\n  /** Empty private constructor prevents end users from constructing a new instance of the API */\n  private constructor() {}\n\n  /** Get the singleton instance of the Context API */\n  public static getInstance(): ContextAPI {\n    if (!this._instance) {\n      this._instance = new ContextAPI();\n    }\n\n    return this._instance;\n  }\n\n  /**\n   * Set the current context manager.\n   *\n   * @returns true if the context manager was successfully registered, else false\n   */\n  public setGlobalContextManager(contextManager: ContextManager): boolean {\n    return registerGlobal(API_NAME, contextManager, DiagAPI.instance());\n  }\n\n  /**\n   * Get the currently active context\n   */\n  public active(): Context {\n    return this._getContextManager().active();\n  }\n\n  /**\n   * Execute a function with an active context\n   *\n   * @param context context to be active during function execution\n   * @param fn function to execute in a context\n   * @param thisArg optional receiver to be used for calling fn\n   * @param args optional arguments forwarded to fn\n   */\n  public with<A extends unknown[], F extends (...args: A) => ReturnType<F>>(\n    context: Context,\n    fn: F,\n    thisArg?: ThisParameterType<F>,\n    ...args: A\n  ): ReturnType<F> {\n    return this._getContextManager().with(context, fn, thisArg, ...args);\n  }\n\n  /**\n   * Bind a context to a target function or event emitter\n   *\n   * @param context context to bind to the event emitter or function. Defaults to the currently active context\n   * @param target function or event emitter to bind\n   */\n  public bind<T>(context: Context, target: T): T {\n    return this._getContextManager().bind(context, target);\n  }\n\n  private _getContextManager(): ContextManager {\n    return getGlobal(API_NAME) || NOOP_CONTEXT_MANAGER;\n  }\n\n  /** Disable and remove the global context manager */\n  public disable() {\n    this._getContextManager().disable();\n    unregisterGlobal(API_NAME, DiagAPI.instance());\n  }\n}\n","/*\n * Copyright The OpenTelemetry Authors\n * SPDX-License-Identifier: Apache-2.0\n */\n/**\n * @since 1.0.0\n */\nexport enum TraceFlags {\n  /** Represents no flag set. */\n  NONE = 0x0,\n  /** Bit to represent whether trace is sampled in trace flags. */\n  SAMPLED = 0x1 << 0,\n}\n","/*\n * Copyright The OpenTelemetry Authors\n * SPDX-License-Identifier: Apache-2.0\n */\n\nimport type { SpanContext } from './span_context';\nimport { TraceFlags } from './trace_flags';\n\n/**\n * @since 1.0.0\n */\nexport const INVALID_SPANID = '0000000000000000';\n\n/**\n * @since 1.0.0\n */\nexport const INVALID_TRACEID = '00000000000000000000000000000000';\n\n/**\n * @since 1.0.0\n */\nexport const INVALID_SPAN_CONTEXT: SpanContext = {\n  traceId: INVALID_TRACEID,\n  spanId: INVALID_SPANID,\n  traceFlags: TraceFlags.NONE,\n};\n","/*\n * Copyright The OpenTelemetry Authors\n * SPDX-License-Identifier: Apache-2.0\n */\n\nimport type { Exception } from '../common/Exception';\nimport type { TimeInput } from '../common/Time';\nimport type { SpanAttributes } from './attributes';\nimport { INVALID_SPAN_CONTEXT } from './invalid-span-constants';\nimport type { Span } from './span';\nimport type { SpanContext } from './span_context';\nimport type { SpanStatus } from './status';\nimport type { Link } from './link';\n\n/**\n * The NonRecordingSpan is the default {@link Span} that is used when no Span\n * implementation is available. All operations are no-op including context\n * propagation.\n */\nexport class NonRecordingSpan implements Span {\n  private readonly _spanContext: SpanContext;\n\n  constructor(spanContext: SpanContext = INVALID_SPAN_CONTEXT) {\n    this._spanContext = spanContext;\n  }\n\n  // Returns a SpanContext.\n  spanContext(): SpanContext {\n    return this._spanContext;\n  }\n\n  // By default does nothing\n  setAttribute(_key: string, _value: unknown): this {\n    return this;\n  }\n\n  // By default does nothing\n  setAttributes(_attributes: SpanAttributes): this {\n    return this;\n  }\n\n  // By default does nothing\n  addEvent(_name: string, _attributes?: SpanAttributes): this {\n    return this;\n  }\n\n  addLink(_link: Link): this {\n    return this;\n  }\n\n  addLinks(_links: Link[]): this {\n    return this;\n  }\n\n  // By default does nothing\n  setStatus(_status: SpanStatus): this {\n    return this;\n  }\n\n  // By default does nothing\n  updateName(_name: string): this {\n    return this;\n  }\n\n  // By default does nothing\n  end(_endTime?: TimeInput): void {}\n\n  // isRecording always returns false for NonRecordingSpan.\n  isRecording(): boolean {\n    return false;\n  }\n\n  // By default does nothing\n  recordException(_exception: Exception, _time?: TimeInput): void {}\n}\n","/*\n * Copyright The OpenTelemetry Authors\n * SPDX-License-Identifier: Apache-2.0\n */\n\nimport { createContextKey } from '../context/context';\nimport type { Context } from '../context/types';\nimport type { Span } from './span';\nimport type { SpanContext } from './span_context';\nimport { NonRecordingSpan } from './NonRecordingSpan';\nimport { ContextAPI } from '../api/context';\n\n/**\n * span key\n */\nconst SPAN_KEY = createContextKey('OpenTelemetry Context Key SPAN');\n\n/**\n * Return the span if one exists\n *\n * @param context context to get span from\n */\nexport function getSpan(context: Context): Span | undefined {\n  return (context.getValue(SPAN_KEY) as Span) || undefined;\n}\n\n/**\n * Gets the span from the current context, if one exists.\n */\nexport function getActiveSpan(): Span | undefined {\n  return getSpan(ContextAPI.getInstance().active());\n}\n\n/**\n * Set the span on a context\n *\n * @param context context to use as parent\n * @param span span to set active\n */\nexport function setSpan(context: Context, span: Span): Context {\n  return context.setValue(SPAN_KEY, span);\n}\n\n/**\n * Remove current span stored in the context\n *\n * @param context context to delete span from\n */\nexport function deleteSpan(context: Context): Context {\n  return context.deleteValue(SPAN_KEY);\n}\n\n/**\n * Wrap span context in a NoopSpan and set as span in a new\n * context\n *\n * @param context context to set active span on\n * @param spanContext span context to be wrapped\n */\nexport function setSpanContext(\n  context: Context,\n  spanContext: SpanContext\n): Context {\n  return setSpan(context, new NonRecordingSpan(spanContext));\n}\n\n/**\n * Get the span context of the span if it exists.\n *\n * @param context context to get values from\n */\nexport function getSpanContext(context: Context): SpanContext | undefined {\n  return getSpan(context)?.spanContext();\n}\n","/*\n * Copyright The OpenTelemetry Authors\n * SPDX-License-Identifier: Apache-2.0\n */\nimport { INVALID_SPANID, INVALID_TRACEID } from './invalid-span-constants';\nimport { NonRecordingSpan } from './NonRecordingSpan';\nimport type { Span } from './span';\nimport type { SpanContext } from './span_context';\n\n// Valid characters (0-9, a-f, A-F) are marked as 1.\nconst isHex = new Uint8Array([\n  0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,\n  0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1,\n  1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0,\n  0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1,\n]);\n\nfunction isValidHex(id: string, length: number): boolean {\n  // As of 1.9.0 the id was allowed to be a non-string value,\n  // even though it was not possible in the types.\n  if (typeof id !== 'string' || id.length !== length) return false;\n\n  let r = 0;\n  for (let i = 0; i < id.length; i += 4) {\n    r +=\n      (isHex[id.charCodeAt(i)] | 0) +\n      (isHex[id.charCodeAt(i + 1)] | 0) +\n      (isHex[id.charCodeAt(i + 2)] | 0) +\n      (isHex[id.charCodeAt(i + 3)] | 0);\n  }\n\n  return r === length;\n}\n\n/**\n * @since 1.0.0\n */\nexport function isValidTraceId(traceId: string): boolean {\n  return isValidHex(traceId, 32) && traceId !== INVALID_TRACEID;\n}\n\n/**\n * @since 1.0.0\n */\nexport function isValidSpanId(spanId: string): boolean {\n  return isValidHex(spanId, 16) && spanId !== INVALID_SPANID;\n}\n\n/**\n * Returns true if this {@link SpanContext} is valid.\n * @return true if this {@link SpanContext} is valid.\n *\n * @since 1.0.0\n */\nexport function isSpanContextValid(spanContext: SpanContext): boolean {\n  return (\n    isValidTraceId(spanContext.traceId) && isValidSpanId(spanContext.spanId)\n  );\n}\n\n/**\n * Wrap the given {@link SpanContext} in a new non-recording {@link Span}\n *\n * @param spanContext span context to be wrapped\n * @returns a new non-recording {@link Span} with the provided context\n */\nexport function wrapSpanContext(spanContext: SpanContext): Span {\n  return new NonRecordingSpan(spanContext);\n}\n","/*\n * Copyright The OpenTelemetry Authors\n * SPDX-License-Identifier: Apache-2.0\n */\n\nimport { ContextAPI } from '../api/context';\nimport type { Context } from '../context/types';\nimport { getSpanContext, setSpan } from '../trace/context-utils';\nimport { NonRecordingSpan } from './NonRecordingSpan';\nimport type { Span } from './span';\nimport { isSpanContextValid } from './spancontext-utils';\nimport type { SpanOptions } from './SpanOptions';\nimport type { SpanContext } from './span_context';\nimport type { Tracer } from './tracer';\n\nconst contextApi = ContextAPI.getInstance();\n\n/**\n * No-op implementations of {@link Tracer}.\n */\nexport class NoopTracer implements Tracer {\n  // startSpan starts a noop span.\n  startSpan(\n    name: string,\n    options?: SpanOptions,\n    context = contextApi.active()\n  ): Span {\n    const root = Boolean(options?.root);\n    if (root) {\n      return new NonRecordingSpan();\n    }\n\n    const parentFromContext = context && getSpanContext(context);\n\n    if (\n      isSpanContext(parentFromContext) &&\n      isSpanContextValid(parentFromContext)\n    ) {\n      return new NonRecordingSpan(parentFromContext);\n    } else {\n      return new NonRecordingSpan();\n    }\n  }\n\n  startActiveSpan<F extends (span: Span) => ReturnType<F>>(\n    name: string,\n    fn: F\n  ): ReturnType<F>;\n  startActiveSpan<F extends (span: Span) => ReturnType<F>>(\n    name: string,\n    opts: SpanOptions | undefined,\n    fn: F\n  ): ReturnType<F>;\n  startActiveSpan<F extends (span: Span) => ReturnType<F>>(\n    name: string,\n    opts: SpanOptions | undefined,\n    ctx: Context | undefined,\n    fn: F\n  ): ReturnType<F>;\n  startActiveSpan<F extends (span: Span) => ReturnType<F>>(\n    name: string,\n    arg2?: F | SpanOptions,\n    arg3?: F | Context,\n    arg4?: F\n  ): ReturnType<F> | undefined {\n    let opts: SpanOptions | undefined;\n    let ctx: Context | undefined;\n    let fn: F;\n\n    if (arguments.length < 2) {\n      return;\n    } else if (arguments.length === 2) {\n      fn = arg2 as F;\n    } else if (arguments.length === 3) {\n      opts = arg2 as SpanOptions | undefined;\n      fn = arg3 as F;\n    } else {\n      opts = arg2 as SpanOptions | undefined;\n      ctx = arg3 as Context | undefined;\n      fn = arg4 as F;\n    }\n\n    const parentContext = ctx ?? contextApi.active();\n    const span = this.startSpan(name, opts, parentContext);\n    const contextWithSpanSet = setSpan(parentContext, span);\n\n    return contextApi.with(contextWithSpanSet, fn, undefined, span);\n  }\n}\n\nfunction isSpanContext(spanContext: unknown): spanContext is SpanContext {\n  return (\n    spanContext !== null &&\n    typeof spanContext === 'object' &&\n    'spanId' in spanContext &&\n    typeof spanContext['spanId'] === 'string' &&\n    'traceId' in spanContext &&\n    typeof spanContext['traceId'] === 'string' &&\n    'traceFlags' in spanContext &&\n    typeof spanContext['traceFlags'] === 'number'\n  );\n}\n","/*\n * Copyright The OpenTelemetry Authors\n * SPDX-License-Identifier: Apache-2.0\n */\n\nimport type { Context } from '../context/types';\nimport { NoopTracer } from './NoopTracer';\nimport type { Span } from './span';\nimport type { SpanOptions } from './SpanOptions';\nimport type { Tracer } from './tracer';\nimport type { TracerOptions } from './tracer_options';\n\nconst NOOP_TRACER = new NoopTracer();\n\n/**\n * Proxy tracer provided by the proxy tracer provider\n *\n * @since 1.0.0\n */\nexport class ProxyTracer implements Tracer {\n  // When a real implementation is provided, this will be it\n  private _delegate?: Tracer;\n  private _provider: TracerDelegator;\n  public readonly name: string;\n  public readonly version?: string;\n  public readonly options?: TracerOptions;\n\n  constructor(\n    provider: TracerDelegator,\n    name: string,\n    version?: string,\n    options?: TracerOptions\n  ) {\n    this._provider = provider;\n    this.name = name;\n    this.version = version;\n    this.options = options;\n  }\n\n  startSpan(name: string, options?: SpanOptions, context?: Context): Span {\n    return this._getTracer().startSpan(name, options, context);\n  }\n\n  startActiveSpan<F extends (span: Span) => unknown>(\n    _name: string,\n    _options: F | SpanOptions,\n    _context?: F | Context,\n    _fn?: F\n  ): ReturnType<F> {\n    const tracer = this._getTracer();\n    return Reflect.apply(tracer.startActiveSpan, tracer, arguments);\n  }\n\n  /**\n   * Try to get a tracer from the proxy tracer provider.\n   * If the proxy tracer provider has no delegate, return a noop tracer.\n   */\n  private _getTracer() {\n    if (this._delegate) {\n      return this._delegate;\n    }\n\n    const tracer = this._provider.getDelegateTracer(\n      this.name,\n      this.version,\n      this.options\n    );\n\n    if (!tracer) {\n      return NOOP_TRACER;\n    }\n\n    this._delegate = tracer;\n    return this._delegate;\n  }\n}\n\n/**\n * @since 1.0.3\n */\nexport interface TracerDelegator {\n  getDelegateTracer(\n    name: string,\n    version?: string,\n    options?: TracerOptions\n  ): Tracer | undefined;\n}\n","/*\n * Copyright The OpenTelemetry Authors\n * SPDX-License-Identifier: Apache-2.0\n */\n\nimport { NoopTracer } from './NoopTracer';\nimport type { Tracer } from './tracer';\nimport type { TracerOptions } from './tracer_options';\nimport type { TracerProvider } from './tracer_provider';\n\n/**\n * An implementation of the {@link TracerProvider} which returns an impotent\n * Tracer for all calls to `getTracer`.\n *\n * All operations are no-op.\n */\nexport class NoopTracerProvider implements TracerProvider {\n  getTracer(\n    _name?: string,\n    _version?: string,\n    _options?: TracerOptions\n  ): Tracer {\n    return new NoopTracer();\n  }\n}\n","/*\n * Copyright The OpenTelemetry Authors\n * SPDX-License-Identifier: Apache-2.0\n */\n\nimport type { Tracer } from './tracer';\nimport type { TracerProvider } from './tracer_provider';\nimport { ProxyTracer } from './ProxyTracer';\nimport { NoopTracerProvider } from './NoopTracerProvider';\nimport type { TracerOptions } from './tracer_options';\n\nconst NOOP_TRACER_PROVIDER = new NoopTracerProvider();\n\n/**\n * Tracer provider which provides {@link ProxyTracer}s.\n *\n * Before a delegate is set, tracers provided are NoOp.\n *   When a delegate is set, traces are provided from the delegate.\n *   When a delegate is set after tracers have already been provided,\n *   all tracers already provided will use the provided delegate implementation.\n *\n * @deprecated This will be removed in the next major version.\n * @since 1.0.0\n */\nexport class ProxyTracerProvider implements TracerProvider {\n  private _delegate?: TracerProvider;\n\n  /**\n   * Get a {@link ProxyTracer}\n   */\n  getTracer(name: string, version?: string, options?: TracerOptions): Tracer {\n    return (\n      this.getDelegateTracer(name, version, options) ??\n      new ProxyTracer(this, name, version, options)\n    );\n  }\n\n  getDelegate(): TracerProvider {\n    return this._delegate ?? NOOP_TRACER_PROVIDER;\n  }\n\n  /**\n   * Set the delegate tracer provider\n   */\n  setDelegate(delegate: TracerProvider) {\n    this._delegate = delegate;\n  }\n\n  getDelegateTracer(\n    name: string,\n    version?: string,\n    options?: TracerOptions\n  ): Tracer | undefined {\n    return this._delegate?.getTracer(name, version, options);\n  }\n}\n","/*\n * Copyright The OpenTelemetry Authors\n * SPDX-License-Identifier: Apache-2.0\n */\n\nimport type { SpanAttributes } from './attributes';\nimport type { TraceState } from './trace_state';\n\n/**\n * @deprecated use the one declared in @opentelemetry/sdk-trace-base instead.\n * A sampling decision that determines how a {@link Span} will be recorded\n * and collected.\n *\n * @since 1.0.0\n */\nexport enum SamplingDecision {\n  /**\n   * `Span.isRecording() === false`, span will not be recorded and all events\n   * and attributes will be dropped.\n   */\n  NOT_RECORD,\n  /**\n   * `Span.isRecording() === true`, but `Sampled` flag in {@link TraceFlags}\n   * MUST NOT be set.\n   */\n  RECORD,\n  /**\n   * `Span.isRecording() === true` AND `Sampled` flag in {@link TraceFlags}\n   * MUST be set.\n   */\n  RECORD_AND_SAMPLED,\n}\n\n/**\n * @deprecated use the one declared in @opentelemetry/sdk-trace-base instead.\n * A sampling result contains a decision for a {@link Span} and additional\n * attributes the sampler would like to added to the Span.\n *\n * @since 1.0.0\n */\nexport interface SamplingResult {\n  /**\n   * A sampling decision, refer to {@link SamplingDecision} for details.\n   */\n  decision: SamplingDecision;\n  /**\n   * The list of attributes returned by SamplingResult MUST be immutable.\n   * Caller may call {@link Sampler}.shouldSample any number of times and\n   * can safely cache the returned value.\n   */\n  attributes?: Readonly<SpanAttributes>;\n  /**\n   * A {@link TraceState} that will be associated with the {@link Span} through\n   * the new {@link SpanContext}. Samplers SHOULD return the TraceState from\n   * the passed-in {@link Context} if they do not intend to change it. Leaving\n   * the value undefined will also leave the TraceState unchanged.\n   */\n  traceState?: TraceState;\n}\n","/*\n * Copyright The OpenTelemetry Authors\n * SPDX-License-Identifier: Apache-2.0\n */\n\n/**\n * @since 1.0.0\n */\nexport enum SpanKind {\n  /** Default value. Indicates that the span is used internally. */\n  INTERNAL = 0,\n\n  /**\n   * Indicates that the span covers server-side handling of an RPC or other\n   * remote request.\n   */\n  SERVER = 1,\n\n  /**\n   * Indicates that the span covers the client-side wrapper around an RPC or\n   * other remote request.\n   */\n  CLIENT = 2,\n\n  /**\n   * Indicates that the span describes producer sending a message to a\n   * broker. Unlike client and server, there is no direct critical path latency\n   * relationship between producer and consumer spans.\n   */\n  PRODUCER = 3,\n\n  /**\n   * Indicates that the span describes consumer receiving a message from a\n   * broker. Unlike client and server, there is no direct critical path latency\n   * relationship between producer and consumer spans.\n   */\n  CONSUMER = 4,\n}\n","/*\n * Copyright The OpenTelemetry Authors\n * SPDX-License-Identifier: Apache-2.0\n */\n\n/**\n * @since 1.0.0\n */\nexport interface SpanStatus {\n  /** The status code of this message. */\n  code: SpanStatusCode;\n  /** A developer-facing error message. */\n  message?: string;\n}\n\n/**\n * An enumeration of status codes.\n *\n * @since 1.0.0\n */\nexport enum SpanStatusCode {\n  /**\n   * The default status.\n   */\n  UNSET = 0,\n  /**\n   * The operation has been validated by an Application developer or\n   * Operator to have completed successfully.\n   */\n  OK = 1,\n  /**\n   * The operation contains an error.\n   */\n  ERROR = 2,\n}\n","/*\n * Copyright The OpenTelemetry Authors\n * SPDX-License-Identifier: Apache-2.0\n */\n\nconst VALID_KEY_CHAR_RANGE = '[_0-9a-z-*/]';\nconst VALID_KEY = `[a-z]${VALID_KEY_CHAR_RANGE}{0,255}`;\nconst VALID_VENDOR_KEY = `[a-z0-9]${VALID_KEY_CHAR_RANGE}{0,240}@[a-z]${VALID_KEY_CHAR_RANGE}{0,13}`;\nconst VALID_KEY_REGEX = new RegExp(`^(?:${VALID_KEY}|${VALID_VENDOR_KEY})$`);\nconst VALID_VALUE_BASE_REGEX = /^[ -~]{0,255}[!-~]$/;\nconst INVALID_VALUE_COMMA_EQUAL_REGEX = /,|=/;\n\n/**\n * Key is opaque string up to 256 characters printable. It MUST begin with a\n * lowercase letter, and can only contain lowercase letters a-z, digits 0-9,\n * underscores _, dashes -, asterisks *, and forward slashes /.\n * For multi-tenant vendor scenarios, an at sign (@) can be used to prefix the\n * vendor name. Vendors SHOULD set the tenant ID at the beginning of the key.\n * see https://www.w3.org/TR/trace-context/#key\n */\nexport function validateKey(key: string): boolean {\n  return VALID_KEY_REGEX.test(key);\n}\n\n/**\n * Value is opaque string up to 256 characters printable ASCII RFC0020\n * characters (i.e., the range 0x20 to 0x7E) except comma , and =.\n */\nexport function validateValue(value: string): boolean {\n  return (\n    VALID_VALUE_BASE_REGEX.test(value) &&\n    !INVALID_VALUE_COMMA_EQUAL_REGEX.test(value)\n  );\n}\n","/*\n * Copyright The OpenTelemetry Authors\n * SPDX-License-Identifier: Apache-2.0\n */\n\nimport type { TraceState } from '../trace_state';\nimport { validateKey, validateValue } from './tracestate-validators';\n\nconst MAX_TRACE_STATE_ITEMS = 32;\nconst MAX_TRACE_STATE_LEN = 512;\nconst LIST_MEMBERS_SEPARATOR = ',';\nconst LIST_MEMBER_KEY_VALUE_SPLITTER = '=';\n\n/**\n * TraceState must be a class and not a simple object type because of the spec\n * requirement (https://www.w3.org/TR/trace-context/#tracestate-field).\n *\n * Here is the list of allowed mutations:\n * - New key-value pair should be added into the beginning of the list\n * - The value of any key can be updated. Modified keys MUST be moved to the\n * beginning of the list.\n */\nexport class TraceStateImpl implements TraceState {\n  private _internalState: Map<string, string> = new Map();\n\n  constructor(rawTraceState?: string) {\n    if (rawTraceState) this._parse(rawTraceState);\n  }\n\n  set(key: string, value: string): TraceStateImpl {\n    // TODO: Benchmark the different approaches(map vs list) and\n    // use the faster one.\n    const traceState = this._clone();\n    if (traceState._internalState.has(key)) {\n      traceState._internalState.delete(key);\n    }\n    traceState._internalState.set(key, value);\n    return traceState;\n  }\n\n  unset(key: string): TraceStateImpl {\n    const traceState = this._clone();\n    traceState._internalState.delete(key);\n    return traceState;\n  }\n\n  get(key: string): string | undefined {\n    return this._internalState.get(key);\n  }\n\n  serialize(): string {\n    return (\n      Array.from(this._internalState.keys())\n        // Use reduceRight() because keys are stored in reverse insertion order.\n        .reduceRight((agg: string[], key) => {\n          agg.push(key + LIST_MEMBER_KEY_VALUE_SPLITTER + this.get(key));\n          return agg;\n        }, [])\n        .join(LIST_MEMBERS_SEPARATOR)\n    );\n  }\n\n  private _parse(rawTraceState: string) {\n    if (rawTraceState.length > MAX_TRACE_STATE_LEN) return;\n    this._internalState = rawTraceState\n      .split(LIST_MEMBERS_SEPARATOR)\n      // Use reduceRight() so new keys (.set(...)) will be placed at the beginning\n      .reduceRight((agg: Map<string, string>, part: string) => {\n        const listMember = part.trim(); // Optional Whitespace (OWS) handling\n        const i = listMember.indexOf(LIST_MEMBER_KEY_VALUE_SPLITTER);\n        if (i !== -1) {\n          const key = listMember.slice(0, i);\n          const value = listMember.slice(i + 1, part.length);\n          if (validateKey(key) && validateValue(value)) {\n            agg.set(key, value);\n          } else {\n            // TODO: Consider to add warning log\n          }\n        }\n        return agg;\n      }, new Map());\n\n    // Because of the reverse() requirement, trunc must be done after map is created\n    if (this._internalState.size > MAX_TRACE_STATE_ITEMS) {\n      this._internalState = new Map(\n        Array.from(this._internalState.entries())\n          .reverse() // Use reverse same as original tracestate parse chain\n          .slice(0, MAX_TRACE_STATE_ITEMS)\n      );\n    }\n  }\n\n  // @ts-expect-error TS6133 Accessed in tests only.\n  private _keys(): string[] {\n    return Array.from(this._internalState.keys()).reverse();\n  }\n\n  private _clone(): TraceStateImpl {\n    const traceState = new TraceStateImpl();\n    traceState._internalState = new Map(this._internalState);\n    return traceState;\n  }\n}\n","/*\n * Copyright The OpenTelemetry Authors\n * SPDX-License-Identifier: Apache-2.0\n */\n\nimport type { TraceState } from '../trace_state';\nimport { TraceStateImpl } from './tracestate-impl';\n\n/**\n * @since 1.1.0\n */\nexport function createTraceState(rawTraceState?: string): TraceState {\n  return new TraceStateImpl(rawTraceState);\n}\n","/*\n * Copyright The OpenTelemetry Authors\n * SPDX-License-Identifier: Apache-2.0\n */\n\n// Split module-level variable definition into separate files to allow\n// tree-shaking on each api instance.\nimport { ContextAPI } from './api/context';\n/**\n * Entrypoint for context API\n * @since 1.0.0\n */\nexport const context = ContextAPI.getInstance();\n","/*\n * Copyright The OpenTelemetry Authors\n * SPDX-License-Identifier: Apache-2.0\n */\n\n// Split module-level variable definition into separate files to allow\n// tree-shaking on each api instance.\nimport { DiagAPI } from './api/diag';\n/**\n * Entrypoint for Diag API.\n * Defines Diagnostic handler used for internal diagnostic logging operations.\n * The default provides a Noop DiagLogger implementation which may be changed via the\n * diag.setLogger(logger: DiagLogger) function.\n *\n * @since 1.0.0\n */\nexport const diag = DiagAPI.instance();\n","/*\n * Copyright The OpenTelemetry Authors\n * SPDX-License-Identifier: Apache-2.0\n */\n\nimport type { Meter, MeterOptions } from './Meter';\nimport type { MeterProvider } from './MeterProvider';\nimport { NOOP_METER } from './NoopMeter';\n\n/**\n * An implementation of the {@link MeterProvider} which returns an impotent Meter\n * for all calls to `getMeter`\n */\nexport class NoopMeterProvider implements MeterProvider {\n  getMeter(_name: string, _version?: string, _options?: MeterOptions): Meter {\n    return NOOP_METER;\n  }\n}\n\nexport const NOOP_METER_PROVIDER = new NoopMeterProvider();\n","/*\n * Copyright The OpenTelemetry Authors\n * SPDX-License-Identifier: Apache-2.0\n */\n\nimport type { Meter, MeterOptions } from '../metrics/Meter';\nimport type { MeterProvider } from '../metrics/MeterProvider';\nimport { NOOP_METER_PROVIDER } from '../metrics/NoopMeterProvider';\nimport {\n  getGlobal,\n  registerGlobal,\n  unregisterGlobal,\n} from '../internal/global-utils';\nimport { DiagAPI } from './diag';\n\nconst API_NAME = 'metrics';\n\n/**\n * Singleton object which represents the entry point to the OpenTelemetry Metrics API\n */\nexport class MetricsAPI {\n  private static _instance?: MetricsAPI;\n\n  /** Empty private constructor prevents end users from constructing a new instance of the API */\n  private constructor() {}\n\n  /** Get the singleton instance of the Metrics API */\n  public static getInstance(): MetricsAPI {\n    if (!this._instance) {\n      this._instance = new MetricsAPI();\n    }\n\n    return this._instance;\n  }\n\n  /**\n   * Set the current global meter provider.\n   * Returns true if the meter provider was successfully registered, else false.\n   */\n  public setGlobalMeterProvider(provider: MeterProvider): boolean {\n    return registerGlobal(API_NAME, provider, DiagAPI.instance());\n  }\n\n  /**\n   * Returns the global meter provider.\n   */\n  public getMeterProvider(): MeterProvider {\n    return getGlobal(API_NAME) || NOOP_METER_PROVIDER;\n  }\n\n  /**\n   * Returns a meter from the global meter provider.\n   */\n  public getMeter(\n    name: string,\n    version?: string,\n    options?: MeterOptions\n  ): Meter {\n    return this.getMeterProvider().getMeter(name, version, options);\n  }\n\n  /** Remove the global meter provider */\n  public disable(): void {\n    unregisterGlobal(API_NAME, DiagAPI.instance());\n  }\n}\n","/*\n * Copyright The OpenTelemetry Authors\n * SPDX-License-Identifier: Apache-2.0\n */\n\n// Split module-level variable definition into separate files to allow\n// tree-shaking on each api instance.\nimport { MetricsAPI } from './api/metrics';\n/**\n * Entrypoint for metrics API\n *\n * @since 1.3.0\n */\nexport const metrics = MetricsAPI.getInstance();\n","/*\n * Copyright The OpenTelemetry Authors\n * SPDX-License-Identifier: Apache-2.0\n */\n\nimport type { Context } from '../context/types';\nimport type { TextMapPropagator } from './TextMapPropagator';\n\n/**\n * No-op implementations of {@link TextMapPropagator}.\n */\nexport class NoopTextMapPropagator implements TextMapPropagator {\n  /** Noop inject function does nothing */\n  inject(_context: Context, _carrier: unknown): void {}\n  /** Noop extract function does nothing and returns the input context */\n  extract(context: Context, _carrier: unknown): Context {\n    return context;\n  }\n  fields(): string[] {\n    return [];\n  }\n}\n","/*\n * Copyright The OpenTelemetry Authors\n * SPDX-License-Identifier: Apache-2.0\n */\n\nimport { ContextAPI } from '../api/context';\nimport { createContextKey } from '../context/context';\nimport type { Context } from '../context/types';\nimport type { Baggage } from './types';\n\n/**\n * Baggage key\n */\nconst BAGGAGE_KEY = createContextKey('OpenTelemetry Baggage Key');\n\n/**\n * Retrieve the current baggage from the given context\n *\n * @param {Context} Context that manage all context values\n * @returns {Baggage} Extracted baggage from the context\n */\nexport function getBaggage(context: Context): Baggage | undefined {\n  return (context.getValue(BAGGAGE_KEY) as Baggage) || undefined;\n}\n\n/**\n * Retrieve the current baggage from the active/current context\n *\n * @returns {Baggage} Extracted baggage from the context\n */\nexport function getActiveBaggage(): Baggage | undefined {\n  return getBaggage(ContextAPI.getInstance().active());\n}\n\n/**\n * Store a baggage in the given context\n *\n * @param {Context} Context that manage all context values\n * @param {Baggage} baggage that will be set in the actual context\n */\nexport function setBaggage(context: Context, baggage: Baggage): Context {\n  return context.setValue(BAGGAGE_KEY, baggage);\n}\n\n/**\n * Delete the baggage stored in the given context\n *\n * @param {Context} Context that manage all context values\n */\nexport function deleteBaggage(context: Context): Context {\n  return context.deleteValue(BAGGAGE_KEY);\n}\n","/*\n * Copyright The OpenTelemetry Authors\n * SPDX-License-Identifier: Apache-2.0\n */\n\nimport type { Context } from '../context/types';\nimport {\n  getGlobal,\n  registerGlobal,\n  unregisterGlobal,\n} from '../internal/global-utils';\nimport { NoopTextMapPropagator } from '../propagation/NoopTextMapPropagator';\nimport type {\n  TextMapGetter,\n  TextMapPropagator,\n  TextMapSetter,\n} from '../propagation/TextMapPropagator';\nimport {\n  defaultTextMapGetter,\n  defaultTextMapSetter,\n} from '../propagation/TextMapPropagator';\nimport {\n  getBaggage,\n  getActiveBaggage,\n  setBaggage,\n  deleteBaggage,\n} from '../baggage/context-helpers';\nimport { createBaggage } from '../baggage/utils';\nimport { DiagAPI } from './diag';\n\nconst API_NAME = 'propagation';\nconst NOOP_TEXT_MAP_PROPAGATOR = new NoopTextMapPropagator();\n\n/**\n * Singleton object which represents the entry point to the OpenTelemetry Propagation API\n *\n * @since 1.0.0\n */\nexport class PropagationAPI {\n  private static _instance?: PropagationAPI;\n\n  /** Empty private constructor prevents end users from constructing a new instance of the API */\n  private constructor() {}\n\n  /** Get the singleton instance of the Propagator API */\n  public static getInstance(): PropagationAPI {\n    if (!this._instance) {\n      this._instance = new PropagationAPI();\n    }\n\n    return this._instance;\n  }\n\n  /**\n   * Set the current propagator.\n   *\n   * @returns true if the propagator was successfully registered, else false\n   */\n  public setGlobalPropagator(propagator: TextMapPropagator): boolean {\n    return registerGlobal(API_NAME, propagator, DiagAPI.instance());\n  }\n\n  /**\n   * Inject context into a carrier to be propagated inter-process\n   *\n   * @param context Context carrying tracing data to inject\n   * @param carrier carrier to inject context into\n   * @param setter Function used to set values on the carrier\n   */\n  public inject<Carrier>(\n    context: Context,\n    carrier: Carrier,\n    setter: TextMapSetter<Carrier> = defaultTextMapSetter\n  ): void {\n    return this._getGlobalPropagator().inject(context, carrier, setter);\n  }\n\n  /**\n   * Extract context from a carrier\n   *\n   * @param context Context which the newly created context will inherit from\n   * @param carrier Carrier to extract context from\n   * @param getter Function used to extract keys from a carrier\n   */\n  public extract<Carrier>(\n    context: Context,\n    carrier: Carrier,\n    getter: TextMapGetter<Carrier> = defaultTextMapGetter\n  ): Context {\n    return this._getGlobalPropagator().extract(context, carrier, getter);\n  }\n\n  /**\n   * Return a list of all fields which may be used by the propagator.\n   */\n  public fields(): string[] {\n    return this._getGlobalPropagator().fields();\n  }\n\n  /** Remove the global propagator */\n  public disable() {\n    unregisterGlobal(API_NAME, DiagAPI.instance());\n  }\n\n  public createBaggage = createBaggage;\n\n  public getBaggage = getBaggage;\n\n  public getActiveBaggage = getActiveBaggage;\n\n  public setBaggage = setBaggage;\n\n  public deleteBaggage = deleteBaggage;\n\n  private _getGlobalPropagator(): TextMapPropagator {\n    return getGlobal(API_NAME) || NOOP_TEXT_MAP_PROPAGATOR;\n  }\n}\n","/*\n * Copyright The OpenTelemetry Authors\n * SPDX-License-Identifier: Apache-2.0\n */\n\n// Split module-level variable definition into separate files to allow\n// tree-shaking on each api instance.\nimport { PropagationAPI } from './api/propagation';\n/**\n * Entrypoint for propagation API\n *\n * @since 1.0.0\n */\nexport const propagation = PropagationAPI.getInstance();\n","/*\n * Copyright The OpenTelemetry Authors\n * SPDX-License-Identifier: Apache-2.0\n */\n\nimport {\n  getGlobal,\n  registerGlobal,\n  unregisterGlobal,\n} from '../internal/global-utils';\nimport { ProxyTracerProvider } from '../trace/ProxyTracerProvider';\nimport {\n  isSpanContextValid,\n  wrapSpanContext,\n} from '../trace/spancontext-utils';\nimport type { Tracer } from '../trace/tracer';\nimport type { TracerProvider } from '../trace/tracer_provider';\nimport {\n  deleteSpan,\n  getActiveSpan,\n  getSpan,\n  getSpanContext,\n  setSpan,\n  setSpanContext,\n} from '../trace/context-utils';\nimport { DiagAPI } from './diag';\n\nconst API_NAME = 'trace';\n\n/**\n * Singleton object which represents the entry point to the OpenTelemetry Tracing API\n *\n * @since 1.0.0\n */\nexport class TraceAPI {\n  private static _instance?: TraceAPI;\n\n  private _proxyTracerProvider = new ProxyTracerProvider();\n\n  /** Empty private constructor prevents end users from constructing a new instance of the API */\n  private constructor() {}\n\n  /** Get the singleton instance of the Trace API */\n  public static getInstance(): TraceAPI {\n    if (!this._instance) {\n      this._instance = new TraceAPI();\n    }\n\n    return this._instance;\n  }\n\n  /**\n   * Set the current global tracer.\n   *\n   * @returns true if the tracer provider was successfully registered, else false\n   */\n  public setGlobalTracerProvider(provider: TracerProvider): boolean {\n    const success = registerGlobal(\n      API_NAME,\n      this._proxyTracerProvider,\n      DiagAPI.instance()\n    );\n    if (success) {\n      this._proxyTracerProvider.setDelegate(provider);\n    }\n    return success;\n  }\n\n  /**\n   * Returns the global tracer provider.\n   */\n  public getTracerProvider(): TracerProvider {\n    return getGlobal(API_NAME) || this._proxyTracerProvider;\n  }\n\n  /**\n   * Returns a tracer from the global tracer provider.\n   */\n  public getTracer(name: string, version?: string): Tracer {\n    return this.getTracerProvider().getTracer(name, version);\n  }\n\n  /** Remove the global tracer provider */\n  public disable() {\n    unregisterGlobal(API_NAME, DiagAPI.instance());\n    this._proxyTracerProvider = new ProxyTracerProvider();\n  }\n\n  public wrapSpanContext = wrapSpanContext;\n\n  public isSpanContextValid = isSpanContextValid;\n\n  public deleteSpan = deleteSpan;\n\n  public getSpan = getSpan;\n\n  public getActiveSpan = getActiveSpan;\n\n  public getSpanContext = getSpanContext;\n\n  public setSpan = setSpan;\n\n  public setSpanContext = setSpanContext;\n}\n","/*\n * Copyright The OpenTelemetry Authors\n * SPDX-License-Identifier: Apache-2.0\n */\n\n// Split module-level variable definition into separate files to allow\n// tree-shaking on each api instance.\nimport { TraceAPI } from './api/trace';\n\n/**\n * Entrypoint for trace API\n *\n * @since 1.0.0\n */\nexport const trace = TraceAPI.getInstance();\n","/*\n * Copyright The OpenTelemetry Authors\n * SPDX-License-Identifier: Apache-2.0\n */\n\n/**\n * @module @opentelemetry/api\n */\n\nexport type {\n  BaggageEntry,\n  BaggageEntryMetadata,\n  Baggage,\n} from './baggage/types';\nexport { baggageEntryMetadataFromString } from './baggage/utils';\nexport type { Exception } from './common/Exception';\nexport type { HrTime, TimeInput } from './common/Time';\nexport type { Attributes, AttributeValue } from './common/Attributes';\n\n// Context APIs\nexport { createContextKey, ROOT_CONTEXT } from './context/context';\nexport type { Context, ContextManager } from './context/types';\nexport type { ContextAPI } from './api/context';\n\n// Diag APIs\nexport { DiagConsoleLogger } from './diag/consoleLogger';\nexport { DiagLogLevel } from './diag/types';\nexport type {\n  DiagLogFunction,\n  DiagLogger,\n  ComponentLoggerOptions,\n  DiagLoggerOptions,\n} from './diag/types';\nexport type { DiagAPI } from './api/diag';\n\n// Metrics APIs\nexport { createNoopMeter } from './metrics/NoopMeter';\nexport type { MeterOptions, Meter } from './metrics/Meter';\nexport type { MeterProvider } from './metrics/MeterProvider';\nexport { ValueType } from './metrics/Metric';\nexport type {\n  Counter,\n  Gauge,\n  Histogram,\n  MetricOptions,\n  UpDownCounter,\n  MetricAdvice,\n  MetricAttributes,\n  MetricAttributeValue,\n  Observable,\n  ObservableCounter,\n  ObservableGauge,\n  ObservableUpDownCounter,\n  BatchObservableCallback,\n  ObservableCallback,\n  BatchObservableResult,\n  ObservableResult,\n} from './metrics/Metric';\nexport type { MetricsAPI } from './api/metrics';\n\n// Propagation APIs\nexport {\n  defaultTextMapGetter,\n  defaultTextMapSetter,\n} from './propagation/TextMapPropagator';\nexport type {\n  TextMapPropagator,\n  TextMapSetter,\n  TextMapGetter,\n} from './propagation/TextMapPropagator';\nexport type { PropagationAPI } from './api/propagation';\n\n// Trace APIs\nexport type { SpanAttributes, SpanAttributeValue } from './trace/attributes';\nexport type { Link } from './trace/link';\nexport { ProxyTracer, type TracerDelegator } from './trace/ProxyTracer';\n// TODO: Remove ProxyTracerProvider export in the next major version.\nexport { ProxyTracerProvider } from './trace/ProxyTracerProvider';\nexport type { Sampler } from './trace/Sampler';\nexport { SamplingDecision, type SamplingResult } from './trace/SamplingResult';\nexport type { SpanContext } from './trace/span_context';\nexport { SpanKind } from './trace/span_kind';\nexport type { Span } from './trace/span';\nexport type { SpanOptions } from './trace/SpanOptions';\nexport { type SpanStatus, SpanStatusCode } from './trace/status';\nexport { TraceFlags } from './trace/trace_flags';\nexport type { TraceState } from './trace/trace_state';\nexport { createTraceState } from './trace/internal/utils';\nexport type { TracerProvider } from './trace/tracer_provider';\nexport type { Tracer } from './trace/tracer';\nexport type { TracerOptions } from './trace/tracer_options';\nexport {\n  isSpanContextValid,\n  isValidTraceId,\n  isValidSpanId,\n} from './trace/spancontext-utils';\nexport {\n  INVALID_SPANID,\n  INVALID_TRACEID,\n  INVALID_SPAN_CONTEXT,\n} from './trace/invalid-span-constants';\nexport type { TraceAPI } from './api/trace';\n\n// Split module-level variable definition into separate files to allow\n// tree-shaking on each api instance.\nimport { context } from './context-api';\nimport { diag } from './diag-api';\nimport { metrics } from './metrics-api';\nimport { propagation } from './propagation-api';\nimport { trace } from './trace-api';\n\n// Named export.\nexport { context, diag, metrics, propagation, trace };\n// Default export.\nexport default {\n  context,\n  diag,\n  metrics,\n  propagation,\n  trace,\n};\n","import { resolveConfig, isProductionDisabled } from \"../env-detection.js\";\nimport { decisionTrace, decisionTraceEnabled } from \"../decision-trace.js\";\n\n/**\n * Module-level flag ensuring the MCP-connection nudge fires at most once\n * per process.\n */\nlet hasFired = false;\n\n/**\n * Module-level flag ensuring the Server Action nudge fires at most once\n * per process.\n */\nlet hasFiredServerAction = false;\n\n/**\n * Strips control characters (except space) from a string to prevent\n * terminal escape sequence injection via error summaries written to stderr.\n */\nfunction sanitize(input: string): string {\n  // eslint-disable-next-line no-control-regex\n  return input.replace(/[\\x00-\\x1f\\x7f]/g, \"\");\n}\n\n/**\n * Checks whether the MCP marker file exists using synchronous filesystem\n * APIs. Returns `false` when `node:fs` or `node:path` cannot be resolved\n * (non-Node environments) or on any I/O error.\n */\nfunction markerFileExists(): boolean {\n  try {\n    // eslint-disable-next-line @typescript-eslint/no-require-imports, glasstrace/no-unguarded-node-require -- guarded by the surrounding try/catch in `markerFileExists`; throw returns `false`, the nudge proceeds as if no marker exists (DISC-1555).\n    const fs = require(\"node:fs\") as typeof import(\"node:fs\");\n    // eslint-disable-next-line @typescript-eslint/no-require-imports, glasstrace/no-unguarded-node-require -- guarded by the same try/catch as the preceding `node:fs` require (DISC-1555).\n    const path = require(\"node:path\") as typeof import(\"node:path\");\n    const markerPath = path.join(process.cwd(), \".glasstrace\", \"mcp-connected\");\n    return fs.existsSync(markerPath);\n  } catch {\n    // node:fs/node:path unavailable, permission denied, ENOENT from\n    // cwd(), or other error — treat as not connected\n    return false;\n  }\n}\n\n/**\n * Shows a one-time stderr nudge when the SDK captures its first error\n * and the MCP connection marker file is absent.\n *\n * The nudge is suppressed when:\n * - It has already fired in this process\n * - The `.glasstrace/mcp-connected` marker file exists at the project root\n * - The environment is detected as production (and force-enable is off)\n *\n * Uses `process.stderr.write()` instead of `console.error()` to avoid\n * being captured by OpenTelemetry console instrumentation.\n */\nexport function maybeShowMcpNudge(errorSummary: string): void {\n  if (hasFired) {\n    return;\n  }\n\n  // Production check — suppress silently, but remember the decision\n  // so subsequent calls fast-exit via hasFired without re-running I/O.\n  const config = resolveConfig();\n  if (isProductionDisabled(config)) {\n    // Decision trace: the MCP nudge was suppressed by the production gate.\n    // Keyed by the closed outcome (`suppressed` / `shown`) AND the code-literal\n    // reason, so the two suppression branches each keep their own one-shot slot\n    // (folding the reason in avoids the production/marker key collision).\n    // Guarded so nothing is built when OFF.\n    if (decisionTraceEnabled()) {\n      decisionTrace(\"env.nudgeSuppressed\", \"suppressed\", {\n        reason: \"production\",\n        oneShotKey: \"env.nudgeSuppressed:suppressed:production\",\n      });\n    }\n    hasFired = true;\n    return;\n  }\n\n  // Check for MCP connection marker file.\n  if (markerFileExists()) {\n    // Decision trace: suppressed because the MCP connection marker is present.\n    if (decisionTraceEnabled()) {\n      decisionTrace(\"env.nudgeSuppressed\", \"suppressed\", {\n        reason: \"marker_present\",\n        oneShotKey: \"env.nudgeSuppressed:suppressed:marker_present\",\n      });\n    }\n    hasFired = true;\n    return;\n  }\n\n  // Fire the nudge exactly once\n  if (decisionTraceEnabled()) {\n    decisionTrace(\"env.nudgeSuppressed\", \"shown\", {\n      oneShotKey: \"env.nudgeSuppressed:shown\",\n    });\n  }\n  hasFired = true;\n\n  const safe = sanitize(errorSummary);\n  process.stderr.write(\n    `[glasstrace] Error captured: ${safe}\\n` +\n      `  Debug with AI: ask your agent \"What's the latest Glasstrace error?\"\\n` +\n      `  Not connected? From the app package: npm exec -- glasstrace mcp add (pnpm: pnpm exec glasstrace mcp add)\\n`,\n  );\n}\n\n/**\n * Shows a one-time stderr nudge when the SDK detects a Next.js Server\n * Action trace whose originating request had no Glasstrace browser\n * extension correlation header (`x-gt-cid`) — meaning the extension was\n * not active for that request and the specific Server Action identifier\n * could not be captured.\n *\n * The nudge is suppressed when:\n * - It has already fired in this process\n * - The environment is detected as production (and force-enable is off)\n * - `GLASSTRACE_SUPPRESS_ACTION_NUDGE=1` is set\n *\n * Routes through `process.stderr.write()` — identical transport to the\n * existing MCP nudge — so it is not captured by OpenTelemetry console\n * instrumentation and plays nicely with existing error-nudge tests.\n */\nexport function maybeShowServerActionNudge(): void {\n  if (hasFiredServerAction) {\n    return;\n  }\n\n  // User opt-out takes precedence over every other check so we never\n  // re-run I/O when silenced.\n  if (process.env.GLASSTRACE_SUPPRESS_ACTION_NUDGE === \"1\") {\n    hasFiredServerAction = true;\n    return;\n  }\n\n  // Production check — suppress silently, but remember the decision so\n  // subsequent calls fast-exit via hasFiredServerAction without re-running\n  // resolveConfig.\n  const config = resolveConfig();\n  if (isProductionDisabled(config)) {\n    hasFiredServerAction = true;\n    return;\n  }\n\n  hasFiredServerAction = true;\n\n  process.stderr.write(\n    `[glasstrace] Detected a Next.js Server Action trace. Install the ` +\n      `Glasstrace browser extension to capture the Server Action identifier ` +\n      `for precise action-level debugging. https://glasstrace.dev/ext\\n`,\n  );\n}\n\n/**\n * Test-only hook: resets both nudge guards so independent tests can\n * reload module state without relying on `vi.resetModules()` side effects.\n * Kept internal — not exported from the SDK barrel.\n */\nexport function __resetNudgeStateForTests(): void {\n  hasFired = false;\n  hasFiredServerAction = false;\n}\n","/**\n * Console error/warn capture module.\n *\n * When enabled, monkey-patches `console.error` and `console.warn` to record\n * their output as OTel span events on the currently active span. SDK-internal\n * log messages (prefixed with \"[glasstrace]\") are never captured.\n */\n\nimport { maybeShowMcpNudge } from \"./nudge/error-nudge.js\";\n\n/**\n * Module-level flag to suppress capture of SDK-internal log messages.\n * Set to `true` before calling `console.warn`/`console.error` from SDK code,\n * then reset to `false` immediately after.\n */\nexport let isGlasstraceLog = false;\n\n/** Saved reference to the original `console.error`. */\nlet originalError: typeof console.error | null = null;\n\n/** Saved reference to the original `console.warn`. */\nlet originalWarn: typeof console.warn | null = null;\n\n/** Whether the console capture is currently installed. */\nlet installed = false;\n\n/** Cached OTel API module reference, resolved at install time. */\nlet otelApi: typeof import(\"@opentelemetry/api\") | null = null;\n\n/**\n * Formats console arguments into a single string for span event attributes.\n * Uses best-effort serialization: strings pass through, Errors preserve their\n * stack trace, and other values are JSON-stringified with a String() fallback.\n */\nfunction formatArgs(args: unknown[]): string {\n  return args\n    .map((arg) => {\n      if (typeof arg === \"string\") return arg;\n      if (arg instanceof Error) return arg.stack ?? arg.message;\n      try {\n        return JSON.stringify(arg);\n      } catch {\n        return String(arg);\n      }\n    })\n    .join(\" \");\n}\n\n/**\n * Returns `true` if the first argument is a string starting with \"[glasstrace]\".\n * Used to skip capture of SDK-internal log messages without requiring every\n * call site to set the `isGlasstraceLog` flag.\n */\nfunction isSdkMessage(args: unknown[]): boolean {\n  return typeof args[0] === \"string\" && args[0].startsWith(\"[glasstrace]\");\n}\n\n/**\n * Installs console capture by replacing `console.error` and `console.warn`\n * with wrappers that record span events on the active OTel span.\n *\n * Must be called after OTel is configured so the API module is available.\n * Safe to call multiple times; subsequent calls are no-ops.\n */\nexport async function installConsoleCapture(): Promise<void> {\n  if (installed) return;\n\n  // Resolve OTel API at install time via dynamic import so that:\n  // 1. tsup inlines @opentelemetry/api into the bundle (it's in noExternal)\n  // 2. vitest's vi.doMock can intercept this import for testing\n  try {\n    otelApi = await import(\"@opentelemetry/api\");\n  } catch {\n    otelApi = null;\n  }\n\n  originalError = console.error;\n  originalWarn = console.warn;\n  installed = true;\n\n  console.error = (...args: unknown[]) => {\n    // Always call the original first to preserve developer experience\n    originalError!.apply(console, args);\n\n    // Skip SDK-internal messages and flagged messages\n    if (isGlasstraceLog || isSdkMessage(args)) return;\n\n    if (otelApi) {\n      const span = otelApi.trace.getSpan(otelApi.context.active());\n      if (span) {\n        const formattedMessage = formatArgs(args);\n        span.addEvent(\"console.error\", {\n          \"console.message\": formattedMessage,\n        });\n        // Show one-time MCP connection nudge on first captured error\n        try {\n          maybeShowMcpNudge(formattedMessage);\n        } catch {\n          // Never allow the monkey-patched console.error wrapper to throw\n        }\n      }\n    }\n  };\n\n  console.warn = (...args: unknown[]) => {\n    originalWarn!.apply(console, args);\n\n    if (isGlasstraceLog || isSdkMessage(args)) return;\n\n    if (otelApi) {\n      const span = otelApi.trace.getSpan(otelApi.context.active());\n      if (span) {\n        span.addEvent(\"console.warn\", {\n          \"console.message\": formatArgs(args),\n        });\n      }\n    }\n  };\n}\n\n/**\n * Restores the original `console.error` and `console.warn` methods.\n * Primarily intended for use in tests.\n */\nexport function uninstallConsoleCapture(): void {\n  if (!installed) return;\n\n  if (originalError) console.error = originalError;\n  if (originalWarn) console.warn = originalWarn;\n\n  originalError = null;\n  originalWarn = null;\n  otelApi = null;\n  installed = false;\n}\n\n/**\n * Logs a message from SDK-internal code without triggering console capture.\n *\n * Use this helper in new SDK code instead of bare `console.warn(...)` calls\n * to prevent SDK log messages from being recorded as user-facing span events.\n *\n * @param level - The console log level to use.\n * @param message - The message to log.\n */\nexport function sdkLog(level: \"warn\" | \"info\" | \"error\", message: string): void {\n  isGlasstraceLog = true;\n  try {\n    console[level](message);\n  } finally {\n    isGlasstraceLog = false;\n  }\n}\n","/**\n * Coexistence state for the signal handler.\n *\n * Set by configureOtel() once the async provider probe completes:\n *   - \"sole-owner\"  — Glasstrace owns the OTel provider (Scenarios A / E).\n *                     The signal handler re-raises after draining hooks.\n *   - \"coexisting\"  — Another provider exists (Scenario B / C / F).\n *                     The signal handler drains our hooks but does NOT\n *                     re-raise, so the existing provider's shutdown can\n *                     complete at its own pace.\n *   - \"unknown\"     — The async probe has not completed yet (startup window).\n *                     Treated the same as \"sole-owner\" — re-raise is the\n *                     safe default because it preserves the process's default\n *                     signal semantics when we have no information.\n */\ntype CoexistenceState = \"unknown\" | \"sole-owner\" | \"coexisting\";\n\nlet coexistenceState: CoexistenceState = \"unknown\";\n\n/**\n * Called by configureOtel() once the async provider probe completes.\n * \"sole-owner\" when Glasstrace owns the provider; \"coexisting\" otherwise.\n */\nexport function setCoexistenceState(s: CoexistenceState): void {\n  coexistenceState = s;\n}\n\n/**\n * Returns the current coexistence state.\n * \"unknown\" until configureOtel() completes its async provider probe.\n */\nexport function getCoexistenceState(): CoexistenceState {\n  return coexistenceState;\n}\n\n/**\n * Resets coexistence state to \"unknown\". For testing only.\n */\nexport function _resetCoexistenceStateForTesting(): void {\n  coexistenceState = \"unknown\";\n}\n","/**\n * Edge-safe optional bridge to the SDK lifecycle event emitter.\n *\n * `./lifecycle.ts` imports `node:events` and is therefore excluded from\n * the F003 edge bundle (`packages/sdk/src/edge-entry.ts`,\n * `packages/sdk/scripts/check-edge-bundle.mjs`). Modules that need to\n * emit a lifecycle event AND need to ship in the edge bundle (e.g.,\n * `./middleware/index.ts`, `./async-context/index.ts`) cannot import\n * from `./lifecycle.ts` directly.\n *\n * This module is the bridge:\n *\n * - `lifecycle.ts` (Node-only) calls {@link _registerLifecycleEmitForBridge}\n *   inside `initLifecycle()`. The registration writes the typed\n *   `emitLifecycleEvent` reference to a `globalThis`-keyed slot.\n * - Edge-safe wrappers call {@link tryEmitLifecycleEvent}, which reads\n *   the slot. When unset (edge runtime, or SDK not yet initialized),\n *   the call is a clean no-op. When set, the call forwards to the\n *   real emitter.\n *\n * This file imports nothing from `node:*` and reads no `process`\n * globals; it is admissible to the edge bundle by the F003 contract.\n *\n * The slot key uses `Symbol.for()` so the bridge survives module\n * re-evaluation (Turbopack HMR rebuilds, Webpack `next dev` rebuilds,\n * vitest module isolation). The same pattern is used by the OTel\n * context-manager guard at `./context-manager.ts:28` and the exporter\n * brand at `./coexistence.ts:31` — all three are per-isolate by V8\n * semantics, which is the correct boundary for this contract (a Node\n * worker thread or `vm.Context` is logically a fresh process).\n *\n * **Why not pass the emitter through the public wrapper API?** The\n * emitter is an internal SDK signal, not a user-facing knob. Keeping\n * it on a global slot rather than as a wrapper option preserves the\n * documented public surface (`tracedRequestMiddleware(options,\n * handler)`) and lets the lifecycle module take ownership of the\n * emit-once / event-key invariants without exposing them.\n */\n\n/** Process-wide brand used to look up the registered emit function. */\nconst EMIT_BRIDGE = Symbol.for(\"glasstrace.lifecycle.emit-bridge\");\n\n/**\n * Type of the registered emit function. Mirrors the signature of\n * `emitLifecycleEvent` from `./lifecycle.ts` but typed as `unknown`\n * here to keep this module free of any cross-import that would couple\n * the edge bundle to `node:events`.\n *\n * The lifecycle module casts to/from this type at the registration\n * site; consumers of {@link tryEmitLifecycleEvent} use the typed\n * overload that re-imposes the `SdkLifecycleEvents` constraint via a\n * second parameter alias.\n */\nexport type LifecycleEmitFn = (\n  event: string,\n  payload: Record<string, unknown>,\n) => void;\n\ninterface BridgeSlot {\n  readonly emit: LifecycleEmitFn;\n}\n\n/**\n * INTERNAL — called by `./lifecycle.ts` during `initLifecycle()` to\n * register the emit function under the global slot. Calling twice is\n * idempotent: the latest registration wins. Never throws.\n */\nexport function _registerLifecycleEmitForBridge(\n  emit: LifecycleEmitFn,\n): void {\n  try {\n    const slot: BridgeSlot = { emit };\n    (globalThis as unknown as Record<symbol, BridgeSlot>)[EMIT_BRIDGE] = slot;\n  } catch {\n    // Defensive: writing to globalThis is observable; some constrained\n    // sandboxes freeze it. The bridge falls back to silent no-op.\n  }\n}\n\n/**\n * INTERNAL — called by `./lifecycle.ts` during\n * `resetLifecycleForTesting()` to clear the slot so a fresh test gets\n * a clean bridge state.\n */\nexport function _clearLifecycleEmitForBridge(): void {\n  try {\n    delete (globalThis as unknown as Record<symbol, unknown>)[EMIT_BRIDGE];\n  } catch {\n    // Defensive: see _registerLifecycleEmitForBridge.\n  }\n}\n\n/**\n * Attempt to emit a lifecycle event through the registered bridge.\n *\n * - When the lifecycle module has registered the bridge (Node runtime\n *   with `registerGlasstrace()` having run): forwards to\n *   `emitLifecycleEvent(event, payload)`.\n * - When the bridge is unset (edge runtime — `lifecycle.ts` not in\n *   closure; or pre-`initLifecycle()` race): no-op.\n *\n * Errors thrown by the registered emit function are swallowed —\n * instrumentation must never break a user request hook.\n */\nexport function tryEmitLifecycleEvent(\n  event: string,\n  payload: Record<string, unknown>,\n): void {\n  try {\n    const slot = (globalThis as unknown as Record<symbol, BridgeSlot | undefined>)[\n      EMIT_BRIDGE\n    ];\n    if (!slot) return;\n    slot.emit(event, payload);\n  } catch {\n    // Swallow — bridge failures are advisory, not fatal.\n  }\n}\n","/**\n * SDK Lifecycle State Machine\n *\n * Provides a single source of truth for SDK state across three runtime\n * layers: core, auth, and OTel coexistence. (The CLI layer is handled\n * separately via the runtime state file bridge.)\n *\n * The core layer provides a shared typed event emitter that other layers\n * and SDK modules use for cross-layer communication.\n *\n * This module imports only from `./signal-handler.js`, which itself has no\n * imports, so the dependency graph remains acyclic. The logger is still\n * injected via initLifecycle() to avoid coupling to console-capture.\n *\n * @see docs/component-designs/sdk-lifecycle.md\n */\n\nimport { EventEmitter } from \"node:events\";\nimport { getCoexistenceState } from \"./signal-handler.js\";\nimport {\n  _registerLifecycleEmitForBridge,\n  _clearLifecycleEmitForBridge,\n} from \"./optional-lifecycle.js\";\n\n// ---------------------------------------------------------------------------\n// State Enums\n// ---------------------------------------------------------------------------\n\nexport const CoreState = {\n  IDLE: \"IDLE\",\n  REGISTERING: \"REGISTERING\",\n  KEY_PENDING: \"KEY_PENDING\",\n  KEY_RESOLVED: \"KEY_RESOLVED\",\n  ACTIVE: \"ACTIVE\",\n  ACTIVE_DEGRADED: \"ACTIVE_DEGRADED\",\n  SHUTTING_DOWN: \"SHUTTING_DOWN\",\n  SHUTDOWN: \"SHUTDOWN\",\n  PRODUCTION_DISABLED: \"PRODUCTION_DISABLED\",\n  REGISTRATION_FAILED: \"REGISTRATION_FAILED\",\n} as const;\nexport type CoreState = (typeof CoreState)[keyof typeof CoreState];\n\nexport const AuthState = {\n  ANONYMOUS: \"ANONYMOUS\",\n  AUTHENTICATED: \"AUTHENTICATED\",\n  CLAIMING: \"CLAIMING\",\n  CLAIMED: \"CLAIMED\",\n} as const;\nexport type AuthState = (typeof AuthState)[keyof typeof AuthState];\n\nexport const OtelState = {\n  UNCONFIGURED: \"UNCONFIGURED\",\n  CONFIGURING: \"CONFIGURING\",\n  OWNS_PROVIDER: \"OWNS_PROVIDER\",\n  AUTO_ATTACHED: \"AUTO_ATTACHED\",\n  PROCESSOR_PRESENT: \"PROCESSOR_PRESENT\",\n  COEXISTENCE_FAILED: \"COEXISTENCE_FAILED\",\n} as const;\nexport type OtelState = (typeof OtelState)[keyof typeof OtelState];\n\n// ---------------------------------------------------------------------------\n// Valid Transitions\n// ---------------------------------------------------------------------------\n\n/**\n * Valid transitions for the core SDK lifecycle state machine.\n *\n * @drift-check ../glasstrace-product/docs/component-designs/sdk-lifecycle.md §4.2 Transition Rules\n */\nconst VALID_CORE_TRANSITIONS: Record<CoreState, readonly CoreState[]> = {\n  [CoreState.IDLE]: [CoreState.REGISTERING, CoreState.REGISTRATION_FAILED, CoreState.SHUTTING_DOWN],\n  [CoreState.REGISTERING]: [\n    CoreState.KEY_PENDING,\n    CoreState.PRODUCTION_DISABLED,\n    CoreState.REGISTRATION_FAILED,\n    CoreState.SHUTTING_DOWN,\n  ],\n  [CoreState.KEY_PENDING]: [\n    CoreState.KEY_RESOLVED,\n    CoreState.REGISTRATION_FAILED,\n    CoreState.SHUTTING_DOWN,\n  ],\n  [CoreState.KEY_RESOLVED]: [\n    CoreState.ACTIVE,\n    CoreState.ACTIVE_DEGRADED,\n    CoreState.SHUTTING_DOWN,\n  ],\n  [CoreState.ACTIVE]: [\n    CoreState.ACTIVE_DEGRADED,\n    CoreState.SHUTTING_DOWN,\n  ],\n  [CoreState.ACTIVE_DEGRADED]: [\n    CoreState.ACTIVE,\n    CoreState.SHUTTING_DOWN,\n  ],\n  [CoreState.SHUTTING_DOWN]: [CoreState.SHUTDOWN],\n  [CoreState.SHUTDOWN]: [],\n  [CoreState.PRODUCTION_DISABLED]: [],\n  [CoreState.REGISTRATION_FAILED]: [],\n};\n\n/**\n * Valid transitions for the auth state machine.\n *\n * @drift-check ../glasstrace-product/docs/component-designs/sdk-lifecycle.md §5.2 Transitions\n */\nconst VALID_AUTH_TRANSITIONS: Record<AuthState, readonly AuthState[]> = {\n  [AuthState.ANONYMOUS]: [AuthState.CLAIMING],\n  [AuthState.AUTHENTICATED]: [AuthState.CLAIMING],\n  [AuthState.CLAIMING]: [AuthState.CLAIMED],\n  [AuthState.CLAIMED]: [AuthState.CLAIMING],\n};\n\n/**\n * Valid transitions for the OTel coexistence state machine.\n *\n * @drift-check ../glasstrace-product/docs/component-designs/sdk-lifecycle.md §6 Layer 3: OTel Coexistence Lifecycle\n */\nconst VALID_OTEL_TRANSITIONS: Record<OtelState, readonly OtelState[]> = {\n  [OtelState.UNCONFIGURED]: [OtelState.CONFIGURING],\n  [OtelState.CONFIGURING]: [\n    OtelState.OWNS_PROVIDER,\n    OtelState.AUTO_ATTACHED,\n    OtelState.PROCESSOR_PRESENT,\n    OtelState.COEXISTENCE_FAILED,\n  ],\n  [OtelState.OWNS_PROVIDER]: [],\n  [OtelState.AUTO_ATTACHED]: [],\n  [OtelState.PROCESSOR_PRESENT]: [],\n  [OtelState.COEXISTENCE_FAILED]: [],\n};\n\n// ---------------------------------------------------------------------------\n// Event Types\n// ---------------------------------------------------------------------------\n\nexport interface SdkLifecycleEvents {\n  \"core:state_changed\": { from: CoreState; to: CoreState };\n  \"core:ready\": Record<string, never>;\n  \"core:shutdown_started\": Record<string, never>;\n  \"core:shutdown_completed\": Record<string, never>;\n  /**\n   * `core:error_boundary_detected` — fired once per boundary-masked-error promotion.\n   *\n   * @property spanId            The OTel spanId of the HTTP **server** span that was promoted to 500.\n   * @property inferredStatus    The promoted status (500, or a 400-599 value parsed from a numeric\n   *                             `error.type` on the server span when present).\n   * @property source            'same_span' when the error signal is on the server span itself;\n   *                             'descendant' when it is on a transitive child span.\n   * @property exceptionSpanId   Present ONLY when source === 'descendant'. The spanId of the\n   *                             earliest-exception descendant (smallest startTimeMs, tie-break\n   *                             smallest spanId). Omitted for same_span. NOTE: this is a DIFFERENT\n   *                             span from `spanId` (the server span).\n   * @property exceptionMessage  First 256 chars of the exception event message (truncated at storage).\n   *                             For source === 'same_span' this is the same content already on the\n   *                             span. For source === 'descendant' it comes from the DESCENDANT span,\n   *                             not the server span, and MAY surface information not otherwise present\n   *                             at the HTTP boundary — a new PII-disclosure surface for descendant source.\n   *\n   * The heuristic fires from the enriching exporter when an HTTP server\n   * span (`http.method` present, `span.kind === SpanKind.SERVER`) has a\n   * resolved `glasstrace.http.status_code` in the trigger set\n   * `{200, 0, undefined}`, `span.status.code` is not explicitly `OK`,\n   * and an error signal is found. Two scopes produce the signal:\n   *\n   *   - **same_span:** the server span itself carries the error signal —\n   *     any of `span.status.code === SpanStatusCode.ERROR`, an\n   *     `exception` event from `recordException()`, or an\n   *     `exception.type` / `exception.message` span attribute.\n   *   - **descendant:** a transitive child of the server span recorded an\n   *     `exception` event (the page-route boundary case where the\n   *     exception lives in a framework render span while the request\n   *     renders an HTTP 200), the child is not a known framework\n   *     control-flow throw, and — for render-route children — the\n   *     exception is in the unexpected/infrastructure class rather than a\n   *     generic expected application `Error`.\n   *\n   * When the heuristic fires, the SDK promotes the inferred\n   * `glasstrace.http.status_code` (typically to 500, or to a value\n   * parsed from a numeric `error.type` attribute when present) and fires\n   * this event. Informational only — subscribers MAY use it for\n   * observability (e.g., heuristic activation rate dashboards) but the\n   * heuristic's behavior does NOT depend on subscribers.\n   *\n   * **PII-safety (load-bearing).** `exceptionMessage` is truncated to 256\n   * characters. For `source === 'same_span'` it is the same content\n   * already present on the server span's exception event or\n   * `exception.message` attribute — no new disclosure surface beyond what\n   * already ships in the trace itself. For `source === 'descendant'`,\n   * `spanId` (the server span) and `exceptionMessage` (the descendant\n   * span) reference DIFFERENT spans: the message is taken from the\n   * descendant and MAY disclose information that is not otherwise present\n   * at the HTTP boundary — a new PII-disclosure surface for descendant\n   * source. `exceptionMessage` is OMITTED from the payload entirely when\n   * no exception message is available (e.g. the `status.code === ERROR`-only\n   * same-span case).\n   */\n  \"core:error_boundary_detected\": {\n    spanId: string;\n    inferredStatus: number;\n    source: \"same_span\" | \"descendant\";\n    exceptionSpanId?: string;\n    exceptionMessage?: string;\n  };\n  /**\n   * An instrumented SDK config-decision point was decided while decision\n   * tracing is enabled. This is the structured, programmatically-capturable\n   * counterpart of the `[glasstrace] decision:` console line: a validator or\n   * test subscribes with `onLifecycleEvent(\"core:decision\", ...)` and asserts\n   * the `{ point, outcome }` sequence for a scenario instead of scraping\n   * console text.\n   *\n   * **Firing condition.** Emitted for every instrumented decision when\n   * decision tracing is enabled (the `decisionTrace` option, the\n   * `GLASSTRACE_DECISION_TRACE` env var, or `verbose`). When tracing is OFF —\n   * the default — this event is **never** emitted, even to a registered\n   * subscriber: the off-by-default guarantee mirrors the log channel exactly,\n   * and gating is on the toggle, never on subscriber count.\n   *\n   * **Payload semantics.** `point` is a stable, dot-separated decision id\n   * (for example `capture.sideEffectEvidence` or `config.tier`); it is typed\n   * as a plain `string` on the event so a future point can ride the bus before\n   * the internal id union is widened. `outcome` is the closed per-point\n   * outcome (for example `enabled` / `disabled`, `in_memory` / `file_cache` /\n   * `defaults`). `reason` is an optional, bounded, allowlisted reason.\n   * `inputs` is an optional, bounded, safe disambiguation subset — the same\n   * tokens the log line renders (for example the capture-gate `surface`\n   * token, which is the only field distinguishing the `recordSideEffect`,\n   * `capture`, and `prismaAdapter` surfaces' otherwise-identical events).\n   *\n   * **No-secret / no-rejected-value contract.** The payload carries flags and\n   * enums only: never a raw secret, never a rejected key or value, never\n   * nested producer input. API keys appear only masked; a key-shaped config\n   * value is reported as `present` / `absent`, never as its value.\n   *\n   * @example\n   * ```ts\n   * onLifecycleEvent(\"core:decision\", (e) => {\n   *   console.log(e.point, e.outcome, e.inputs?.surface);\n   * });\n   * ```\n   */\n  \"core:decision\": {\n    point: string;\n    outcome: string;\n    reason?: string;\n    inputs?: Record<string, string | number | boolean>;\n  };\n\n  \"auth:key_resolved\": { key: string; mode: \"anonymous\" | \"dev\" };\n  \"auth:claim_started\": { accountId: string };\n  \"auth:claim_completed\": { newKey: string; accountId: string };\n\n  \"otel:configured\": { state: OtelState; scenario?: string };\n  \"otel:injection_succeeded\": { method: string };\n  \"otel:injection_failed\": { reason: string };\n  /**\n   * Structured fail-loud diagnostic emitted when the OTel coexistence\n   * path observes an unrecoverable auto-attach failure.\n   * Distinct from `otel:injection_failed` (which carries a free-form\n   * `reason` string for logging) — `otel:failed` carries a\n   * machine-readable payload destined for the runtime-state CLI bridge.\n   *\n   * **PII-safety:** the payload's `message` is built from a fixed\n   * template; `providerClass` is a sanitized constructor name. See\n   * `RuntimeStateLastError` in `runtime-state.ts` for the full contract.\n   */\n  \"otel:failed\": {\n    category: \"auto-attach-returned-null\";\n    message: string;\n    timestamp: string;\n    providerClass?: string;\n  };\n  /**\n   * The export-path circuit breaker has tripped from CLOSED to OPEN.\n   * Fired exactly once per outage; the\n   * `category` discriminates the failure class that crossed the\n   * consecutive-failure threshold and `nextProbeMs` reports the\n   * scheduled HALF_OPEN delay.\n   *\n   * **PII-safety:** the payload's `message` is built from a fixed\n   * template and references only the closed `category` enum and the\n   * failure count; never URLs, headers, payload bodies, or the\n   * underlying error message text. Mirrors the `otel:failed`\n   * contract.\n   */\n  \"otel:circuit_opened\": {\n    category:\n      | \"auth\"\n      | \"client_error\"\n      | \"rate_limit\"\n      | \"server_error\"\n      | \"network\";\n    message: string;\n    timestamp: string;\n    consecutiveFailures: number;\n    nextProbeMs: number;\n  };\n  /**\n   * The breaker's backoff timer expired and the next real export\n   * batch is being permitted as a probe. `previousTimerMs`\n   * reports the timer that just elapsed; useful for surfacing a\n   * recovery-attempt diagnostic in the CLI bridge.\n   */\n  \"otel:circuit_half_open\": {\n    timestamp: string;\n    previousTimerMs: number;\n  };\n  /**\n   * The breaker has transitioned back to CLOSED, either because a\n   * probe succeeded or because credential rotation reset the breaker.\n   * `outageDurationMs` reports the wall-clock duration\n   * the breaker spent in OPEN+HALF_OPEN; `0` when the close was a\n   * defensive no-op (already CLOSED).\n   */\n  \"otel:circuit_closed\": {\n    timestamp: string;\n    outageDurationMs: number;\n  };\n  /**\n   * `tracedMiddleware` ran for a procedure invocation under a\n   * `wrapBatchedHttpHandler` batch envelope but could not resolve\n   * the invocation to a positional batch member (the\n   * `procedureName` does not appear in the envelope's procedure\n   * list, OR the per-name occurrence count exceeds the positional\n   * matches available). The middleware emits the span as today\n   * (no batch attributes); this event is informational only — the\n   * trace shape is preserved.\n   *\n   * **PII-safety:** `procedureName` and `batchMembers` are tRPC\n   * procedure names already on the trace; no new disclosure\n   * surface. `spanId` is the OTel span identifier of the\n   * unmatched member span.\n   */\n  \"otel:trpc_batch_member_mismatch\": {\n    procedureName: string;\n    batchMembers: ReadonlyArray<string>;\n    spanId: string;\n  };\n  \"otel:shutdown_started\": Record<string, never>;\n  \"otel:shutdown_completed\": Record<string, never>;\n\n  \"health:init_succeeded\": Record<string, never>;\n  \"health:init_failed\": { error: string };\n  \"health:heartbeat_tick\": Record<string, never>;\n  \"health:config_refreshed\": Record<string, never>;\n\n  /**\n   * `tracedRequestMiddleware` from `@glasstrace/sdk/middleware` was\n   * invoked but the SDK is not registered (early-init race or\n   * `OtelState.UNCONFIGURED`). The wrapped middleware still runs;\n   * the span landed on the OTel API's noop tracer and was discarded.\n   *\n   * Emitted at most once per process by the wrapper to avoid log\n   * floods on a hot request path; a single signal is sufficient to\n   * surface the misconfiguration.\n   *\n   * **PII-safety:** payload is empty by construction.\n   */\n  \"middleware:skipped_uninstalled\": Record<string, never>;\n  /**\n   * `withAsyncCausality` from `@glasstrace/sdk/async-context` was\n   * invoked outside an active request span (no captured\n   * `SpanContext` at call time). The continuation still runs; the\n   * resulting span has no `glasstrace.causal.post_response_async`\n   * link.\n   *\n   * Emitted at most once per process. **PII-safety:** payload is\n   * empty by construction.\n   */\n  \"async:no_originating_context\": Record<string, never>;\n  /**\n   * `withAsyncCausality` continuation fired but the SDK is not\n   * registered. The continuation still runs; the span landed on the\n   * noop tracer.\n   *\n   * Emitted at most once per process. **PII-safety:** payload is\n   * empty by construction.\n   */\n  \"async:skipped_uninstalled\": Record<string, never>;\n}\n\n// ---------------------------------------------------------------------------\n// Module State\n// ---------------------------------------------------------------------------\n\nlet _coreState: CoreState = CoreState.IDLE;\nlet _authState: AuthState = AuthState.ANONYMOUS;\nlet _otelState: OtelState = OtelState.UNCONFIGURED;\nlet _emitter: EventEmitter = new EventEmitter();\nlet _logger: ((level: \"warn\" | \"info\" | \"error\", message: string) => void) | null = null;\nlet _initialized = false;\nlet _initWarned = false;\nlet _coreReadyEmitted = false;\nlet _authInitialized = false;\nlet _emitting = false;\n\n// ---------------------------------------------------------------------------\n// Initialization\n// ---------------------------------------------------------------------------\n\n/**\n * Initialize the lifecycle module. Must be called before any state\n * transitions. Accepts a logger function to avoid importing SDK modules.\n *\n * Calling this twice logs a warning and is ignored.\n */\nexport function initLifecycle(options: {\n  logger: (level: \"warn\" | \"info\" | \"error\", message: string) => void;\n}): void {\n  if (_initialized) {\n    options.logger(\"warn\", \"[glasstrace] initLifecycle() called twice — ignored.\");\n    return;\n  }\n  _logger = options.logger;\n  _initialized = true;\n\n  // Register the lifecycle-emit bridge so edge-safe wrappers\n  // (`./middleware/index.ts`, `./async-context/index.ts`) can emit\n  // lifecycle events without a static import on this Node-only\n  // module. See `./optional-lifecycle.ts` for the contract.\n  _registerLifecycleEmitForBridge((event, payload) => {\n    emitLifecycleEvent(\n      event as keyof SdkLifecycleEvents,\n      payload as SdkLifecycleEvents[keyof SdkLifecycleEvents],\n    );\n  });\n}\n\n// ---------------------------------------------------------------------------\n// State Transitions\n// ---------------------------------------------------------------------------\n\n/** Warn once if lifecycle functions are called before initLifecycle(). */\nfunction warnIfNotInitialized(): void {\n  if (!_initialized && !_initWarned) {\n    _initWarned = true;\n    // Use console.warn directly since _logger is null\n    console.warn(\n      \"[glasstrace] Lifecycle state changed before initLifecycle() was called. \" +\n      \"Logger not available — errors will be silent.\",\n    );\n  }\n}\n\n/**\n * Transition the core lifecycle state. Invalid transitions are logged\n * and ignored — the state does not change.\n *\n * Guards against reentrant calls: if a listener calls setCoreState()\n * during emission, the inner transition completes first. The outer\n * call's post-transition events (core:ready, shutdown) check the\n * current state before emitting to avoid stale signals.\n */\nexport function setCoreState(to: CoreState): void {\n  warnIfNotInitialized();\n\n  const from = _coreState;\n  if (from === to) return;\n\n  const valid = VALID_CORE_TRANSITIONS[from];\n  if (!valid.includes(to)) {\n    _logger?.(\n      \"warn\",\n      `[glasstrace] Invalid core state transition: ${from} → ${to}. Ignored.`,\n    );\n    return;\n  }\n\n  _coreState = to;\n\n  // Guard against reentrant emission: if a listener calls setCoreState(),\n  // the inner call will complete (including its own events). The outer call\n  // skips its post-transition events to avoid stale/duplicate signals.\n  if (_emitting) return;\n\n  _emitting = true;\n  try {\n    emitSafe(\"core:state_changed\", { from, to });\n\n    // Check current state (not `to`) in case a listener changed it\n    const current = _coreState;\n\n    if (!_coreReadyEmitted && (current === CoreState.ACTIVE || current === CoreState.ACTIVE_DEGRADED)) {\n      _coreReadyEmitted = true;\n      emitSafe(\"core:ready\", {});\n    }\n\n    if (current === CoreState.SHUTTING_DOWN) {\n      emitSafe(\"core:shutdown_started\", {});\n    }\n    if (current === CoreState.SHUTDOWN) {\n      emitSafe(\"core:shutdown_completed\", {});\n    }\n  } finally {\n    _emitting = false;\n  }\n\n  // Catch-up after entering ACTIVE: if a degradation source was\n  // pushed while core was still in a pre-ACTIVE state\n  // (KEY_PENDING/KEY_RESOLVED), `recomputeCoreFromDegradationSources()`\n  // no-op'd at push time because the guard said \"only act if core is\n  // ACTIVE\". Now that we've reached ACTIVE, re-evaluate so the\n  // registry's truth wins (Codex P1, 2026-05-08; covers the export\n  // circuit + future degradation sources uniformly).\n  if (to === CoreState.ACTIVE && _degradationSources.size > 0) {\n    recomputeCoreFromDegradationSources();\n  }\n}\n\n/**\n * Set the initial auth state. Must be called exactly once during\n * registration, before any auth transitions. This bypasses transition\n * validation because the initial state (ANONYMOUS vs AUTHENTICATED)\n * is determined by configuration, not by a runtime transition.\n *\n * Subsequent calls log a warning and are ignored.\n */\nexport function initAuthState(state: AuthState): void {\n  if (_authInitialized) {\n    _logger?.(\n      \"warn\",\n      \"[glasstrace] initAuthState() called after auth state already initialized. Ignored.\",\n    );\n    return;\n  }\n  _authInitialized = true;\n  _authState = state;\n}\n\n/**\n * Transition the auth lifecycle state. Invalid transitions are logged\n * and ignored.\n */\nexport function setAuthState(to: AuthState): void {\n  warnIfNotInitialized();\n\n  const from = _authState;\n  if (from === to) return;\n\n  const valid = VALID_AUTH_TRANSITIONS[from];\n  if (!valid.includes(to)) {\n    _logger?.(\n      \"warn\",\n      `[glasstrace] Invalid auth state transition: ${from} → ${to}. Ignored.`,\n    );\n    return;\n  }\n\n  _authState = to;\n}\n\n/**\n * Transition the OTel coexistence state. Invalid transitions are logged\n * and ignored.\n */\nexport function setOtelState(to: OtelState): void {\n  warnIfNotInitialized();\n\n  const from = _otelState;\n  if (from === to) return;\n\n  const valid = VALID_OTEL_TRANSITIONS[from];\n  if (!valid.includes(to)) {\n    _logger?.(\n      \"warn\",\n      `[glasstrace] Invalid OTel state transition: ${from} → ${to}. Ignored.`,\n    );\n    return;\n  }\n\n  _otelState = to;\n}\n\n// ---------------------------------------------------------------------------\n// Degradation Source Registry (DISC-1568 / Wave 15C)\n//\n// Multiple subsystems can independently push the SDK into\n// `CoreState.ACTIVE_DEGRADED`. Each source registers a key here when\n// it goes degraded and clears the same key when it recovers.\n// `recomputeCoreFromDegradationSources()` reads the registry and\n// transitions `ACTIVE ↔ ACTIVE_DEGRADED` only when the SDK is in one\n// of those two states — `OtelState.COEXISTENCE_FAILED` and other\n// pre-`ACTIVE` states are untouched.\n//\n// Keys are namespaced strings (e.g., `\"export-circuit\"`) so multiple\n// sources can coexist without clobbering each other. Centralising the\n// recompute prevents the \"two sources of truth\" bug where one source\n// thinks the SDK is healthy but another still has it degraded.\n// ---------------------------------------------------------------------------\n\nconst _degradationSources = new Set<string>();\n\n/**\n * Register a subsystem-specific degradation source. Idempotent — calling\n * twice with the same key has no additional effect. After updating the\n * registry the function calls {@link recomputeCoreFromDegradationSources}\n * so a transition fires immediately when appropriate.\n */\nexport function pushDegradationSource(key: string): void {\n  _degradationSources.add(key);\n  recomputeCoreFromDegradationSources();\n}\n\n/**\n * Clear a previously-registered degradation source. Triggers a\n * recompute so the SDK can return to `CoreState.ACTIVE` if no other\n * source remains.\n */\nexport function clearDegradationSource(key: string): void {\n  _degradationSources.delete(key);\n  recomputeCoreFromDegradationSources();\n}\n\n/**\n * Re-evaluate the core state against the degradation registry:\n *\n * - At least one source AND core is `ACTIVE` → transition to\n *   `ACTIVE_DEGRADED`.\n * - Zero sources AND core is `ACTIVE_DEGRADED` → transition to\n *   `ACTIVE`.\n * - Otherwise: no-op. We do not push a pre-ACTIVE state forward and\n *   we do not transition out of terminal/shutdown states.\n *\n * Centralised so a future degradation source (e.g., heartbeat\n * failures) can reuse the same path without duplicating the guard.\n */\nexport function recomputeCoreFromDegradationSources(): void {\n  const hasDegradation = _degradationSources.size > 0;\n  if (hasDegradation && _coreState === CoreState.ACTIVE) {\n    setCoreState(CoreState.ACTIVE_DEGRADED);\n    return;\n  }\n  if (!hasDegradation && _coreState === CoreState.ACTIVE_DEGRADED) {\n    setCoreState(CoreState.ACTIVE);\n  }\n}\n\n// ---------------------------------------------------------------------------\n// State Queries\n// ---------------------------------------------------------------------------\n\n/** Returns the current core lifecycle state. */\nexport function getCoreState(): CoreState {\n  return _coreState;\n}\n\n/** Returns the current auth lifecycle state. */\nexport function getAuthState(): AuthState {\n  return _authState;\n}\n\n/** Returns the current OTel coexistence state. */\nexport function getOtelState(): OtelState {\n  return _otelState;\n}\n\n/** Returns the full internal state across all layers. */\nexport function getSdkState(): {\n  core: CoreState;\n  auth: AuthState;\n  otel: OtelState;\n} {\n  return {\n    core: _coreState,\n    auth: _authState,\n    otel: _otelState,\n  };\n}\n\n// ---------------------------------------------------------------------------\n// Event Emitter\n// ---------------------------------------------------------------------------\n\n/**\n * Subscribe to a lifecycle event. The listener is synchronous.\n * Errors in listeners are caught and logged.\n */\nexport function onLifecycleEvent<K extends keyof SdkLifecycleEvents>(\n  event: K,\n  listener: (payload: SdkLifecycleEvents[K]) => void,\n): void {\n  _emitter.on(event, listener);\n}\n\n/**\n * Emit a typed lifecycle event. Exported so that other SDK modules\n * (auth, OTel, health) can emit their layer-specific events through\n * the shared emitter with type safety.\n */\nexport function emitLifecycleEvent<K extends keyof SdkLifecycleEvents>(\n  event: K,\n  payload: SdkLifecycleEvents[K],\n): void {\n  emitSafe(event, payload);\n}\n\n/**\n * Unsubscribe from a lifecycle event.\n */\nexport function offLifecycleEvent<K extends keyof SdkLifecycleEvents>(\n  event: K,\n  listener: (payload: SdkLifecycleEvents[K]) => void,\n): void {\n  _emitter.off(event, listener);\n}\n\n/**\n * Emit a lifecycle event. Each listener is called individually so that\n * an error in one listener does not prevent subsequent listeners from\n * running. Both synchronous throws and async rejections are caught and\n * logged via the lifecycle logger.\n */\nfunction emitSafe<K extends keyof SdkLifecycleEvents>(\n  event: K,\n  payload: SdkLifecycleEvents[K],\n): void {\n  const listeners = _emitter.listeners(event);\n  for (const listener of listeners) {\n    try {\n      const result = (listener as (p: SdkLifecycleEvents[K]) => unknown)(payload);\n      // Catch async listeners that return a rejected promise\n      if (result && typeof (result as Promise<unknown>).catch === \"function\") {\n        (result as Promise<unknown>).catch((err: unknown) => {\n          _logger?.(\n            \"error\",\n            `[glasstrace] Async error in lifecycle event listener for \"${event}\": ${\n              err instanceof Error ? err.message : String(err)\n            }`,\n          );\n        });\n      }\n    } catch (err) {\n      _logger?.(\n        \"error\",\n        `[glasstrace] Error in lifecycle event listener for \"${event}\": ${\n          err instanceof Error ? err.message : String(err)\n        }`,\n      );\n    }\n  }\n}\n\n// ---------------------------------------------------------------------------\n// Readiness API\n// ---------------------------------------------------------------------------\n\n/**\n * Returns true when the SDK is in ACTIVE or ACTIVE_DEGRADED state.\n */\nexport function isReady(): boolean {\n  return _coreState === CoreState.ACTIVE || _coreState === CoreState.ACTIVE_DEGRADED;\n}\n\n/**\n * Resolves when the SDK reaches ACTIVE or ACTIVE_DEGRADED.\n * Rejects on PRODUCTION_DISABLED, REGISTRATION_FAILED, or timeout.\n *\n * Checks current state synchronously first — resolves/rejects immediately\n * if the SDK has already reached a terminal or ready state.\n */\nexport function waitForReady(timeoutMs = 30000): Promise<void> {\n  // Check current state synchronously\n  if (isReady()) {\n    return Promise.resolve();\n  }\n  if (\n    _coreState === CoreState.PRODUCTION_DISABLED ||\n    _coreState === CoreState.REGISTRATION_FAILED ||\n    _coreState === CoreState.SHUTTING_DOWN ||\n    _coreState === CoreState.SHUTDOWN\n  ) {\n    return Promise.reject(new Error(`SDK is in terminal state: ${_coreState}`));\n  }\n\n  return new Promise<void>((resolve, reject) => {\n    let settled = false;\n\n    const listener = ({ to }: { from: CoreState; to: CoreState }) => {\n      if (settled) return;\n      if (to === CoreState.ACTIVE || to === CoreState.ACTIVE_DEGRADED) {\n        settled = true;\n        offLifecycleEvent(\"core:state_changed\", listener);\n        resolve();\n      } else if (\n        to === CoreState.PRODUCTION_DISABLED ||\n        to === CoreState.REGISTRATION_FAILED ||\n        to === CoreState.SHUTTING_DOWN ||\n        to === CoreState.SHUTDOWN\n      ) {\n        settled = true;\n        offLifecycleEvent(\"core:state_changed\", listener);\n        reject(new Error(`SDK reached terminal state: ${to}`));\n      }\n    };\n\n    onLifecycleEvent(\"core:state_changed\", listener);\n\n    if (timeoutMs > 0) {\n      const timer = setTimeout(() => {\n        if (settled) return;\n        settled = true;\n        offLifecycleEvent(\"core:state_changed\", listener);\n        reject(new Error(`waitForReady timed out after ${timeoutMs}ms (state: ${_coreState})`));\n      }, timeoutMs);\n      // unref() so this timer doesn't prevent process exit\n      if (typeof timer === \"object\" && \"unref\" in timer) {\n        timer.unref();\n      }\n    }\n  });\n}\n\n/**\n * Simplified public state query for external consumers.\n * Hides implementation details like coexistence scenarios.\n *\n * The returned `tracing` field is the canonical user-observable signal\n * for OTel coexistence outcomes:\n *\n * - `\"active\"` — the SDK owns the OTel provider and is exporting spans.\n * - `\"coexistence\"` — another OTel provider was detected and the SDK\n *   either auto-attached its span processor or found one already\n *   present. Spans are exported through the existing pipeline.\n * - `\"degraded\"` — the SDK is exporting but the core lifecycle entered\n *   `ACTIVE_DEGRADED` (e.g., a non-fatal export failure).\n * - `\"not-configured\"` — the SDK could not configure tracing. Covers\n *   `OtelState.UNCONFIGURED`, `OtelState.CONFIGURING`, and\n *   `OtelState.COEXISTENCE_FAILED` (the Next 16 production\n *   \"auto-attach returned null\" path). When the value is\n *   `\"not-configured\"` after `registerGlasstrace()` has resolved,\n *   spans are NOT reaching the Glasstrace exporter and the manual\n *   `createGlasstraceSpanProcessor()` workaround should be applied.\n *   See `runtime-state.json`'s `lastError` field for the structured\n *   failure record.\n */\nexport function getStatus(): {\n  ready: boolean;\n  mode: \"anonymous\" | \"authenticated\" | \"claiming\" | \"disabled\";\n  tracing: \"active\" | \"degraded\" | \"not-configured\" | \"coexistence\";\n} {\n  let mode: \"anonymous\" | \"authenticated\" | \"claiming\" | \"disabled\";\n  if (_coreState === CoreState.PRODUCTION_DISABLED) {\n    mode = \"disabled\";\n  } else if (_authState === AuthState.CLAIMING || _authState === AuthState.CLAIMED) {\n    mode = \"claiming\";\n  } else if (_authState === AuthState.AUTHENTICATED) {\n    mode = \"authenticated\";\n  } else {\n    mode = \"anonymous\";\n  }\n\n  let tracing: \"active\" | \"degraded\" | \"not-configured\" | \"coexistence\";\n  if (_otelState === OtelState.COEXISTENCE_FAILED || _otelState === OtelState.UNCONFIGURED || _otelState === OtelState.CONFIGURING) {\n    tracing = \"not-configured\";\n  } else if (_coreState === CoreState.ACTIVE_DEGRADED) {\n    tracing = \"degraded\";\n  } else if (_otelState === OtelState.AUTO_ATTACHED || _otelState === OtelState.PROCESSOR_PRESENT) {\n    tracing = \"coexistence\";\n  } else {\n    tracing = \"active\";\n  }\n\n  return {\n    ready: isReady(),\n    mode,\n    tracing,\n  };\n}\n\n// ---------------------------------------------------------------------------\n// Shutdown Coordinator\n//\n// IMPORTANT: The shutdown system has two parts that must stay in sync:\n//   1. HOOKS — registered via registerShutdownHook() by each module\n//   2. TRIGGERS — registerSignalHandlers() for signal-based exit, or\n//      registerBeforeExitTrigger() for event-loop-drain exit. Both\n//      call executeShutdown() which is idempotent.\n//\n// Rules for agents modifying shutdown behavior:\n//   - When registering a hook, verify its trigger exists in the same PR.\n//     A hook without a trigger is dead code.\n//   - When removing a trigger, verify no hooks depend on it.\n//     A trigger removal without hook cleanup drops spans on exit.\n//   - Scenario A (bare path): register BOTH signal handlers AND\n//     beforeExit trigger. Signals cover SIGTERM/SIGINT, beforeExit\n//     covers clean event loop drain (all timers unref'd).\n//   - Scenario B (coexistence): signal handlers are ALWAYS installed\n//     (DISC-1265) but do NOT re-raise (coexistenceState=\"coexisting\").\n//     The beforeExit trigger also fires for event-loop-drain exit.\n//     The existing provider owns signal re-raise and its own flush.\n// ---------------------------------------------------------------------------\n\nexport interface ShutdownHook {\n  name: string;\n  priority: number;\n  fn: () => Promise<void>;\n}\n\nlet _shutdownHooks: ShutdownHook[] = [];\nlet _signalHandlersRegistered = false;\nlet _signalHandler: ((signal: NodeJS.Signals) => void) | null = null;\nlet _beforeExitRegistered = false;\nlet _beforeExitHandler: (() => void) | null = null;\nlet _shutdownExecuted = false;\n\n/**\n * Register a shutdown hook. Hooks are executed in priority order\n * (lower number = earlier execution) during shutdown.\n */\nexport function registerShutdownHook(hook: ShutdownHook): void {\n  _shutdownHooks.push(hook);\n  _shutdownHooks.sort((a, b) => a.priority - b.priority);\n}\n\n/**\n * Execute all registered shutdown hooks in priority order.\n * Each hook runs with a timeout. Errors in individual hooks are caught\n * and logged — remaining hooks still execute.\n *\n * Idempotent: calling this multiple times has no effect after the first.\n */\nexport async function executeShutdown(timeoutMs = 5000): Promise<void> {\n  if (_shutdownExecuted) return;\n  _shutdownExecuted = true;\n\n  setCoreState(CoreState.SHUTTING_DOWN);\n\n  for (const hook of _shutdownHooks) {\n    try {\n      // Suppress unhandled rejection on the hook promise if the timeout wins the race.\n      const hookPromise = hook.fn();\n      hookPromise.catch(() => {});\n\n      await Promise.race([\n        hookPromise,\n        new Promise<void>((_, reject) => {\n          const timer = setTimeout(() => reject(new Error(`Shutdown hook \"${hook.name}\" timed out`)), timeoutMs);\n          if (typeof timer === \"object\" && \"unref\" in timer) {\n            timer.unref();\n          }\n        }),\n      ]);\n    } catch (err) {\n      _logger?.(\n        \"warn\",\n        `[glasstrace] Shutdown hook \"${hook.name}\" failed: ${\n          err instanceof Error ? err.message : String(err)\n        }`,\n      );\n    }\n  }\n\n  setCoreState(CoreState.SHUTDOWN);\n}\n\n/**\n * Register SIGTERM and SIGINT handlers that trigger the shutdown coordinator.\n * Always installed by registerGlasstrace(), regardless of whether another\n * OTel provider exists. The re-raise decision is deferred to\n * delivery time: the handler checks coexistenceState (set by configureOtel()\n * once its async provider probe completes) and only re-raises when NOT\n * \"coexisting\". In coexistence mode, hooks still run but the existing\n * provider is responsible for re-raising the signal.\n */\nexport function registerSignalHandlers(): void {\n  if (_signalHandlersRegistered) return;\n  if (typeof process === \"undefined\" || typeof process.once !== \"function\") return;\n\n  _signalHandlersRegistered = true;\n\n  // Snapshot listener counts BEFORE we install our own handlers. A non-zero\n  // count means another party (Sentry, Datadog, the existing provider) already\n  // owns SIGTERM/SIGINT and will re-raise when it is done flushing. Zero means\n  // nobody else handles the signal — if we don't re-raise, the process hangs.\n  // This check is needed because `coexistenceState === \"coexisting\"` only tells\n  // us that ANOTHER OTEL PROVIDER exists, not that it installed signal handlers.\n  // A bare BasicTracerProvider has no signal handlers, so we must still re-raise.\n  const otherSigtermListeners = process.listenerCount(\"SIGTERM\");\n  const otherSigintListeners = process.listenerCount(\"SIGINT\");\n\n  const handler = (signal: NodeJS.Signals) => {\n    void executeShutdown().finally(() => {\n      // Remove our handler to avoid re-entry on re-raise.\n      if (_signalHandler) {\n        process.removeListener(\"SIGTERM\", _signalHandler);\n        process.removeListener(\"SIGINT\", _signalHandler);\n      }\n      // Re-raise the signal to restore default OS behavior UNLESS we are in\n      // coexistence mode AND the other provider had its own signal handlers at\n      // registration time. When both conditions hold, that provider owns signal\n      // re-raise and will terminate the process on its own schedule; re-raising\n      // here would race against its async flush and could kill the process\n      // before buffered spans are delivered.\n      //\n      // When coexisting but NO pre-existing signal listeners were detected, we\n      // must still re-raise — the other provider (e.g. a bare BasicTracerProvider)\n      // has no signal ownership, so OS default termination will not happen\n      // otherwise and the process would hang indefinitely.\n      //\n      // During the async-window (\"unknown\"), re-raise is the safe default because\n      // it preserves standard process termination semantics when we have no\n      // information about provider ownership.\n      const otherListeners = signal === \"SIGTERM\" ? otherSigtermListeners : otherSigintListeners;\n      const otherProviderOwnsSignal = getCoexistenceState() === \"coexisting\" && otherListeners > 0;\n      if (!otherProviderOwnsSignal) {\n        process.kill(process.pid, signal);\n      }\n    });\n  };\n\n  _signalHandler = handler;\n  process.once(\"SIGTERM\", handler);\n  process.once(\"SIGINT\", handler);\n}\n\n/**\n * Register a beforeExit handler that triggers the shutdown coordinator.\n * beforeExit fires when the event loop drains (not on signals).\n *\n * For Scenario B (coexistence): Glasstrace installs signal handlers\n * but does not re-raise — the existing provider owns signal re-raise. This\n * beforeExit trigger covers the edge case where the process exits without\n * signals (event loop drains naturally).\n *\n * Both signal handlers and beforeExit triggers call the same executeShutdown(),\n * which is idempotent — if signals already ran shutdown, beforeExit is a no-op.\n */\nexport function registerBeforeExitTrigger(): void {\n  if (_beforeExitRegistered) return;\n  if (typeof process === \"undefined\" || typeof process.once !== \"function\") return;\n\n  _beforeExitRegistered = true;\n\n  const handler = () => {\n    void executeShutdown();\n  };\n\n  _beforeExitHandler = handler;\n  process.once(\"beforeExit\", handler);\n}\n\n// ---------------------------------------------------------------------------\n// Testing\n// ---------------------------------------------------------------------------\n\n/**\n * Reset all lifecycle state to initial values. For testing only.\n * Removes all event listeners, resets all state enums, and clears\n * the initialized flag.\n */\nexport function resetLifecycleForTesting(): void {\n  _coreState = CoreState.IDLE;\n  _authState = AuthState.ANONYMOUS;\n  _otelState = OtelState.UNCONFIGURED;\n  _emitter.removeAllListeners();\n  _emitter = new EventEmitter();\n  _logger = null;\n  _initialized = false;\n  _initWarned = false;\n  _coreReadyEmitted = false;\n  _authInitialized = false;\n  _emitting = false;\n  _shutdownHooks = [];\n  _shutdownExecuted = false;\n  _degradationSources.clear();\n  if (_signalHandler && typeof process !== \"undefined\") {\n    process.removeListener(\"SIGTERM\", _signalHandler);\n    process.removeListener(\"SIGINT\", _signalHandler);\n  }\n  _signalHandler = null;\n  _signalHandlersRegistered = false;\n  if (_beforeExitHandler && typeof process !== \"undefined\") {\n    process.removeListener(\"beforeExit\", _beforeExitHandler);\n  }\n  _beforeExitHandler = null;\n  _beforeExitRegistered = false;\n  _clearLifecycleEmitForBridge();\n}\n","/**\n * Build-time metadata plumbed to the runtime exporter.\n *\n * Today this module exposes a single value — the build hash — which the\n * SDK stamps on every server span as `glasstrace.build.hash`. The value\n * is read once from `process.env.GLASSTRACE_BUILD_HASH` at module load\n * and cached. The intended convention is for the deploy / build step to\n * set the env var to `git rev-parse HEAD` (or the equivalent CI commit\n * SHA) so the runtime span and the upload-time source-map manifest\n * agree on the same hash. Ingestion uses the value to construct the\n * sourcemap blob key (`sourcemaps/{accountId}/{buildHash}/{file}`); a\n * mismatched or missing hash means the dashboard cannot render mapped\n * frames for the affected traces.\n *\n * The captured value is shape-validated against the typical git SHA\n * pattern (7-64 hex characters, covering abbreviated SHA-1, full\n * SHA-1, and full SHA-256). On mismatch the SDK logs a one-shot\n * warning and continues startup — the build hash is informational\n * metadata, not a correctness requirement, so misconfiguration must\n * never prevent the SDK from starting.\n *\n * @remarks\n * Node-only. The read happens at module load on a Node process where\n * `process.env` is always defined — this module is imported only by\n * `enriching-exporter.ts`, which is itself excluded from the edge\n * bundle by the F003 runtime-partition gate (see\n * `scripts/check-edge-bundle.mjs`). Importing this file from an edge\n * bundle would crash at evaluation when the bundler resolves the\n * `process.env` access; the gate catches that as a build-time\n * regression.\n */\n\nimport { sdkLog } from \"./console-capture.js\";\n\n/**\n * Sentinel value indicating the runtime did not provide a build hash.\n *\n * The exporter checks for this rather than `undefined` so a future\n * configuration mistake (e.g., setting the env var to an empty string)\n * is handled identically to \"unset\" — the attribute is omitted from\n * the span rather than written as a misleading empty value.\n */\nconst UNSET = \"\" as const;\n\n/**\n * Regex matching the typical git build-hash shape: 7-64 hexadecimal\n * characters, case-insensitive. Covers:\n *\n *   - abbreviated SHA-1 (`git rev-parse --short HEAD` defaults to 7+)\n *   - full SHA-1 (40 chars)\n *   - full SHA-256 (64 chars; git supports SHA-256 since 2.29)\n *\n * Anchored at both ends so internal whitespace, path-traversal\n * characters, and non-hex bytes all trigger the mismatch warning.\n * The Latin-only `[0-9a-f]` character class deliberately excludes\n * Unicode homoglyphs (e.g., Cyrillic `а` U+0430), which would\n * otherwise pass a casual visual review but fail blob-key lookup.\n */\nconst SHA_SHAPE = /^[0-9a-f]{7,64}$/i;\n\n/**\n * Redact a captured value for safe inclusion in a diagnostic warning.\n *\n * Mirrors the {@link maskKey} convention used by `register.ts` for\n * opaque tokens: short values become `xxxx...`; longer values become\n * `xxxxxxxx...yyyy`. A user who accidentally substitutes a secret\n * for the build-hash env var (e.g.,\n * `GLASSTRACE_BUILD_HASH=$SOME_SECRET`) sees at most a redacted\n * prefix in the SDK warning, never the full secret value.\n *\n * The build-hash itself is not sensitive, but defense-in-depth\n * dictates that any env-var value echoed back to logs is redacted —\n * the SDK cannot distinguish a legitimate non-SHA build identifier\n * from a misconfigured secret at the read site.\n *\n * Control bytes (`\\x00`-`\\x1F` and DEL `\\x7F`) are replaced with `?`\n * before insertion into the warning. Without this, an env-var value\n * containing `\\n` / `\\r` / `\\t` / `\\x1B` (escape) would corrupt log\n * formatting, enable log-injection attacks against downstream log\n * aggregators, or hide the surrounding warning text under a terminal\n * control sequence.\n */\nfunction redactBuildHash(value: string): string {\n  // eslint-disable-next-line no-control-regex\n  const sanitize = (s: string): string => s.replace(/[\\x00-\\x1F\\x7F]/g, \"?\");\n  if (value.length <= 12) return sanitize(value.slice(0, 4)) + \"...\";\n  return sanitize(value.slice(0, 8)) + \"...\" + sanitize(value.slice(-4));\n}\n\n/**\n * Read `GLASSTRACE_BUILD_HASH` from the environment and normalize it.\n * Trim whitespace; an empty/whitespace-only string is indistinguishable\n * from unset. When the trimmed value does not match the typical SHA\n * shape, log a one-shot warning and still return the value — the SDK\n * never refuses to start over a metadata field.\n *\n * Called lazily from {@link getBuildHash} on first access (not at\n * module load). This avoids firing the diagnostic warning during\n * build-time entry points that incidentally evaluate this module\n * (e.g., `withGlasstraceConfig` running under `next build`); the\n * warning is reserved for the runtime exporter path.\n */\nfunction readBuildHashFromEnv(): string {\n  const raw = process.env.GLASSTRACE_BUILD_HASH;\n  if (typeof raw !== \"string\") return UNSET;\n  const trimmed = raw.trim();\n  if (trimmed.length === 0) return UNSET;\n  if (!SHA_SHAPE.test(trimmed)) {\n    sdkLog(\n      \"warn\",\n      `[glasstrace] warning: GLASSTRACE_BUILD_HASH=${redactBuildHash(trimmed)} ` +\n        `does not match expected SHA shape (7-64 hex characters); ` +\n        `source-map enrichment may not work as expected.`,\n    );\n  }\n  return trimmed;\n}\n\nlet cachedBuildHash: string | null = null;\n\n/**\n * Returns the build hash captured from `process.env.GLASSTRACE_BUILD_HASH`\n * on first access, or `undefined` when the env var was unset, empty, or\n * whitespace-only.\n *\n * The value is captured once on the first call and cached for the\n * lifetime of the process: a deployment that rotates the env var\n * after the SDK starts cannot retroactively re-tag in-flight spans\n * with a value the source-map manifest does not know about. The\n * deferred read also keeps build-time entry points (config wrappers\n * that incidentally evaluate this module) from firing the SHA-shape\n * warning — the warning fires only when the runtime exporter\n * actually requests the hash.\n */\nexport function getBuildHash(): string | undefined {\n  if (cachedBuildHash === null) {\n    cachedBuildHash = readBuildHashFromEnv();\n  }\n  return cachedBuildHash === UNSET ? undefined : cachedBuildHash;\n}\n\n/**\n * Returns the build hash only when it matches the expected SHA shape,\n * otherwise `undefined`. Intended for contexts that echo the value into\n * logs (e.g., the decision-trace correlation suffix): a non-SHA value may\n * be a misconfigured secret substituted for the env var, so it must never\n * be printed. A non-SHA value is also useless as a correlation key — it\n * cannot match the source-map manifest — so suppressing it loses nothing.\n */\nexport function getCorrelationBuildHash(): string | undefined {\n  const hash = getBuildHash();\n  if (hash === undefined || !SHA_SHAPE.test(hash)) return undefined;\n  return hash;\n}\n","/**\n * Decision tracing — make the SDK's silent config-decision points\n * observable behind a single ON/OFF toggle that defaults OFF.\n *\n * Many of the SDK's capture / emit / redact decisions are decided\n * silently: when capture produces nothing, an operator or a validator\n * cannot tell *which* config gate closed. This module adds a thin,\n * behavior-neutral emitter that every instrumented gate calls at the\n * moment it decides. It routes through the SDK's existing plumbing — the\n * internal console logger (`sdkLog`) for human debugging and the\n * in-process lifecycle bus (`core:decision`) for programmatic\n * assertions — so no new logging subsystem is introduced.\n *\n * The emitter is a strict no-op when the toggle is OFF, never changes a\n * branch outcome, never throws into the caller, and never prints a\n * secret or a rejected value.\n *\n * This module reads `process.env` directly (the early-bootstrap gate\n * below), so it is **Node-only by design** and must not be wired into\n * the edge bundle or any `/edge` subpath export.\n */\n\nimport { sdkLog } from \"./console-capture.js\";\nimport { emitLifecycleEvent } from \"./lifecycle.js\";\nimport { getCorrelationBuildHash } from \"./build-info.js\";\n\n/**\n * The stable diagnostic id of an instrumented SDK decision point.\n *\n * Part of the SDK's stable diagnostic contract: existing members are\n * immutable (validators and tests match on them); the union may be\n * extended with new points in a minor release. Ids are case-sensitive,\n * dot-separated, camelCase components (for example\n * `capture.fidelity.hmacKey`) — the dotted path mirrors the config\n * surface the gate reads.\n *\n * The full Priority 1–5 inventory is declared here up front so later\n * call-site additions do not widen the union.\n *\n * @internal\n */\nexport type DecisionPoint =\n  | \"capture.sideEffectEvidence\"\n  | \"capture.fidelity.identifier\"\n  | \"capture.fidelity.idModel\"\n  | \"capture.fidelity.hmacKey\"\n  | \"config.tier\"\n  | \"sideEffect.fieldRejected\"\n  | \"feature.consoleErrors\"\n  | \"feature.errorResponseBodies\"\n  | \"feature.discovery\"\n  | \"otel.path\"\n  | \"env.forceEnable\"\n  | \"env.nudgeSuppressed\"\n  | \"env.upgradeNoticeSuppressed\";\n\n/**\n * Optional detail for a decision emission.\n *\n * @internal\n */\nexport interface DecisionDetail {\n  /** Short, bounded reason from a closed, code-literal vocabulary. */\n  reason?: string;\n  /**\n   * Bounded, safe disambiguation tokens. Keys are always code-literals\n   * (never producer input); values follow the sensitive-value rule\n   * (never a raw secret, never a rejected value).\n   */\n  inputs?: Record<string, string | number | boolean>;\n  /** Dedup key for hot-path gates; when present, the line emits at most once per key. */\n  oneShotKey?: string;\n}\n\n/** Maximum number of distinct one-shot keys retained (bounded memory). */\nconst _DEDUP_MAX_KEYS = 100;\n\n/** Maximum number of `inputs` keys rendered (extra keys dropped in insertion order). */\nconst _MAX_INPUT_KEYS = 8;\n\n/** Maximum UTF-8 byte length of a rendered `inputs` value before truncation. */\nconst _MAX_INPUT_VALUE_BYTES = 100;\n\n/**\n * Number of characters of the build hash included in the correlation\n * stamp. The full hash is typically a 40-char SHA; a short prefix is\n * enough to correlate a decision line with a deployment.\n */\nconst _BUILD_HASH_PREFIX_LEN = 12;\n\n/**\n * The resolved decision-trace flag, set by `registerGlasstrace()` after\n * `resolveConfig()` runs (mirrors `setSideEffectVerboseFlag`). `null`\n * means \"not yet resolved\" — before the threaded flag is set, the gate\n * falls back to the raw env var so early-bootstrap emissions are not\n * silently dropped. Holds the folded `decisionTrace || verbose` value\n * once set.\n */\nlet _flag: boolean | null = null;\n\n/** One-shot keys already emitted this process, bounded by `_DEDUP_MAX_KEYS`. */\nconst _seenKeys = new Set<string>();\n\n/**\n * Set the resolved decision-trace flag. Called from `registerGlasstrace()`\n * with `decisionTrace || verbose`. Not exposed from the public package\n * barrel — internal coordination only.\n *\n * @internal\n */\nexport function setDecisionTraceFlag(enabled: boolean): void {\n  _flag = enabled;\n}\n\n/**\n * The single decision-trace gate. Returns `true` when decision tracing\n * is on.\n *\n * Two phases share one predicate:\n *\n *   - **After `setDecisionTraceFlag` has run** (the common case), the\n *     resolved, folded flag governs — `decisionTrace || verbose`.\n *   - **Before it runs** (decisions decided during early bootstrap, before\n *     `setDecisionTraceFlag` is threaded, such as\n *     `env.upgradeNoticeSuppressed`), the resolved flag does not yet exist,\n *     so the gate reads the raw env var directly. This is correct by\n *     necessity: `verbose` comes from resolved config that does not exist\n *     that early, so the env var (`GLASSTRACE_DECISION_TRACE`) is the only\n *     available pre-config signal — such a point is reachable only via the\n *     env var, not the programmatic `decisionTrace` / `verbose` option.\n *\n * @internal\n */\nexport function decisionTraceEnabled(): boolean {\n  if (_flag !== null) return _flag;\n  return process.env.GLASSTRACE_DECISION_TRACE === \"true\";\n}\n\n/**\n * Emit a single decision-trace line (and, when subscribed, a\n * `core:decision` lifecycle event) for an instrumented decision point.\n *\n * No-op when the toggle is OFF. On hot paths the caller MUST additionally\n * guard with `decisionTraceEnabled()` before building `detail`, because\n * the `detail` argument is evaluated before this function is entered —\n * the first-line guard here is defence-in-depth for cold paths and a\n * missed call-site guard, not a substitute for the call-site guard.\n *\n * The whole body is fenced: a throwing host `console` or lifecycle\n * listener can never disrupt the behavior-neutral path.\n *\n * @internal\n */\nexport function decisionTrace(\n  point: DecisionPoint,\n  outcome: string,\n  detail?: DecisionDetail,\n): void {\n  if (!decisionTraceEnabled()) return;\n\n  try {\n    // One-shot / dedup on hot paths. Once the cap is reached, new keys\n    // are silently skipped — better to lose a late line than grow without\n    // bound. A key seen before suppresses the repeat.\n    const key = detail?.oneShotKey;\n    if (key !== undefined) {\n      if (_seenKeys.has(key)) return;\n      if (_seenKeys.size >= _DEDUP_MAX_KEYS) return;\n      _seenKeys.add(key);\n    }\n\n    const safeInputs = boundInputs(detail?.inputs);\n\n    sdkLog(\"info\", formatLine(point, outcome, detail?.reason, safeInputs));\n\n    emitLifecycleEvent(\"core:decision\", {\n      point,\n      outcome,\n      ...(detail?.reason !== undefined ? { reason: detail.reason } : {}),\n      ...(safeInputs !== undefined ? { inputs: safeInputs } : {}),\n    });\n  } catch {\n    // Diagnostic deliverability is best-effort; never propagate into the\n    // caller's path.\n  }\n}\n\n/**\n * Apply the `inputs` bounds: at most `_MAX_INPUT_KEYS` keys (extra keys\n * dropped in insertion order); each value coerced to a string/number/\n * boolean with string values truncated to `_MAX_INPUT_VALUE_BYTES` UTF-8\n * bytes (trailing `…` when truncated); `undefined` / `null` values\n * omitted. Returns `undefined` when nothing survives so the caller can\n * omit the field entirely.\n */\nfunction boundInputs(\n  inputs: Record<string, string | number | boolean> | undefined,\n): Record<string, string | number | boolean> | undefined {\n  if (inputs === undefined) return undefined;\n  const out: Record<string, string | number | boolean> = {};\n  let count = 0;\n  for (const k of Object.keys(inputs)) {\n    if (count >= _MAX_INPUT_KEYS) break;\n    const v = inputs[k];\n    if (v === undefined || v === null) continue;\n    out[k] = typeof v === \"string\" ? truncateUtf8(v, _MAX_INPUT_VALUE_BYTES) : v;\n    count++;\n  }\n  return count > 0 ? out : undefined;\n}\n\n/**\n * Truncate a string to at most `maxBytes` UTF-8 bytes, appending a\n * trailing `…` when truncation occurred. Truncates on a character\n * boundary so a multi-byte code point is never split.\n */\nfunction truncateUtf8(value: string, maxBytes: number): string {\n  const encoder = new TextEncoder();\n  if (encoder.encode(value).length <= maxBytes) return value;\n  let out = \"\";\n  let bytes = 0;\n  for (const ch of value) {\n    const chBytes = encoder.encode(ch).length;\n    if (bytes + chBytes > maxBytes) break;\n    out += ch;\n    bytes += chBytes;\n  }\n  return out + \"…\";\n}\n\n/**\n * Render the single decision line:\n * `[glasstrace] decision: <point>=<outcome> (<reason>; <inputs>) [build=…]`.\n *\n * The exact `[glasstrace]` prefix (closing bracket included) routes the\n * line past console-capture; the `decision:` discriminator follows the\n * closing bracket so the guard still matches. The `(<reason>; <inputs>)`\n * group and the `[...]` correlation suffix are each omitted when empty.\n */\nfunction formatLine(\n  point: string,\n  outcome: string,\n  reason: string | undefined,\n  inputs: Record<string, string | number | boolean> | undefined,\n): string {\n  let line = `[glasstrace] decision: ${point}=${outcome}`;\n\n  const inner = renderInner(reason, inputs);\n  if (inner.length > 0) {\n    line += ` (${inner})`;\n  }\n\n  const suffix = renderCorrelation();\n  if (suffix.length > 0) {\n    line += ` ${suffix}`;\n  }\n\n  return line;\n}\n\n/** Render the `<reason>; <inputs>` inner group; empty string when both absent. */\nfunction renderInner(\n  reason: string | undefined,\n  inputs: Record<string, string | number | boolean> | undefined,\n): string {\n  const parts: string[] = [];\n  if (reason !== undefined) parts.push(reason);\n  if (inputs !== undefined) {\n    const rendered = Object.keys(inputs)\n      .map((k) => `${k}=${String(inputs[k])}`)\n      .join(\",\");\n    if (rendered.length > 0) parts.push(rendered);\n  }\n  return parts.join(\"; \");\n}\n\n/**\n * Render the optional `[build=…]` correlation suffix, or the empty string\n * when no build hash is present (the suffix never blocks emission on a\n * missing correlation value).\n *\n * Only the build token is stamped: a session id is deliberately not\n * threaded into the emitter, since that would couple every hot-path gate\n * to the api key. The bracket group is present only when a SHA-shaped\n * build hash is available, and absent otherwise. The SHA-shape gate\n * (via `getCorrelationBuildHash()`) ensures a misconfigured\n * `GLASSTRACE_BUILD_HASH` holding a non-SHA secret is never echoed into\n * the decision line, upholding the emitter's no-secret guarantee.\n */\nfunction renderCorrelation(): string {\n  const tokens: string[] = [];\n  const build = getCorrelationBuildHash();\n  if (build !== undefined && build.length > 0) {\n    tokens.push(`build=${build.slice(0, _BUILD_HASH_PREFIX_LEN)}`);\n  }\n  return tokens.length > 0 ? `[${tokens.join(\" \")}]` : \"\";\n}\n\n/**\n * Test-only reset for the decision-trace toggle and dedup state. Not\n * exposed from the public package barrel. Tests must call this between\n * describe blocks so the toggle and one-shot state do not leak.\n *\n * @internal\n */\nexport function _resetDecisionTraceForTesting(): void {\n  _flag = null;\n  _seenKeys.clear();\n}\n","import * as fs from \"node:fs/promises\";\nimport * as path from \"node:path\";\nimport * as crypto from \"node:crypto\";\nimport { execFileSync } from \"node:child_process\";\nimport { sdkLog } from \"./console-capture.js\";\nimport {\n  SourceMapUploadResponseSchema,\n  type SourceMapUploadResponse,\n  PresignedUploadResponseSchema,\n  type PresignedUploadResponse,\n  SourceMapManifestResponseSchema,\n  type SourceMapManifestResponse,\n} from \"@glasstrace/protocol\";\n\n/**\n * In-memory source map entry: a file path paired with its full text content.\n *\n * @remarks\n * Node-only. Describes the legacy in-memory shape consumed by\n * {@link uploadSourceMaps} and {@link uploadSourceMapsAuto}. The type\n * itself erases at runtime and is safe to import from edge code, but\n * every function that produces or consumes it depends on `node:fs`\n * and cannot run at the edge.\n */\nexport interface SourceMapEntry {\n  filePath: string;\n  content: string;\n}\n\n/**\n * Metadata for a discovered source map file, without its content loaded.\n * Used by the streaming upload flow to defer file reads until upload time.\n *\n * @remarks\n * Node-only. Describes the shape of data produced by the Node-only\n * source-map upload flow ({@link discoverSourceMapFiles},\n * {@link uploadSourceMapsAuto}). The type itself erases at runtime and\n * is safe to import from edge code, but every function that produces\n * or consumes it depends on `node:fs`/`node:path` and cannot run at\n * the edge.\n */\nexport interface SourceMapFileInfo {\n  /** Relative path to the compiled JS file (`.map` extension stripped). */\n  filePath: string;\n  /** Absolute path on disk for reading the file content on demand. */\n  absolutePath: string;\n  /** File size in bytes. */\n  sizeBytes: number;\n}\n\n/** Threshold (50 MB) above which a single source map triggers a warning. */\nconst LARGE_FILE_WARNING_BYTES = 50 * 1024 * 1024;\n\n/**\n * Recursively discovers all `.map` files in the given build directory.\n * Returns metadata only — file content is NOT read into memory.\n *\n * @remarks\n * Node-only. Walks the filesystem with `node:fs/promises` (`readdir`,\n * `stat`) and resolves paths with `node:path`. No edge-safe\n * alternative — call from a Node context (build script, Next.js\n * `next.config.ts`, CI job).\n */\nexport async function discoverSourceMapFiles(\n  buildDir: string,\n): Promise<SourceMapFileInfo[]> {\n  // Resolve to absolute so absolutePath in results is always absolute,\n  // even when buildDir is relative (e.g. \".next\").\n  const resolvedDir = path.resolve(buildDir);\n  const results: SourceMapFileInfo[] = [];\n\n  try {\n    await walkDirMetadata(resolvedDir, resolvedDir, results);\n  } catch {\n    // Directory doesn't exist or is unreadable — return empty\n    return [];\n  }\n\n  // Warn about oversized source map files\n  for (const file of results) {\n    if (file.sizeBytes >= LARGE_FILE_WARNING_BYTES) {\n      const sizeMB = (file.sizeBytes / (1024 * 1024)).toFixed(1);\n      sdkLog(\n        \"warn\",\n        `[glasstrace] Large source map detected: ${file.filePath} (${sizeMB}MB). Consider enabling source map compression.`,\n      );\n    }\n  }\n\n  return results;\n}\n\nasync function walkDirMetadata(\n  baseDir: string,\n  currentDir: string,\n  results: SourceMapFileInfo[],\n): Promise<void> {\n  let entries: import(\"node:fs\").Dirent[];\n  try {\n    entries = await fs.readdir(currentDir, { withFileTypes: true });\n  } catch {\n    return;\n  }\n\n  for (const entry of entries) {\n    const fullPath = path.join(currentDir, entry.name);\n\n    if (entry.isDirectory()) {\n      await walkDirMetadata(baseDir, fullPath, results);\n    } else if (entry.isFile() && entry.name.endsWith(\".map\")) {\n      try {\n        const stat = await fs.stat(fullPath);\n        const relativePath = path.relative(baseDir, fullPath).replace(/\\\\/g, \"/\");\n        // Strip the trailing .map extension so the key matches the compiled\n        // JS path that the runtime uses for stack-frame lookups (e.g.\n        // \"static/chunks/main.js\" instead of \"static/chunks/main.js.map\").\n        const compiledPath = relativePath.replace(/\\.map$/, \"\");\n        results.push({\n          filePath: compiledPath,\n          absolutePath: fullPath,\n          sizeBytes: stat.size,\n        });\n      } catch {\n        // Skip unreadable files\n      }\n    }\n  }\n}\n\n/**\n * Reads the content of a single source map file from disk.\n */\nasync function readSourceMapContent(absolutePath: string): Promise<string> {\n  return fs.readFile(absolutePath, \"utf-8\");\n}\n\n/**\n * Recursively finds all .map files in the given build directory.\n * Returns relative paths and file contents.\n *\n * @deprecated Prefer {@link discoverSourceMapFiles} to avoid loading all\n * source maps into memory simultaneously.\n *\n * @remarks\n * Node-only. Reads every discovered `.map` file into memory via\n * `node:fs/promises` (`readFile`). No edge-safe alternative — call\n * from a Node context (build script, Next.js `next.config.ts`, CI job).\n */\nexport async function collectSourceMaps(\n  buildDir: string,\n): Promise<SourceMapEntry[]> {\n  const fileInfos = await discoverSourceMapFiles(buildDir);\n  const results: SourceMapEntry[] = [];\n\n  for (const info of fileInfos) {\n    try {\n      const content = await readSourceMapContent(info.absolutePath);\n      results.push({ filePath: info.filePath, content });\n    } catch {\n      // Skip unreadable files — consistent with previous behavior\n    }\n  }\n\n  return results;\n}\n\n/**\n * Computes a build hash for source map uploads.\n *\n * First tries `git rev-parse HEAD` to get the git commit SHA.\n * On failure, falls back to a deterministic content hash:\n * sort source map file paths alphabetically, concatenate each as\n * `{relativePath}\\n{fileLength}\\n{fileContent}`, then SHA-256 the result.\n *\n * Accepts either `SourceMapEntry[]` (legacy, in-memory) or\n * `SourceMapFileInfo[]` (streaming, reads on demand).\n *\n * @remarks\n * Node-only. Spawns `git rev-parse HEAD` via `node:child_process`\n * (`execFileSync`), hashes with `node:crypto` (`createHash(\"sha256\")`),\n * and reads map contents from disk with `node:fs/promises`. No\n * edge-safe alternative — call from a Node context (build script,\n * Next.js `next.config.ts`, CI job). If a pre-computed build hash is\n * already known (e.g., provided as a CI environment variable), pass\n * it directly to {@link uploadSourceMaps} instead of calling this\n * helper.\n */\nexport async function computeBuildHash(\n  maps?: SourceMapEntry[] | SourceMapFileInfo[],\n): Promise<string> {\n  // Try git first\n  try {\n    const sha = execFileSync(\"git\", [\"rev-parse\", \"HEAD\"], { encoding: \"utf-8\" }).trim();\n    if (sha) {\n      return sha;\n    }\n  } catch {\n    // Git not available, fall through to content hash\n  }\n\n  // Fallback: content-based hash\n  const sortedMaps = [...(maps ?? [])].sort((a, b) =>\n    a.filePath.localeCompare(b.filePath),\n  );\n\n  const hash = crypto.createHash(\"sha256\");\n\n  for (const m of sortedMaps) {\n    let content: string;\n    if (\"content\" in m) {\n      content = m.content;\n    } else {\n      try {\n        content = await readSourceMapContent(m.absolutePath);\n      } catch {\n        // Skip unreadable files — consistent with collectSourceMaps behavior\n        continue;\n      }\n    }\n    hash.update(`${m.filePath}\\n${content.length}\\n${content}`);\n  }\n\n  return hash.digest(\"hex\");\n}\n\n/**\n * Uploads source maps to the ingestion API.\n *\n * POSTs to `{endpoint}/v1/source-maps` with the API key, build hash,\n * and file entries. Validates the response against SourceMapUploadResponseSchema.\n *\n * Accepts either `SourceMapEntry[]` (legacy, in-memory) or\n * `SourceMapFileInfo[]` (deferred reads). With `SourceMapFileInfo[]`,\n * file content is read at upload time rather than at discovery time.\n * Note: the legacy endpoint sends all files in a single JSON body, so\n * peak memory is similar — the benefit is deferring reads past discovery.\n *\n * @remarks\n * Node-only. Reads map contents from disk via `node:fs/promises` when\n * invoked with `SourceMapFileInfo[]`. The network call uses the\n * platform-standard `fetch` (edge-safe on its own), but the upstream\n * discovery and read path is Node-only, so the function is only\n * reachable from a Node context (build script, Next.js\n * `next.config.ts`, CI job). No edge-safe alternative.\n */\nexport async function uploadSourceMaps(\n  apiKey: string,\n  endpoint: string,\n  buildHash: string,\n  maps: SourceMapEntry[] | SourceMapFileInfo[],\n): Promise<SourceMapUploadResponse> {\n  // Read files on demand — for SourceMapEntry[], content is already available;\n  // for SourceMapFileInfo[], each file is read individually to limit memory.\n  // Individual reads are guarded so one transient failure (deleted file,\n  // permission change) does not abort the entire upload.\n  const files: Array<{ filePath: string; sourceMap: string }> = [];\n  for (const m of maps) {\n    try {\n      const content = \"content\" in m\n        ? m.content\n        : await readSourceMapContent(m.absolutePath);\n      files.push({ filePath: m.filePath, sourceMap: content });\n    } catch {\n      sdkLog(\"warn\", `[glasstrace] Skipping unreadable source map: ${m.filePath}`);\n    }\n  }\n\n  const body = {\n    buildHash,\n    files,\n  };\n\n  const baseUrl = stripTrailingSlashes(endpoint);\n  const response = await fetch(`${baseUrl}/v1/source-maps`, {\n    method: \"POST\",\n    headers: {\n      \"Content-Type\": \"application/json\",\n      Authorization: `Bearer ${apiKey}`,\n    },\n    body: JSON.stringify(body),\n  });\n\n  if (!response.ok) {\n    // Consume the response body to release the connection back to the pool.\n    // Without this, the underlying TCP socket stays allocated until GC, which\n    // causes connection pool exhaustion under sustained error conditions.\n    // Wrapped in try-catch so a stream error doesn't mask the HTTP status error.\n    try { await response.text(); } catch { /* body drain is best-effort */ }\n    throw new Error(\n      `Source map upload failed: ${String(response.status)} ${response.statusText}`,\n    );\n  }\n\n  const json: unknown = await response.json();\n  return SourceMapUploadResponseSchema.parse(json);\n}\n\n// ---------------------------------------------------------------------------\n// Presigned source map upload (3-phase flow for large builds)\n// ---------------------------------------------------------------------------\n\n/**\n * Builds at or above this byte size route to the presigned upload flow.\n *\n * @remarks\n * Node-only. The numeric value itself is pure (a constant is evaluable\n * anywhere), but it is meaningful only alongside\n * {@link uploadSourceMapsPresigned} and {@link uploadSourceMapsAuto},\n * both of which depend on `node:fs` and `@vercel/blob`. No edge-safe\n * alternative — consume from a Node context.\n */\nexport const PRESIGNED_THRESHOLD_BYTES = 4_500_000;\n\n/**\n * Signature for the blob upload function, injectable for testing.\n *\n * @remarks\n * Node-only. Describes the shape of the uploader consumed by\n * {@link uploadSourceMapsPresigned} and {@link uploadSourceMapsAuto},\n * both of which depend on `@vercel/blob` and `node:fs`. The type itself\n * erases at runtime and is safe to import from edge code, but every\n * producer and consumer is Node-only.\n */\nexport type BlobUploader = (\n  clientToken: string,\n  pathname: string,\n  content: string,\n) => Promise<{ url: string; size: number }>;\n\n/**\n * Strips trailing slashes from a URL string.\n * Uses an iterative approach to avoid regex (CodeQL js/polynomial-redos).\n */\nfunction stripTrailingSlashes(url: string): string {\n  let result = url;\n  while (result.endsWith(\"/\")) {\n    result = result.slice(0, -1);\n  }\n  return result;\n}\n\n/**\n * Phase 1: Request presigned upload tokens from the ingestion API.\n *\n * POSTs to `{endpoint}/v1/source-maps/presign` with the build hash and\n * file metadata. Returns presigned tokens for each file that the client\n * uses to upload directly to blob storage.\n */\nexport async function requestPresignedTokens(\n  apiKey: string,\n  endpoint: string,\n  buildHash: string,\n  files: Array<{ filePath: string; sizeBytes: number }>,\n): Promise<PresignedUploadResponse> {\n  const baseUrl = stripTrailingSlashes(endpoint);\n  const response = await fetch(`${baseUrl}/v1/source-maps/presign`, {\n    method: \"POST\",\n    headers: {\n      \"Content-Type\": \"application/json\",\n      Authorization: `Bearer ${apiKey}`,\n    },\n    body: JSON.stringify({ buildHash, files }),\n  });\n\n  if (!response.ok) {\n    try { await response.text(); } catch { /* body drain is best-effort */ }\n    throw new Error(\n      `Presigned token request failed: ${String(response.status)} ${response.statusText}`,\n    );\n  }\n\n  const json: unknown = await response.json();\n  return PresignedUploadResponseSchema.parse(json);\n}\n\n/** Shape of the subset of `@vercel/blob/client` the SDK consumes. */\ntype BlobClientModule = {\n  put: (\n    pathname: string,\n    body: Blob,\n    options: { access: string; token: string },\n  ) => Promise<{ url: string }>;\n};\n\n/**\n * Loads `@vercel/blob/client` at runtime using the `Function()`-based\n * dynamic-import evasion trick.\n *\n * The indirection hides the specifier from static bundler analysis — webpack,\n * tsup, esbuild, and rollup all resolve literal `await import(\"...\")` targets\n * at build time and would raise `Module not found` for consumers without\n * `@vercel/blob` installed (it is an optional peer dependency).\n *\n * **CSP note:** `Function()` is semantically equivalent to `eval()` and will\n * trigger `unsafe-eval` CSP violations in restricted environments. Source-map\n * upload only runs in Node.js at build time, so CSP does not apply here. The\n * same caveat documented on `tryImport` in `otel-config.ts` applies if this\n * code is ever re-used in a browser-equivalent runtime.\n *\n * Exported for internal test injection via {@link _setBlobClientLoaderForTesting}\n * only; not part of the public API.\n */\nasync function defaultBlobClientLoader(): Promise<BlobClientModule> {\n  const dynamicImport = Function(\"id\", \"return import(id)\") as (\n    id: string,\n  ) => Promise<BlobClientModule>;\n  return dynamicImport(\"@vercel/blob/client\");\n}\n\nlet _blobClientLoader: () => Promise<BlobClientModule> = defaultBlobClientLoader;\n\n/**\n * Replaces the blob client loader. For test use only.\n *\n * The production loader uses a `Function()`-based dynamic import to evade\n * static bundler analysis, which in turn bypasses Vitest's\n * module-mock interceptor. Tests that need to stub `@vercel/blob/client`\n * call this helper to install a fake loader, then restore the default\n * with {@link _resetBlobClientLoaderForTesting}.\n *\n * @internal\n */\nexport function _setBlobClientLoaderForTesting(\n  loader: () => Promise<BlobClientModule>,\n): void {\n  _blobClientLoader = loader;\n}\n\n/**\n * Restores the default `@vercel/blob/client` loader. For test use only.\n *\n * @internal\n */\nexport function _resetBlobClientLoaderForTesting(): void {\n  _blobClientLoader = defaultBlobClientLoader;\n}\n\n/**\n * Phase 2: Upload a single source map to blob storage using a presigned token.\n *\n * Dynamically imports `@vercel/blob/client` via {@link defaultBlobClientLoader}\n * to avoid bundling the optional peer dependency. Throws a descriptive error\n * if the package is not installed.\n */\nexport async function uploadToBlob(\n  clientToken: string,\n  pathname: string,\n  content: string,\n): Promise<{ url: string; size: number }> {\n  let mod: BlobClientModule;\n  try {\n    mod = await _blobClientLoader();\n  } catch (err) {\n    // Distinguish \"not installed\" from other import errors\n    const code = (err as NodeJS.ErrnoException).code;\n    if (code === \"ERR_MODULE_NOT_FOUND\" || code === \"MODULE_NOT_FOUND\") {\n      throw new Error(\n        \"Presigned upload requires @vercel/blob. Install it: npm install @vercel/blob\",\n      );\n    }\n    throw err;\n  }\n\n  const result = await mod.put(pathname, new Blob([content]), {\n    access: \"public\",\n    token: clientToken,\n  });\n\n  return { url: result.url, size: Buffer.byteLength(content, \"utf-8\") };\n}\n\n/**\n * Phase 3: Submit the upload manifest to finalize a presigned upload.\n *\n * POSTs to `{endpoint}/v1/source-maps/manifest` with the upload ID,\n * build hash, and blob URLs for each uploaded file. The backend activates\n * the source maps for stack trace resolution.\n */\nexport async function submitManifest(\n  apiKey: string,\n  endpoint: string,\n  uploadId: string,\n  buildHash: string,\n  files: Array<{ filePath: string; sizeBytes: number; blobUrl: string }>,\n): Promise<SourceMapManifestResponse> {\n  const baseUrl = stripTrailingSlashes(endpoint);\n  const response = await fetch(`${baseUrl}/v1/source-maps/manifest`, {\n    method: \"POST\",\n    headers: {\n      \"Content-Type\": \"application/json\",\n      Authorization: `Bearer ${apiKey}`,\n    },\n    body: JSON.stringify({ uploadId, buildHash, files }),\n  });\n\n  if (!response.ok) {\n    try { await response.text(); } catch { /* body drain is best-effort */ }\n    throw new Error(\n      `Source map manifest submission failed: ${String(response.status)} ${response.statusText}`,\n    );\n  }\n\n  const json: unknown = await response.json();\n  return SourceMapManifestResponseSchema.parse(json);\n}\n\n/**\n * Orchestrates the 3-phase presigned upload flow.\n *\n * 1. Requests presigned tokens for all source map files\n * 2. Uploads each file to blob storage with a concurrency limit of 5,\n *    reading file content from disk just before each upload\n * 3. Submits the manifest to finalize the upload\n *\n * Accepts either `SourceMapEntry[]` (legacy, in-memory) or\n * `SourceMapFileInfo[]` (streaming, reads on demand).\n *\n * Accepts an optional `blobUploader` for test injection; defaults to\n * {@link uploadToBlob}.\n *\n * @remarks\n * Node-only. Streams map contents from disk via `node:fs/promises`\n * and uploads through `@vercel/blob/client` (loaded lazily as an\n * optional peer dependency). No edge-safe alternative — call from a\n * Node context (build script, Next.js `next.config.ts`, CI job).\n */\nexport async function uploadSourceMapsPresigned(\n  apiKey: string,\n  endpoint: string,\n  buildHash: string,\n  maps: SourceMapEntry[] | SourceMapFileInfo[],\n  blobUploader: BlobUploader = uploadToBlob,\n): Promise<SourceMapManifestResponse> {\n  if (maps.length === 0) {\n    throw new Error(\"No source maps to upload\");\n  }\n\n  // Determine file metadata for the presign request\n  const fileMetadata = maps.map((m) => ({\n    filePath: m.filePath,\n    sizeBytes: \"content\" in m\n      ? Buffer.byteLength(m.content, \"utf-8\")\n      : m.sizeBytes,\n  }));\n\n  // Phase 1: request presigned tokens\n  const presigned = await requestPresignedTokens(\n    apiKey, endpoint, buildHash, fileMetadata,\n  );\n\n  // Build a lookup map for O(1) access by filePath\n  const mapsByPath = new Map(maps.map((m) => [m.filePath, m]));\n\n  if (mapsByPath.size !== maps.length) {\n    throw new Error(\"Duplicate filePath entries in source maps\");\n  }\n\n  // Validate all tokens have matching entries before starting any uploads.\n  for (const token of presigned.files) {\n    if (!mapsByPath.has(token.filePath)) {\n      throw new Error(\n        `Presigned token for \"${token.filePath}\" has no matching source map entry`,\n      );\n    }\n  }\n\n  // Phase 2: upload to blob storage in chunks of CONCURRENCY.\n  // File content is read from disk just before each upload to avoid\n  // holding all source maps in memory simultaneously.\n  const CONCURRENCY = 5;\n  const uploadResults: Array<{ filePath: string; sizeBytes: number; blobUrl: string }> = [];\n\n  for (let i = 0; i < presigned.files.length; i += CONCURRENCY) {\n    const chunk = presigned.files.slice(i, i + CONCURRENCY);\n    const chunkResults = await Promise.all(\n      chunk.map(async (token) => {\n        const entry = mapsByPath.get(token.filePath)!;\n        let content: string;\n        if (\"content\" in entry) {\n          content = entry.content;\n        } else {\n          try {\n            content = await readSourceMapContent(entry.absolutePath);\n          } catch {\n            sdkLog(\"warn\", `[glasstrace] Skipping unreadable source map: ${token.filePath}`);\n            return null;\n          }\n        }\n        const result = await blobUploader(token.clientToken, token.pathname, content);\n        return {\n          filePath: token.filePath,\n          sizeBytes: result.size,\n          blobUrl: result.url,\n        };\n      }),\n    );\n    for (const r of chunkResults) {\n      if (r !== null) {\n        uploadResults.push(r);\n      }\n    }\n  }\n\n  // Phase 3: submit manifest\n  return submitManifest(apiKey, endpoint, presigned.uploadId, buildHash, uploadResults);\n}\n\n/**\n * Options for {@link uploadSourceMapsAuto}, primarily used for test injection.\n *\n * @remarks\n * Node-only. Describes the shape of overrides consumed by\n * {@link uploadSourceMapsAuto}, which depends on `node:fs` and\n * `@vercel/blob`. The type itself erases at runtime and is safe to\n * import from edge code, but the surrounding function is Node-only.\n */\nexport interface AutoUploadOptions {\n  /** Override blob availability check (for testing). */\n  checkBlobAvailable?: () => Promise<boolean>;\n  /** Override blob uploader (for testing). */\n  blobUploader?: BlobUploader;\n}\n\n/**\n * Automatically routes source map uploads based on total build size.\n *\n * - Below {@link PRESIGNED_THRESHOLD_BYTES}: uses the legacy single-request\n *   {@link uploadSourceMaps} endpoint.\n * - At or above the threshold: checks if `@vercel/blob` is available and\n *   uses the presigned 3-phase flow. Falls back to legacy with a warning\n *   if the package is not installed.\n *\n * Accepts either `SourceMapEntry[]` (legacy, in-memory) or\n * `SourceMapFileInfo[]` (streaming, reads on demand).\n *\n * @remarks\n * Node-only. Reads source map sizes/contents via `node:fs/promises`\n * and, above the threshold, dynamically loads `@vercel/blob/client`\n * (optional peer dependency) for direct blob storage uploads. No\n * edge-safe alternative — call from a Node context (build script,\n * Next.js `next.config.ts`, CI job). This is the recommended entry\n * point for source-map upload in most projects.\n */\nexport async function uploadSourceMapsAuto(\n  apiKey: string,\n  endpoint: string,\n  buildHash: string,\n  maps: SourceMapEntry[] | SourceMapFileInfo[],\n  options?: AutoUploadOptions,\n): Promise<SourceMapUploadResponse | SourceMapManifestResponse> {\n  if (maps.length === 0) {\n    throw new Error(\"No source maps to upload\");\n  }\n\n  const totalBytes = maps.reduce(\n    (sum, m) => {\n      const bytes = \"content\" in m\n        ? Buffer.byteLength(m.content, \"utf-8\")\n        : m.sizeBytes;\n      return sum + bytes;\n    },\n    0,\n  );\n\n  if (totalBytes < PRESIGNED_THRESHOLD_BYTES) {\n    return uploadSourceMaps(apiKey, endpoint, buildHash, maps);\n  }\n\n  // Check if @vercel/blob is available. Uses the shared blob client loader\n  // (which goes through the `Function()` evasion trick) so webpack / tsup /\n  // esbuild do not resolve `@vercel/blob/client` at build time (DISC-1255).\n  const checkAvailable = options?.checkBlobAvailable ?? (async () => {\n    try {\n      await _blobClientLoader();\n      return true;\n    } catch {\n      return false;\n    }\n  });\n\n  const blobAvailable = await checkAvailable();\n\n  if (blobAvailable) {\n    return uploadSourceMapsPresigned(\n      apiKey, endpoint, buildHash, maps, options?.blobUploader,\n    );\n  }\n\n  // Fall back to legacy upload with a warning\n  sdkLog(\"warn\",\n    `[glasstrace] Build exceeds 4.5MB (${String(totalBytes)} bytes). Install @vercel/blob for ` +\n    `presigned uploads to avoid serverless body size limits. Falling back to legacy upload.`\n  );\n\n  return uploadSourceMaps(apiKey, endpoint, buildHash, maps);\n}\n","/**\n * Node-runtime entry point for `@glasstrace/sdk`.\n *\n * Re-exports every symbol from the current root barrel whose transitive\n * import closure touches a Node built-in (`fs`, `path`, `events`,\n * `async_hooks`, `https`, `http`, `url`, `crypto`, `child_process`,\n * `module`, etc.) or `@vercel/blob`. This is the Node-only surface of\n * the SDK.\n *\n * The classification was produced by a per-symbol esbuild-probe\n * reconnaissance pass. This file, plus `edge-entry.ts`,\n * partitions the root barrel into two runtime-scoped views. The root\n * barrel (`index.ts`) is narrowed separately; a follow-up wires the\n * subpath exports map.\n *\n * Consumers do **not** import this file directly yet — `package.json`\n * `exports` still points every consumer at `./dist/index.js`.\n */\n\n// ---------- Symbols also re-exported from edge-entry (for completeness) ----------\n// Node runtimes have no reason to import the edge subset via a separate\n// entry; they can use this file alone.\n\nexport { SdkError } from \"./errors.js\";\n\nexport {\n  readEnvVars,\n  resolveConfig,\n  isProductionDisabled,\n  isAnonymousMode,\n} from \"./env-detection.js\";\nexport type { ResolvedConfig } from \"./env-detection.js\";\n\nexport {\n  deriveSessionId,\n  getOrigin,\n  getDateString,\n  SessionManager,\n} from \"./session.js\";\n\nexport { classifyFetchTarget } from \"./fetch-classifier.js\";\nexport type { FetchTarget } from \"./fetch-classifier.js\";\n\nexport { GlasstraceSpanProcessor } from \"./span-processor.js\";\n\nexport { captureCorrelationId } from \"./correlation-id.js\";\nexport type { CorrelationIdRequest } from \"./correlation-id.js\";\n\n// ---------- Node-only symbols (refuted from edge-entry) ----------\n\nexport { getOrCreateAnonKey, readAnonKey } from \"./anon-key.js\";\n\nexport {\n  loadCachedConfig,\n  saveCachedConfig,\n  sendInitRequest,\n  performInit,\n  getActiveConfig,\n  getLinkedAccountId,\n} from \"./init-client.js\";\nexport type { InitClaimResult } from \"./init-client.js\";\n\nexport { GlasstraceExporter } from \"./enriching-exporter.js\";\nexport type { GlasstraceExporterOptions } from \"./enriching-exporter.js\";\n\nexport {\n  registerGlasstrace,\n  getDiscoveryHandler,\n} from \"./register.js\";\n\nexport { withGlasstraceConfig } from \"./config-wrapper.js\";\n\nexport { isReady, waitForReady, getStatus } from \"./lifecycle.js\";\n\nexport { createGlasstraceSpanProcessor } from \"./coexistence.js\";\n\nexport { captureError } from \"./capture-error.js\";\n\n// ---------- Symbols also re-exported from node-subpath ----------\n// Mirrored here so the Node-only audience gets the full current surface\n// from a single entry; the subpath re-exports the same symbols at\n// `@glasstrace/sdk/node` (wired in SDK-030).\n\nexport {\n  discoverSourceMapFiles,\n  collectSourceMaps,\n  computeBuildHash,\n  uploadSourceMaps,\n  PRESIGNED_THRESHOLD_BYTES,\n  uploadSourceMapsPresigned,\n  uploadSourceMapsAuto,\n} from \"./source-map-uploader.js\";\nexport type {\n  SourceMapFileInfo,\n  SourceMapEntry,\n  BlobUploader,\n  AutoUploadOptions,\n} from \"./source-map-uploader.js\";\n\nexport {\n  discoverTestFiles,\n  extractImports,\n  buildImportGraph,\n} from \"./import-graph.js\";\n","import type { SdkDiagnosticCode } from \"@glasstrace/protocol\";\n\n/**\n * Internal SDK error class with a typed diagnostic code.\n * Caught at the boundary and converted to a log message + diagnostic entry.\n * Never thrown to the developer.\n */\nexport class SdkError extends Error {\n  readonly code: SdkDiagnosticCode;\n\n  constructor(code: SdkDiagnosticCode, message: string, cause?: Error) {\n    super(message, { cause });\n    this.name = \"SdkError\";\n    this.code = code;\n  }\n}\n","import { deriveSessionId } from \"@glasstrace/protocol\";\nimport type { SessionId } from \"@glasstrace/protocol\";\n\n/**\n * Re-export of {@link deriveSessionId} from `@glasstrace/protocol`. The\n * implementation lives in the protocol package so that non-SDK consumers\n * (for example the Glasstrace browser extension) can derive the same\n * session ID the SDK produces from the same inputs. SDK callers continue\n * to import it from `@glasstrace/sdk` for backward compatibility.\n */\nexport { deriveSessionId };\n\nconst FOUR_HOURS_MS = 4 * 60 * 60 * 1000;\n\n/** Cached at module load to avoid reading process.env on every span. */\nlet cachedGlasstraceEnv: string | undefined = process.env.GLASSTRACE_ENV;\nlet cachedPort: string = process.env.PORT ?? \"3000\";\n\n/**\n * Re-reads cached environment variables. For testing only.\n */\nexport function _resetEnvCacheForTesting(): void {\n  cachedGlasstraceEnv = process.env.GLASSTRACE_ENV;\n  cachedPort = process.env.PORT ?? \"3000\";\n}\n\n/**\n * Returns the origin string for the current process.\n * If GLASSTRACE_ENV is set, returns that value.\n * Otherwise returns `localhost:{PORT}` (PORT defaults to 3000).\n *\n * @returns The origin string used as a session derivation input.\n */\nexport function getOrigin(): string {\n  if (cachedGlasstraceEnv) {\n    return cachedGlasstraceEnv;\n  }\n  return `localhost:${cachedPort}`;\n}\n\n/**\n * Returns the current UTC date as a YYYY-MM-DD string.\n *\n * @returns The UTC date formatted as \"YYYY-MM-DD\".\n */\nexport function getDateString(): string {\n  const now = new Date();\n  const year = now.getUTCFullYear();\n  const month = String(now.getUTCMonth() + 1).padStart(2, \"0\");\n  const day = String(now.getUTCDate()).padStart(2, \"0\");\n  return `${year}-${month}-${day}`;\n}\n\n/**\n * Tracks the current session state with 4-hour window tracking.\n * Instantiated once by the orchestrator.\n */\nexport class SessionManager {\n  private windowIndex: number = 0;\n  private lastActivityTimestamp: number = 0;\n  private lastDate: string = \"\";\n  private lastApiKey: string = \"\";\n  private currentSessionId: SessionId | null = null;\n\n  /**\n   * Returns the current session ID, deriving a new one if:\n   * - More than 4 hours have elapsed since last activity\n   * - The UTC date has changed (resets window index to 0)\n   * - The API key has changed (e.g., deferred anonymous key swap)\n   * - This is the first call\n   *\n   * @param apiKey - The project's API key used in session derivation.\n   * @returns The current or newly derived SessionId.\n   */\n  getSessionId(apiKey: string): SessionId {\n    const now = Date.now();\n    const currentDate = getDateString();\n    const origin = getOrigin();\n\n    const elapsed = now - this.lastActivityTimestamp;\n    const dateChanged = currentDate !== this.lastDate;\n    const apiKeyChanged = apiKey !== this.lastApiKey;\n\n    if (dateChanged) {\n      // New UTC day: reset window index\n      this.windowIndex = 0;\n      this.lastDate = currentDate;\n      this.lastApiKey = apiKey;\n      this.currentSessionId = deriveSessionId(apiKey, origin, currentDate, this.windowIndex);\n    } else if (apiKeyChanged) {\n      // API key changed (e.g., anonymous key resolved): re-derive with same window\n      this.lastApiKey = apiKey;\n      this.currentSessionId = deriveSessionId(apiKey, origin, currentDate, this.windowIndex);\n    } else if (this.currentSessionId === null || elapsed > FOUR_HOURS_MS) {\n      // First call or gap exceeding 4 hours: increment window\n      if (this.currentSessionId !== null) {\n        this.windowIndex++;\n      }\n      this.lastApiKey = apiKey;\n      this.currentSessionId = deriveSessionId(apiKey, origin, currentDate, this.windowIndex);\n      this.lastDate = currentDate;\n    }\n\n    this.lastActivityTimestamp = now;\n    return this.currentSessionId;\n  }\n}\n","/**\n * The set of recognized fetch target categories.\n */\nexport type FetchTarget = \"supabase\" | \"stripe\" | \"internal\" | \"unknown\";\n\n/** Cached at module load to avoid reading process.env on every span. */\nlet cachedPort: string = process.env.PORT ?? \"3000\";\n\n/**\n * Re-reads cached environment variables. For testing only.\n */\nexport function _resetEnvCacheForTesting(): void {\n  cachedPort = process.env.PORT ?? \"3000\";\n}\n\n/**\n * Classifies an outbound fetch target URL into a known category.\n * Classification is case-insensitive and based on the URL hostname.\n * Uses dot-boundary matching to avoid false positives (e.g. evilstripe.com).\n *\n * Returns one of: 'supabase', 'stripe', 'internal', or 'unknown'.\n */\nexport function classifyFetchTarget(url: string): FetchTarget {\n  let parsed: URL;\n  try {\n    parsed = new URL(url);\n  } catch {\n    return \"unknown\";\n  }\n\n  const hostname = parsed.hostname.toLowerCase();\n\n  if (\n    hostname === \"supabase.co\" ||\n    hostname.endsWith(\".supabase.co\") ||\n    hostname === \"supabase.in\" ||\n    hostname.endsWith(\".supabase.in\")\n  ) {\n    return \"supabase\";\n  }\n\n  if (hostname === \"stripe.com\" || hostname.endsWith(\".stripe.com\")) {\n    return \"stripe\";\n  }\n\n  const internalOrigin = `localhost:${cachedPort}`;\n  const parsedPort = parsed.port || (parsed.protocol === \"https:\" ? \"443\" : \"80\");\n  const urlOrigin = `${hostname}:${parsedPort}`;\n\n  if (urlOrigin === internalOrigin) {\n    return \"internal\";\n  }\n\n  return \"unknown\";\n}\n","import type { SpanProcessor, ReadableSpan } from \"@opentelemetry/sdk-trace-base\";\nimport type { Span } from \"@opentelemetry/sdk-trace-base\";\nimport type { CaptureConfig } from \"@glasstrace/protocol\";\nimport type { SessionManager } from \"./session.js\";\n\n/**\n * Lightweight SpanProcessor that delegates to a wrapped processor.\n *\n * All glasstrace.* attribute enrichment has been moved to {@link GlasstraceExporter}\n * (see enriching-exporter.ts), which enriches spans at export time. This resolves:\n * - Cold-start spans are buffered in the exporter, not dropped\n * - Vercel's CompositeSpanProcessor skips onEnding(); the exporter doesn't need it\n * - Session ID is computed at export time with the resolved API key\n *\n * This class is retained for backward compatibility. New code should use\n * GlasstraceExporter directly.\n *\n * @deprecated Use GlasstraceExporter for span enrichment. This processor is now a pass-through.\n */\nexport class GlasstraceSpanProcessor implements SpanProcessor {\n  private readonly wrappedProcessor: SpanProcessor;\n\n  /* eslint-disable @typescript-eslint/no-unused-vars -- backward compat signature */\n  constructor(\n    wrappedProcessor: SpanProcessor,\n    _sessionManager?: SessionManager,\n    _apiKey?: string | (() => string),\n    _getConfig?: () => CaptureConfig,\n    _environment?: string,\n  ) {\n    /* eslint-enable @typescript-eslint/no-unused-vars */\n    this.wrappedProcessor = wrappedProcessor;\n  }\n\n  onStart(span: Span, parentContext: Parameters<SpanProcessor[\"onStart\"]>[1]): void {\n    this.wrappedProcessor.onStart(span, parentContext);\n  }\n\n  onEnd(readableSpan: ReadableSpan): void {\n    this.wrappedProcessor.onEnd(readableSpan);\n  }\n\n  async shutdown(): Promise<void> {\n    return this.wrappedProcessor.shutdown();\n  }\n\n  async forceFlush(): Promise<void> {\n    return this.wrappedProcessor.forceFlush();\n  }\n}\n","import { trace } from \"@opentelemetry/api\";\nimport { GLASSTRACE_ATTRIBUTE_NAMES } from \"@glasstrace/protocol\";\n\nconst ATTR = GLASSTRACE_ATTRIBUTE_NAMES;\nconst HEADER_NAME = \"x-gt-cid\";\n\n/**\n * Hard cap on the correlation ID length we accept from the wire. Our\n * own extension emits ULIDs (26 characters); 128 is a generous ceiling\n * that still prevents a hostile client from ballooning span payloads.\n */\nconst MAX_CID_LENGTH = 128;\n\n/**\n * Minimal Fetch-API `Headers`-like interface supporting case-insensitive\n * single-value lookup. Matches `Headers` from `undici` / the Web Fetch API.\n */\ninterface FetchHeadersLike {\n  get(name: string): string | null;\n}\n\n/**\n * Minimal Node `IncomingMessage.headers`-like shape: a dictionary mapping\n * (typically lower-cased) header names to a value, a list of values, or\n * `undefined`.\n */\ntype NodeHeadersLike = Record<\n  string,\n  string | string[] | undefined\n>;\n\n/**\n * Accepted request shape for {@link captureCorrelationId}. Intentionally\n * loose so callers can pass either a Fetch `Request` (or `NextRequest`)\n * or a Node `IncomingMessage` without adapting the type.\n */\nexport interface CorrelationIdRequest {\n  headers: FetchHeadersLike | NodeHeadersLike | undefined;\n}\n\n/**\n * Captures the Glasstrace correlation ID header (`x-gt-cid`) from an\n * incoming request and materializes it as the\n * `glasstrace.correlation.id` attribute on the currently active OTel span.\n *\n * The SDK does not own any HTTP instrumentation, so it cannot read this\n * header itself. Users opt in by calling this helper from a hook that\n * runs inside the request's OTel context — typically a Next.js\n * `middleware.ts` or a custom server request handler.\n *\n * The function is intentionally forgiving:\n * - No active span → no-op.\n * - Missing / empty header → no-op.\n * - Array header values (Node IncomingMessage) → the first non-empty\n *   value is used; subsequent values are ignored because a correlation\n *   ID is a single logical value.\n * - Malformed or unexpected `headers` shapes → caught and ignored; the\n *   helper never throws.\n *\n * @example\n * ```ts\n * // Next.js middleware.ts\n * import { captureCorrelationId } from \"@glasstrace/sdk\";\n *\n * export function middleware(req: Request) {\n *   captureCorrelationId(req);\n *   return NextResponse.next();\n * }\n * ```\n */\nexport function captureCorrelationId(req: CorrelationIdRequest | null | undefined): void {\n  try {\n    if (!req || !req.headers) {\n      return;\n    }\n\n    const value = readHeader(req.headers);\n    if (!value) {\n      return;\n    }\n\n    const span = trace.getActiveSpan();\n    if (!span) {\n      return;\n    }\n\n    span.setAttribute(ATTR.CORRELATION_ID, value);\n  } catch {\n    // Never throw from a request hook — correlation is a best-effort\n    // enrichment and must not break the user's request pipeline.\n  }\n}\n\n/**\n * Reads the `x-gt-cid` header from either a Fetch-API `Headers` object\n * or a Node-style dictionary. Returns a trimmed single value, or\n * `undefined` if the header is missing or empty.\n */\nfunction readHeader(\n  headers: FetchHeadersLike | NodeHeadersLike,\n): string | undefined {\n  // Fetch-API Headers: duck-type on `.get(name)` being a function.\n  const asFetch = headers as FetchHeadersLike;\n  if (typeof asFetch.get === \"function\") {\n    const raw = asFetch.get(HEADER_NAME);\n    return firstToken(raw);\n  }\n\n  // Node IncomingMessage headers: case-insensitive dictionary lookup.\n  // Node normalizes to lower-case but some frameworks preserve case, so\n  // scan keys defensively.\n  const dict = headers as NodeHeadersLike;\n  const direct = dict[HEADER_NAME];\n  if (direct !== undefined) {\n    return firstValue(direct);\n  }\n\n  for (const key of Object.keys(dict)) {\n    if (key.toLowerCase() === HEADER_NAME) {\n      return firstValue(dict[key]);\n    }\n  }\n\n  return undefined;\n}\n\n/**\n * Picks the first value from a possibly-array header and trims it.\n * Correlation IDs are logically single-valued; when duplicated we keep\n * the first occurrence and drop the rest.\n *\n * Also handles the comma-joined form that intermediaries (and some\n * Node.js HTTP stacks) produce when the same header is sent multiple\n * times — `x-gt-cid: cid1, x-gt-cid: cid2` may surface as the single\n * string `\"cid1, cid2\"` via `Headers.get()` or `IncomingMessage.headers`.\n * Storing that raw merged value would both fail correlation and\n * silently suppress the Server Action nudge (which only\n * checks attribute presence, not validity). We split on commas and\n * keep the first non-empty token.\n */\nfunction firstValue(value: string | string[] | undefined): string | undefined {\n  if (Array.isArray(value)) {\n    for (const entry of value) {\n      const token = firstToken(entry);\n      if (token) return token;\n    }\n    return undefined;\n  }\n  return firstToken(value);\n}\n\n/**\n * Extracts the first comma-separated token from a header-like string\n * and normalizes it. Returns undefined when no non-empty token exists\n * within the length bound.\n */\nfunction firstToken(value: string | null | undefined): string | undefined {\n  if (typeof value !== \"string\") return undefined;\n  // Split on commas (HTTP list-header separator). Trim each token and\n  // return the first non-empty one that fits within MAX_CID_LENGTH.\n  // A single un-merged header has no commas and this reduces to the\n  // previous normalize() behavior.\n  const parts = value.split(\",\");\n  for (const part of parts) {\n    const trimmed = part.trim();\n    if (trimmed.length === 0) continue;\n    if (trimmed.length > MAX_CID_LENGTH) return undefined;\n    return trimmed;\n  }\n  return undefined;\n}\n","import { AnonApiKeySchema, DevApiKeySchema, createAnonApiKey } from \"@glasstrace/protocol\";\nimport type { AnonApiKey, DevApiKey } from \"@glasstrace/protocol\";\n\nconst GLASSTRACE_DIR = \".glasstrace\";\nconst ANON_KEY_FILE = \"anon_key\";\nconst CLAIMED_KEY_FILE = \"claimed-key\";\n\n/**\n * Lazily imports `node:fs/promises` and `node:path`. Returns `null` if\n * the modules are unavailable (non-Node environments). The result is\n * cached after first resolution.\n */\nlet fsPathCache: { fs: typeof import(\"node:fs/promises\"); path: typeof import(\"node:path\") } | null | undefined;\n\nasync function loadFsPath(): Promise<{ fs: typeof import(\"node:fs/promises\"); path: typeof import(\"node:path\") } | null> {\n  if (fsPathCache !== undefined) return fsPathCache;\n  try {\n    const [fs, path] = await Promise.all([\n      import(\"node:fs/promises\"),\n      import(\"node:path\"),\n    ]);\n    fsPathCache = { fs, path };\n    return fsPathCache;\n  } catch {\n    fsPathCache = null;\n    return null;\n  }\n}\n\n/**\n * In-memory cache for ephemeral keys when filesystem persistence fails.\n * Keyed by resolved project root to support multiple roots in tests.\n */\nconst ephemeralKeyCache = new Map<string, AnonApiKey>();\n\n/**\n * Reads an existing anonymous key from the filesystem.\n * Returns the key if valid, or null if:\n * - The file does not exist\n * - The file content is invalid\n * - An I/O error occurs\n * - `node:fs` is unavailable (non-Node environment)\n */\nexport async function readAnonKey(projectRoot?: string): Promise<AnonApiKey | null> {\n  const root = projectRoot ?? process.cwd();\n\n  const modules = await loadFsPath();\n  if (modules) {\n    const keyPath = modules.path.join(root, GLASSTRACE_DIR, ANON_KEY_FILE);\n    try {\n      const content = await modules.fs.readFile(keyPath, \"utf-8\");\n      const result = AnonApiKeySchema.safeParse(content);\n      if (result.success) {\n        return result.data;\n      }\n    } catch {\n      // Fall through to check ephemeral cache\n    }\n  }\n\n  // Check in-memory cache (used when filesystem persistence failed\n  // or when node:fs is unavailable)\n  const cached = ephemeralKeyCache.get(root);\n  if (cached !== undefined) {\n    return cached;\n  }\n\n  return null;\n}\n\n/**\n * Reads a claimed developer API key persisted at\n * `.glasstrace/claimed-key`. The file is the runtime fallback used by\n * {@link import(\"./init-client.js\").writeClaimedKey} when `.env.local`\n * is not writable.\n *\n * Returns the key when the file exists and its contents pass\n * `DevApiKeySchema` validation. Returns `null` when:\n * - The file does not exist.\n * - The file content fails strict schema validation (a malformed or\n *   stale value cannot be distinguished from a valid one without a\n *   server roundtrip — callers should treat this as \"no key\").\n * - An I/O error occurs.\n * - `node:fs` is unavailable (non-Node environment).\n */\nexport async function readClaimedKey(projectRoot?: string): Promise<DevApiKey | null> {\n  const root = projectRoot ?? process.cwd();\n\n  const modules = await loadFsPath();\n  if (!modules) return null;\n\n  const keyPath = modules.path.join(root, GLASSTRACE_DIR, CLAIMED_KEY_FILE);\n  try {\n    const content = await modules.fs.readFile(keyPath, \"utf-8\");\n    const trimmed = content.trim();\n    const parsed = DevApiKeySchema.safeParse(trimmed);\n    if (parsed.success) {\n      return parsed.data;\n    }\n  } catch {\n    // Fall through — file missing, unreadable, or invalid; treat as absent.\n  }\n\n  return null;\n}\n\n/**\n * Gets an existing anonymous key from the filesystem, or creates a new one.\n *\n * - If file exists and contains a valid key, returns it\n * - If file does not exist or content is invalid, generates a new key via createAnonApiKey()\n * - Writes the new key to `.glasstrace/anon_key`, creating the directory if needed\n * - On file write failure: logs a warning, caches an ephemeral in-memory key so\n *   repeated calls in the same process return the same key\n * - In non-Node environments: returns an ephemeral in-memory key\n */\nexport async function getOrCreateAnonKey(projectRoot?: string): Promise<AnonApiKey> {\n  const root = projectRoot ?? process.cwd();\n\n  // Try reading existing key from filesystem\n  const existingKey = await readAnonKey(root);\n  if (existingKey !== null) {\n    return existingKey;\n  }\n\n  // Check in-memory cache (used when filesystem is unavailable)\n  const cached = ephemeralKeyCache.get(root);\n  if (cached !== undefined) {\n    return cached;\n  }\n\n  // Generate a new key\n  const newKey = createAnonApiKey();\n\n  // Attempt filesystem persistence (only in Node.js environments)\n  const modules = await loadFsPath();\n  if (!modules) {\n    // No filesystem access — cache in memory\n    ephemeralKeyCache.set(root, newKey);\n    return newKey;\n  }\n\n  const dirPath = modules.path.join(root, GLASSTRACE_DIR);\n  const keyPath = modules.path.join(dirPath, ANON_KEY_FILE);\n\n  // Persist to filesystem using atomic create-or-fail (O_CREAT | O_EXCL)\n  // to prevent TOCTOU races where concurrent cold starts both generate keys.\n  try {\n    await modules.fs.mkdir(dirPath, { recursive: true, mode: 0o700 });\n    await modules.fs.writeFile(keyPath, newKey, { flag: \"wx\", mode: 0o600 });\n    return newKey;\n  } catch (err) {\n    const code = (err as NodeJS.ErrnoException).code;\n    if (code === \"EEXIST\") {\n      // Another process won the race. Retry reading their key with\n      // short delays — the winner's writeFile is atomic for small\n      // payloads but the filesystem may not have flushed yet.\n      for (let attempt = 0; attempt < 3; attempt++) {\n        const winnerKey = await readAnonKey(root);\n        if (winnerKey !== null) {\n          return winnerKey;\n        }\n        // Short delay before next retry (50ms), skip after final attempt\n        if (attempt < 2) {\n          await new Promise((resolve) => setTimeout(resolve, 50));\n        }\n      }\n      // All retries exhausted — overwrite as last resort.\n      // Use explicit chmod after overwrite since writeFile mode only\n      // applies on creation on some platforms.\n      try {\n        await modules.fs.writeFile(keyPath, newKey, { mode: 0o600 });\n        await modules.fs.chmod(keyPath, 0o600);\n        return newKey;\n      } catch {\n        // Overwrite failed — fall through to ephemeral cache\n      }\n    }\n\n    // Non-EEXIST error (EACCES, ENOTDIR, etc.) — cache in memory so\n    // repeated calls get the same ephemeral key within this process.\n    ephemeralKeyCache.set(root, newKey);\n    console.warn(\n      `[glasstrace] Failed to persist anonymous key to ${keyPath}: ${err instanceof Error ? err.message : String(err)}. Using ephemeral key.`,\n    );\n    return newKey;\n  }\n}\n","import {\n  SdkInitResponseSchema,\n  SdkCachedConfigSchema,\n  DEFAULT_CAPTURE_CONFIG,\n} from \"@glasstrace/protocol\";\nimport type {\n  SdkInitResponse,\n  CaptureConfig,\n  AnonApiKey,\n  ImportGraphPayload,\n  SdkHealthReport,\n  SdkDiagnosticCode,\n} from \"@glasstrace/protocol\";\nimport type { ResolvedConfig } from \"./env-detection.js\";\nimport { recordInitFailure, recordConfigSync, acknowledgeHealthReport } from \"./health-collector.js\";\nimport {\n  httpsPostJson,\n  HttpsStatusError,\n  HttpsTransportError,\n  HttpsBodyParseError,\n} from \"./https-transport.js\";\nimport {\n  resolveEffectiveMcpCredential,\n  refreshGenericMcpConfigAtRuntime,\n} from \"./mcp-runtime.js\";\nimport { atomicWriteFile } from \"./atomic-write.js\";\nimport {\n  getActiveConfigResponse,\n  getActiveConfigOrigin,\n  setActiveConfig,\n  isConfigCacheChecked,\n  markConfigCacheChecked,\n  getStoredAttrHmacKey,\n  _resetActiveConfigForTesting,\n  type ActiveConfigOrigin,\n} from \"./active-config-store.js\";\nimport { decisionTrace, decisionTraceEnabled } from \"./decision-trace.js\";\n\nconst GLASSTRACE_DIR = \".glasstrace\";\nconst CONFIG_FILE = \"config\";\nconst TWENTY_FOUR_HOURS_MS = 24 * 60 * 60 * 1000;\nconst INIT_TIMEOUT_MS = 10_000;\n\n/**\n * Lazily imports `node:fs/promises` and `node:path`. Returns `null` if\n * the modules are unavailable (non-Node environments). Cached after first call.\n */\nlet fsPathAsyncCache: { fs: typeof import(\"node:fs/promises\"); path: typeof import(\"node:path\") } | null | undefined;\n\nasync function loadFsPathAsync(): Promise<{ fs: typeof import(\"node:fs/promises\"); path: typeof import(\"node:path\") } | null> {\n  if (fsPathAsyncCache !== undefined) return fsPathAsyncCache;\n  try {\n    const [fs, path] = await Promise.all([\n      import(\"node:fs/promises\"),\n      import(\"node:path\"),\n    ]);\n    fsPathAsyncCache = { fs, path };\n    return fsPathAsyncCache;\n  } catch {\n    fsPathAsyncCache = null;\n    return null;\n  }\n}\n\n/**\n * Lazily imports synchronous `node:fs` and `node:path` via `require()`.\n * Returns `null` when unavailable. Used by `loadCachedConfig` which is\n * synchronous for startup performance.\n */\nfunction loadFsSyncOrNull(): { readFileSync: typeof import(\"node:fs\").readFileSync; join: typeof import(\"node:path\").join } | null {\n  try {\n    // eslint-disable-next-line @typescript-eslint/no-require-imports, glasstrace/no-unguarded-node-require -- guarded by the surrounding try/catch in `loadFsSyncOrNull`; throw returns `null`, callers (e.g. `loadCachedConfig`) treat it as no cached config (DISC-1555).\n    const fs = require(\"node:fs\") as typeof import(\"node:fs\");\n    // eslint-disable-next-line @typescript-eslint/no-require-imports, glasstrace/no-unguarded-node-require -- guarded by the same try/catch as the preceding `node:fs` require (DISC-1555).\n    const path = require(\"node:path\") as typeof import(\"node:path\");\n    return { readFileSync: fs.readFileSync, join: path.join };\n  } catch {\n    return null;\n  }\n}\n\n/**\n * Test-only transport hook. When set, `sendInitRequest` calls this\n * instead of `httpsPostJson`. Enables unit tests to assert that the\n * SDK never routes through `globalThis.fetch` (Next.js patching) by\n * injecting a pure-function transport that never touches the network.\n *\n * Production code never sets this. Reset via `_resetConfigForTesting()`.\n */\ntype HttpsPostJsonFn = typeof httpsPostJson;\nlet transportOverride: HttpsPostJsonFn | null = null;\n\n// The resolved active capture-config (`currentConfig`) and the once-per-\n// process disk-cache-checked flag (`configCacheChecked`) live in the\n// `active-config-store` globalThis singleton, not in module-level state.\n// Under Turbopack `next dev` HMR and the edge/node bundle split the\n// bundler can evaluate more than one copy of this module, and plain\n// module-level state would let the copy that applies the served config\n// diverge from the copy the in-request emitter reads — silently dropping\n// capture at the call site. The singleton makes every bundle instance\n// share one record. See `active-config-store.ts`.\n\n/** Whether the next init call should be skipped (rate-limit backoff). */\nlet rateLimitBackoff = false;\n\n/** Whether the most recent performInit call completed the success path. */\nlet lastInitSucceeded = false;\n\n/**\n * Normalize a capture config for the on-disk cache. The per-account\n * `attrHmacKey` secret is never persisted, and a `full` posture without that\n * key is invalid on disk — a cold start that loaded it would make every\n * id-only Prisma query record a spurious `unhashed_id` omission — so `full` is\n * downgraded to `strict`. Applied on both write and read, so a cache written\n * by an older SDK (which may hold `full` from the pre-existing schema) is\n * normalized on load too. Returns the input unchanged when already clean.\n */\nfunction normalizeCachedCaptureConfig(config: CaptureConfig): CaptureConfig {\n  if (config.attrHmacKey === undefined && config.captureFidelity !== \"full\") {\n    return config;\n  }\n  const normalized: CaptureConfig = { ...config };\n  delete normalized.attrHmacKey;\n  if (normalized.captureFidelity === \"full\") {\n    normalized.captureFidelity = \"strict\";\n  }\n  return normalized;\n}\n\n/**\n * Reads and validates a cached config file from `.glasstrace/config`.\n * Returns the parsed `SdkInitResponse` or `null` on any failure,\n * including when `node:fs` is unavailable (non-Node environments).\n */\nexport function loadCachedConfig(projectRoot?: string): SdkInitResponse | null {\n  const modules = loadFsSyncOrNull();\n  if (!modules) return null;\n\n  const root = projectRoot ?? process.cwd();\n  const configPath = modules.join(root, GLASSTRACE_DIR, CONFIG_FILE);\n\n  try {\n    // Use synchronous read for startup performance (this is called during init)\n    const content = modules.readFileSync(configPath, \"utf-8\");\n    const parsed = JSON.parse(content);\n    const cached = SdkCachedConfigSchema.parse(parsed);\n\n    // Warn if cache is stale\n    const age = Date.now() - cached.cachedAt;\n    if (age > TWENTY_FOUR_HOURS_MS) {\n      console.warn(\n        `[glasstrace] Cached config is ${Math.round(age / 3600000)}h old. Will refresh on next init.`,\n      );\n    }\n\n    // Parse the response through the schema\n    const result = SdkInitResponseSchema.safeParse(cached.response);\n    if (result.success) {\n      recordConfigSync(cached.cachedAt);\n      return {\n        ...result.data,\n        config: normalizeCachedCaptureConfig(result.data.config),\n      };\n    }\n\n    console.warn(\"[glasstrace] Cached config failed validation. Using defaults.\");\n    return null;\n  } catch {\n    return null;\n  }\n}\n\n/**\n * Persists the init response to `.glasstrace/config` using the SDK 2.0\n * atomic-write protocol (`tmp + fsync(tmp) + rename + fsync(parent)`).\n * Silently skipped when `node:fs` is unavailable (non-Node environments).\n * On I/O failure, logs a warning.\n *\n * Atomicity: the payload is written to `.glasstrace/config.tmp`, fsynced\n * to durable storage, then renamed into place; the parent directory is\n * fsynced last so the rename survives an immediate crash. `rename` is\n * atomic on POSIX filesystems, so readers either see the previous valid\n * config or the new valid config — never a truncated or partially-written\n * file. If any step fails, the temp file is\n * cleaned up on a best-effort basis.\n */\nexport async function saveCachedConfig(\n  response: SdkInitResponse,\n  projectRoot?: string,\n): Promise<void> {\n  const modules = await loadFsPathAsync();\n  if (!modules) return;\n\n  const root = projectRoot ?? process.cwd();\n  const dirPath = modules.path.join(root, GLASSTRACE_DIR);\n  const configPath = modules.path.join(dirPath, CONFIG_FILE);\n\n  try {\n    await modules.fs.mkdir(dirPath, { recursive: true, mode: 0o700 });\n    await modules.fs.chmod(dirPath, 0o700);\n    // Strip the per-account HMAC secret (a tenant secret that must never reach\n    // disk) and downgrade an unkeyed `full` posture before persisting — see\n    // normalizeCachedCaptureConfig.\n    const cached = {\n      response: {\n        ...response,\n        config: normalizeCachedCaptureConfig(response.config),\n      },\n      cachedAt: Date.now(),\n    };\n    // Atomic write per SDK 2.0 §4.3: tmp + fsync(tmp) + rename +\n    // fsync(parent). Sibling temp guarantees same-filesystem rename\n    // (atomic per POSIX). The helper best-effort cleans up the tmp\n    // file on failure (DISC-1247 Scenario 5).\n    await atomicWriteFile(configPath, JSON.stringify(cached), {\n      encoding: \"utf-8\",\n      mode: 0o600,\n    });\n    // chmod the final path to defend against platforms that don't honor\n    // the mode passed to writeFile/rename on first creation.\n    await modules.fs.chmod(configPath, 0o600);\n  } catch (err) {\n    console.warn(\n      `[glasstrace] Failed to cache config to ${configPath}: ${err instanceof Error ? err.message : String(err)}`,\n    );\n  }\n}\n\n/**\n * Sends a POST request to `/v1/sdk/init`.\n * Validates the response against `SdkInitResponseSchema`.\n *\n * Uses `node:https` via {@link httpsPostJson} rather than the global\n * `fetch` because Next.js 16 patches `fetch` for caching/revalidation\n * and can cause the init request to silently hang.\n * Retries transport-level failures (DNS, TCP, TLS) twice with 500ms +\n * 1500ms backoff, capped at a 20-second total deadline. Server responses\n * (HTTP 4xx/5xx) are never retried and are surfaced immediately.\n */\nexport async function sendInitRequest(\n  config: ResolvedConfig,\n  anonKey: AnonApiKey | null,\n  sdkVersion: string,\n  importGraph?: ImportGraphPayload,\n  healthReport?: SdkHealthReport,\n  diagnostics?: Array<{ code: SdkDiagnosticCode; message: string; timestamp: number }>,\n  signal?: AbortSignal,\n): Promise<SdkInitResponse> {\n  // Determine the API key for auth. Use || (not ??) so empty strings\n  // fall through to the anonymous key — defense in depth for DISC-467.\n  const effectiveKey = config.apiKey || anonKey;\n  if (!effectiveKey) {\n    throw new Error(\"No API key available for init request\");\n  }\n\n  // Build the request payload\n  const payload: Record<string, unknown> = {\n    sdkVersion,\n  };\n\n  // Straggler linking: if dev key is set AND anonKey is provided\n  if (config.apiKey && anonKey) {\n    payload.anonKey = anonKey;\n  }\n\n  if (config.environment) {\n    payload.environment = config.environment;\n  }\n  if (importGraph) {\n    payload.importGraph = importGraph;\n  }\n  if (healthReport) {\n    payload.healthReport = healthReport;\n  }\n  if (diagnostics) {\n    payload.diagnostics = diagnostics;\n  }\n\n  const url = `${config.endpoint}/v1/sdk/init`;\n\n  const transport = transportOverride ?? httpsPostJson;\n  let result;\n  try {\n    result = await transport(url, payload, {\n      headers: {\n        \"Content-Type\": \"application/json\",\n        Authorization: `Bearer ${effectiveKey}`,\n      },\n      timeoutMs: INIT_TIMEOUT_MS,\n      signal,\n    });\n  } catch (err) {\n    if (err instanceof HttpsStatusError) {\n      const error = new Error(`Init request failed with status ${err.status}`);\n      (error as unknown as Record<string, unknown>).status = err.status;\n      throw error;\n    }\n    if (err instanceof HttpsBodyParseError) {\n      // Preserve SyntaxError name so callers can distinguish parse failures\n      // (existing test contract uses `name === \"SyntaxError\"`).\n      const cause = err.cause;\n      if (cause instanceof SyntaxError) throw cause;\n      throw err;\n    }\n    if (err instanceof HttpsTransportError) {\n      // Transport error — surface as-is; callers classify via message/name.\n      throw err;\n    }\n    throw err;\n  }\n\n  return SdkInitResponseSchema.parse(result.body);\n}\n\n/**\n * Result returned by {@link performInit} when the backend reports an\n * account claim transition. `null` means no claim was present.\n */\nexport interface InitClaimResult {\n  claimResult: NonNullable<SdkInitResponse[\"claimResult\"]>;\n}\n\n/**\n * Result of {@link writeClaimedKey}. The discriminator tells the\n * caller which on-disk source the key now lives at — and, if both\n * file writes failed, that no refresh of dependent state should be\n * attempted because there is no on-disk credential to back it.\n */\nexport interface WriteClaimedKeyResult {\n  persisted: \"env-local\" | \"claimed-key\" | \"none\";\n}\n\n/**\n * Writes a claimed API key to disk using a fallback chain:\n *   1. `.env.local` — update or create with the new key\n *   2. `.glasstrace/claimed-key` — fallback if `.env.local` is not writable\n *   3. Dashboard message — if all file writes fail (key is never logged)\n *\n * The key value MUST NOT appear in any log output or stderr message.\n * In non-Node environments where `node:fs` is unavailable, falls through\n * directly to the dashboard message (step 3).\n *\n * Returns a {@link WriteClaimedKeyResult} so the caller can gate\n * downstream actions (specifically: managed MCP config refresh) on\n * the key actually having reached disk. Returning `persisted: \"none\"`\n * means the SDK could not write the key anywhere; refreshing\n * `.glasstrace/mcp.json` from the new key would put it out of sync\n * with the credential the runtime can actually read on the next\n * cold start.\n */\nexport async function writeClaimedKey(\n  newApiKey: string,\n  projectRoot?: string,\n): Promise<WriteClaimedKeyResult> {\n  const modules = await loadFsPathAsync();\n\n  if (modules) {\n    const root = projectRoot ?? process.cwd();\n    const envLocalPath = modules.path.join(root, \".env.local\");\n\n    // Step 1: Try writing to .env.local\n    let envLocalWritten = false;\n    try {\n      let content: string;\n      try {\n        content = await modules.fs.readFile(envLocalPath, \"utf-8\");\n        // Replace all existing GLASSTRACE_API_KEY lines or append\n        if (/^GLASSTRACE_API_KEY=.*/m.test(content)) {\n          content = content.replace(\n            /^GLASSTRACE_API_KEY=.*$/gm,\n            `GLASSTRACE_API_KEY=${newApiKey}`,\n          );\n        } else {\n          // Ensure trailing newline before appending\n          if (content.length > 0 && !content.endsWith(\"\\n\")) {\n            content += \"\\n\";\n          }\n          content += `GLASSTRACE_API_KEY=${newApiKey}\\n`;\n        }\n      } catch (readErr: unknown) {\n        // Only create a new file when the file genuinely does not exist.\n        // Other read errors (e.g., permission denied) should not silently\n        // overwrite an existing .env.local that we cannot read.\n        const code = readErr instanceof Error ? (readErr as NodeJS.ErrnoException).code : undefined;\n        if (code !== \"ENOENT\") {\n          throw readErr;\n        }\n        content = `GLASSTRACE_API_KEY=${newApiKey}\\n`;\n      }\n\n      await modules.fs.writeFile(envLocalPath, content, { encoding: \"utf-8\", mode: 0o600 });\n      await modules.fs.chmod(envLocalPath, 0o600);\n      envLocalWritten = true;\n    } catch {\n      // .env.local write failed — fall through to step 2\n    }\n\n    if (envLocalWritten) {\n      try {\n        process.stderr.write(\n          \"[glasstrace] Account claimed! API key written to .env.local. Restart your dev server to use it.\\n\",\n        );\n      } catch { /* stderr is best-effort */ }\n      return { persisted: \"env-local\" };\n    }\n\n    // Step 2: Try writing to .glasstrace/claimed-key\n    let claimedKeyWritten = false;\n    try {\n      const dirPath = modules.path.join(root, GLASSTRACE_DIR);\n      await modules.fs.mkdir(dirPath, { recursive: true, mode: 0o700 });\n      await modules.fs.chmod(dirPath, 0o700);\n      const claimedKeyPath = modules.path.join(dirPath, \"claimed-key\");\n      await modules.fs.writeFile(claimedKeyPath, newApiKey, {\n        encoding: \"utf-8\",\n        mode: 0o600,\n      });\n      await modules.fs.chmod(claimedKeyPath, 0o600);\n      claimedKeyWritten = true;\n    } catch {\n      // .glasstrace write also failed — fall through to step 3\n    }\n\n    if (claimedKeyWritten) {\n      try {\n        process.stderr.write(\n          \"[glasstrace] Account claimed! API key written to .glasstrace/claimed-key. Copy it to your .env.local file.\\n\",\n        );\n      } catch { /* stderr is best-effort */ }\n      return { persisted: \"claimed-key\" };\n    }\n  }\n\n  // Step 3: All file writes failed (or node:fs unavailable) — log a message WITHOUT the key\n  try {\n    process.stderr.write(\n      \"[glasstrace] Account claimed but could not write key to disk. Visit your dashboard settings to rotate and retrieve a new API key.\\n\",\n    );\n  } catch { /* stderr is best-effort */ }\n  return { persisted: \"none\" };\n}\n\n/**\n * Orchestrates the full init flow: send request, update config, cache result.\n * This function MUST NOT throw.\n *\n * Returns the claim result when the backend reports an account claim\n * transition, or `null` when no claim result is available (including\n * when init is skipped due to rate-limit backoff, missing API key,\n * or request failure). Callers that do not need claim information\n * can safely ignore the return value.\n */\nexport async function performInit(\n  config: ResolvedConfig,\n  anonKey: AnonApiKey | null,\n  sdkVersion: string,\n  healthReport?: SdkHealthReport | null,\n): Promise<InitClaimResult | null> {\n  lastInitSucceeded = false;\n\n  // Skip if in rate-limit backoff\n  if (rateLimitBackoff) {\n    rateLimitBackoff = false; // Reset for next call\n    return null;\n  }\n\n  // Guard flag: prevents recordInitFailure() from being called twice if the\n  // inner catch body itself throws (e.g., an unexpected error in console.warn\n  // or the instanceof checks). Without this flag, the outer safety-net catch\n  // would call recordInitFailure() a second time, inflating initFailures in\n  // the health report. Fix for DISC-1121.\n  let failureRecorded = false;\n\n  try {\n    const effectiveKey = config.apiKey || anonKey;\n    if (!effectiveKey) {\n      console.warn(\"[glasstrace] No API key available for init request.\");\n      return null;\n    }\n\n    // No outer AbortController timeout: `httpsPostJson` enforces a\n    // per-attempt timeout (INIT_TIMEOUT_MS = 10s) AND a 20s total\n    // deadline across retries. An outer 10s abort would race the first\n    // attempt's own timeout and prevent the backoff-retry window from\n    // ever running, defeating the transport's retry behavior.\n    try {\n      // Delegate to sendInitRequest to avoid duplicating fetch logic\n      const result = await sendInitRequest(\n        config,\n        anonKey,\n        sdkVersion,\n        undefined,\n        healthReport ?? undefined,\n        undefined,\n      );\n\n      // Update the shared active config (visible to every bundle instance)\n      setActiveConfig(result);\n      recordConfigSync(Date.now());\n      if (healthReport) {\n        acknowledgeHealthReport(healthReport);\n      }\n      lastInitSucceeded = true;\n\n      // Persist to disk\n      await saveCachedConfig(result);\n\n      // Handle account claim transition — write key to disk, never to stderr\n      if (result.claimResult) {\n        let persisted: WriteClaimedKeyResult[\"persisted\"] = \"none\";\n        try {\n          const w = await writeClaimedKey(result.claimResult.newApiKey);\n          persisted = w.persisted;\n        } catch {\n          // writeClaimedKey handles its own errors internally, but guard\n          // against unexpected failures to ensure claimResult is never lost\n        }\n\n        // When the claimed key actually reached disk, refresh the\n        // managed `.glasstrace/mcp.json` (if SDK-shaped) so MCP queries\n        // start using the same credential ingestion now writes traces\n        // with. Refresh failure must not lose claimResult — wrap the\n        // whole thing in its own try/catch.\n        if (persisted !== \"none\") {\n          try {\n            const resolved = await resolveEffectiveMcpCredential();\n            await refreshGenericMcpConfigAtRuntime(\n              process.cwd(),\n              resolved.effective,\n              resolved.anonKey,\n            );\n          } catch {\n            // Refresh failure leaves the existing managed config in\n            // place. The next CLI-driven `glasstrace mcp add` run will\n            // detect the marker mismatch and prompt a re-run.\n          }\n        }\n\n        return { claimResult: result.claimResult };\n      }\n\n      return null;\n    } catch (err) {\n      recordInitFailure();\n      failureRecorded = true;\n\n      // HttpsTransportError covers DNS/TCP/TLS/timeout from the\n      // node:https transport itself — `httpsPostJson` raises timeouts\n      // via this error class when its internal deadlines expire.\n      if (err instanceof HttpsTransportError) {\n        if (/timed out|aborted/i.test(err.message)) {\n          console.warn(\"[glasstrace] ingestion_unreachable: Init request timed out.\");\n        } else {\n          console.warn(`[glasstrace] ingestion_unreachable: ${err.message}`);\n        }\n        return null;\n      }\n\n      // Check for HTTP status errors attached by sendInitRequest\n      const status = (err as Record<string, unknown>).status;\n      if (status === 401) {\n        console.warn(\n          \"[glasstrace] ingestion_auth_failed: Check your GLASSTRACE_API_KEY.\",\n        );\n        return null;\n      }\n\n      if (status === 429) {\n        console.warn(\"[glasstrace] ingestion_rate_limited: Backing off.\");\n        rateLimitBackoff = true;\n        return null;\n      }\n\n      if (typeof status === \"number\" && status >= 400) {\n        console.warn(\n          `[glasstrace] Init request failed with status ${status}. Using cached config.`,\n        );\n        return null;\n      }\n\n      // Schema validation failure from sendInitRequest.parse\n      // NOTE: Health report was already sent to the backend (HTTP 200).\n      // Not acknowledging here means the next report will double-count\n      // these values. This is intentional — over-reporting is preferable\n      // to data loss when the response is unparseable (DISC-1120).\n      if (err instanceof Error && err.name === \"ZodError\") {\n        console.warn(\n          \"[glasstrace] Init response failed validation (schema version mismatch?). Using cached config.\",\n        );\n        return null;\n      }\n\n      // Network error or other fetch failure\n      console.warn(\n        `[glasstrace] ingestion_unreachable: ${err instanceof Error ? err.message : String(err)}`,\n      );\n      return null;\n    }\n  } catch (err) {\n    // Outermost catch — safety net for unexpected throws from the inner catch\n    // body itself (e.g., an error in console.warn or instanceof checks).\n    // Only record the failure if the inner catch did not already do so (DISC-1121).\n    if (!failureRecorded) {\n      recordInitFailure();\n    }\n    // Guard console.warn itself: performInit MUST NOT throw. If console.warn\n    // throws here (the same failure mode this catch was added to handle), swallow\n    // silently rather than violating the \"never throws\" contract.\n    try {\n      console.warn(\n        `[glasstrace] Unexpected init error: ${err instanceof Error ? err.message : String(err)}`,\n      );\n    } catch { /* best-effort logging; never propagate */ }\n  }\n\n  return null;\n}\n\n/**\n * Resolves the current capture config from the three-tier fallback chain:\n * 1. In-memory config from latest init response\n * 2. File cache (read at most once per process lifetime)\n * 3. DEFAULT_CAPTURE_CONFIG\n *\n * Internal: the returned object may still carry the per-account `attrHmacKey`\n * secret, so it must not be handed to callers outside this module. The disk\n * read is cached via the shared store's cache-checked flag to avoid repeated\n * synchronous I/O on the hot path (called by GlasstraceExporter on every span\n * export batch). State is read through the `active-config-store` singleton so\n * every bundle instance resolves the same config.\n */\nfunction resolveActiveConfig(): CaptureConfig {\n  // Tier 1: in-memory (shared across bundle instances)\n  const current = getActiveConfigResponse();\n  if (current) {\n    // Decision trace (hot path): which fallback tier produced this config.\n    // The in-memory store holds BOTH a live server response and a promoted\n    // disk cache (the cache is promoted into the store on first read), so the\n    // true tier comes from the record's origin — not its mere presence — to\n    // keep a promoted cache reporting `cached` rather than `served`. Call-site\n    // guarded so nothing is built when OFF; keyed by the closed tier outcome\n    // (three values) so it stays bounded and re-emits once per tier as init\n    // progresses (default → cached → served).\n    if (decisionTraceEnabled()) {\n      const tier = getActiveConfigOrigin() === \"cache\" ? \"cached\" : \"served\";\n      decisionTrace(\"config.tier\", tier, {\n        oneShotKey: `config.tier:${tier}`,\n      });\n    }\n    return current.config;\n  }\n\n  // Tier 2: file cache (only attempt once per process)\n  if (!isConfigCacheChecked()) {\n    markConfigCacheChecked();\n    const cached = loadCachedConfig();\n    if (cached) {\n      // Promote the disk cache into the shared store tagged with its `cache`\n      // origin, so a subsequent read takes the tier-1 branch but still reports\n      // `cached` (not `served`) — the promotion must not masquerade as a live\n      // server config.\n      setActiveConfig(cached, \"cache\");\n      if (decisionTraceEnabled()) {\n        decisionTrace(\"config.tier\", \"cached\", {\n          oneShotKey: \"config.tier:cached\",\n        });\n      }\n      return cached.config;\n    }\n  }\n\n  // Tier 3: defaults\n  if (decisionTraceEnabled()) {\n    decisionTrace(\"config.tier\", \"default\", {\n      oneShotKey: \"config.tier:default\",\n    });\n  }\n  return { ...DEFAULT_CAPTURE_CONFIG };\n}\n\n/**\n * Returns the active capture config with the per-account `attrHmacKey` secret\n * redacted. This is the public getter (exported from the package barrel), so\n * application code importing the SDK can never read the tenant secret through\n * it. The passive value-capture adapter reads the key via the internal\n * {@link getAttrHmacKey} accessor instead.\n *\n * The shared store no longer carries the secret in the config object (it is\n * split into the active-config record's closure holder on apply), so this\n * redaction is a defensive safety net for any path that surfaces a config still\n * holding the field — it is kept to preserve the invariant regardless of how\n * the config reaches here.\n */\nexport function getActiveConfig(): CaptureConfig {\n  const config = resolveActiveConfig();\n  if (config.attrHmacKey === undefined) {\n    return config;\n  }\n  const redacted: CaptureConfig = { ...config };\n  delete redacted.attrHmacKey;\n  return redacted;\n}\n\n/**\n * The per-account HMAC secret used to pseudonymize `*Id` columns, or\n * `undefined` when none is provisioned. Internal — deliberately NOT exported\n * from the package barrel, so the secret stays off the public API surface;\n * only the passive value-capture adapter reads it.\n *\n * Read from the shared active-config record's closure holder, so it is\n * reachable across bundle copies — including a copy that runs the Prisma\n * projection without having applied the config itself (the Turbopack-dev bundle\n * split). The raw key is held in a closure, off the record's enumerable\n * surface, so it never lands in a serialized dump. See `active-config-store.ts`.\n */\nexport function getAttrHmacKey(): string | undefined {\n  return getStoredAttrHmacKey();\n}\n\n/**\n * Whether side-effect / value capture is enabled by the active capture\n * config. Reads the active capture config on every call so config rotation\n * takes effect on the next emission. Fail-closed: any error (or absent\n * config) resolves to `false`. Internal — not exported from the package\n * barrel.\n */\nexport function isCaptureEnabled(): boolean {\n  try {\n    return resolveActiveConfig().sideEffectEvidence === true;\n  } catch {\n    return false;\n  }\n}\n\n/**\n * Returns the `linkedAccountId` from the current in-memory init response,\n * or `undefined` if no init response is available or no account is linked.\n *\n * Used by the discovery endpoint to determine whether `claimed: true`\n * should be included in the response.\n */\nexport function getLinkedAccountId(): string | undefined {\n  return getActiveConfigResponse()?.linkedAccountId;\n}\n\n/**\n * Returns the `claimResult` from the current in-memory init response,\n * or `undefined` if no init response is available or no claim occurred.\n *\n * Used by the discovery endpoint to detect in-flight claims: a valid\n * init response can include `claimResult` (claim happening NOW) without\n * `linkedAccountId` being set yet.\n */\nexport function getClaimResult(): SdkInitResponse[\"claimResult\"] {\n  return getActiveConfigResponse()?.claimResult;\n}\n\n/**\n * Resets the in-memory config store. For testing only.\n */\nexport function _resetConfigForTesting(): void {\n  _resetActiveConfigForTesting();\n  rateLimitBackoff = false;\n  lastInitSucceeded = false;\n  transportOverride = null;\n}\n\n/**\n * Installs a test-only transport that replaces the `node:https` path\n * used by `sendInitRequest` and `performInit`. Tests use this to avoid\n * opening real sockets and to assert the SDK never routes through\n * `globalThis.fetch`. Pass `null` to restore the default transport.\n *\n * @internal Test-only. Never called from production code paths.\n */\nexport function _setTransportForTesting(fn: HttpsPostJsonFn | null): void {\n  transportOverride = fn;\n}\n\n/**\n * Sets the in-memory config directly. Used by performInit and the orchestrator.\n * Writes through the shared store so every bundle instance sees the value.\n *\n * `origin` records the config's provenance for the decision-trace\n * `config.tier` gate; it defaults to `\"server\"` (a live response) and should\n * be passed as `\"cache\"` when applying a config loaded from the on-disk cache.\n */\nexport function _setCurrentConfig(\n  config: SdkInitResponse,\n  origin: ActiveConfigOrigin = \"server\",\n): void {\n  setActiveConfig(config, origin);\n}\n\n/**\n * Returns whether rate-limit backoff is active. For testing only.\n */\nexport function _isRateLimitBackoff(): boolean {\n  return rateLimitBackoff;\n}\n\n/**\n * Reads and clears the rate-limit backoff flag.\n * Called by the heartbeat after performInit returns null to detect 429 responses.\n * Returns true if a 429 occurred, false otherwise.\n */\nexport function consumeRateLimitFlag(): boolean {\n  if (rateLimitBackoff) {\n    rateLimitBackoff = false;\n    return true;\n  }\n  return false;\n}\n\n/**\n * Returns true if the most recent performInit call completed the success path\n * (recordConfigSync + acknowledgeHealthReport were called).\n * Used by backgroundInit to decide whether to start the heartbeat.\n */\nexport function didLastInitSucceed(): boolean {\n  return lastInitSucceeded;\n}\n\n/**\n * Result of {@link verifyInitReachable}.\n *\n * - `ok: true` — server acknowledged the init call with a valid, schema-\n *   compliant payload. The anon key (if any) is registered server-side.\n * - `ok: false` with `reason: \"transport\"` — DNS/TCP/TLS/timeout failure.\n *   No response reached the server (or couldn't be parsed off the wire).\n *   `detail` is the raw cause (e.g. \"ECONNREFUSED\") with any leading\n *   `fetch failed: ` prefix stripped; callers that render to the user\n *   should add the prefix themselves to avoid doubling it.\n * - `ok: false` with `reason: \"rejected\"` — HTTP 4xx/5xx status. The\n *   server received the call but declined it. `status` is set.\n * - `ok: false` with `reason: \"malformed\"` — HTTP 2xx but the body was\n *   not valid JSON or did not match the protocol schema.\n */\nexport type VerifyInitResult =\n  | { ok: true; response: SdkInitResponse }\n  | { ok: false; reason: \"transport\"; detail: string }\n  | { ok: false; reason: \"rejected\"; status: number; detail: string }\n  | { ok: false; reason: \"malformed\"; detail: string };\n\n/**\n * Synchronously verifies that `/v1/sdk/init` is reachable and that the\n * provided anon key (if any) is registered server-side. Unlike\n * {@link performInit}, this function does NOT swallow errors — it\n * classifies them into the three user-actionable categories and\n * returns them.\n *\n * Used by the CLI `init` command to fail loudly when the init request\n * fails, rather than relying on the\n * runtime fire-and-forget call which can silently fail inside a\n * Next.js 16 process.\n *\n * The anon key is NEVER logged by this function. Error `detail`\n * strings are sanitized to the failure class only — the key does not\n * appear in transport, rejection, or malformed messages.\n */\nexport async function verifyInitReachable(\n  config: ResolvedConfig,\n  anonKey: AnonApiKey | null,\n  sdkVersion: string,\n): Promise<VerifyInitResult> {\n  try {\n    const response = await sendInitRequest(config, anonKey, sdkVersion);\n    return { ok: true, response };\n  } catch (err) {\n    // HTTP status error — server rejected the key.\n    const status = (err as Record<string, unknown>).status;\n    if (typeof status === \"number\") {\n      return {\n        ok: false,\n        reason: \"rejected\",\n        status,\n        detail: `server returned HTTP ${status}`,\n      };\n    }\n\n    // Schema validation failure (ZodError) or JSON parse error\n    // (SyntaxError). Both mean the server responded but the body is\n    // not a shape we can use.\n    if (err instanceof Error && (err.name === \"ZodError\" || err.name === \"SyntaxError\")) {\n      return {\n        ok: false,\n        reason: \"malformed\",\n        detail: \"server returned malformed response\",\n      };\n    }\n\n    // Everything else (transport errors, timeouts, abort, unknown) is\n    // classified as transport. `detail` is the raw cause without a\n    // `fetch failed:` prefix so the CLI (the only caller that renders\n    // this) can format it as `fetch failed: <detail>` without risking\n    // the double-prefix that would occur when the underlying error\n    // already starts with `fetch failed:` (e.g., `HttpsTransportError`\n    // from `sendSingleRequest`).\n    const rawMessage = err instanceof Error ? err.message : String(err);\n    const detail = rawMessage.startsWith(\"fetch failed: \")\n      ? rawMessage.slice(\"fetch failed: \".length)\n      : rawMessage;\n    return { ok: false, reason: \"transport\", detail };\n  }\n}\n","import type { SdkHealthReport } from \"@glasstrace/protocol\";\n\n// --- Module-level state (singleton pattern matching init-client.ts) ---\n\n/** Spans successfully forwarded to the delegate exporter since last collect. */\nlet tracesExported = 0;\n\n/** Spans dropped: buffer overflow evictions + spans lost on shutdown. */\nlet tracesDropped = 0;\n\n/** Failed performInit attempts since last collect. */\nlet initFailures = 0;\n\n/** Timestamp (ms) of the last successful config sync (performInit success or cached config load). */\nlet lastConfigSyncAt: number | null = null;\n\n// --- Recording functions (called by other modules) ---\n\n/**\n * Records that spans were submitted to the delegate exporter.\n * Counts submission, not confirmed delivery.\n * Called by GlasstraceExporter after delegate.export() is invoked.\n */\nexport function recordSpansExported(count: number): void {\n  if (!Number.isFinite(count) || count < 0 || !Number.isInteger(count)) return;\n  tracesExported += count;\n}\n\n/**\n * Records that spans were dropped (buffer overflow eviction or shutdown loss).\n * Called by GlasstraceExporter on buffer eviction and unresolved-key shutdown.\n */\nexport function recordSpansDropped(count: number): void {\n  if (!Number.isFinite(count) || count < 0 || !Number.isInteger(count)) return;\n  tracesDropped += count;\n}\n\n/**\n * Records a failed performInit attempt.\n * Called by performInit when the init request fails for any reason.\n */\nexport function recordInitFailure(): void {\n  try { initFailures += 1; } catch { /* best-effort */ }\n}\n\n/**\n * Records the timestamp of a successful config sync.\n * Called by performInit on success and by loadCachedConfig when loading a valid cache.\n */\nexport function recordConfigSync(timestamp: number): void {\n  try { lastConfigSyncAt = timestamp; } catch { /* best-effort */ }\n}\n\n// --- Collection ---\n\n/**\n * Snapshots the current health metrics into an SdkHealthReport without\n * resetting counters. Counters are only reset when {@link acknowledgeHealthReport}\n * is called after the init request succeeds. This two-phase approach prevents\n * metric loss when `performInit` fails — the counters persist for the next\n * init attempt.\n *\n * On the first init call, all counters will be zero, which is correct.\n *\n * @param sdkVersion - The SDK version string to include in the report.\n * @returns The health report, or null if collection fails unexpectedly.\n */\nexport function collectHealthReport(sdkVersion: string): SdkHealthReport | null {\n  try {\n    const now = Date.now();\n    const configAge = lastConfigSyncAt !== null ? Math.max(0, now - lastConfigSyncAt) : 0;\n\n    return {\n      tracesExportedSinceLastInit: tracesExported,\n      tracesDropped,\n      initFailures,\n      configAge: Math.round(configAge),\n      sdkVersion,\n    };\n  } catch {\n    return null;\n  }\n}\n\n/**\n * Subtracts the reported values from the running counters after a health\n * report has been successfully delivered to the backend. Called by\n * `performInit` on the success path. If init fails, counters persist\n * for the next attempt.\n *\n * Uses subtraction instead of zeroing to preserve any increments that\n * occurred between the snapshot (`collectHealthReport`) and delivery\n * (e.g., spans exported during the init HTTP call). Values are clamped\n * to 0 to guard against edge cases.\n *\n * Core invariant: for any finite counter C and finite reported\n * value, after acknowledge:\n *   C_new = max(0, C_before_ack - reported_value)\n * This guarantees:\n *   1. Reported finite, non-negative values are removed exactly once\n *      (no double-counting).\n *   2. Activity between snapshot and acknowledge is preserved (not lost).\n *   3. The counter never goes negative (clamp prevents underflow).\n * Corruption vectors guarded: non-finite report fields (NaN/±Infinity)\n * preserve the counter; negative finite report fields are clamped to 0\n * before subtraction.\n *\n * `lastConfigSyncAt` is NOT affected — config age measures time since\n * the last successful sync, not the last acknowledgment.\n */\nexport function acknowledgeHealthReport(report: SdkHealthReport): void {\n  const exp = Math.max(0, report.tracesExportedSinceLastInit);\n  const expVal = tracesExported - exp;\n  tracesExported = Number.isFinite(expVal) ? Math.max(0, expVal) : tracesExported;\n\n  const drop = Math.max(0, report.tracesDropped);\n  const dropVal = tracesDropped - drop;\n  tracesDropped = Number.isFinite(dropVal) ? Math.max(0, dropVal) : tracesDropped;\n\n  const fail = Math.max(0, report.initFailures);\n  const failVal = initFailures - fail;\n  initFailures = Number.isFinite(failVal) ? Math.max(0, failVal) : initFailures;\n}\n\n// --- Test support ---\n\n/**\n * Resets all health metrics to initial state. For testing only.\n */\nexport function _resetHealthForTesting(): void {\n  tracesExported = 0;\n  tracesDropped = 0;\n  initFailures = 0;\n  lastConfigSyncAt = null;\n}\n","/**\n * Minimal Node-native HTTPS transport used by the SDK init call.\n *\n * ## Why this exists\n *\n * Next.js 16 patches the global `fetch` to add caching, revalidation,\n * and request deduplication. When the SDK is bundled into a Next.js\n * process (instrumentation.ts path), outbound calls to\n * `api.glasstrace.dev` get intercepted by the patched fetch and can\n * silently hang — the fetch promise never resolves.\n *\n * A silent init hang is catastrophic: the SDK stays in \"pending key\"\n * state forever, enriched spans are buffered without ever being\n * exported, and anonymous keys are never registered server-side.\n *\n * ## Why `node:https`\n *\n * `node:https` is a Node.js core module. It has zero bundle weight\n * (important because the SDK is tsup-inlined into every consumer's\n * bundle) and is always available on Node.js >= 20. Using it directly\n * bypasses the global `fetch` patching entirely — Next.js never sees\n * the request.\n *\n * Alternatives considered and rejected:\n *\n * - **`undici` as a runtime dep** — adds ~400KB inlined into every\n *   consumer bundle.\n * - **`fetch(..., { cache: \"no-store\", next: { revalidate: 0 } })`** —\n *   bandaid. Couples the SDK to Next.js's fetch-extension API and still\n *   relies on Next's patched fetch behaving correctly. Explicitly\n *   forbidden by the task brief for this reason.\n * - **Monkey-patch `globalThis.fetch`** — forbidden in the public SDK\n *   (`glasstrace-sdk/CLAUDE.md`). Bypassing the patched fetch by\n *   calling a different API is avoidance, not patching.\n *\n * ## Structure\n *\n * `httpsPostJson` is the only exported function. It:\n *   - Sends a POST to a URL with a JSON body\n *   - Applies a per-request timeout (default 10s)\n *   - Retries transport-level failures (DNS, TCP, TLS) with backoff\n *   - Never retries HTTP status errors — those are surfaced immediately\n *   - Distinguishes transport failure, server error, and body-parse error\n *     so callers can render actionable messages\n */\nimport {\n  request as httpsRequest,\n  type RequestOptions as HttpsRequestOptions,\n} from \"node:https\";\nimport {\n  request as httpRequest,\n  type IncomingMessage,\n} from \"node:http\";\nimport { URL } from \"node:url\";\n\n/** Error thrown when the HTTP request never completed (DNS/TCP/TLS/timeout). */\nexport class HttpsTransportError extends Error {\n  readonly kind = \"transport\" as const;\n  readonly cause?: unknown;\n  constructor(message: string, cause?: unknown) {\n    super(message);\n    this.name = \"HttpsTransportError\";\n    this.cause = cause;\n  }\n}\n\n/** Error thrown when the server returned a non-2xx HTTP status. */\nexport class HttpsStatusError extends Error {\n  readonly kind = \"status\" as const;\n  readonly status: number;\n  /** Raw response body text (may be truncated by caller if large). */\n  readonly body: string;\n  constructor(status: number, body: string) {\n    super(`Server returned HTTP ${status}`);\n    this.name = \"HttpsStatusError\";\n    this.status = status;\n    this.body = body;\n  }\n}\n\n/** Error thrown when the response body was not parseable JSON. */\nexport class HttpsBodyParseError extends Error {\n  readonly kind = \"parse\" as const;\n  readonly status: number;\n  readonly cause?: unknown;\n  constructor(status: number, cause?: unknown) {\n    super(`Server returned malformed response (HTTP ${status})`);\n    this.name = \"HttpsBodyParseError\";\n    this.status = status;\n    this.cause = cause;\n  }\n}\n\n/** Options controlling timeout and retry behavior. */\nexport interface HttpsPostJsonOptions {\n  /** Parsed headers (including Content-Type, Authorization, etc). */\n  headers: Record<string, string>;\n  /** Per-attempt timeout, ms. Defaults to 10000. */\n  timeoutMs?: number;\n  /**\n   * Total number of attempts INCLUDING the first. Defaults to 3\n   * (initial + 2 retries). Only transport errors are retried.\n   */\n  maxAttempts?: number;\n  /**\n   * Backoff delays between retries, ms. The array length should be\n   * `maxAttempts - 1`. Defaults to [500, 1500].\n   */\n  retryDelaysMs?: readonly number[];\n  /**\n   * Total deadline across all attempts, ms. Defaults to 20000.\n   * If exceeded, no further retries are attempted and the last error\n   * is surfaced. Guards against CLI hang on flaky networks.\n   */\n  totalDeadlineMs?: number;\n  /**\n   * Abort signal. When aborted, the in-flight request is terminated and\n   * no further retries are attempted.\n   */\n  signal?: AbortSignal;\n  /**\n   * Scheduler injection point for tests. Defaults to `setTimeout`.\n   * Using fake timers in tests requires the injected scheduler to honor\n   * `vi.advanceTimersByTime()` — Node's real setTimeout is fine when no\n   * fake timers are installed.\n   */\n  scheduler?: (fn: () => void, ms: number) => { unref?: () => void };\n  /**\n   * Alternate HTTPS request function. Injected by tests to simulate\n   * Next.js-style fetch patching (assert call count stays zero) or to\n   * mock transport behavior without opening real sockets.\n   */\n  requestImpl?: typeof httpsRequest;\n  /**\n   * Alternate HTTP request function, used when the URL is `http://`.\n   * Splitting http/https lets tests use a local non-TLS mock server.\n   */\n  httpRequestImpl?: typeof httpRequest;\n}\n\n/** Shape of a successful response. */\nexport interface HttpsPostJsonResult {\n  /** HTTP status code. Always in [200, 299] for success. */\n  status: number;\n  /** Parsed JSON body. May be `undefined` for 204 No Content. */\n  body: unknown;\n  /** Raw body text for diagnostics. */\n  raw: string;\n}\n\n/** Delays so a failing test still completes before the suite's timeout. */\nconst DEFAULT_TIMEOUT_MS = 10_000;\nconst DEFAULT_RETRY_DELAYS_MS = [500, 1500] as const;\nconst DEFAULT_TOTAL_DEADLINE_MS = 20_000;\n\n/**\n * Sends a POST request with a JSON body using `node:https`. Bypasses\n * any `globalThis.fetch` patching (Next.js 16, MSW, etc).\n *\n * @throws {HttpsTransportError} DNS failure, TCP reset, TLS handshake\n * failure, request timeout, or abort.\n * @throws {HttpsStatusError} HTTP response with status >= 400.\n * @throws {HttpsBodyParseError} HTTP 2xx with non-JSON body (status not\n * equal to 204).\n */\nexport async function httpsPostJson(\n  url: string,\n  jsonBody: unknown,\n  options: HttpsPostJsonOptions,\n): Promise<HttpsPostJsonResult> {\n  const parsed = new URL(url);\n  const isHttps = parsed.protocol === \"https:\";\n  const isHttp = parsed.protocol === \"http:\";\n  if (!isHttps && !isHttp) {\n    throw new HttpsTransportError(\n      `Unsupported protocol: ${parsed.protocol} (expected http: or https:)`,\n    );\n  }\n  const timeoutMs = options.timeoutMs ?? DEFAULT_TIMEOUT_MS;\n  const maxAttempts = options.maxAttempts ?? 3;\n  const retryDelaysMs = options.retryDelaysMs ?? DEFAULT_RETRY_DELAYS_MS;\n  const totalDeadlineMs = options.totalDeadlineMs ?? DEFAULT_TOTAL_DEADLINE_MS;\n  const scheduler = options.scheduler ?? ((fn, ms) => setTimeout(fn, ms));\n  const requestImpl = isHttps\n    ? (options.requestImpl ?? httpsRequest)\n    : (options.httpRequestImpl ?? httpRequest);\n\n  // Serialize once so retries use the exact same bytes.\n  let payload: string;\n  try {\n    payload = JSON.stringify(jsonBody);\n  } catch (err) {\n    throw new HttpsTransportError(\n      `Failed to serialize request body: ${err instanceof Error ? err.message : String(err)}`,\n      err,\n    );\n  }\n  const payloadBuffer = Buffer.from(payload, \"utf-8\");\n\n  const startedAt = Date.now();\n  let lastError: unknown;\n\n  for (let attempt = 0; attempt < maxAttempts; attempt += 1) {\n    if (options.signal?.aborted) {\n      throw new HttpsTransportError(\"Request aborted\");\n    }\n    // Respect the total deadline — don't start another attempt if we'd\n    // blow past it even before issuing the request.\n    const elapsed = Date.now() - startedAt;\n    if (elapsed >= totalDeadlineMs) {\n      break;\n    }\n    const remainingBudget = totalDeadlineMs - elapsed;\n    const attemptTimeoutMs = Math.min(timeoutMs, remainingBudget);\n\n    try {\n      return await sendSingleRequest(\n        parsed,\n        payloadBuffer,\n        options.headers,\n        attemptTimeoutMs,\n        options.signal,\n        requestImpl,\n      );\n    } catch (err) {\n      lastError = err;\n      // Never retry status/parse errors — they're server responses, not\n      // transient network failures.\n      if (err instanceof HttpsStatusError || err instanceof HttpsBodyParseError) {\n        throw err;\n      }\n      const isLast = attempt === maxAttempts - 1;\n      if (isLast) break;\n\n      const delayMs = retryDelaysMs[attempt] ?? retryDelaysMs[retryDelaysMs.length - 1] ?? 0;\n      const elapsedBeforeSleep = Date.now() - startedAt;\n      const remaining = totalDeadlineMs - elapsedBeforeSleep;\n      if (remaining <= 0) break;\n      const actualDelayMs = Math.min(delayMs, remaining);\n      await sleep(actualDelayMs, scheduler, options.signal);\n    }\n  }\n\n  if (lastError instanceof HttpsTransportError) throw lastError;\n  throw new HttpsTransportError(\n    lastError instanceof Error ? lastError.message : \"Request failed\",\n    lastError,\n  );\n}\n\n/**\n * Fires a single HTTPS request. Resolves with the parsed result on 2xx,\n * throws the appropriate typed error otherwise. Caller handles retries.\n */\nfunction sendSingleRequest(\n  url: URL,\n  payload: Buffer,\n  headers: Record<string, string>,\n  timeoutMs: number,\n  signal: AbortSignal | undefined,\n  requestImpl: typeof httpsRequest,\n): Promise<HttpsPostJsonResult> {\n  return new Promise<HttpsPostJsonResult>((resolve, reject) => {\n    // Merge caller headers with Content-Length so Node doesn't chunk\n    // the body. Explicit content-length also prevents confusion from\n    // servers that reject chunked POSTs.\n    const finalHeaders: Record<string, string | number> = {\n      ...headers,\n      \"Content-Length\": payload.byteLength,\n    };\n\n    const reqOptions: HttpsRequestOptions = {\n      method: \"POST\",\n      hostname: url.hostname,\n      port: url.port === \"\" ? undefined : Number(url.port),\n      path: `${url.pathname}${url.search}`,\n      headers: finalHeaders,\n      // Explicit timeout at the socket level. Still complemented by a\n      // manual timer below because `timeout` only fires when the socket\n      // is idle — it does not cover \"TLS handshake hangs forever\".\n      timeout: timeoutMs,\n    };\n\n    let settled = false;\n    // Hoisted so every settle path can clear the manual timer and drop\n    // the optional abort listener. Assigned below once `req`, `timer`,\n    // and `onAbort` exist.\n    let cleanup = (): void => {};\n    const settle = (fn: () => void): void => {\n      if (settled) return;\n      settled = true;\n      cleanup();\n      fn();\n    };\n\n    const req = requestImpl(reqOptions, (res: IncomingMessage) => {\n      const chunks: Buffer[] = [];\n      res.on(\"data\", (chunk: Buffer | string) => {\n        chunks.push(typeof chunk === \"string\" ? Buffer.from(chunk, \"utf-8\") : chunk);\n      });\n      res.on(\"end\", () => {\n        const raw = Buffer.concat(chunks).toString(\"utf-8\");\n        const status = res.statusCode ?? 0;\n        if (status < 200 || status >= 300) {\n          settle(() => reject(new HttpsStatusError(status, raw)));\n          return;\n        }\n        // HTTP 204: no body is expected; resolve with undefined.\n        if (status === 204 || raw.length === 0) {\n          settle(() => resolve({ status, body: undefined, raw }));\n          return;\n        }\n        try {\n          const parsed = JSON.parse(raw);\n          settle(() => resolve({ status, body: parsed, raw }));\n        } catch (err) {\n          settle(() => reject(new HttpsBodyParseError(status, err)));\n        }\n      });\n      res.on(\"error\", (err) => {\n        settle(() => reject(new HttpsTransportError(`Response stream error: ${err.message}`, err)));\n      });\n    });\n\n    // A single manual timeout guards against handshake/DNS hangs that\n    // the `timeout` option in `request()` does not cover. We destroy the\n    // socket on timeout so the node:https layer doesn't keep it alive.\n    const timer = setTimeout(() => {\n      settle(() => {\n        req.destroy(new Error(\"Request timed out\"));\n        reject(new HttpsTransportError(`Request timed out after ${timeoutMs}ms`));\n      });\n    }, timeoutMs);\n    // Don't block process exit while the timer is running.\n    if (typeof timer.unref === \"function\") timer.unref();\n\n    // Hoisted so `cleanup` can remove it on settle. Only registered\n    // on the signal below when `signal !== undefined`.\n    const onAbort = (): void => {\n      settle(() => {\n        req.destroy(new Error(\"Aborted\"));\n        reject(new HttpsTransportError(\"Request aborted\"));\n      });\n    };\n\n    // Install cleanup now that `timer` and `onAbort` exist. Invoked by\n    // every settle path (success, status-error, parse-error, transport\n    // error, timeout, abort) to clear the manual timer and drop the\n    // abort listener so long-lived signals don't accumulate listeners.\n    cleanup = (): void => {\n      clearTimeout(timer);\n      if (signal !== undefined) {\n        signal.removeEventListener(\"abort\", onAbort);\n      }\n    };\n\n    req.on(\"error\", (err) => {\n      settle(() => reject(new HttpsTransportError(`fetch failed: ${err.message}`, err)));\n    });\n\n    req.on(\"timeout\", () => {\n      settle(() => {\n        req.destroy(new Error(\"Request timed out\"));\n        reject(new HttpsTransportError(`Request timed out after ${timeoutMs}ms`));\n      });\n    });\n\n    if (signal !== undefined) {\n      if (signal.aborted) {\n        req.destroy(new Error(\"Aborted\"));\n        settle(() => reject(new HttpsTransportError(\"Request aborted\")));\n        return;\n      }\n      signal.addEventListener(\"abort\", onAbort, { once: true });\n    }\n\n    req.end(payload);\n  });\n}\n\n/**\n * Delay helper that honors an AbortSignal. We cannot use `setTimeout`'s\n * built-in `signal` option because it is not available in older Node 20\n * patch releases (added in 20.6).\n *\n * Both settle paths (timer fires, signal aborts) clear the pending\n * timer and remove the abort listener so this helper remains leak-free\n * under heavy retry/abort usage.\n */\nfunction sleep(\n  ms: number,\n  scheduler: (fn: () => void, ms: number) => { unref?: () => void },\n  signal: AbortSignal | undefined,\n): Promise<void> {\n  return new Promise<void>((resolve, reject) => {\n    let settled = false;\n    // Forward-declared so `settle` below can reference it. Assigned\n    // once `timer` exists.\n    let cleanup = (): void => {};\n    const settle = (fn: () => void): void => {\n      if (settled) return;\n      settled = true;\n      cleanup();\n      fn();\n    };\n    const onAbort = (): void => {\n      settle(() => reject(new HttpsTransportError(\"Request aborted\")));\n    };\n    const timer = scheduler(() => {\n      settle(resolve);\n    }, ms);\n    if (typeof timer.unref === \"function\") timer.unref();\n    cleanup = (): void => {\n      // `scheduler` returns whatever `setTimeout` returns (NodeJS.Timeout\n      // in Node, number in jsdom). Both are accepted by `clearTimeout`.\n      clearTimeout(timer as unknown as NodeJS.Timeout);\n      if (signal !== undefined) {\n        signal.removeEventListener(\"abort\", onAbort);\n      }\n    };\n    if (signal !== undefined) {\n      if (signal.aborted) {\n        onAbort();\n        return;\n      }\n      signal.addEventListener(\"abort\", onAbort, { once: true });\n    }\n  });\n}\n","import { createHash } from \"node:crypto\";\nimport {\n  AnonApiKeySchema,\n  DevApiKeySchema,\n  type AnonApiKey,\n  type DevApiKey,\n} from \"@glasstrace/protocol\";\nimport { readAnonKey, readClaimedKey } from \"./anon-key.js\";\nimport { atomicWriteFile } from \"./atomic-write.js\";\n\n/**\n * Glasstrace MCP endpoint embedded in managed MCP configs and used by\n * the runtime claim-refresh path. Lives here (not in `cli/constants.ts`)\n * so the runtime helper can reach it without crossing the runtime/CLI\n * boundary; CLI callers import it directly from this module.\n */\nexport const MCP_ENDPOINT = \"https://api.glasstrace.dev/mcp\";\n\n/**\n * Runtime-safe MCP credential and config utilities.\n *\n * This module is loaded into user processes at SDK boot. It must not\n * import from `cli/*` or `agent-detection/*` so the runtime bundle does\n * not pull in CLI scaffolding or filesystem scanners. The boundary is\n * enforced by an import-graph guard test.\n *\n * Internal: not re-exported via `node-entry.ts` or `index.ts`.\n *\n * @module\n */\n\nlet fsPathCache:\n  | { fs: typeof import(\"node:fs/promises\"); path: typeof import(\"node:path\") }\n  | null\n  | undefined;\n\nasync function loadFsPath(): Promise<\n  | { fs: typeof import(\"node:fs/promises\"); path: typeof import(\"node:path\") }\n  | null\n> {\n  if (fsPathCache !== undefined) return fsPathCache;\n  try {\n    const [fs, path] = await Promise.all([\n      import(\"node:fs/promises\"),\n      import(\"node:path\"),\n    ]);\n    fsPathCache = { fs, path };\n    return fsPathCache;\n  } catch {\n    fsPathCache = null;\n    return null;\n  }\n}\n\n/**\n * Computes a stable identity fingerprint for deduplication purposes.\n * This is NOT password hashing — the input is an opaque token used as\n * a marker identity, not a credential stored for authentication.\n *\n * @internal Exported for unit testing and for `cli/scaffolder.ts`'s\n *   marker writer.\n */\nexport function identityFingerprint(token: string): string {\n  return `sha256:${createHash(\"sha256\").update(token).digest(\"hex\")}`;\n}\n\n/**\n * Compares two MCP config strings for strict canonical-JSON equality.\n * Returns `true` when both inputs parse as JSON and produce structurally\n * equal objects after recursive key sorting; falls back to trimmed text\n * comparison for TOML and other non-JSON formats. Returns `false` on\n * parse errors that don't fall through to text comparison.\n *\n * Used to detect manually-edited MCP configs before overwriting them\n * and as the staleness signal for SDK-managed\n * configs that must be refreshed when the project's effective\n * credential changes.\n *\n * The matcher is intentionally strict: a hand-edited file that drops\n * any field (including `type: \"http\"` on a Claude `.mcp.json`) must\n * NOT be treated as SDK-managed and silently overwritten on re-init.\n * Callers that need backwards-compatible recognition of the legacy\n * generic `.glasstrace/mcp.json` shape (no `type: \"http\"`, written by\n * older SDK versions) should use\n * {@link genericMcpConfigOrLegacyShapeMatches} instead.\n *\n * @internal Exported for unit testing only.\n */\nexport function mcpConfigMatches(\n  existingContent: string,\n  expectedContent: string,\n): boolean {\n  const trimmedExpected = expectedContent.trim();\n\n  try {\n    const existingParsed: unknown = JSON.parse(existingContent);\n    const expectedParsed: unknown = JSON.parse(trimmedExpected);\n    return (\n      JSON.stringify(canonicalize(existingParsed)) ===\n      JSON.stringify(canonicalize(expectedParsed))\n    );\n  } catch {\n    // Fall through to text comparison for TOML and other non-JSON formats.\n  }\n\n  return existingContent.trim() === trimmedExpected;\n}\n\n/**\n * Generic-shape variant of {@link mcpConfigMatches} that also recognizes\n * the legacy `.glasstrace/mcp.json` shape written by older SDK\n * versions (the same generic shape minus `type: \"http\"`).\n *\n * Scoped to callers that operate exclusively on `.glasstrace/mcp.json`\n * (currently {@link refreshMcpConfigAfterClaim}). It must not be used\n * by per-agent init paths: `decideMcpConfigAction` runs against every\n * detected agent's `.mcp.json`, and a Claude file whose `type` field\n * was hand-edited away must NOT be treated as SDK-managed and silently\n * overwritten on re-init. The shared {@link mcpConfigMatches} stays\n * strict for that reason; the legacy fallback lives here.\n *\n * The fallback is bounded: only the specific legacy generic shape\n * (the new shape minus `type: \"http\"`) is accepted; arbitrary field\n * omissions still report a mismatch.\n *\n * @internal Exported for unit testing only.\n */\nexport function genericMcpConfigOrLegacyShapeMatches(\n  existingContent: string,\n  expectedGenericContent: string,\n): boolean {\n  if (mcpConfigMatches(existingContent, expectedGenericContent)) {\n    return true;\n  }\n\n  try {\n    const expectedParsed: unknown = JSON.parse(expectedGenericContent.trim());\n    const expectedLegacy = stripTypeFromGlasstraceServer(expectedParsed);\n    if (expectedLegacy === null) {\n      return false;\n    }\n    const existingParsed: unknown = JSON.parse(existingContent);\n    return (\n      JSON.stringify(canonicalize(existingParsed)) ===\n      JSON.stringify(canonicalize(expectedLegacy))\n    );\n  } catch {\n    return false;\n  }\n}\n\n/**\n * Returns a copy of `value` with `type: \"http\"` removed from\n * `mcpServers.glasstrace`, or `null` when `value` is not the new\n * Claude-compatible SDK shape. Used by\n * {@link genericMcpConfigOrLegacyShapeMatches} to recognize legacy\n * on-disk files written by older SDK versions.\n *\n * The helper is deliberately narrow: it only strips when `type` is\n * exactly the string `\"http\"`, and only from the `glasstrace` server\n * entry. Any structural mismatch (non-object root, missing\n * `mcpServers`, missing `glasstrace`, or `type !== \"http\"`) yields\n * `null`, leaving the strict canonical comparison's verdict in place.\n */\nfunction stripTypeFromGlasstraceServer(value: unknown): unknown | null {\n  if (value === null || typeof value !== \"object\" || Array.isArray(value)) {\n    return null;\n  }\n  const root = value as Record<string, unknown>;\n  const servers = root[\"mcpServers\"];\n  if (\n    servers === null ||\n    typeof servers !== \"object\" ||\n    Array.isArray(servers)\n  ) {\n    return null;\n  }\n  const serversObj = servers as Record<string, unknown>;\n  const server = serversObj[\"glasstrace\"];\n  if (\n    server === null ||\n    typeof server !== \"object\" ||\n    Array.isArray(server)\n  ) {\n    return null;\n  }\n  const serverObj = server as Record<string, unknown>;\n  if (serverObj[\"type\"] !== \"http\") {\n    return null;\n  }\n  const { type: _omittedType, ...serverWithoutType } = serverObj;\n  void _omittedType;\n  return {\n    ...root,\n    mcpServers: {\n      ...serversObj,\n      glasstrace: serverWithoutType,\n    },\n  };\n}\n\nfunction canonicalize(value: unknown): unknown {\n  if (Array.isArray(value)) {\n    return value.map(canonicalize);\n  }\n  if (value !== null && typeof value === \"object\") {\n    const obj = value as Record<string, unknown>;\n    const sorted: Record<string, unknown> = {};\n    for (const key of Object.keys(obj).sort()) {\n      sorted[key] = canonicalize(obj[key]);\n    }\n    return sorted;\n  }\n  return value;\n}\n\n/**\n * Parses a `.env.local` file's text content for `GLASSTRACE_API_KEY`,\n * returning the last assignment's value. Empty values\n * (`GLASSTRACE_API_KEY=`) and the `your_key_here` placeholder are\n * filtered out. Surrounding single or double quotes are stripped.\n *\n * The resolver validates the returned value against `DevApiKeySchema`\n * before accepting it; this parser is permissive on purpose so that\n * malformed values can be flagged with a `malformed-env-local`\n * warning rather than silently dropped.\n *\n * @internal Exported for unit testing only.\n */\nexport function readEnvLocalApiKey(content: string): string | null {\n  let last: string | null = null;\n  const regex = /^\\s*GLASSTRACE_API_KEY\\s*=\\s*(.*)$/gm;\n  let match: RegExpExecArray | null;\n  while ((match = regex.exec(content)) !== null) {\n    const raw = match[1].trim();\n    if (raw === \"\") continue;\n    const unquoted = raw.replace(/^(['\"])(.*)\\1$/, \"$2\");\n    if (unquoted === \"\" || unquoted === \"your_key_here\") continue;\n    last = unquoted;\n  }\n  return last;\n}\n\n/**\n * Returns true when the given API key value looks like a claimed\n * developer key (prefix `gt_dev_`). Defensive against leading or\n * trailing whitespace.\n *\n * **This is a prefix-only check, not strict validation.** Use it as a\n * fast path for \"looks like a claimed key, do not overwrite\". The\n * effective-credential resolver validates with\n * `DevApiKeySchema.safeParse` because a `gt_dev_` prefix alone is not\n * sufficient to authenticate against the backend.\n *\n * @internal Exported for unit testing only.\n */\nexport function isDevApiKey(value: string | null | undefined): boolean {\n  if (value === null || value === undefined) return false;\n  return value.trim().startsWith(\"gt_dev_\");\n}\n\n/**\n * Returns true when the given API key value is a fully-valid anonymous\n * API key (matches `AnonApiKeySchema`). Used by `registerViaCli` as a\n * runtime guard so that a `DevApiKey` cannot be passed via process\n * arguments to vendor MCP CLIs (which would expose it via `ps` on\n * multi-user hosts).\n *\n * @internal Exported for unit testing only.\n */\nexport function isAnonApiKey(value: string | null | undefined): boolean {\n  if (value === null || value === undefined) return false;\n  return AnonApiKeySchema.safeParse(value).success;\n}\n\n/**\n * The MCP-effective credential, tagged by which on-disk source produced\n * it. `env-local` and `claimed-key` carry a branded `DevApiKey`;\n * `anon` carries a branded `AnonApiKey`. Internal — not re-exported.\n */\nexport type EffectiveMcpCredential =\n  | { source: \"env-local\"; key: DevApiKey }\n  | { source: \"claimed-key\"; key: DevApiKey }\n  | { source: \"anon\"; key: AnonApiKey };\n\n/**\n * Surfaced when the resolver detected a recoverable anomaly the caller\n * should inform the user about without printing key material.\n *\n * - `malformed-env-local`: `.env.local` set `GLASSTRACE_API_KEY` to a\n *   value that fails `DevApiKeySchema`. The resolver fell through.\n * - `claimed-key-only`: the effective credential came from\n *   `.glasstrace/claimed-key` because `.env.local` had no usable dev\n *   key. Suggest the user copy the key into `.env.local`.\n */\nexport type ResolveWarning = \"malformed-env-local\" | \"claimed-key-only\";\n\n/**\n * The resolved credential plus the on-disk anon key (returned\n * separately so the staleness check does not have to re-read the\n * file) and any warnings the caller should surface to the user.\n */\nexport interface ResolveResult {\n  effective: EffectiveMcpCredential | null;\n  anonKey: AnonApiKey | null;\n  warnings: ReadonlyArray<ResolveWarning>;\n}\n\n/**\n * Resolves the MCP-effective credential for a project, in priority\n * order: `.env.local` `GLASSTRACE_API_KEY` (validated as\n * `DevApiKeySchema`) → `.glasstrace/claimed-key` (validated as\n * `DevApiKeySchema`) → `.glasstrace/anon_key` (`AnonApiKey`). Returns\n * `null` for `effective` only when no source produced a usable key.\n *\n * The function is async because it touches the filesystem. It is\n * called only on the post-claim runtime branch and from the CLI\n * commands `glasstrace init` and `glasstrace mcp add`. It is **not**\n * on the steady-state init path.\n */\nexport async function resolveEffectiveMcpCredential(\n  projectRoot?: string,\n): Promise<ResolveResult> {\n  const root = projectRoot ?? process.cwd();\n  const warnings: ResolveWarning[] = [];\n\n  const envLocalKey = await readEnvLocalDevKey(root, warnings);\n  const claimedKey = envLocalKey === null ? await readClaimedKey(root) : null;\n  const anonKey = await readAnonKey(root);\n\n  let effective: EffectiveMcpCredential | null = null;\n  if (envLocalKey !== null) {\n    effective = { source: \"env-local\", key: envLocalKey };\n  } else if (claimedKey !== null) {\n    effective = { source: \"claimed-key\", key: claimedKey };\n    warnings.push(\"claimed-key-only\");\n  } else if (anonKey !== null) {\n    effective = { source: \"anon\", key: anonKey };\n  }\n\n  return { effective, anonKey, warnings };\n}\n\nasync function readEnvLocalDevKey(\n  root: string,\n  warnings: ResolveWarning[],\n): Promise<DevApiKey | null> {\n  const modules = await loadFsPath();\n  if (!modules) return null;\n\n  const envPath = modules.path.join(root, \".env.local\");\n  let content: string;\n  try {\n    content = await modules.fs.readFile(envPath, \"utf-8\");\n  } catch {\n    return null;\n  }\n\n  const raw = readEnvLocalApiKey(content);\n  if (raw === null) return null;\n\n  const parsed = DevApiKeySchema.safeParse(raw);\n  if (!parsed.success) {\n    warnings.push(\"malformed-env-local\");\n    return null;\n  }\n  return parsed.data;\n}\n\n/**\n * Source label for the credential a marker file describes.\n *\n * @internal\n */\nexport type MarkerCredentialSource = \"env-local\" | \"claimed-key\" | \"anon\";\n\n/**\n * Descriptor passed to {@link writeMcpMarker} and matched by\n * {@link readMcpMarker}. `credentialHash` is the\n * `identityFingerprint` of the credential actually written into the\n * managed MCP config — never the credential itself.\n *\n * @internal\n */\nexport interface MarkerTarget {\n  credentialSource: MarkerCredentialSource;\n  credentialHash: string;\n}\n\n/**\n * Normalized state of a `.glasstrace/mcp-connected` marker on disk.\n *\n * - `absent`: no marker file present.\n * - `valid`: a v1 or v2 marker that parsed cleanly. v1 markers are\n *   reported as `credentialSource = \"anon\"` with `credentialHash`\n *   taken from the legacy `keyHash` field (the v1 schema can only\n *   describe an anon credential).\n * - `unknown-version`: the marker has `version > 2`. Treat as\n *   not-configured so a future SDK that wrote the marker doesn't\n *   block this SDK from refreshing.\n * - `corrupted`: parse failure or schema mismatch. Treat as\n *   not-configured.\n *\n * @internal\n */\nexport type MarkerState =\n  | { status: \"absent\" }\n  | { status: \"valid\"; credentialSource: MarkerCredentialSource; credentialHash: string }\n  | { status: \"unknown-version\" }\n  | { status: \"corrupted\" };\n\nconst MCP_MARKER_FILE = \"mcp-connected\";\nconst GLASSTRACE_DIR = \".glasstrace\";\n\n/**\n * Reads `.glasstrace/mcp-connected` and returns its normalized state.\n * Used by `mcp add` (marker-mismatch detection) and by\n * {@link writeMcpMarker} (skip-if-match optimization).\n *\n * Reader rules per the design:\n * - `version === undefined` → v1: `{ keyHash, configuredAt }`. Mapped\n *   to `credentialSource: \"anon\"`, `credentialHash: keyHash`. v1's\n *   `keyHash` is itself produced by `identityFingerprint`, so the\n *   format matches v2 without conversion.\n * - `version === 2` → v2 reader.\n * - `version > 2` → `unknown-version` (conservative-fail).\n * - Parse failure → `corrupted` (conservative-fail).\n *\n * @internal Exported for unit testing only.\n */\nexport async function readMcpMarker(projectRoot?: string): Promise<MarkerState> {\n  const root = projectRoot ?? process.cwd();\n  const modules = await loadFsPath();\n  if (!modules) return { status: \"absent\" };\n\n  const markerPath = modules.path.join(root, GLASSTRACE_DIR, MCP_MARKER_FILE);\n  let content: string;\n  try {\n    content = await modules.fs.readFile(markerPath, \"utf-8\");\n  } catch {\n    return { status: \"absent\" };\n  }\n\n  let parsed: unknown;\n  try {\n    parsed = JSON.parse(content);\n  } catch {\n    return { status: \"corrupted\" };\n  }\n\n  if (parsed === null || typeof parsed !== \"object\") {\n    return { status: \"corrupted\" };\n  }\n\n  const obj = parsed as Record<string, unknown>;\n  const version = obj[\"version\"];\n\n  if (version === undefined) {\n    // v1: { keyHash, configuredAt }\n    const keyHash = obj[\"keyHash\"];\n    if (typeof keyHash !== \"string\" || keyHash === \"\") {\n      return { status: \"corrupted\" };\n    }\n    return {\n      status: \"valid\",\n      credentialSource: \"anon\",\n      credentialHash: keyHash,\n    };\n  }\n\n  if (version === 2) {\n    const source = obj[\"credentialSource\"];\n    const hash = obj[\"credentialHash\"];\n    if (\n      (source !== \"env-local\" && source !== \"claimed-key\" && source !== \"anon\") ||\n      typeof hash !== \"string\" ||\n      hash === \"\"\n    ) {\n      return { status: \"corrupted\" };\n    }\n    return {\n      status: \"valid\",\n      credentialSource: source,\n      credentialHash: hash,\n    };\n  }\n\n  if (typeof version === \"number\" && version > 2) {\n    return { status: \"unknown-version\" };\n  }\n\n  return { status: \"corrupted\" };\n}\n\n/**\n * Writes a v2 `.glasstrace/mcp-connected` marker. Returns `true` when\n * the marker was created or updated, `false` when an existing marker\n * already records the same `(credentialSource, credentialHash)` pair\n * and was left untouched.\n *\n * Writer always emits v2 with `version: 2`. The legacy `keyHash`\n * field is intentionally omitted from new writes — v1 readers ignore\n * unknown fields and the duplicate would diverge over time. v3+ and\n * corrupted markers are unconditionally overwritten.\n *\n * The directory is created with `0o700` and the file with `0o600`,\n * matching existing scaffolder behavior.\n *\n * @internal Exported for unit testing only.\n */\nexport async function writeMcpMarker(\n  projectRoot: string,\n  target: MarkerTarget,\n): Promise<boolean> {\n  const modules = await loadFsPath();\n  if (!modules) return false;\n\n  const dirPath = modules.path.join(projectRoot, GLASSTRACE_DIR);\n  const markerPath = modules.path.join(dirPath, MCP_MARKER_FILE);\n\n  const state = await readMcpMarker(projectRoot);\n  if (\n    state.status === \"valid\" &&\n    state.credentialSource === target.credentialSource &&\n    state.credentialHash === target.credentialHash\n  ) {\n    return false;\n  }\n\n  await modules.fs.mkdir(dirPath, { recursive: true, mode: 0o700 });\n\n  const body = JSON.stringify(\n    {\n      version: 2,\n      credentialSource: target.credentialSource,\n      credentialHash: target.credentialHash,\n      configuredAt: new Date().toISOString(),\n    },\n    null,\n    2,\n  );\n\n  await modules.fs.writeFile(markerPath, body, { mode: 0o600 });\n  // writeFile mode only applies on creation on some platforms.\n  await modules.fs.chmod(markerPath, 0o600);\n  return true;\n}\n\nconst MCP_CONFIG_FILE = \"mcp.json\";\n\n/**\n * The set of outcomes the runtime claim-refresh helper can produce.\n *\n * - `rewrote`: `.glasstrace/mcp.json` matched the SDK-shaped output\n *   for the on-disk anon key, was rewritten with the effective\n *   credential, and the marker was updated.\n * - `preserved`: `.glasstrace/mcp.json` exists but does not match the\n *   SDK-shaped output for the on-disk anon key. The file is left\n *   untouched (the user may have hand-edited it). The marker is not\n *   touched.\n * - `absent`: `.glasstrace/mcp.json` does not exist (`ENOENT`), or\n *   no anon key is on disk so there is nothing to compare against. A\n *   project without an anon key never had an SDK-shaped `mcp.json`\n *   written by the runtime path, so this branch is a true no-op.\n * - `skipped-anon-source`: the effective credential is `null` or its\n *   source is `\"anon\"`. Either way, there is no claim transition to\n *   refresh for. Caller should generally gate on\n *   `effective.source !== \"anon\"` before invoking the helper; this\n *   branch is the runtime-side belt-and-suspenders.\n * - `skipped-not-persisted`: never reached in practice — the caller\n *   in `init-client.ts` gates on `writeClaimedKey`'s `persisted` not\n *   being `\"none\"`. The variant exists so an exhaustive switch in\n *   the caller stays exhaustive if the gate is removed.\n *\n * @internal\n */\nexport type RuntimeRefreshAction =\n  | \"rewrote\"\n  | \"preserved\"\n  | \"absent\"\n  | \"skipped-anon-source\"\n  | \"skipped-not-persisted\";\n\nlet refreshNudgeEmitted = false;\n\n/**\n * @internal Exported for unit testing only — resets the per-process\n *   \"refresh nudge already emitted\" flag.\n */\nexport function __resetRefreshNudgeForTest(): void {\n  refreshNudgeEmitted = false;\n}\n\n/**\n * Emits a single redacted stderr line announcing the MCP config\n * refresh. Deduplicated per process via a module-level flag — a\n * second call within the same process is a no-op. Cross-process\n * dedup (the same user running `mcp add` in another terminal moments\n * later) is explicitly out of scope.\n */\nfunction emitRefreshNudge(persistedSource: \"env-local\" | \"claimed-key\"): void {\n  if (refreshNudgeEmitted) return;\n  refreshNudgeEmitted = true;\n  try {\n    if (persistedSource === \"claimed-key\") {\n      process.stderr.write(\n        \"[glasstrace] MCP config refreshed for the new credential. \" +\n          \"Copy .glasstrace/claimed-key into .env.local so Codex can pick it up on next restart.\\n\",\n      );\n    } else {\n      process.stderr.write(\n        \"[glasstrace] MCP config refreshed for the new credential.\\n\",\n      );\n    }\n  } catch {\n    // stderr is best-effort; refresh outcome must not depend on it.\n  }\n}\n\n/**\n * Returns the SDK-shaped JSON for `.glasstrace/mcp.json` (the generic\n * MCP config used at runtime). Inlined here — and intentionally not\n * imported from `agent-detection/configs.ts` — because the runtime\n * path must not pull `agent-detection` into the runtime bundle. The\n * shape matches what `generateMcpConfig({ name: \"generic\", ... },\n * endpoint, bearer)` would produce. If the agent-detection version\n * diverges, the staleness check stops detecting SDK-managed configs;\n * a regression test against `generateMcpConfig`'s \"generic\" branch\n * lives in `tests/unit/sdk/mcp-runtime.test.ts`.\n */\nfunction genericMcpConfigContent(endpoint: string, bearer: string): string {\n  return JSON.stringify(\n    {\n      mcpServers: {\n        glasstrace: {\n          type: \"http\",\n          url: endpoint,\n          headers: {\n            Authorization: `Bearer ${bearer}`,\n          },\n        },\n      },\n    },\n    null,\n    2,\n  );\n}\n\n/**\n * Refreshes `.glasstrace/mcp.json` after a successful account claim\n * transition has persisted a dev/account credential to disk (via\n * `writeClaimedKey`). The file is rewritten only when its content\n * matches the SDK-shaped output for the project's on-disk anon key\n * (canonical-JSON equivalence via `mcpConfigMatches` — whitespace and\n * key order are normalised before comparison). User-edited or\n * third-party `mcp.json` content is preserved.\n *\n * Atomic write protocol: write the replacement to a sibling temp\n * path, set `0o600`, then `rename` into place. This matches the\n * existing pattern at `init-client.ts` for `.glasstrace/config`,\n * `anon-key.ts` for `.glasstrace/anon_key`, and `runtime-state.ts`.\n * The temp must be on the same filesystem as the destination for the\n * `rename` to be atomic.\n *\n * The helper is invoked only on the post-claim runtime branch (see\n * `init-client.ts` `performInit`) and never on the steady-state init\n * path. It must not throw — failures during write/chmod/rename or\n * marker update surface as `\"preserved\"` so the caller's\n * `claimResult` return is preserved. The temp file is best-effort\n * cleaned up on failure to avoid leaving stale `.tmp` siblings on\n * disk.\n *\n * @internal Exported for unit testing only; not re-exported from\n *   `node-entry.ts` or `index.ts`.\n */\nexport async function refreshGenericMcpConfigAtRuntime(\n  projectRoot: string,\n  effective: EffectiveMcpCredential | null,\n  anonKeyOnDisk: AnonApiKey | null,\n): Promise<{ action: RuntimeRefreshAction }> {\n  if (effective === null || effective.source === \"anon\") {\n    return { action: \"skipped-anon-source\" };\n  }\n\n  // Dev-key-only project (no .glasstrace/anon_key on disk): the\n  // staleness check has nothing to compare against. The SDK never\n  // wrote mcp.json without an anon key, so there is nothing to\n  // refresh.\n  if (anonKeyOnDisk === null) {\n    return { action: \"absent\" };\n  }\n\n  const modules = await loadFsPath();\n  if (!modules) return { action: \"absent\" };\n\n  const dirPath = modules.path.join(projectRoot, GLASSTRACE_DIR);\n  const configPath = modules.path.join(dirPath, MCP_CONFIG_FILE);\n\n  let existing: string;\n  try {\n    existing = await modules.fs.readFile(configPath, \"utf-8\");\n  } catch (err) {\n    const code = (err as NodeJS.ErrnoException).code;\n    if (code === \"ENOENT\") {\n      return { action: \"absent\" };\n    }\n    return { action: \"preserved\" };\n  }\n\n  const expectedAnon = genericMcpConfigContent(MCP_ENDPOINT, anonKeyOnDisk);\n  if (!genericMcpConfigOrLegacyShapeMatches(existing, expectedAnon)) {\n    return { action: \"preserved\" };\n  }\n\n  // SDK-managed and stale. Replace atomically per SDK 2.0 §4.3:\n  // tmp + fsync(tmp) + rename + fsync(parent). Any failure in the\n  // helper or marker update path must produce a non-throw outcome\n  // so the caller's claimResult return is preserved; the helper\n  // best-effort cleans up the .tmp sibling on failure.\n  const replacement = genericMcpConfigContent(MCP_ENDPOINT, effective.key);\n  try {\n    await atomicWriteFile(configPath, replacement, { mode: 0o600 });\n\n    await writeMcpMarker(projectRoot, {\n      credentialSource: effective.source,\n      credentialHash: identityFingerprint(effective.key),\n    });\n  } catch {\n    return { action: \"preserved\" };\n  }\n\n  emitRefreshNudge(effective.source);\n\n  return { action: \"rewrote\" };\n}\n","/**\n * Atomic file-write helper.\n *\n * Implements the durability half of the atomic-write protocol\n * (`docs/component-designs/sdk-architecture.md` §4.3 — Atomic file\n * writes; durability protocol steps 6–9):\n *\n *   1. Write the payload to a sibling temp file in the **same**\n *      directory as the final target. The shared directory guarantees\n *      `rename(2)` stays on the same filesystem and therefore atomic\n *      per POSIX semantics.\n *   2. **fsync the temp file.** Forces data and metadata to durable\n *      storage before the rename is observable.\n *   3. **rename atomically into place.** Readers see either the old\n *      file contents or the new ones, never a partial write.\n *   4. **fsync the parent directory.** On POSIX, `rename(2)` durability\n *      is not guaranteed until the containing directory's own metadata\n *      is synced. Without this step, a power loss between rename and\n *      parent-dir sync can leave the rename invisible after reboot\n *      (the kernel acknowledges the syscall but the metadata never\n *      reached durable storage).\n *\n * Closes a durability gap where an anonymous key could be unlinked\n * silently on re-init under crash interleavings.\n *\n * Out-of-scope by design:\n *   - The `lstat → tmp → rename → re-lstat` TOCTOU re-check (spec\n *     §4.3 steps 1–2 and 7's re-verification) is next-major scope per\n *     `sdk-architecture.md` §4.3 — TOCTOU protection.\n *   - The `GLASSTRACE_TEST_CRASH_AFTER` crash-injection harness is\n *     next-major scope per `sdk-architecture.md` §4.3 — Crash-injection\n *     harness.\n *   - Structured error-with-step-number reporting is next-major scope\n *     per `sdk-architecture.md` §4.3 — durability protocol step 9.\n *\n * Cross-platform behavior:\n *   - On POSIX (Linux, macOS), the parent-directory fsync uses an\n *     `open(O_RDONLY) → fsync → close` sequence. This is the canonical\n *     way to flush directory metadata.\n *   - On Windows, opening a directory for read returns `EISDIR` (and\n *     `fsync` on the resulting handle would fail with `EINVAL` even\n *     if the open succeeded). NTFS's rename semantics also do not\n *     require an explicit directory fsync to commit the rename\n *     metadata. The helper therefore swallows `EISDIR`, `EINVAL`,\n *     `EPERM`, and `ENOTSUP` from the parent-dir fsync step. Any\n *     other error from the open/fsync/close sequence still propagates\n *     so genuine I/O failures are not silently ignored.\n *\n * Concurrency:\n *   - Two processes writing the same target concurrently follow\n *     last-rename-wins semantics. The helper does not lock; the\n *     caller is responsible for any external mutual-exclusion. This\n *     matches the existing 0.19.x behavior of every migrated call\n *     site — the helper does not change concurrency guarantees, only\n *     durability.\n *\n * Performance:\n *   - `fsync` is intrinsically expensive on rotational media (one\n *     full disk-cache flush). The sync variant is exposed for the\n *     `runtime-state.ts` writer, which runs in a signal handler with\n *     a strict time budget; existing callers were already issuing a\n *     blocking `writeFileSync + renameSync`, so the additional cost\n *     is the two `fsync` calls. On modern SSDs this remains in the\n *     low-millisecond range.\n *\n * Module-load safety: `node:fs` and `node:fs/promises` are loaded\n *   lazily so the module can be imported in non-Node environments\n *   (Edge Runtime, browser bundles) without crashing at import time.\n *   Calling any helper export in such an environment throws a clear\n *   error; callers that may run on the edge must therefore probe\n *   their own Node-availability before reaching this module (see\n *   `init-client.ts`'s `loadFsPathAsync`).\n *\n * @internal Not re-exported from `index.ts`/`node-entry.ts`/\n *   `edge-entry.ts`. Importable only from sibling SDK modules.\n */\n\nimport type { FileHandle } from \"node:fs/promises\";\n\n/**\n * Resolves the parent directory of a path without importing `node:path`,\n * so this module remains importable in non-Node environments where\n * `node:path` is unavailable. Handles both POSIX (`/`) and Windows\n * (`\\\\`) separators because Windows paths can use either form.\n *\n * Behavior matches `path.dirname` for the inputs this module receives\n * (always absolute paths produced by SDK callers): finds the last\n * separator and returns the prefix; returns `\".\"` if no separator is\n * present (a relative leaf name); preserves the root for `/foo` →\n * `/`. Edge cases like trailing-separator inputs are not exercised by\n * SDK callers so are not modeled here.\n */\nfunction parentDir(filePath: string): string {\n  const lastSlash = filePath.lastIndexOf(\"/\");\n  const lastBackslash = filePath.lastIndexOf(\"\\\\\");\n  const lastSep = Math.max(lastSlash, lastBackslash);\n  if (lastSep < 0) return \".\";\n  if (lastSep === 0) return filePath.slice(0, 1); // root: \"/x\" → \"/\"\n  return filePath.slice(0, lastSep);\n}\n\n/**\n * Options accepted by both `atomicWriteFile` and `atomicWriteFileSync`.\n *\n * The shape mirrors the relevant subset of `fs.writeFile`'s options\n * object. `mode` defaults to `0o600` (state files); callers writing\n * static or discoverable files (e.g., `.well-known/glasstrace.json`)\n * may pass `0o644`. `encoding` defaults to `\"utf-8\"` when the payload\n * is a string and is ignored when the payload is a `Uint8Array`.\n */\nexport interface AtomicWriteOptions {\n  /**\n   * POSIX file mode applied to the temp file before the rename.\n   * Defaults to `0o600`. The mode applies to the temp file and is\n   * carried through the rename; callers that need a different\n   * post-rename mode should call `chmod` themselves after this\n   * helper resolves.\n   *\n   * The helper re-applies this mode unconditionally via `chmod`/`chmodSync`\n   * after writing, so a pre-existing temp file (e.g., residue from a\n   * crashed prior run) cannot carry stale permissive bits into the\n   * caller's renamed target. The fsync handle is opened read-only so\n   * callers passing a read-only mode (e.g. `0o444`) are still supported.\n   */\n  mode?: number;\n  /**\n   * Encoding for string payloads. Defaults to `\"utf-8\"`. Ignored when\n   * the payload is a `Uint8Array`.\n   */\n  encoding?: BufferEncoding;\n}\n\n/** Errno codes that the parent-dir fsync step is permitted to swallow. */\nconst PARENT_FSYNC_SWALLOWED_CODES: ReadonlySet<string> = new Set([\n  \"EISDIR\",\n  \"EINVAL\",\n  \"EPERM\",\n  \"ENOTSUP\",\n]);\n\n/**\n * Reads the `code` property off an `unknown` thrown value if present.\n * Helper avoids `as` casts on `err` and works with both plain objects\n * and `NodeJS.ErrnoException` instances.\n */\nfunction errnoCodeOf(err: unknown): string | undefined {\n  if (err === null || typeof err !== \"object\") return undefined;\n  const code = (err as { code?: unknown }).code;\n  return typeof code === \"string\" ? code : undefined;\n}\n\n/**\n * Builds the path of the sibling temp file. The temp lives in the\n * same directory as the target so the eventual `rename(2)` stays on\n * the same filesystem.\n *\n * Callers may pre-compute their own temp paths (e.g., `<path>.tmp-\n * <pid>` for the discovery-file write to keep multi-process collisions\n * disambiguated). When they do, they call the helper's `*WithTmp`\n * variants. The default temp suffix is `.tmp` for parity with the\n * existing 0.19.x call sites.\n */\nfunction defaultTmpPath(targetPath: string): string {\n  return `${targetPath}.tmp`;\n}\n\n// ---------------------------------------------------------------------------\n// Lazy module loaders\n// ---------------------------------------------------------------------------\n\nlet fsPromisesCache: typeof import(\"node:fs/promises\") | null | undefined;\nlet fsSyncCache: typeof import(\"node:fs\") | null | undefined;\n\nasync function loadFsPromises(): Promise<typeof import(\"node:fs/promises\")> {\n  if (fsPromisesCache !== undefined) {\n    if (fsPromisesCache === null) {\n      throw new Error(\n        \"node:fs/promises is unavailable in this environment; atomicWriteFile cannot be used here.\",\n      );\n    }\n    return fsPromisesCache;\n  }\n  try {\n    fsPromisesCache = await import(\"node:fs/promises\");\n    return fsPromisesCache;\n  } catch {\n    fsPromisesCache = null;\n    throw new Error(\n      \"node:fs/promises is unavailable in this environment; atomicWriteFile cannot be used here.\",\n    );\n  }\n}\n\nfunction loadFsSync(): typeof import(\"node:fs\") {\n  if (fsSyncCache !== undefined) {\n    if (fsSyncCache === null) {\n      throw new Error(\n        \"node:fs is unavailable in this environment; atomicWriteFileSync cannot be used here.\",\n      );\n    }\n    return fsSyncCache;\n  }\n  try {\n    // eslint-disable-next-line @typescript-eslint/no-require-imports, glasstrace/no-unguarded-node-require -- guarded by the surrounding try/catch which caches `null` and surfaces a clean Error on subsequent calls; consumers gate with `isSyncFsAvailable()` (DISC-1555).\n    fsSyncCache = require(\"node:fs\") as typeof import(\"node:fs\");\n    return fsSyncCache;\n  } catch {\n    fsSyncCache = null;\n    throw new Error(\n      \"node:fs is unavailable in this environment; atomicWriteFileSync cannot be used here.\",\n    );\n  }\n}\n\n// ---------------------------------------------------------------------------\n// Async variant\n// ---------------------------------------------------------------------------\n\n/**\n * Atomically writes `payload` to `targetPath` using\n * `tmp + fsync(tmp) + rename + fsync(parent)` semantics.\n *\n * On any error from the write/fsync/rename steps, the helper makes a\n * best-effort attempt to remove the temp file and rethrows the\n * original error. The parent-dir fsync step swallows\n * `EISDIR`/`EINVAL`/`EPERM`/`ENOTSUP` to support platforms where\n * directory fsync is not supported (notably Windows on NTFS).\n *\n * @param targetPath Absolute path to the final destination.\n * @param payload    `string` or `Uint8Array` payload.\n * @param options    See {@link AtomicWriteOptions}.\n */\nexport async function atomicWriteFile(\n  targetPath: string,\n  payload: string | Uint8Array,\n  options: AtomicWriteOptions = {},\n): Promise<void> {\n  return atomicWriteFileWithTmp(targetPath, defaultTmpPath(targetPath), payload, options);\n}\n\n/**\n * Async variant accepting an explicit `tmpPath`. The temp path MUST\n * live in the same directory as `targetPath` to preserve rename\n * atomicity. Used by `cli/discovery-file.ts` to disambiguate\n * concurrent writers via a `.tmp-<pid>` suffix.\n */\nexport async function atomicWriteFileWithTmp(\n  targetPath: string,\n  tmpPath: string,\n  payload: string | Uint8Array,\n  options: AtomicWriteOptions = {},\n): Promise<void> {\n  const mode = options.mode ?? 0o600;\n  const encoding = options.encoding ?? \"utf-8\";\n  const fsp = await loadFsPromises();\n\n  let handle: FileHandle | null = null;\n  try {\n    // Step 1: write payload to the temp file.\n    if (typeof payload === \"string\") {\n      await fsp.writeFile(tmpPath, payload, { encoding, mode });\n    } else {\n      await fsp.writeFile(tmpPath, payload, { mode });\n    }\n\n    // Step 1a: re-apply the requested mode unconditionally. `writeFile`\n    // only honors `mode` when it CREATES the file; if `tmpPath` is a\n    // pre-existing residue from a prior crash (or a hostile actor) the\n    // existing permissions are preserved, which would silently rename a\n    // world-readable temp into place. Path-based `chmod` lets the fsync\n    // handle below remain read-only, so callers that pass a read-only\n    // mode (e.g. 0o444) are still supported.\n    await fsp.chmod(tmpPath, mode);\n\n    // Step 2: fsync the temp file. Open then fsync via the\n    // `FileHandle.sync()` method — `writeFile` closes its internal\n    // handle immediately, so we re-open here. Read-only is sufficient\n    // for `fsync` and works for callers that supply a read-only `mode`.\n    handle = await fsp.open(tmpPath, \"r\");\n    await handle.sync();\n    await handle.close();\n    handle = null;\n\n    // Step 3: rename into place. POSIX-atomic on same-filesystem.\n    await fsp.rename(tmpPath, targetPath);\n  } catch (err) {\n    if (handle !== null) {\n      try {\n        await handle.close();\n      } catch {\n        // Best-effort: the original error takes precedence.\n      }\n    }\n    await removeTmpResidueAsync(fsp, tmpPath);\n    throw err;\n  }\n\n  // Step 4: fsync the parent directory. Failures on platforms that\n  // do not support directory fsync are swallowed; genuine I/O errors\n  // still propagate.\n  await fsyncParentDirAsync(targetPath, fsp);\n}\n\n/**\n * Best-effort removal of the temp file after a failed atomic-write\n * step. Tries `unlink` first (the common case where the temp is a\n * regular file). If `unlink` fails with `EISDIR`/`EPERM` — meaning the\n * temp path resolves to a directory left behind by a prior crash or\n * misconfiguration — falls back to a non-recursive `rmdir`. Any error\n * from either operation is swallowed so the caller can rethrow the\n * original I/O failure.\n */\nasync function removeTmpResidueAsync(\n  fsp: typeof import(\"node:fs/promises\"),\n  tmpPath: string,\n): Promise<void> {\n  try {\n    await fsp.unlink(tmpPath);\n    return;\n  } catch (err) {\n    const code = errnoCodeOf(err);\n    if (code !== \"EISDIR\" && code !== \"EPERM\") {\n      // Tmp may not exist (ENOENT), or unlink may have failed for an\n      // unrelated reason. Either way, nothing more to do — the\n      // original error takes precedence in the caller.\n      return;\n    }\n  }\n  try {\n    await fsp.rmdir(tmpPath);\n  } catch {\n    // Directory may be non-empty or otherwise unremovable; the original\n    // I/O failure remains the actionable error for the caller.\n  }\n}\n\nasync function fsyncParentDirAsync(\n  targetPath: string,\n  fsp: typeof import(\"node:fs/promises\"),\n): Promise<void> {\n  const parent = parentDir(targetPath);\n  let handle: FileHandle | null = null;\n  try {\n    handle = await fsp.open(parent, \"r\");\n    await handle.sync();\n  } catch (err) {\n    const code = errnoCodeOf(err);\n    if (code !== undefined && PARENT_FSYNC_SWALLOWED_CODES.has(code)) {\n      // Platform does not support directory fsync (Windows / NTFS).\n      // The rename has already returned successfully; durability\n      // semantics on those filesystems do not require an explicit\n      // directory sync.\n      return;\n    }\n    throw err;\n  } finally {\n    if (handle !== null) {\n      try {\n        await handle.close();\n      } catch {\n        // Close errors after a successful fsync are not actionable.\n      }\n    }\n  }\n}\n\n// ---------------------------------------------------------------------------\n// Sync variant\n// ---------------------------------------------------------------------------\n\n/**\n * Synchronous counterpart to {@link atomicWriteFile}. Exists for\n * `runtime-state.ts`, which writes from a signal handler that\n * cannot await. Otherwise prefer the async variant.\n */\nexport function atomicWriteFileSync(\n  targetPath: string,\n  payload: string | Uint8Array,\n  options: AtomicWriteOptions = {},\n): void {\n  atomicWriteFileSyncWithTmp(targetPath, defaultTmpPath(targetPath), payload, options);\n}\n\n/**\n * Sync variant accepting an explicit `tmpPath`. Mirrors\n * {@link atomicWriteFileWithTmp}.\n */\nexport function atomicWriteFileSyncWithTmp(\n  targetPath: string,\n  tmpPath: string,\n  payload: string | Uint8Array,\n  options: AtomicWriteOptions = {},\n): void {\n  const mode = options.mode ?? 0o600;\n  const encoding = options.encoding ?? \"utf-8\";\n  const fs = loadFsSync();\n\n  let fd: number | null = null;\n  try {\n    if (typeof payload === \"string\") {\n      fs.writeFileSync(tmpPath, payload, { encoding, mode });\n    } else {\n      fs.writeFileSync(tmpPath, payload, { mode });\n    }\n\n    // Re-apply the requested mode unconditionally — see the matching\n    // comment in `atomicWriteFileWithTmp` for the credential-leak\n    // rationale when `tmpPath` is pre-existing residue.\n    fs.chmodSync(tmpPath, mode);\n\n    // Read-only is sufficient for `fsync` and works for callers that\n    // supply a read-only `mode`.\n    fd = fs.openSync(tmpPath, \"r\");\n    fs.fsyncSync(fd);\n    fs.closeSync(fd);\n    fd = null;\n\n    fs.renameSync(tmpPath, targetPath);\n  } catch (err) {\n    if (fd !== null) {\n      try {\n        fs.closeSync(fd);\n      } catch {\n        // Best-effort.\n      }\n    }\n    removeTmpResidueSync(fs, tmpPath);\n    throw err;\n  }\n\n  fsyncParentDirSyncWithFs(targetPath, fs);\n}\n\n/**\n * Synchronous counterpart to {@link removeTmpResidueAsync}. See the\n * async variant's JSDoc for the `EISDIR`/`EPERM` rationale.\n */\nfunction removeTmpResidueSync(\n  fs: typeof import(\"node:fs\"),\n  tmpPath: string,\n): void {\n  try {\n    fs.unlinkSync(tmpPath);\n    return;\n  } catch (err) {\n    const code = errnoCodeOf(err);\n    if (code !== \"EISDIR\" && code !== \"EPERM\") {\n      return;\n    }\n  }\n  try {\n    fs.rmdirSync(tmpPath);\n  } catch {\n    // Directory may be non-empty; original error takes precedence.\n  }\n}\n\n/**\n * Synchronously fsyncs the parent directory of `targetPath`. Errors\n * matching {@link PARENT_FSYNC_SWALLOWED_CODES} (Windows / NTFS does\n * not support directory fsync) are silently ignored; other errors\n * propagate. Exposed for callers like `cli/discovery-file.ts` that\n * need to compose the steps manually around a backup-rollback flow.\n *\n * @internal Sibling-module use only.\n */\nexport function fsyncParentDirSync(targetPath: string): void {\n  fsyncParentDirSyncWithFs(targetPath, loadFsSync());\n}\n\nfunction fsyncParentDirSyncWithFs(\n  targetPath: string,\n  fs: typeof import(\"node:fs\"),\n): void {\n  const parent = parentDir(targetPath);\n  let fd: number | null = null;\n  try {\n    fd = fs.openSync(parent, \"r\");\n    fs.fsyncSync(fd);\n  } catch (err) {\n    const code = errnoCodeOf(err);\n    if (code !== undefined && PARENT_FSYNC_SWALLOWED_CODES.has(code)) {\n      return;\n    }\n    throw err;\n  } finally {\n    if (fd !== null) {\n      try {\n        fs.closeSync(fd);\n      } catch {\n        // Close errors after a successful fsync are not actionable.\n      }\n    }\n  }\n}\n\n/**\n * Synchronously writes `payload` to `tmpPath` and fsyncs the\n * resulting file so its data and metadata are durable on disk\n * before any rename is observable. Throws on any I/O error from\n * either step; on throw, the partially-written tmp file is left\n * in place (callers handle cleanup so they can decide between\n * `unlink` and a backup-rollback strategy).\n *\n * Steps 1 and 2 of the SDK 2.0 §4.3 protocol. Pair with a `rename`\n * (step 3) and {@link fsyncParentDirSync} (step 4) — or use\n * {@link atomicWriteFileSync}/{@link atomicWriteFileSyncWithTmp}\n * which compose all four steps internally.\n *\n * @internal Sibling-module use only.\n */\nexport function writeAndFsyncTempSync(\n  tmpPath: string,\n  payload: string | Uint8Array,\n  options: AtomicWriteOptions = {},\n): void {\n  const mode = options.mode ?? 0o600;\n  const encoding = options.encoding ?? \"utf-8\";\n  const fs = loadFsSync();\n  if (typeof payload === \"string\") {\n    fs.writeFileSync(tmpPath, payload, { encoding, mode });\n  } else {\n    fs.writeFileSync(tmpPath, payload, { mode });\n  }\n  // Re-apply the requested mode in case `tmpPath` already existed —\n  // `writeFileSync` only honors `mode` when creating the file, so a\n  // stale residue could otherwise carry permissive bits into the\n  // caller's eventual rename. Path-based `chmodSync` keeps the fsync\n  // handle below read-only.\n  fs.chmodSync(tmpPath, mode);\n  // Read-only is sufficient for `fsync` and works for callers that\n  // pass a read-only `mode`.\n  const fd = fs.openSync(tmpPath, \"r\");\n  try {\n    fs.fsyncSync(fd);\n  } finally {\n    try {\n      fs.closeSync(fd);\n    } catch {\n      // Close errors after fsync are not actionable.\n    }\n  }\n}\n\n/**\n * Returns `true` when synchronous `node:fs` is reachable in the current\n * runtime, `false` otherwise. Callers that prefer a silent-skip path\n * over a thrown `node:fs is unavailable` error use this probe before\n * dispatching to {@link atomicWriteFileSync}.\n *\n * The probe shares the lazy-loader cache with the sync helpers, so a\n * `true` result also primes the cache for the subsequent write. This\n * keeps the probe overhead to one `require(\"node:fs\")` per process.\n *\n * Background: tsup's bundled `__require` shim throws \"Dynamic require\n * of \\\"node:fs\\\" is not supported\" when the SDK is loaded as an ESM\n * module from a host like Next.js. The runtime is a real\n * Node process — it just lacks a working synchronous `require()`\n * binding in the ESM scope. Async helpers are unaffected because\n * `await import(\"node:fs/promises\")` is ESM-native.\n *\n * @internal Sibling-module use only.\n */\nexport function isSyncFsAvailable(): boolean {\n  try {\n    loadFsSync();\n    return true;\n  } catch {\n    return false;\n  }\n}\n\n/**\n * Test-only: clear the cached lazy-loaded modules. Allows test suites\n * that mock `node:fs`/`node:fs/promises` to ensure the helper re-runs\n * its module probe.\n *\n * @internal Tests only.\n */\nexport function _resetModuleCacheForTesting(): void {\n  fsPromisesCache = undefined;\n  fsSyncCache = undefined;\n}\n","import type { SdkInitResponse } from \"@glasstrace/protocol\";\n\n/**\n * Cross-bundle-instance store for the resolved active capture-config **and** the\n * per-account `attrHmacKey` secret.\n *\n * Why a `globalThis` singleton: under Turbopack `next dev` (HMR rebuilds) and\n * the edge-vs-node bundle split, the bundler can evaluate more than one copy of\n * this module in a single process. With plain module-level state, the copy that\n * the background init writes (`setActiveConfig`) is not necessarily the copy the\n * in-request emitter reads (`getActiveConfig` / `isCaptureEnabled` /\n * `getStoredAttrHmacKey`), so a served capture-config silently fails to reach\n * the call site and the gate falls through to the fail-closed default. Keying\n * the state on a `Symbol.for()` global symbol makes every bundle instance read\n * and write the same record. The brand survives module re-evaluation (Turbopack\n * HMR, Webpack `next dev`, Vitest module isolation). Per V8 semantics\n * `globalThis` is per-isolate, so Node `worker_threads` and `vm.Context` each\n * get a fresh slot and resolve their own config — the correct behavior.\n *\n * The per-account `attrHmacKey` lives here too, on the shared record, behind a\n * closure accessor. Glasstrace is a non-production (development-time) SDK, and\n * full-fidelity `*Id` pseudonymization must work in exactly the Turbopack-dev\n * bundle-split runtime above — the copy that runs the Prisma projection is\n * often not the copy that applied the config, so it must be able to read the\n * provisioned key. An earlier design kept the raw key in module-local state to\n * confine it to the applying copy (so arbitrary in-isolate code could not\n * recover it via the well-known symbol); that confinement is precisely what\n * broke cross-copy id capture. We deliberately relocate the key onto the shared\n * record: for a dev-only SDK the residual threat — other in-process code on a\n * developer's own machine reading a per-account hashing key that is already in\n * process memory — is low, and cross-copy reachability is required for the\n * feature to work at all. The key is held in a CLOSURE (see\n * {@link AttrHmacKeyHolder}), not an enumerable field, so it is absent from\n * `Object.keys` / `JSON.stringify` of the record and never lands in a casual\n * dump or log; it is intentionally reachable by code that calls the accessor.\n *\n * Edge-safety: this module touches only `globalThis` and a `Symbol.for` symbol.\n * It pulls in no Node built-in, no `@vercel/blob`, and never reaches the\n * `process` global, so it stays inside the F003 edge-safe contract enforced by\n * `scripts/check-edge-bundle.mjs`.\n */\n\n/**\n * Branded discriminator on the stored record. Lets us detect at runtime whether\n * the value on `globalThis[STORE]` has the shape Glasstrace stores or is a\n * foreign value that happens to collide on the well-known symbol. A foreign or\n * shape-mismatched value is treated as a fresh store and overwritten rather\n * than trusted as config. This is a robustness guard, not a security boundary:\n * any code in the same isolate can write a conforming object to the slot.\n *\n * Bumped to `2` when the record shape changed: the per-account key moved onto\n * the record (behind a closure accessor), replacing the prior module-local-key\n * plus `keyToken`/`keyProvisioned` pairing design. Bumped to `3` when the\n * `origin` field was added so a reader can tell a server-served config from a\n * promoted disk-cache one (the two are otherwise indistinguishable once the\n * cache is promoted into the in-memory record).\n */\nconst GLASSTRACE_BRAND = 3 as const;\n\n/**\n * Process-wide (per-isolate) symbol under which the active-config record is\n * stored on `globalThis`, shared across every bundle instance in this isolate.\n */\nconst STORE = Symbol.for(\"glasstrace.active-config\");\n\n/**\n * Holds the per-account `attrHmacKey` in a closure rather than an enumerable\n * field, so the raw secret is absent from `Object.keys` / `JSON.stringify` of\n * the shared record (no accidental serialization or logging) while remaining\n * readable cross-copy by code that calls {@link AttrHmacKeyHolder.read}. Exactly\n * one holder is created per record (in {@link getStore}) and shared by every\n * bundle copy, so a `set` through one copy is observed by `read` in any other.\n */\ninterface AttrHmacKeyHolder {\n  read(): string | undefined;\n  set(key: string | undefined): void;\n}\n\nfunction createAttrHmacKeyHolder(): AttrHmacKeyHolder {\n  let key: string | undefined;\n  return {\n    read: () => key,\n    set: (next) => {\n      key = next;\n    },\n  };\n}\n\n/**\n * Provenance of the currently-applied {@link ActiveConfigRecord.config}:\n * `\"server\"` for a config returned by a live init/heartbeat call, `\"cache\"`\n * for one promoted from the on-disk cache, or `null` when none is applied.\n * Read by the decision-trace `config.tier` gate so a promoted disk cache keeps\n * reporting `cached` rather than masquerading as `served` on later reads.\n */\nexport type ActiveConfigOrigin = \"server\" | \"cache\";\n\n/**\n * Mutable record stored under `globalThis[STORE]`.\n *\n * - `config` — the latest successfully-resolved init response, or `null` when\n *   none has been applied yet. Carries no `attrHmacKey` secret — that is split\n *   off into {@link ActiveConfigRecord.attrHmacKeyHolder} on apply.\n * - `cacheChecked` — whether the synchronous disk-cache read has already been\n *   attempted this process (capped at most once so the export hot path never\n *   repeats synchronous I/O).\n * - `attrHmacKeyHolder` — the closure holding the per-account key, off the\n *   record's enumerable surface (see {@link AttrHmacKeyHolder}). Last-writer-\n *   wins: each `setActiveConfig` sets or clears it, so every bundle copy reads\n *   the currently-active key and no copy can hash with a stale/wrong-tenant key.\n *\n * All fields are mutated in place; the same record instance is reused for the\n * lifetime of the isolate, so a reference held by one bundle copy observes\n * writes made through any other copy.\n */\ninterface ActiveConfigRecord {\n  readonly glasstraceActiveConfigBrand: typeof GLASSTRACE_BRAND;\n  config: SdkInitResponse | null;\n  /**\n   * Provenance of `config` — `\"server\"`, `\"cache\"`, or `null` when `config`\n   * is `null`. Set by {@link setActiveConfig} so a reader can distinguish a\n   * live-served config from a promoted disk cache.\n   */\n  origin: ActiveConfigOrigin | null;\n  cacheChecked: boolean;\n  attrHmacKeyHolder: AttrHmacKeyHolder;\n}\n\n/**\n * Type-narrowing predicate that identifies a record Glasstrace itself stored.\n * Anything else — a primitive, an object missing the brand, an old\n * Glasstrace-shaped value with a different brand version, a value whose\n * `config` / `cacheChecked` fields are the wrong type, or one missing the\n * closure holder — is treated as \"no store yet\" so {@link getStore} replaces it\n * with a fresh record.\n */\nfunction isActiveConfigRecord(value: unknown): value is ActiveConfigRecord {\n  if (typeof value !== \"object\" || value === null) return false;\n  const candidate = value as Partial<ActiveConfigRecord>;\n  if (candidate.glasstraceActiveConfigBrand !== GLASSTRACE_BRAND) return false;\n  if (typeof candidate.cacheChecked !== \"boolean\") return false;\n  if (\n    candidate.origin !== null &&\n    candidate.origin !== \"server\" &&\n    candidate.origin !== \"cache\"\n  ) {\n    return false;\n  }\n  if (\n    typeof candidate.attrHmacKeyHolder?.read !== \"function\" ||\n    typeof candidate.attrHmacKeyHolder?.set !== \"function\"\n  ) {\n    return false;\n  }\n  return (\n    candidate.config === null ||\n    (typeof candidate.config === \"object\" && candidate.config !== undefined)\n  );\n}\n\n/**\n * Returns the shared active-config record, installing a fresh one on\n * `globalThis` if none (or a foreign value) is present. Every reader and writer\n * in this module goes through here, so all bundle instances converge on the\n * same record (and the same {@link AttrHmacKeyHolder}).\n */\nfunction getStore(): ActiveConfigRecord {\n  const slot = globalThis as Record<symbol, unknown>;\n  const existing = slot[STORE];\n  if (isActiveConfigRecord(existing)) {\n    return existing;\n  }\n  const fresh: ActiveConfigRecord = {\n    glasstraceActiveConfigBrand: GLASSTRACE_BRAND,\n    config: null,\n    origin: null,\n    cacheChecked: false,\n    attrHmacKeyHolder: createAttrHmacKeyHolder(),\n  };\n  slot[STORE] = fresh;\n  return fresh;\n}\n\n/**\n * The current resolved init response, or `null` when none has been applied.\n * Read fresh on every call so config/key rotation takes effect on the next read.\n */\nexport function getActiveConfigResponse(): SdkInitResponse | null {\n  return getStore().config;\n}\n\n/**\n * Replaces the resolved init response and the per-account key. The non-secret\n * config is written to the shared record (visible to every bundle instance on\n * the next {@link getActiveConfigResponse}); the per-account `attrHmacKey`, if\n * present, is stored in the shared record's closure holder and removed from the\n * stored config object. Last-writer-wins: a later apply by any bundle copy —\n * key rotation, a different tenant, or a key-less downgrade / disk-cache\n * promotion — overwrites or clears the key, so no copy hashes with a stale key.\n * Passing `null` clears both.\n *\n * `origin` records where the config came from — `\"server\"` (a live init /\n * heartbeat response, the default) or `\"cache\"` (a promotion from the on-disk\n * cache). It is read by the decision-trace `config.tier` gate so a promoted\n * disk cache keeps reporting `cached` rather than `served` on later reads.\n */\nexport function setActiveConfig(\n  config: SdkInitResponse | null,\n  origin: ActiveConfigOrigin = \"server\",\n): void {\n  const store = getStore();\n  if (config === null) {\n    store.config = null;\n    store.origin = null;\n    store.attrHmacKeyHolder.set(undefined);\n    return;\n  }\n  store.origin = origin;\n  const innerKey = config.config.attrHmacKey;\n  if (innerKey === undefined) {\n    // No key in this config — including the key-less disk-cache promotion path\n    // (`init-client.ts` strips the secret before caching). Clear any\n    // previously-applied key so this key-less apply wins (last-writer-wins).\n    store.config = config;\n    store.attrHmacKeyHolder.set(undefined);\n    return;\n  }\n  // Store a secret-free copy on the shared record. The clone is shallow at the\n  // response level with a fresh `config` object so the stored value does not\n  // alias the caller's object, and `attrHmacKey` is removed from that fresh\n  // `config`; the secret goes into the closure holder, never an enumerable field.\n  const { attrHmacKey: _omit, ...redactedInner } = config.config;\n  void _omit;\n  store.config = { ...config, config: redactedInner };\n  store.attrHmacKeyHolder.set(innerKey);\n}\n\n/**\n * Provenance of the currently-applied config, or `null` when none is applied.\n * Read fresh on every call (last-writer-wins). Used by the decision-trace\n * `config.tier` gate to distinguish a server-served config from a promoted\n * disk cache. Internal — not exported from the package barrel.\n */\nexport function getActiveConfigOrigin(): ActiveConfigOrigin | null {\n  return getStore().origin;\n}\n\n/**\n * The per-account `attrHmacKey` for the config that is currently active across\n * all bundle instances, or `undefined` when none is provisioned. Read fresh on\n * every call (last-writer-wins). Held in the shared record's closure holder so\n * any bundle copy — including one that runs the Prisma projection without having\n * applied the config itself (the Turbopack-dev bundle split) — can read it.\n * Internal — not exported from the package barrel.\n */\nexport function getStoredAttrHmacKey(): string | undefined {\n  return getStore().attrHmacKeyHolder.read();\n}\n\n/**\n * Whether the synchronous disk-cache read has already been attempted this\n * process.\n */\nexport function isConfigCacheChecked(): boolean {\n  return getStore().cacheChecked;\n}\n\n/** Marks the synchronous disk-cache read as attempted for this process. */\nexport function markConfigCacheChecked(): void {\n  getStore().cacheChecked = true;\n}\n\n/**\n * Clears the shared active-config record (and with it the per-account key). For\n * testing only, so same-process test cases do not leak config across each other.\n * Mirrors `context-manager.ts`'s `_resetContextManagerForTesting`. Not exported\n * from the package barrel.\n *\n * @internal\n */\nexport function _resetActiveConfigForTesting(): void {\n  delete (globalThis as Record<symbol, unknown>)[STORE];\n}\n","import { SpanKind, SpanStatusCode } from \"@opentelemetry/api\";\nimport type { ReadableSpan, SpanExporter } from \"@opentelemetry/sdk-trace-base\";\nimport type { ExportResult } from \"@opentelemetry/core\";\nimport { GLASSTRACE_ATTRIBUTE_NAMES } from \"@glasstrace/protocol\";\nimport type { CaptureConfig } from \"@glasstrace/protocol\";\nimport type { SessionManager } from \"./session.js\";\nimport { classifyFetchTarget } from \"./fetch-classifier.js\";\nimport { recordSpansExported, recordSpansDropped } from \"./health-collector.js\";\nimport { sdkLog } from \"./console-capture.js\";\nimport { maybeShowServerActionNudge } from \"./nudge/error-nudge.js\";\nimport {\n  coerceHttpStatus,\n  isHttpErrorStatus,\n  prepareErrorResponseBody,\n} from \"./error-response-body.js\";\nimport { prepareStack } from \"./error-stack.js\";\nimport { getBuildHash } from \"./build-info.js\";\nimport {\n  getExportCircuitBreaker,\n  type ExportCircuitBreaker,\n  type ExceptionLineageEntry,\n  type TraceErrorState,\n} from \"./export-circuit-breaker.js\";\nimport {\n  emitLifecycleEvent,\n  pushDegradationSource,\n  clearDegradationSource,\n} from \"./lifecycle.js\";\nimport { decisionTrace, decisionTraceEnabled } from \"./decision-trace.js\";\n\nconst ATTR = GLASSTRACE_ATTRIBUTE_NAMES;\n\n/**\n * Sentinel value indicating the API key has not yet been resolved.\n */\nexport const API_KEY_PENDING = \"pending\" as const;\n\n/**\n * Reads the `GLASSTRACE_DISABLE_BOUNDARY_MASKED` opt-out flag from the\n * environment. When truthy (`'1'` or `'true'`, case-insensitive), the SDK\n * skips boundary-masked-error promotion entirely — for both the same-span\n * and the descendant paths — so a user who does not want any inferred 500\n * status (and no `boundary_masked` / scope attribute, and no\n * `core:error_boundary_detected` lifecycle event) can opt out cleanly.\n *\n * Read once at module load (not per span) to keep the export hot path free\n * of a repeated `process.env` lookup.\n */\nfunction readBoundaryMaskedDisabled(): boolean {\n  const raw = process.env.GLASSTRACE_DISABLE_BOUNDARY_MASKED;\n  if (typeof raw !== \"string\") return false;\n  const v = raw.trim().toLowerCase();\n  return v === \"1\" || v === \"true\";\n}\n\nconst BOUNDARY_MASKED_DISABLED = readBoundaryMaskedDisabled();\n\n/**\n * The `next.span_type` value Next.js sets on a render-route span. A\n * boundary-masked exception on this span is the page-route case: the route\n * renders an HTTP 200 while a descendant render span carries the exception.\n */\nconst RENDER_ROUTE_SPAN_TYPE = \"AppRender.getBodyResult\";\n\n/**\n * Next.js App Router control-flow throw markers. These are NOT errors —\n * `notFound()` / `redirect()` throw internally to unwind rendering — so a\n * descendant carrying one of these must never be promoted. v1 matches\n * case-sensitively against the recorded exception type and message only\n * (defense-in-depth: these cases usually carry no exception event and so fail\n * the exception-event gate already, which excludes the no-event control-flow\n * paths).\n */\nconst NEXT_CONTROL_FLOW_MARKERS = [\n  \"NEXT_NOT_FOUND\",\n  \"NEXT_REDIRECT\",\n  \"not_found\",\n] as const;\n\n/**\n * Unexpected/infrastructure exception class markers that promote a\n * render-route descendant. A render-route descendant is suppressed by\n * default (an expected `error.tsx` fallback over a generic application\n * `Error` is a legitimate HTTP 200 that must stay 200); it is promoted only\n * when its exception type or message matches one of these database /\n * driver failure classes (e.g. a Prisma error or a database-unreachable\n * failure). Other infrastructure families (network / fetch failures, etc.)\n * are an intentional v1 omission — a non-match degrades to a documented miss\n * (see below), and the list is extended additively as fixtures confirm a\n * family. A boundary can still suppress promotion\n * regardless of class via the `glasstrace.error.expected === true` escape\n * hatch (checked by the caller). The list is an explicit, source-pinned\n * heuristic: a non-match on a real infrastructure failure degrades to a\n * documented miss, never a false 500.\n */\nconst RENDER_ROUTE_INFRA_MARKERS = [\n  \"PrismaClientKnownRequestError\",\n  \"PrismaClientInitializationError\",\n  \"PrismaClientRustPanicError\",\n  \"DriverAdapterError\",\n  \"P1001\",\n  \"Can't reach database server\",\n] as const;\n\n/**\n * Maximum number of spans to buffer while waiting for key resolution.\n * Prevents unbounded memory growth if the key never resolves.\n *\n * @drift-check ../glasstrace-product/docs/component-designs/sdk-architecture.md §5.4 Buffering during KEY_PENDING\n */\nconst MAX_PENDING_SPANS = 1024;\n\n\n/**\n * Options for constructing a {@link GlasstraceExporter}.\n */\nexport interface GlasstraceExporterOptions {\n  getApiKey: () => string;\n  sessionManager: SessionManager;\n  getConfig: () => CaptureConfig;\n  environment: string | undefined;\n  endpointUrl: string;\n  createDelegate: ((url: string, headers: Record<string, string>) => SpanExporter) | null;\n  /** When true, logs diagnostic details about enrichment decisions via sdkLog. */\n  verbose?: boolean;\n}\n\ninterface PendingBatch {\n  spans: ReadableSpan[];\n  resultCallback: (result: ExportResult) => void;\n}\n\n/**\n * A SpanExporter that enriches spans with glasstrace.* attributes at export\n * time, then delegates to a real OTLP exporter.\n *\n * This design resolves three issues:\n * - Spans emitted before the API key resolves are buffered (not dropped)\n *   and flushed once the key is available.\n * - Enrichment happens in the exporter (not onEnding), so it works\n *   on Vercel where CompositeSpanProcessor does not forward onEnding().\n * - Session ID is computed at export time using the resolved API key,\n *   not the \"pending\" placeholder.\n */\nexport class GlasstraceExporter implements SpanExporter {\n  private readonly getApiKey: () => string;\n  private readonly sessionManager: SessionManager;\n  private readonly getConfig: () => CaptureConfig;\n  private readonly environment: string | undefined;\n  private readonly endpointUrl: string;\n  private readonly createDelegateFn: ((url: string, headers: Record<string, string>) => SpanExporter) | null;\n  private readonly verbose: boolean;\n\n  private delegate: SpanExporter | null = null;\n  private delegateKey: string | null = null;\n  private pendingBatches: PendingBatch[] = [];\n  private pendingSpanCount = 0;\n  private overflowLogged = false;\n  /**\n   * Lazily-bound reference to the export-path circuit breaker.\n   * Resolved on first export so this\n   * constructor stays side-effect-free. The breaker is a module-\n   * singleton — every `GlasstraceExporter` instance shares the same\n   * one so a rotation event observed in `init-client.ts` reaches\n   * every active exporter.\n   */\n  private circuitBreaker: ExportCircuitBreaker | null = null;\n\n  constructor(options: GlasstraceExporterOptions) {\n    this.getApiKey = options.getApiKey;\n    this.sessionManager = options.sessionManager;\n    this.getConfig = options.getConfig;\n    this.environment = options.environment;\n    this.endpointUrl = options.endpointUrl;\n    this.createDelegateFn = options.createDelegate;\n    this.verbose = options.verbose ?? false;\n\n    // Brand for coexistence detection — allows isGlasstraceProcessorPresent()\n    // to detect our exporter across bundled copies via a global symbol registry.\n    (this as unknown as Record<symbol, boolean>)[Symbol.for(\"glasstrace.exporter\")] = true;\n  }\n\n  /**\n   * Returns the export-path circuit breaker, lazily wiring it on\n   * first call. The breaker is a module-singleton so all exporter\n   * instances share state — a credential rotation observed once\n   * resets the breaker for every active exporter, and a single\n   * outage at the OTLP endpoint trips a single breaker rather than\n   * one per exporter copy.\n   *\n   * The wiring binds:\n   * - the lifecycle event sink to the SDK's lifecycle bus\n   *   (`emitLifecycleEvent`) so the `otel:circuit_*` events surface\n   *   to runtime-state, the CLI bridge, and any user-installed\n   *   subscribers.\n   * - the dropped-span counter to {@link recordSpansDropped} so OPEN-\n   *   state drops show up in the existing health surface.\n   * - the FSM hooks to {@link pushDegradationSource} /\n   *   {@link clearDegradationSource} keyed on `\"export-circuit\"`,\n   *   which routes the OPEN/CLOSED transitions through the\n   *   centralised `recomputeCoreFromDegradationSources()` helper.\n   *   That helper guards `ACTIVE ↔ ACTIVE_DEGRADED` so a circuit\n   *   recovery never clobbers an unrelated `OtelState.COEXISTENCE_FAILED`\n   *   degradation source.\n   */\n  private getCircuitBreaker(): ExportCircuitBreaker {\n    if (this.circuitBreaker !== null) return this.circuitBreaker;\n    this.circuitBreaker = getExportCircuitBreaker({\n      events: {\n        emitOpened: (payload) => emitLifecycleEvent(\"otel:circuit_opened\", payload),\n        emitHalfOpen: (payload) => emitLifecycleEvent(\"otel:circuit_half_open\", payload),\n        emitClosed: (payload) => emitLifecycleEvent(\"otel:circuit_closed\", payload),\n      },\n      recordDropped: (count) => recordSpansDropped(count),\n      fsm: {\n        onCircuitOpened: () => pushDegradationSource(\"export-circuit\"),\n        onCircuitClosed: () => clearDegradationSource(\"export-circuit\"),\n      },\n    });\n    return this.circuitBreaker;\n  }\n\n  export(spans: ReadableSpan[], resultCallback: (result: ExportResult) => void): void {\n    const currentKey = this.getApiKey();\n    if (currentKey === API_KEY_PENDING) {\n      // Buffer raw (unenriched) spans — enrichment deferred to flush time\n      // so session IDs are computed with the resolved key, not \"pending\".\n      this.bufferSpans(spans, resultCallback);\n      return;\n    }\n\n    const breaker = this.getCircuitBreaker();\n\n    // Pass 1 (boundary-masked descendant tracking): record every span's\n    // parent link and any exception-bearing span into the per-trace error\n    // store BEFORE the circuit-breaker OPEN-drop gate below. The descendant,\n    // an intermediate non-error span, and the parent HTTP server span can\n    // each arrive in a different batch — and a batch dropped by an OPEN\n    // breaker would otherwise lose lineage that a later parent batch needs.\n    // Only the cheap map writes are hoisted; the parent's own enrichment\n    // still respects the OPEN gate.\n    this.recordTraceErrorPass(spans, breaker);\n\n    // Circuit-breaker gate (DISC-1568 / Wave 15C). When OPEN, drop\n    // the batch entirely: increment the dropped-spans health counter\n    // and call back with `{ code: 0 }` so the BSP retries nothing\n    // (the OPEN window itself is the backoff). The decision to drop\n    // (rather than buffer) is documented in the design memo §Decision 4\n    // — buffering during OPEN created the permanent-export-disabled\n    // failure mode the original PR #26 had to revert.\n    if (!breaker.shouldExport()) {\n      breaker.onSpansDropped(spans.length);\n      resultCallback({ code: 0 });\n      return;\n    }\n\n    // Key is available — enrich and export\n    const enrichedSpans = spans.map((span) => this.enrichSpan(span, spans));\n    const exporter = this.ensureDelegate();\n    if (exporter) {\n      // Snapshot the breaker's generation counter so a credential\n      // rotation that fires while this batch is in flight can be\n      // detected on the result callback (memo §Decision 7 edge case).\n      // The probe-during-rotation race must NOT push a stale failure\n      // into the post-rotation breaker.\n      const generationAtIssue = breaker.getGeneration();\n      exporter.export(enrichedSpans, (result) => {\n        if (result.code !== 0) {\n          sdkLog(\"warn\", `[glasstrace] Span export failed: ${result.error?.message ?? \"unknown error\"}`);\n        }\n        // Discard the result if the breaker rotated mid-flight.\n        if (breaker.getGeneration() !== generationAtIssue) {\n          resultCallback(result);\n          return;\n        }\n        if (result.code === 0) {\n          breaker.recordSuccess();\n        } else {\n          breaker.recordFailure({ error: result.error });\n        }\n        resultCallback(result);\n      });\n      recordSpansExported(enrichedSpans.length);\n    } else {\n      // No delegate factory — spans are discarded, count as dropped\n      recordSpansDropped(enrichedSpans.length);\n      resultCallback({ code: 0 });\n    }\n  }\n\n  /**\n   * Called when the API key transitions from \"pending\" to a resolved value.\n   * Creates the delegate exporter and flushes all buffered spans.\n   */\n  notifyKeyResolved(): void {\n    this.flushPending();\n  }\n\n  async shutdown(): Promise<void> {\n    const currentKey = this.getApiKey();\n    if (currentKey !== API_KEY_PENDING && this.pendingBatches.length > 0) {\n      this.flushPending();\n    } else if (this.pendingBatches.length > 0) {\n      console.warn(\n        `[glasstrace] Shutdown with ${this.pendingSpanCount} buffered spans — API key never resolved, spans lost.`,\n      );\n      recordSpansDropped(this.pendingSpanCount);\n      // Complete pending callbacks so pipeline doesn't hang\n      for (const batch of this.pendingBatches) {\n        batch.resultCallback({ code: 0 });\n      }\n      this.pendingBatches = [];\n      this.pendingSpanCount = 0;\n    }\n\n    if (this.delegate) {\n      return this.delegate.shutdown();\n    }\n  }\n\n  /**\n   * Flushes any pending buffered spans (if the API key has resolved) and\n   * delegates to the underlying exporter's forceFlush to drain its queue.\n   */\n  forceFlush(): Promise<void> {\n    // Flush pending batches if the key has resolved but they haven't been\n    // drained yet (e.g., key resolved between the last export and this flush).\n    if (this.getApiKey() !== API_KEY_PENDING && this.pendingBatches.length > 0) {\n      this.flushPending();\n    }\n\n    if (this.delegate?.forceFlush) {\n      return this.delegate.forceFlush();\n    }\n    return Promise.resolve();\n  }\n\n  /**\n   * Enriches a ReadableSpan with all glasstrace.* attributes.\n   * Returns a new ReadableSpan wrapper; the original span is not mutated.\n   *\n   * Only {@link SessionManager.getSessionId} is individually guarded because\n   * it calls into crypto and schema validation — a session ID failure should\n   * not prevent the rest of enrichment. The other helper calls\n   * ({@link deriveErrorCategory}, {@link deriveOrmProvider},\n   * {@link classifyFetchTarget}) are pure functions on typed string inputs\n   * and rely on the outer catch for any unexpected failure.\n   *\n   * On total failure, returns the original span unchanged.\n   *\n   * `batch` is the set of spans being enriched in the current export call;\n   * the descendant boundary-masked consult uses it as a same-batch fallback\n   * when resolving an ancestor span's parent link that pass-1 has not yet\n   * persisted.\n   */\n  private enrichSpan(span: ReadableSpan, batch: ReadableSpan[]): ReadableSpan {\n    try {\n      const attrs = span.attributes ?? {};\n      const name = span.name ?? \"\";\n      const extra: Record<string, string | number | boolean> = {};\n\n      // glasstrace.trace.type\n      extra[ATTR.TRACE_TYPE] = \"server\";\n\n      // glasstrace.session.id — calls external code (crypto, schema validation)\n      try {\n        const sessionId = this.sessionManager.getSessionId(this.getApiKey());\n        extra[ATTR.SESSION_ID] = sessionId;\n      } catch { /* session ID omitted */ }\n\n      // glasstrace.environment\n      const env = this.environment ?? process.env.GLASSTRACE_ENV;\n      if (env) {\n        extra[ATTR.ENVIRONMENT] = env;\n      }\n\n      // glasstrace.build.hash (DISC-1543 / SDK-040).\n      // Stamped from `process.env.GLASSTRACE_BUILD_HASH` captured at\n      // module load by `build-info.ts`. Ingestion uses the value to\n      // construct the sourcemap blob key\n      // (`sourcemaps/{accountId}/{buildHash}/{file}`); a missing hash\n      // leaves stored traces' `buildHash` column null and prevents the\n      // dashboard from rendering mapped frames for those traces. The\n      // SDK silently omits the attribute when the env var is unset so\n      // deployments that have not adopted the convention behave\n      // exactly as before.\n      const buildHash = getBuildHash();\n      if (buildHash) {\n        extra[ATTR.BUILD_HASH] = buildHash;\n      }\n\n      // glasstrace.correlation.id\n      const existingCid = attrs[\"glasstrace.correlation.id\"];\n      if (typeof existingCid === \"string\") {\n        extra[ATTR.CORRELATION_ID] = existingCid;\n      }\n\n      // glasstrace.route\n      // OTel's AttributeValue allows non-string shapes (number, boolean,\n      // array) on `http.route`. A custom instrumentation could set a\n      // non-string there and blow up `.trim()` / `.startsWith()` calls\n      // below; guard with typeof so malformed route attributes fall back\n      // to `name` (always a string per OTel span contract) instead of\n      // disabling all enrichment for the span.\n      const rawRoute = attrs[\"http.route\"];\n      const route = typeof rawRoute === \"string\" ? rawRoute : name;\n      if (route) {\n        extra[ATTR.ROUTE] = route;\n      }\n\n      // Capture the raw HTTP URL once; multiple downstream blocks\n      // depend on it (tRPC procedure extraction, SDK-041 framework\n      // fallback original-path detection). Variable name reflects\n      // its general HTTP-URL role rather than any single use site.\n      const rawUrlAttr = attrs[\"http.url\"] ?? attrs[\"url.full\"] ?? attrs[\"http.target\"];\n      const rawHttpUrl = typeof rawUrlAttr === \"string\" ? rawUrlAttr : undefined;\n\n      // glasstrace.trpc.procedure\n      // Extract tRPC procedure name from URL path (DISC-1215).\n      // Pattern: /api/trpc/{procedure} where procedure is a single path segment\n      // that may contain dots (polls.modify) or commas (batched: proc1,proc2).\n      if (rawHttpUrl) {\n        const trpcMatch = rawHttpUrl.match(/\\/api\\/trpc\\/([^/?#]+)/);\n        if (trpcMatch) {\n          let procedure: string;\n          try {\n            procedure = decodeURIComponent(trpcMatch[1]);\n          } catch {\n            procedure = trpcMatch[1];\n          }\n          if (procedure) {\n            extra[ATTR.TRPC_PROCEDURE] = procedure;\n          }\n        }\n      }\n\n      // glasstrace.http.method\n      const method =\n        (attrs[\"http.method\"] as string | undefined) ??\n        (attrs[\"http.request.method\"] as string | undefined);\n      if (method) {\n        extra[ATTR.HTTP_METHOD] = method;\n      }\n\n      // glasstrace.next.action.detected — DISC-1253.\n      // Heuristic: a POST to a page route (not /api/*, not /_next/*) is\n      // almost always a Server Action in idiomatic Next.js App Router code.\n      // We cannot identify the specific action without extra metadata —\n      // DISC-1254 covers that path. Label \"detected\" not \"confirmed\" to\n      // leave room for rare false-positive cases (legacy form POSTs,\n      // hand-rolled page-route POST handlers).\n      //\n      // `route` may come from `http.route` (a bare path like \"/login\") or\n      // fall back to `span.name` (which Next.js formats as \"POST /login\",\n      // sometimes \"middleware POST\", etc.). We normalize to the leading\n      // path segment before matching so a span named \"POST /api/auth\"\n      // does not slip past the `/api/` guard and get falsely flagged.\n      const actionRoute = extractLeadingPath(route);\n      if (method === \"POST\" && actionRoute) {\n        const isApiRoute = actionRoute === \"/api\" || actionRoute.startsWith(\"/api/\");\n        const isInternalRoute = actionRoute.startsWith(\"/_next/\");\n        if (!isApiRoute && !isInternalRoute) {\n          extra[ATTR.NEXT_ACTION_DETECTED] = true;\n          // Developer-facing nudge (once per process): when a Server Action\n          // trace is detected but no glasstrace.correlation.id is present,\n          // the Glasstrace browser extension is likely absent. Installing it\n          // unlocks per-action identification via the Next-Action header\n          // (DISC-1254 covers capture).\n          if (typeof extra[ATTR.CORRELATION_ID] !== \"string\") {\n            maybeShowServerActionNudge();\n          }\n        }\n      }\n\n      // glasstrace.http.status_code\n      //\n      // OTel attribute values are typed\n      // `string | number | boolean | (string | number | boolean)[]`.\n      // Several real-world instrumentations (custom HTTP wrappers,\n      // edge runtimes that round-trip headers verbatim, some community\n      // Node adapters) emit `http.status_code` and\n      // `http.response.status_code` as strings. A TypeScript `as number`\n      // cast applies no runtime coercion, so a string-shaped `\"200\"`\n      // would (a) flow verbatim into the wire payload — downstream\n      // ingestion and UI assume numeric — and (b) defeat the inference\n      // block below (`statusCode === 200` is `false` for `\"200\"`),\n      // silently failing the Next.js timing-race promotion\n      // (DISC-1134 / DISC-1204) on string-status spans (DISC-1551).\n      // `coerceHttpStatus` returns `number | undefined` at runtime, not\n      // just at the TS type level.\n      const statusCode =\n        coerceHttpStatus(attrs[\"http.status_code\"]) ??\n        coerceHttpStatus(attrs[\"http.response.status_code\"]);\n      if (statusCode !== undefined) {\n        extra[ATTR.HTTP_STATUS_CODE] = statusCode;\n      }\n\n      // Infer error status when Next.js timing race reports 200 on error spans.\n      // Three signals indicate an error span:\n      //   1. span.status.code === ERROR (explicit, most reliable)\n      //   2. span.events contains an \"exception\" event (recordException fired)\n      //   3. span attributes contain exception.type or exception.message\n      // The timing race in Next.js dev server (DISC-1134) can cause span\n      // export before closeSpanWithError runs, leaving status.code as UNSET.\n      // Exception events from recordException may still be present (DISC-1204).\n      // Does NOT trigger when status is explicitly OK (handler recovered).\n      const isErrorByStatus = span.status?.code === SpanStatusCode.ERROR;\n      const isErrorByEvent = hasExceptionEvent(span);\n      const isErrorByAttrs = typeof attrs[\"exception.type\"] === \"string\"\n                          || typeof attrs[\"exception.message\"] === \"string\";\n      const statusNotExplicitlyOK = span.status?.code !== SpanStatusCode.OK;\n\n      if (this.verbose && method) {\n        sdkLog(\"info\",\n          `[glasstrace] enrichSpan \"${name}\": status.code=${span.status?.code}, ` +\n          `http.status_code=${statusCode}, isErrorByStatus=${isErrorByStatus}, ` +\n          `isErrorByEvent=${isErrorByEvent}, isErrorByAttrs=${isErrorByAttrs}`,\n        );\n      }\n\n      // Gate on SpanKind.SERVER. A boundary-masked HTTP *response* status\n      // belongs to an inbound request span. OTel CLIENT spans (outbound\n      // fetch, DB-over-HTTP, the SDK's own OTLP export POST) also carry\n      // `http.method`, and a failed outbound request typically has an\n      // exception event / ERROR status with no/200 status — without this\n      // gate it would be wrongly promoted to a 500 + boundary_masked,\n      // surfacing as a spurious error trace. Mirrors the explicit\n      // `span.kind === SpanKind.CLIENT` gate on the fetch-target\n      // classifier below. SERVER (not `!== CLIENT`) is correct here:\n      // the only inbound request spans carrying `http.method` in this\n      // stack (`@opentelemetry/instrumentation-http` incoming, Next.js\n      // request spans) are SERVER kind, so narrowing to SERVER fixes the\n      // false positive without losing any legitimate promotion.\n      // Boundary-masked-error promotion. The opt-out env flag disables the\n      // whole auto-promotion behavior (same-span AND descendant) — when set,\n      // no status promotion, no boundary_masked / scope attribute, and no\n      // lifecycle emit.\n      if (\n        !BOUNDARY_MASKED_DISABLED &&\n        method &&\n        span.kind === SpanKind.SERVER &&\n        (statusCode === undefined || statusCode === 0 || statusCode === 200)\n      ) {\n        const sameSpanSignal =\n          statusNotExplicitlyOK && (isErrorByStatus || isErrorByEvent || isErrorByAttrs);\n        if (sameSpanSignal) {\n          // ---- Same-span scope -------------------------------------------\n          const httpErrorType = attrs[\"error.type\"];\n          if (typeof httpErrorType === \"string\") {\n            const parsed = parseInt(httpErrorType, 10);\n            if (!isNaN(parsed) && parsed >= 400 && parsed <= 599) {\n              extra[ATTR.HTTP_STATUS_CODE] = parsed;\n            } else {\n              extra[ATTR.HTTP_STATUS_CODE] = 500;\n            }\n          } else {\n            extra[ATTR.HTTP_STATUS_CODE] = 500;\n          }\n\n          // Boundary-masked-error audit attribute (set to true exactly when\n          // the inference block fires) plus the scope discriminator. Strict\n          // additivity: backend ignores unknown attributes today; this\n          // surface is for downstream observability of heuristic activation\n          // rate. The same-span and descendant-aware scopes share the wire\n          // attribute and differ only on `boundary_masked_scope`.\n          extra[ATTR.HTTP_BOUNDARY_MASKED] = true;\n          extra[ATTR.HTTP_BOUNDARY_MASKED_SCOPE] = \"same_span\";\n\n          // Emit lifecycle event for subscribers (informational; the\n          // heuristic's behavior does NOT depend on subscribers). The\n          // payload's `exceptionMessage` is truncated to 256 chars and is\n          // the same content already on the span's own exception event — no\n          // new disclosure surface beyond the trace itself for same-span.\n          const inferredStatus = extra[ATTR.HTTP_STATUS_CODE] as number;\n          const eventDetails = getExceptionEventDetails(span);\n          const exceptionMessage = eventDetails.message\n            ?? (typeof attrs[\"exception.message\"] === \"string\"\n                  ? (attrs[\"exception.message\"] as string)\n                  : undefined);\n          emitLifecycleEvent(\"core:error_boundary_detected\", {\n            spanId: span.spanContext().spanId,\n            inferredStatus,\n            source: \"same_span\",\n            ...(exceptionMessage !== undefined\n              ? { exceptionMessage: exceptionMessage.slice(0, 256) }\n              : {}),\n          });\n\n          if (this.verbose) {\n            sdkLog(\"info\",\n              `[glasstrace] enrichSpan \"${name}\": inferred status_code=${extra[ATTR.HTTP_STATUS_CODE]} ` +\n              `(was ${statusCode}), error.type=${attrs[\"error.type\"]}`,\n            );\n          }\n        } else {\n          // ---- Descendant scope ------------------------------------------\n          // No same-span error signal on this SERVER span, so consult the\n          // per-trace error store for a transitive-descendant exception (the\n          // page-route boundary case). Runs only here, so exactly one\n          // promotion and one lifecycle emit happen per server span.\n          this.tryDescendantPromotion(span, attrs, name, statusCode, extra, batch);\n        }\n        // If statusCode is already >= 400, leave it alone (correct value)\n      }\n\n      // glasstrace.http.duration_ms\n      if (span.startTime && span.endTime) {\n        const [startSec, startNano] = span.startTime;\n        const [endSec, endNano] = span.endTime;\n        const durationMs =\n          (endSec - startSec) * 1000 + (endNano - startNano) / 1_000_000;\n        if (durationMs >= 0) {\n          extra[ATTR.HTTP_DURATION_MS] = durationMs;\n        }\n      }\n\n      // glasstrace.error.message + glasstrace.error.code + glasstrace.error.category\n      // Primary source: span attributes. Fallback: exception event attributes.\n      // OTel's recordException() stores exception info in events, not span\n      // attributes, so the fallback is needed for most error spans (DISC-1204).\n      // Event fallback is gated on statusNotExplicitlyOK to avoid labeling\n      // recovered OK spans with error metadata from handled exceptions.\n      const eventDetails = statusNotExplicitlyOK\n        ? getExceptionEventDetails(span)\n        : { type: undefined, message: undefined, stacktrace: undefined };\n\n      // SDK-041 / DISC-1535: track which surface produced the error\n      // facts so product consumers can tell `otel_exception` (event)\n      // from `otel_event` (`exception.*` set as span attributes) from\n      // `framework_fallback` (route-rewrite). Set on any span where\n      // we emit at least one of the new `glasstrace.error.*`\n      // attributes; falls through to undefined when no error attrs\n      // land.\n      //\n      // Precedence: `otel_exception > otel_event > framework_fallback`.\n      // The exception event is the canonical OTel surface for\n      // exceptions (it's what `recordException()` emits); attributes\n      // are a non-canonical alternative some instrumentations use.\n      // When both are present, the event wins so downstream evidence\n      // ranking treats the canonical surface as the more authoritative\n      // source.\n      let errorSource: string | undefined;\n\n      // Prefer the exception event; fall back to span attributes\n      // (this inverts SDK <= 1.5.x precedence, which preferred span\n      // attrs — that ordering mislabeled provenance and lost the\n      // canonical-OTel-surface signal).\n      const attrMessage = attrs[\"exception.message\"];\n      if (eventDetails.message) {\n        extra[ATTR.ERROR_MESSAGE] = eventDetails.message;\n        errorSource = \"otel_exception\";\n      } else if (typeof attrMessage === \"string\") {\n        extra[ATTR.ERROR_MESSAGE] = attrMessage;\n        errorSource = \"otel_event\";\n      }\n\n      // Guard against non-string attribute values (OTel attributes can be\n      // string | number | boolean | Array) to prevent toLowerCase() throws.\n      const attrType = attrs[\"exception.type\"];\n      if (eventDetails.type) {\n        extra[ATTR.ERROR_CODE] = eventDetails.type;\n        extra[ATTR.ERROR_CATEGORY] = deriveErrorCategory(eventDetails.type);\n        errorSource = errorSource ?? \"otel_exception\";\n      } else if (typeof attrType === \"string\") {\n        extra[ATTR.ERROR_CODE] = attrType;\n        extra[ATTR.ERROR_CATEGORY] = deriveErrorCategory(attrType);\n        errorSource = errorSource ?? \"otel_event\";\n      }\n\n      // glasstrace.error.stack + glasstrace.error.stack.{truncated,redacted}\n      // SDK-041 / DISC-1535. Bounded `exception.stacktrace` capture,\n      // sanitized for absolute paths + URL query/fragment + credential\n      // patterns, then truncated to a UTF-8 byte budget. Sibling\n      // metadata attributes carry truncated/redacted booleans so\n      // product can disclaim partial evidence to agents.\n      //\n      // Read precedence mirrors the new event-first error.message\n      // ordering: the OTel exception event (set by `recordException()`)\n      // is the canonical primary source; an `exception.stacktrace`\n      // span attribute is the fallback for instrumentations that\n      // bypass the event mechanism. Same statusNotExplicitlyOK gate\n      // as message/type so a recovered span doesn't get labeled with\n      // a handled exception's stack.\n      if (statusNotExplicitlyOK) {\n        const rawStack = eventDetails.stacktrace\n          ?? (typeof attrs[\"exception.stacktrace\"] === \"string\"\n                ? (attrs[\"exception.stacktrace\"] as string)\n                : undefined);\n        if (rawStack) {\n          const prepared = prepareStack(rawStack);\n          if (prepared !== null) {\n            extra[ATTR.ERROR_STACK] = prepared.stack;\n            extra[ATTR.ERROR_STACK_TRUNCATED] = prepared.truncated;\n            extra[ATTR.ERROR_STACK_REDACTED] = prepared.redacted;\n            // Stack source mirrors the message/type source so a span\n            // with both facts gets a consistent provenance label.\n            errorSource = errorSource\n              ?? (eventDetails.stacktrace ? \"otel_exception\" : \"otel_event\");\n          }\n        }\n      }\n\n      // glasstrace.error.framework.kind + glasstrace.error.original_path + glasstrace.error.fallback_route\n      // SDK-041 / DISC-1535 / AESC §5.5. When a request reaches a\n      // framework fallback route (Next.js `/_error`, `/_not-found`,\n      // etc.), the framework rewrites `http.route` to the fallback,\n      // which loses the originally requested path. We preserve both:\n      //\n      //   - `glasstrace.route` continues to carry whatever the\n      //     framework set (so existing consumers keep working).\n      //   - `glasstrace.error.fallback_route` carries the fallback\n      //     path explicitly.\n      //   - `glasstrace.error.original_path` carries the concrete\n      //     requested path, parsed from `http.url` / `url.full` /\n      //     `http.target` (whichever the upstream instrumentation\n      //     populated). Path-only — no query, no fragment.\n      //\n      // We only mark a fallback when both (a) the route looks like a\n      // known fallback AND (b) we have an original path that\n      // differs. Otherwise we'd label an actual visit to `/_error`\n      // (an app might have a real `/_error` page) as a framework\n      // fallback by accident.\n      const routeIsFallback =\n        route === \"/_error\" ||\n        route === \"/_not-found\" ||\n        route === \"/_404\" ||\n        route === \"/_500\";\n      if (routeIsFallback && rawHttpUrl) {\n        const originalPath = extractPathOnly(rawHttpUrl);\n        // Normalize trailing slashes on both sides before the\n        // differ check so frameworks/proxies that round-trip a\n        // trailing slash on `http.url` (e.g., `/_error/`) don't\n        // produce a false-positive fallback marker on a real visit\n        // to the literal fallback page (Codex P2 review on PR #251).\n        const normOriginal = stripTrailingSlash(originalPath);\n        const normRoute = stripTrailingSlash(route);\n        if (normOriginal && normOriginal !== normRoute) {\n          extra[ATTR.ERROR_ORIGINAL_PATH] = normOriginal;\n          extra[ATTR.ERROR_FALLBACK_ROUTE] = route;\n          extra[ATTR.ERROR_FRAMEWORK_KIND] = \"fallback\";\n          // Promote to framework_fallback only when no upstream OTel\n          // source has already claimed provenance — otherwise we'd\n          // overwrite a more specific `otel_exception` label with a\n          // less specific framework one.\n          errorSource = errorSource ?? \"framework_fallback\";\n        }\n      }\n\n      if (errorSource !== undefined) {\n        extra[ATTR.ERROR_SOURCE] = errorSource;\n      }\n\n      if (this.verbose && (extra[ATTR.ERROR_MESSAGE] || extra[ATTR.ERROR_CODE])) {\n        // Source label reflects which surface won under the new\n        // event-first precedence (SDK-041 / DISC-1535).\n        const msgSource = eventDetails.message ? \"event\"\n          : typeof attrMessage === \"string\" ? \"attrs\"\n          : \"none\";\n        const typeSource = eventDetails.type ? \"event\"\n          : typeof attrType === \"string\" ? \"attrs\"\n          : \"none\";\n        sdkLog(\"info\",\n          `[glasstrace] enrichSpan \"${name}\": error.message source=${msgSource}, ` +\n          `error.code source=${typeSource}`,\n        );\n      }\n\n      // glasstrace.error.field\n      const errorField = attrs[\"error.field\"];\n      if (typeof errorField === \"string\") {\n        extra[ATTR.ERROR_FIELD] = errorField;\n      }\n\n      // glasstrace.error.response_body (DISC-1216)\n      //\n      // Adapters (e.g., a tRPC handler wrapper) populate the internal\n      // attribute `glasstrace.internal.response_body` on the active span\n      // when an HTTP handler returns a 4xx/5xx body. The exporter\n      // conditionally promotes it to the public attribute under three\n      // gates:\n      //\n      //   1. Account opt-in via `captureConfig.errorResponseBodies`. The\n      //      flag defaults to `false`, so capture is off unless the\n      //      account has explicitly enabled it server-side.\n      //   2. HTTP status in the inclusive range [400..599]. We read the\n      //      *enriched* status (`extra[HTTP_STATUS_CODE]`) first because\n      //      the inference block above may have promoted a misreported\n      //      0/200 to 5xx based on `error.type` / exception events; if\n      //      that block did not run we fall through to the raw OTel\n      //      attributes. A successful response (2xx/3xx) never leaks\n      //      even if an adapter mistakenly populated the internal attr.\n      //   3. Body shape: must be a non-empty string. Binary streams,\n      //      `null`, and structured values are silently ignored.\n      //\n      // Before promotion the body is (a) sanitized to redact common\n      // secret patterns (Bearer tokens, JWTs, Glasstrace API keys, AWS\n      // access keys, generic key/secret/password/token=value pairs) and\n      // (b) truncated to a UTF-8 byte budget with a `...[truncated]`\n      // marker appended when truncation fires. Sanitization runs before\n      // truncation so secrets straddling the boundary are still removed\n      // from the visible portion.\n      const errorResponseBodiesEnabled =\n        this.getConfig().errorResponseBodies === true;\n      // Decision trace (hot path): whether error-response-body capture is\n      // enabled for this account. Read the config once and reuse it for the\n      // gate below. Keyed by the closed outcome (two values) so it stays\n      // bounded. Call-site guarded so no detail is built when OFF.\n      if (decisionTraceEnabled()) {\n        const outcome = errorResponseBodiesEnabled ? \"enabled\" : \"disabled\";\n        decisionTrace(\"feature.errorResponseBodies\", outcome, {\n          oneShotKey: `feature.errorResponseBodies:${outcome}`,\n        });\n      }\n      if (errorResponseBodiesEnabled) {\n        const responseBody = attrs[\"glasstrace.internal.response_body\"];\n        if (typeof responseBody === \"string\") {\n          // Prefer the enriched status from the inference block above\n          // (covers the Next.js timing-race promotion of 0/200 → 5xx);\n          // fall back to the raw `statusCode` computed earlier which\n          // already merges `http.status_code` and `http.response.status_code`.\n          const enrichedStatus = extra[ATTR.HTTP_STATUS_CODE];\n          const effectiveStatus =\n            typeof enrichedStatus === \"number\" ? enrichedStatus : statusCode;\n          if (isHttpErrorStatus(effectiveStatus)) {\n            const prepared = prepareErrorResponseBody(responseBody);\n            if (prepared !== null) {\n              extra[ATTR.ERROR_RESPONSE_BODY] = prepared;\n            }\n          }\n        }\n      }\n\n      // glasstrace.orm.*\n      const spanAny = span as unknown as Record<string, { name?: string } | undefined>;\n      const instrumentationName =\n        (spanAny.instrumentationScope?.name ?? spanAny.instrumentationLibrary?.name) ?? \"\";\n      const ormProvider = deriveOrmProvider(instrumentationName);\n      if (ormProvider) {\n        extra[ATTR.ORM_PROVIDER] = ormProvider;\n\n        const table = attrs[\"db.sql.table\"];\n        const prismaModel = attrs[\"db.prisma.model\"];\n        const model = typeof table === \"string\" ? table\n          : typeof prismaModel === \"string\" ? prismaModel\n          : undefined;\n        if (model) {\n          extra[ATTR.ORM_MODEL] = model;\n        }\n\n        const operation = attrs[\"db.operation\"];\n        if (typeof operation === \"string\") {\n          extra[ATTR.ORM_OPERATION] = operation;\n        }\n      }\n\n      // glasstrace.fetch.target\n      const httpUrl = attrs[\"http.url\"];\n      const fullUrl = attrs[\"url.full\"];\n      const url = typeof httpUrl === \"string\" ? httpUrl\n        : typeof fullUrl === \"string\" ? fullUrl\n        : undefined;\n      if (url && span.kind === SpanKind.CLIENT) {\n        extra[ATTR.FETCH_TARGET] = classifyFetchTarget(url);\n      }\n\n      return createEnrichedSpan(span, extra);\n    } catch {\n      // Return original span unchanged so the export pipeline is never blocked\n      return span;\n    }\n  }\n\n  /**\n   * Lazily creates the delegate OTLP exporter once the API key is resolved.\n   * Recreates the delegate if the key has changed (e.g., after key rotation)\n   * so the Authorization header stays current.\n   */\n  private ensureDelegate(): SpanExporter | null {\n    if (!this.createDelegateFn) return null;\n\n    const currentKey = this.getApiKey();\n    if (currentKey === API_KEY_PENDING) return null;\n\n    // Recreate delegate if the key has changed since last creation\n    if (this.delegate && this.delegateKey === currentKey) {\n      return this.delegate;\n    }\n\n    // Shut down old delegate if key rotated. Catch errors to prevent\n    // unhandled rejections from crashing the process during rotation.\n    if (this.delegate) {\n      void this.delegate.shutdown?.().catch(() => {});\n    }\n\n    this.delegate = this.createDelegateFn(this.endpointUrl, {\n      Authorization: `Bearer ${currentKey}`,\n    });\n    this.delegateKey = currentKey;\n    return this.delegate;\n  }\n\n  /**\n   * Buffers raw (unenriched) spans while the API key is pending.\n   * Evicts oldest batches if the buffer exceeds MAX_PENDING_SPANS.\n   * Re-checks the key after buffering to close the race window where\n   * the key resolves between the caller's check and this buffer call.\n   */\n  private bufferSpans(\n    spans: ReadableSpan[],\n    resultCallback: (result: ExportResult) => void,\n  ): void {\n    this.pendingBatches.push({ spans, resultCallback });\n    this.pendingSpanCount += spans.length;\n\n    // Evict oldest batches if over limit\n    while (this.pendingSpanCount > MAX_PENDING_SPANS && this.pendingBatches.length > 1) {\n      const evicted = this.pendingBatches.shift()!;\n      this.pendingSpanCount -= evicted.spans.length;\n      recordSpansDropped(evicted.spans.length);\n      // Complete callback so pipeline doesn't hang\n      evicted.resultCallback({ code: 0 });\n\n      if (!this.overflowLogged) {\n        this.overflowLogged = true;\n        console.warn(\n          \"[glasstrace] Pending span buffer overflow — oldest spans evicted. \" +\n          \"This usually means the API key is taking too long to resolve.\",\n        );\n      }\n    }\n\n    // Re-check: if the key resolved between the caller's check and now,\n    // flush immediately to avoid spans stuck in the buffer.\n    if (this.getApiKey() !== API_KEY_PENDING) {\n      this.flushPending();\n    }\n  }\n\n  /**\n   * Flushes all buffered spans through the delegate exporter.\n   * Enriches spans at flush time (not buffer time) so that session IDs\n   * are computed with the resolved API key instead of the \"pending\" sentinel.\n   *\n   * Honors the circuit breaker symmetrically with {@link export}: if the\n   * breaker is OPEN at flush time, every buffered batch is dropped via\n   * `recordSpansDropped` and its callback completed with `{ code: 0 }`,\n   * preserving the bounded-memory contract during outages.\n   */\n  private flushPending(): void {\n    if (this.pendingBatches.length === 0) return;\n\n    const exporter = this.ensureDelegate();\n    if (!exporter) {\n      // No delegate factory — complete callbacks and count as dropped\n      let discardedCount = 0;\n      for (const batch of this.pendingBatches) {\n        discardedCount += batch.spans.length;\n        batch.resultCallback({ code: 0 });\n      }\n      recordSpansDropped(discardedCount);\n      this.pendingBatches = [];\n      this.pendingSpanCount = 0;\n      return;\n    }\n\n    const breaker = this.getCircuitBreaker();\n    const batches = this.pendingBatches;\n    this.pendingBatches = [];\n    this.pendingSpanCount = 0;\n\n    for (const batch of batches) {\n      // Pass 1 (boundary-masked descendant tracking): record parent links\n      // and exception-bearing spans BEFORE the per-batch OPEN-drop gate, so a\n      // dropped buffered batch still contributes lineage that a later parent\n      // batch may need. See the matching hoist in {@link export}.\n      this.recordTraceErrorPass(batch.spans, breaker);\n\n      // Circuit-breaker gate: honor OPEN state on flush too (buffered\n      // batches that survive a key-pending → key-resolved transition\n      // arrive here and would otherwise bypass the gate).\n      if (!breaker.shouldExport()) {\n        breaker.onSpansDropped(batch.spans.length);\n        batch.resultCallback({ code: 0 });\n        continue;\n      }\n      // Enrich at flush time with the now-resolved key\n      const enriched = batch.spans.map((span) => this.enrichSpan(span, batch.spans));\n      const generationAtIssue = breaker.getGeneration();\n      exporter.export(enriched, (result) => {\n        if (result.code !== 0) {\n          sdkLog(\"warn\", `[glasstrace] Span export failed: ${result.error?.message ?? \"unknown error\"}`);\n        }\n        if (breaker.getGeneration() !== generationAtIssue) {\n          batch.resultCallback(result);\n          return;\n        }\n        if (result.code === 0) {\n          breaker.recordSuccess();\n        } else {\n          breaker.recordFailure({ error: result.error });\n        }\n        batch.resultCallback(result);\n      });\n      recordSpansExported(enriched.length);\n    }\n  }\n\n  /**\n   * Pass 1 of the descendant boundary-masked detection. For each span in the\n   * batch, records its `spanId → parentSpanId` link (every span — error and\n   * non-error) plus, for exception-bearing spans, a full lineage entry into\n   * the per-trace error store keyed by `${traceId}#${sessionId}`. Runs before\n   * the OPEN-drop gate in both entry points so lineage is captured even on a\n   * dropped batch. A no-op when the opt-out flag is set.\n   *\n   * Key validation is strict: the trace key is recorded only when `traceId`\n   * is 32 lowercase-hex chars and the resolved `sessionId` is a non-empty\n   * string. A failure increments the store's key-validation counter and\n   * skips the write — never synthesizing a placeholder key (which could risk\n   * cross-context promotion).\n   */\n  private recordTraceErrorPass(spans: ReadableSpan[], breaker: ExportCircuitBreaker): void {\n    if (BOUNDARY_MASKED_DISABLED) return;\n    let sessionId: string | undefined;\n    try {\n      sessionId = this.sessionManager.getSessionId(this.getApiKey());\n    } catch {\n      sessionId = undefined;\n    }\n    const store = breaker.traceErrors;\n    const nowMs = Date.now();\n    for (const span of spans) {\n      try {\n        const ctx = span.spanContext();\n        const traceId = ctx?.traceId;\n        const key = buildTraceKey(traceId, sessionId);\n        if (key === undefined) {\n          store.recordKeyValidationFailure();\n          continue;\n        }\n        const parentSpanId = span.parentSpanContext?.spanId;\n        store.recordParentLink(key, ctx.spanId, parentSpanId, nowMs);\n        if (hasExceptionEvent(span)) {\n          const details = getExceptionEventDetails(span);\n          const attrs = span.attributes ?? {};\n          const nextSpanType = attrs[\"next.span_type\"];\n          const entry: ExceptionLineageEntry = {\n            spanId: ctx.spanId,\n            parentSpanId,\n            startTimeMs: hrTimeToMs(span.startTime),\n            message: details.message,\n            type: details.type,\n            nextSpanType: typeof nextSpanType === \"string\" ? nextSpanType : undefined,\n            // Capture the expected-error escape hatch on the exception-bearer\n            // itself. The descendant carrying `glasstrace.error.expected` (an\n            // app-marked, intentional boundary) must never be promoted — the\n            // server span may be unmarked, so reading the flag only on the\n            // server span at consult time would miss a per-descendant opt-out.\n            expected: attrs[\"glasstrace.error.expected\"] === true,\n          };\n          store.recordException(key, entry, nowMs);\n        }\n      } catch {\n        // A malformed span must never break the export pipeline.\n      }\n    }\n  }\n\n  /**\n   * Descendant-scope boundary-masked promotion (the else-branch consult). The\n   * SERVER span had no same-span error signal; promote it to 500 only when a\n   * transitive-descendant exception passes the full fence:\n   *\n   *   - the descendant is in the same trace AND session (the namespaced key);\n   *   - it is a transitive child of this SERVER span (ancestor walk);\n   *   - it recorded an `exception` event (graceful-degradation fence);\n   *   - it is not a known Next control-flow throw;\n   *   - for a render-route descendant, the exception is in the\n   *     unexpected/infrastructure class (a generic expected `Error` from an\n   *     `error.tsx` fallback is NOT promoted);\n   *   - the expected-error escape hatch (`glasstrace.error.expected === true`\n   *     on the descendant or the SERVER span) is not set.\n   */\n  private tryDescendantPromotion(\n    span: ReadableSpan,\n    attrs: ReadableSpan[\"attributes\"],\n    name: string,\n    statusCode: number | undefined,\n    extra: Record<string, string | number | boolean>,\n    batch: ReadableSpan[],\n  ): void {\n    // Status-trigger fence (#2): an explicitly-OK server span has already\n    // resolved its status — the handler recovered. Never promote it from a\n    // descendant exception. This mirrors the `statusNotExplicitlyOK` guard the\n    // same-span path applies before its own promotion.\n    if (span.status?.code === SpanStatusCode.OK) return;\n\n    const breaker = this.getCircuitBreaker();\n    const store = breaker.traceErrors;\n    let sessionId: string | undefined;\n    try {\n      sessionId = this.sessionManager.getSessionId(this.getApiKey());\n    } catch {\n      sessionId = undefined;\n    }\n    const ctx = span.spanContext();\n    const key = buildTraceKey(ctx?.traceId, sessionId);\n    if (key === undefined) {\n      store.recordKeyValidationFailure();\n      return;\n    }\n    const state = store.consult(key, Date.now());\n    if (state === undefined) return;\n\n    // Expected-error escape hatch on the SERVER span itself.\n    if (attrs[\"glasstrace.error.expected\"] === true) return;\n\n    // Find the EARLIEST qualifying exception descendant (smallest startTimeMs,\n    // tie-break smallest spanId — deterministic). Only the qualifying set is\n    // ranked, so a non-qualifying earlier exception (control-flow, expected\n    // render-route Error) does not suppress a later real infrastructure one.\n    let chosen: ExceptionLineageEntry | undefined;\n    for (const entry of state.lineageBySpanId.values()) {\n      if (!isPromotableDescendant(entry)) continue;\n      if (!isTransitiveDescendant(entry, ctx.spanId, state, batch)) continue;\n      if (\n        chosen === undefined ||\n        entry.startTimeMs < chosen.startTimeMs ||\n        (entry.startTimeMs === chosen.startTimeMs && entry.spanId < chosen.spanId)\n      ) {\n        chosen = entry;\n      }\n    }\n    if (chosen === undefined) return;\n\n    // Promote. Mirror the same-span path: a numeric error.type on the SERVER\n    // span overrides the default 500 with a 400-599 wire status.\n    const httpErrorType = attrs[\"error.type\"];\n    let inferredStatus = 500;\n    if (typeof httpErrorType === \"string\") {\n      const parsed = parseInt(httpErrorType, 10);\n      if (!isNaN(parsed) && parsed >= 400 && parsed <= 599) {\n        inferredStatus = parsed;\n      }\n    }\n    extra[ATTR.HTTP_STATUS_CODE] = inferredStatus;\n    extra[ATTR.HTTP_BOUNDARY_MASKED] = true;\n    extra[ATTR.HTTP_BOUNDARY_MASKED_SCOPE] = \"descendant\";\n\n    emitLifecycleEvent(\"core:error_boundary_detected\", {\n      spanId: ctx.spanId,\n      inferredStatus,\n      source: \"descendant\",\n      exceptionSpanId: chosen.spanId,\n      ...(chosen.message !== undefined\n        ? { exceptionMessage: chosen.message.slice(0, 256) }\n        : {}),\n    });\n\n    if (this.verbose) {\n      sdkLog(\"info\",\n        `[glasstrace] enrichSpan \"${name}\": inferred status_code=${inferredStatus} ` +\n        `(was ${statusCode}) from descendant exception span ${chosen.spanId}`,\n      );\n    }\n  }\n\n}\n\n/**\n * Creates a ReadableSpan wrapper that inherits all properties from the\n * original span but overrides `attributes` to include additional entries.\n * The original span is not mutated.\n */\nfunction createEnrichedSpan(\n  span: ReadableSpan,\n  extra: Record<string, string | number | boolean>,\n): ReadableSpan {\n  const enrichedAttributes = { ...span.attributes, ...extra };\n  return Object.create(span, {\n    attributes: {\n      value: enrichedAttributes,\n      enumerable: true,\n    },\n  }) as ReadableSpan;\n}\n\n/**\n * Returns true if the span has at least one \"exception\" event.\n * This signals that `span.recordException()` was called, even if\n * `span.setStatus(ERROR)` was not yet applied due to the timing race\n * in Next.js dev server.\n */\nfunction hasExceptionEvent(span: ReadableSpan): boolean {\n  return span.events?.some((e) => e.name === \"exception\") ?? false;\n}\n\n/**\n * Builds the namespaced per-trace error-store key `${traceId}#${sessionId}`,\n * or `undefined` when either component fails validation. `traceId` must be a\n * 32-char lowercase-hex string; `sessionId` must be a non-empty string. The\n * `#sessionId` namespace prevents UUID collisions in deterministic fixtures,\n * distributed-trace retries that reuse a propagated `traceId`, and\n * cross-tenant bleed.\n */\nfunction buildTraceKey(\n  traceId: string | undefined,\n  sessionId: string | undefined,\n): string | undefined {\n  if (typeof traceId !== \"string\" || !/^[0-9a-f]{32}$/.test(traceId)) {\n    return undefined;\n  }\n  if (typeof sessionId !== \"string\" || sessionId.length === 0) {\n    return undefined;\n  }\n  return `${traceId}#${sessionId}`;\n}\n\n/**\n * Converts an OTel `HrTime` ([seconds, nanoseconds]) to milliseconds. Used\n * for the deterministic earliest-exception tie-break. Returns 0 for a\n * malformed input so a bad time value never makes ranking throw.\n */\nfunction hrTimeToMs(hrTime: ReadableSpan[\"startTime\"] | undefined): number {\n  if (!Array.isArray(hrTime) || hrTime.length < 2) return 0;\n  const [sec, nano] = hrTime;\n  if (typeof sec !== \"number\" || typeof nano !== \"number\") return 0;\n  return sec * 1000 + nano / 1_000_000;\n}\n\n/**\n * Applies the load-bearing false-positive fence to a recorded\n * exception-bearing descendant: returns true only if it should promote the\n * SERVER span. Excludes Next control-flow throws; for render-route\n * descendants, requires an unexpected/infrastructure exception class (a\n * generic expected application `Error` from an `error.tsx` fallback is NOT\n * promoted). The lineage/kind/transitivity checks are applied by the caller.\n */\nfunction isPromotableDescendant(entry: ExceptionLineageEntry): boolean {\n  // 5c — expected-error escape hatch on the exception-bearer itself. A\n  // descendant marked `glasstrace.error.expected === true` is an app-declared\n  // intentional boundary and is never promoted, regardless of exception class.\n  if (entry.expected === true) return false;\n\n  const haystack = `${entry.type ?? \"\"}\\n${entry.message ?? \"\"}`;\n\n  // 5a — control-flow exclusion (case-sensitive substring).\n  for (const marker of NEXT_CONTROL_FLOW_MARKERS) {\n    if (haystack.includes(marker)) return false;\n  }\n\n  // 5b — render-route generic-error suppression. A render-route descendant\n  // promotes only on an unexpected/infrastructure exception class.\n  if (entry.nextSpanType === RENDER_ROUTE_SPAN_TYPE) {\n    for (const marker of RENDER_ROUTE_INFRA_MARKERS) {\n      if (haystack.includes(marker)) return true;\n    }\n    return false;\n  }\n\n  // Non-render-route descendants promote on any non-control-flow exception.\n  return true;\n}\n\n/**\n * Confirms `entry` is a transitive child of the SERVER span identified by\n * `serverSpanId`, by threading `parentSpanId` links up the tree. Resolves\n * each ancestor's parent in fixed precedence: the persistent `parentLinks`\n * map first (lets the walk cross a non-error intermediate that ended in an\n * earlier batch), then an exception-bearing ancestor's stored parent, then\n * the current pass-2 batch. A visited-set guard makes a corrupt/cyclic chain\n * safe. Bounded by trace depth; a missing link stops the walk (no promote).\n */\nfunction isTransitiveDescendant(\n  entry: ExceptionLineageEntry,\n  serverSpanId: string,\n  state: TraceErrorState,\n  batch: ReadableSpan[],\n): boolean {\n  let curParent = entry.parentSpanId;\n  const visited = new Set<string>([entry.spanId]);\n  while (curParent !== undefined) {\n    if (curParent === serverSpanId) return true;\n    if (visited.has(curParent)) return false; // cycle guard\n    visited.add(curParent);\n    const next = resolveParent(curParent, state, batch);\n    curParent = next;\n  }\n  return false;\n}\n\n/**\n * Resolves the parentSpanId of `spanId` for the ancestor walk, in the fixed\n * precedence: persistent parentLinks → exception-bearer's stored parent →\n * current pass-2 batch scan. Returns `undefined` (stop) when no link is\n * found.\n */\nfunction resolveParent(\n  spanId: string,\n  state: TraceErrorState,\n  batch: ReadableSpan[],\n): string | undefined {\n  if (state.parentLinks.has(spanId)) {\n    return state.parentLinks.get(spanId);\n  }\n  const lineage = state.lineageBySpanId.get(spanId);\n  if (lineage !== undefined) {\n    return lineage.parentSpanId;\n  }\n  for (const s of batch) {\n    try {\n      if (s.spanContext().spanId === spanId) {\n        return s.parentSpanContext?.spanId;\n      }\n    } catch {\n      // ignore malformed span\n    }\n  }\n  return undefined;\n}\n\n/**\n * Extracts exception.type and exception.message from the first \"exception\"\n * event on the span. Returns undefined values if not found.\n *\n * OTel's `recordException()` stores error details in event attributes, not\n * span attributes. The enrichment code needs this fallback to populate\n * glasstrace.error.message and glasstrace.error.code when the standard\n * span attributes are absent.\n */\nfunction getExceptionEventDetails(span: ReadableSpan): {\n  type: string | undefined;\n  message: string | undefined;\n  stacktrace: string | undefined;\n} {\n  const event = span.events?.find((e) => e.name === \"exception\");\n  if (!event?.attributes) {\n    return { type: undefined, message: undefined, stacktrace: undefined };\n  }\n  const type = event.attributes[\"exception.type\"];\n  const message = event.attributes[\"exception.message\"];\n  const stacktrace = event.attributes[\"exception.stacktrace\"];\n  return {\n    type: typeof type === \"string\" ? type : undefined,\n    message: typeof message === \"string\" ? message : undefined,\n    stacktrace: typeof stacktrace === \"string\" ? stacktrace : undefined,\n  };\n}\n\n/**\n * Extracts the leading path from a route-or-span-name string so the\n * Server Action heuristic can match reliably regardless of\n * whether the value came from `http.route` (bare path, e.g. \"/login\")\n * or from `span.name` (Next.js-formatted, e.g. \"POST /login\" or\n * \"middleware POST /login\").\n *\n * Returns the first `/…`-prefixed token, or `undefined` if no such\n * token is present. Empty input yields `undefined` so callers can use\n * the result as a truthy guard.\n */\nexport function extractLeadingPath(raw: string | undefined): string | undefined {\n  if (!raw) return undefined;\n  const trimmed = raw.trim();\n  if (trimmed.length === 0) return undefined;\n\n  // Fast path: already a bare path.\n  if (trimmed.startsWith(\"/\")) {\n    const firstSpace = trimmed.indexOf(\" \");\n    return firstSpace === -1 ? trimmed : trimmed.slice(0, firstSpace);\n  }\n\n  // Fallback: scan for the first whitespace-separated token that looks\n  // like a path. Handles \"POST /login\", \"middleware POST /login\", etc.\n  for (const token of trimmed.split(/\\s+/)) {\n    if (token.startsWith(\"/\")) {\n      return token;\n    }\n  }\n\n  return undefined;\n}\n\n/**\n * Strips a trailing `/` from a path so two paths that differ only in\n * trailing-slash form compare equal. Used by the framework-\n * fallback differ check; frameworks/proxies inconsistently round-trip\n * trailing slashes between `http.route` and `http.url`, and a\n * literal-string compare without normalization would produce\n * false-positive fallback markers on real visits to a literal\n * `/_error` page (Codex P2 review on PR #251).\n *\n * Returns the original input for `undefined` and for the root path\n * `\"/\"` (where stripping the slash would lose the path entirely);\n * otherwise returns the input with any single trailing slash removed.\n */\nfunction stripTrailingSlash(path: string | undefined): string | undefined {\n  if (!path) return path;\n  if (path === \"/\") return path;\n  return path.endsWith(\"/\") ? path.slice(0, -1) : path;\n}\n\n/**\n * Extracts the path component (no query, no fragment) from a URL or\n * a bare path. Used by the framework-fallback handler to\n * compute `glasstrace.error.original_path` from the upstream\n * `http.url` / `url.full` / `http.target` value when a request gets\n * rewritten to a fallback route like `/_error`.\n *\n * Accepts:\n *\n *   - Absolute URLs: `http://host:3000/api/storage/x?foo=bar` → `/api/storage/x`\n *   - Protocol-relative URLs: `//host/api/x?q=y` → `/api/x`\n *   - Bare paths with query/fragment: `/api/x?q=y#z` → `/api/x`\n *   - Bare paths: `/api/x` → `/api/x`\n *\n * Returns `undefined` for empty / whitespace-only input or values\n * that do not contain a recognizable path component (e.g.\n * `mailto:...`, `data:...`, or arbitrary non-URL strings). Callers\n * use the undefined return as a truthy guard.\n *\n * Rejects values that don't ultimately resolve to a `/`-prefixed\n * path so the framework-fallback handler doesn't accidentally\n * promote a non-path URL into `glasstrace.error.original_path`.\n */\nexport function extractPathOnly(raw: string | undefined): string | undefined {\n  if (!raw) return undefined;\n  const trimmed = raw.trim();\n  if (trimmed.length === 0) return undefined;\n\n  // URL parser handles absolute URLs (`http://...`, `https://...`)\n  // and protocol-relative URLs (`//host/path`); both forms have a\n  // recognizable scheme prefix. Only invoke the parser for those\n  // forms — invoking it on arbitrary relative strings like\n  // `\"api/users\"` resolves them against the sentinel base\n  // (`http://_/api/users`) and silently coerces a non-path input\n  // into a fake path, which would falsely emit\n  // `glasstrace.error.original_path` for unparseable upstream\n  // values (Copilot review on PR #251).\n  const isAbsoluteUrl = /^https?:\\/\\//i.test(trimmed);\n  const isProtocolRelative = trimmed.startsWith(\"//\");\n  if (isAbsoluteUrl || isProtocolRelative) {\n    try {\n      const parsed = new URL(trimmed, \"http://_/\");\n      if (parsed.pathname && parsed.pathname.startsWith(\"/\")) {\n        return parsed.pathname;\n      }\n    } catch {\n      // Fall through to bare-path fast path below.\n    }\n  }\n\n  // Bare-path fast path: strip query/fragment if present. Requires\n  // a leading `/` so we don't accept `\"api/users\"` as if it were a\n  // path.\n  if (trimmed.startsWith(\"/\")) {\n    const queryIdx = trimmed.indexOf(\"?\");\n    const fragIdx = trimmed.indexOf(\"#\");\n    let cut = trimmed.length;\n    if (queryIdx >= 0) cut = Math.min(cut, queryIdx);\n    if (fragIdx >= 0) cut = Math.min(cut, fragIdx);\n    return trimmed.slice(0, cut);\n  }\n\n  return undefined;\n}\n\n/**\n * Derives ORM provider from the instrumentation library name.\n */\nexport function deriveOrmProvider(instrumentationName: string): string | null {\n  const lower = instrumentationName.toLowerCase();\n  if (lower.includes(\"prisma\")) {\n    return \"prisma\";\n  }\n  if (lower.includes(\"drizzle\")) {\n    return \"drizzle\";\n  }\n  return null;\n}\n\n/**\n * Derives error category from error type string.\n */\nexport function deriveErrorCategory(errorType: string): string {\n  const lower = errorType.toLowerCase();\n  if (lower.includes(\"validation\") || lower.includes(\"zod\")) {\n    return \"validation\";\n  }\n  if (\n    lower.includes(\"network\") ||\n    lower.includes(\"econnrefused\") ||\n    lower.includes(\"fetch\") ||\n    lower.includes(\"timeout\")\n  ) {\n    return \"network\";\n  }\n  if (lower.includes(\"auth\") || lower.includes(\"unauthorized\") || lower.includes(\"forbidden\")) {\n    return \"auth\";\n  }\n  if (lower.includes(\"notfound\") || lower.includes(\"not_found\")) {\n    return \"not-found\";\n  }\n  return \"internal\";\n}\n","/**\n * Helpers for the `glasstrace.error.response_body` span attribute.\n *\n * The exporter promotes an internal `glasstrace.internal.response_body`\n * attribute to the public `glasstrace.error.response_body` attribute when\n * three conditions hold:\n *\n *   1. The account-side `captureConfig.errorResponseBodies` flag is `true`.\n *   2. The HTTP status on the span is in the inclusive range `[400..599]`.\n *   3. The body is a non-empty string.\n *\n * Before promotion, the body is sanitized to strip well-known secret-ish\n * patterns and then truncated to a hard byte budget. Sanitization runs\n * BEFORE truncation so that secrets straddling the truncation boundary are\n * still redacted in the visible portion. Truncation respects UTF-8 codepoint\n * boundaries — slicing a JS string at a UTF-16 code unit can leave a lone\n * surrogate or split a multi-byte UTF-8 sequence in the encoded form, and\n * downstream consumers (the ingestion pipeline, the Glasstrace UI) re-encode\n * spans through a Buffer round-trip that does not tolerate malformed input.\n *\n * Design constraints:\n *   - Zero new runtime dependencies. Inline regex only.\n *   - Pure functions: easy to unit-test without span mocks.\n *   - Conservative redaction: when in doubt, redact. False positives that\n *     turn a JSON `password` field into `[REDACTED]` are acceptable; false\n *     negatives that leak a token are not.\n *\n * Phase 2 behavior: sanitize, status-gate, raise the truncation cap.\n */\n\n/**\n * Maximum byte length for the captured response body.\n *\n * Set to 4096 bytes to fit comfortably under typical OTel span attribute\n * size limits (commonly 8 KB) while leaving headroom for the rest of the\n * `glasstrace.*` attribute set on the same span. The Phase 1 cap was\n * 500 chars, which truncated typical tRPC error envelopes mid-payload.\n */\nexport const ERROR_RESPONSE_BODY_MAX_BYTES = 4096;\n\n/**\n * Marker appended when the body was truncated to fit the byte budget.\n * Lets downstream consumers detect that the body is partial and avoid\n * parsing a partial JSON envelope as authoritative.\n */\nexport const ERROR_RESPONSE_BODY_TRUNCATION_MARKER = \"...[truncated]\";\n\n/**\n * Replacement token written into the body in place of any matched secret.\n * Kept ASCII-only so it never inflates the byte count past truncation.\n */\nconst REDACTED = \"[REDACTED]\";\n\n/**\n * Inclusive lower bound of the HTTP status range that triggers capture.\n */\nexport const ERROR_STATUS_MIN = 400;\n\n/**\n * Inclusive upper bound of the HTTP status range that triggers capture.\n */\nexport const ERROR_STATUS_MAX = 599;\n\n/**\n * Coerces an OTel attribute value to an HTTP status number, or returns\n * `undefined` when the value is not a finite numeric (or numeric-string)\n * representation of a status.\n *\n * The OpenTelemetry attribute spec allows\n * `string | number | boolean | (string | number | boolean)[]`. Several\n * real-world instrumentations (custom HTTP wrappers, edge runtimes that\n * round-trip headers verbatim, some community Node adapters) emit\n * `http.status_code` and `http.response.status_code` as strings (e.g.\n * `\"500\"`). The SDK exporter previously read these via TypeScript\n * `as number | undefined` casts that perform no runtime coercion, so a\n * string-shaped `\"200\"` would (a) flow verbatim into the public\n * `glasstrace.http.status_code` wire attribute (which downstream\n * ingestion expects to be numeric) and (b) fail the\n * `statusCode === 200` comparison that the Next.js timing-race\n * inference block relies on. This helper closes\n * both gaps at the read site.\n *\n * Postel's Law: be liberal in what we accept. The behavior is identical\n * to {@link isHttpErrorStatus}'s coercion step (the latter delegates\n * here for symmetry), and `Number()`'s semantics determine string\n * acceptance:\n *\n *   - Numbers pass through when {@link Number.isFinite} is `true`.\n *     `NaN` and `±Infinity` return `undefined`.\n *   - Strings are trimmed and rejected when the trimmed value is\n *     empty (so `\"\"`, `\"   \"`, `\"\\t\\n\"` all return `undefined`). The\n *     trimmed value is then coerced via `Number(value)` and accepted\n *     when the result is finite. `\"500\"`, `\" 500 \"`, `\"5e2\"`, `\"0x1F4\"`\n *     all yield `500`.\n *   - Empty / whitespace-only strings, non-numeric strings (`\"foo\"`,\n *     `\"4xx\"`), `null`, `undefined`, booleans, objects, arrays, and\n *     symbols all return `undefined`.\n *\n * The whitespace-only guard matters: `Number(\"   \") === 0`, so without\n * the trim check a whitespace-only attribute would (a) emit a numeric\n * `0` into the wire payload — masking a fallback to\n * `http.response.status_code` via `??` — and (b) trigger the\n * inference block's `statusCode === 0` discriminator, synthesizing a\n * 500 from blank input. Treat blank strings the same as the empty\n * string and the other invalid shapes.\n *\n * Note: this helper coerces to a numeric *type*; it does not validate\n * the value lies in any HTTP-status range. The caller is responsible\n * for any further range checks (e.g. {@link isHttpErrorStatus} for the\n * 4xx/5xx capture gate).\n */\nexport function coerceHttpStatus(value: unknown): number | undefined {\n  let numeric: number;\n  if (typeof value === \"number\") {\n    numeric = value;\n  } else if (typeof value === \"string\") {\n    const trimmed = value.trim();\n    if (trimmed.length === 0) return undefined;\n    numeric = Number(trimmed);\n  } else {\n    return undefined;\n  }\n  return Number.isFinite(numeric) ? numeric : undefined;\n}\n\n/**\n * Returns `true` when the supplied status code is an HTTP error status\n * (4xx or 5xx). Non-finite, non-numeric, and out-of-range values yield\n * `false`. The status comes from OTel attribute values which are typed\n * `unknown`-ish in practice (string | number | boolean | array), so the\n * caller may pass anything and rely on this guard.\n *\n * Numeric strings (e.g. `\"500\"`) are coerced via {@link coerceHttpStatus}\n * before the range check. The OTel attribute spec allows\n * `string | number | boolean | array`, and several real-world\n * instrumentations (custom HTTP wrappers, edge runtimes that round-trip\n * headers verbatim) emit `http.status_code` and\n * `http.response.status_code` as strings. Without coercion the exporter\n * would silently drop `glasstrace.error.response_body` on those spans,\n * which is a false negative — Postel's Law: be liberal in what we accept.\n * `Number(non-numeric)` returns `NaN`, which fails the\n * `Number.isFinite` check, so `\"foo\"` still yields `false`. Empty and\n * whitespace-only strings are rejected by `coerceHttpStatus` before\n * reaching the range check, so they cannot coerce to `0` and trigger an\n * out-of-range `false` via the numeric path.\n */\nexport function isHttpErrorStatus(status: unknown): boolean {\n  const numeric = coerceHttpStatus(status);\n  if (numeric === undefined) return false;\n  return numeric >= ERROR_STATUS_MIN && numeric <= ERROR_STATUS_MAX;\n}\n\n/**\n * Redaction patterns applied in order. Each entry's regex is global so\n * `String.replace` substitutes every match. Patterns are intentionally\n * narrow enough that ordinary error text (e.g. a stack trace, an SQL\n * query echoed back in the error envelope) is not over-redacted.\n *\n * Pattern provenance:\n *   - `Bearer`: HTTP Authorization header echoed in error responses.\n *   - JWT: any 3-segment base64url-encoded token, common in OAuth/OIDC\n *     misconfiguration errors.\n *   - `gt_dev_*` / `gt_anon_*`: Glasstrace API key prefixes; these MUST\n *     never reach the ingestion pipeline because the pipeline keys auth\n *     on the same prefix.\n *   - AWS access keys: `AKIA…` (long-lived) and `ASIA…` (session) are\n *     fixed 20-char identifiers.\n *   - `key=value` style: any of `api_key`, `apikey`, `secret`, `password`,\n *     `token` followed by `:` or `=`. The trailing capture is non-greedy\n *     and stops at whitespace, comma, semicolon, or closing brace/bracket\n *     so we do not redact past the value into surrounding context.\n */\nconst REDACTION_PATTERNS: ReadonlyArray<{ name: string; pattern: RegExp }> = [\n  // Order matters: redact specific token shapes BEFORE the generic\n  // key=value catcher so a literal `Bearer eyJ…` collapses into a single\n  // [REDACTED] and the JWT regex does not separately match the suffix.\n  {\n    name: \"bearer\",\n    // Case-insensitive on the scheme: HTTP frameworks and proxies\n    // round-trip the auth scheme with inconsistent casing\n    // (`Bearer`, `bearer`, `BEARER`), and a real token leaks just as\n    // badly under any of them.\n    pattern: /\\bBearer\\s+[A-Za-z0-9._\\-+/=]+/gi,\n  },\n  {\n    name: \"jwt\",\n    // Three base64url segments separated by dots. Real JWTs encode at\n    // minimum a small JSON header in the first segment, which alone is\n    // typically ≥10 chars after base64url; a 16-char floor avoids false\n    // positives on dotted text like a stack-trace frame\n    // (`react.dom.server`) while still catching every real JWT we have\n    // seen in the wild. Anchored with word boundaries on both sides so\n    // a 3-dot semantic version like \"next@15.4.1.2\" does not match.\n    pattern: /\\b[A-Za-z0-9_-]{16,}\\.[A-Za-z0-9_-]{8,}\\.[A-Za-z0-9_-]{8,}\\b/g,\n  },\n  {\n    name: \"glasstrace-api-key\",\n    // gt_dev_* and gt_anon_* keys are >=24 chars of [A-Za-z0-9].\n    pattern: /\\bgt_(?:dev|anon)_[A-Za-z0-9]{16,}\\b/g,\n  },\n  {\n    name: \"aws-access-key\",\n    // 20-char prefix-fixed identifier.\n    pattern: /\\b(?:AKIA|ASIA)[0-9A-Z]{16}\\b/g,\n  },\n  {\n    name: \"key-value-secret-quoted\",\n    // Quoted-string variant: (key) [:=] \"<value>\". The value runs to\n    // the next unescaped closing quote so a multi-word secret like\n    // `password=\"my secret phrase\"` is fully consumed instead of\n    // splitting at the first space and leaving the tail visible.\n    // The leading `(?<![A-Za-z0-9_])` prevents matching inside\n    // identifiers like `passwordless`. The trailing `\"?` after the\n    // keyword absorbs the closing quote in JSON-style `\"apikey\":\n    // \"value\"` so the colon is still seen as the separator.\n    pattern: /(?<![A-Za-z0-9_])(?:api[_-]?key|apikey|secret|password|token)\"?\\s*[:=]\\s*\"(?:[^\"\\\\]|\\\\.)*\"/gi,\n  },\n  {\n    name: \"key-value-secret-bare\",\n    // Unquoted variant: (key) [:=] <bare-value>. The bare value\n    // capture stops at common JSON/text delimiters so we redact only\n    // the value, not surrounding structure. Listed AFTER the quoted\n    // variant so a quoted value's surrounding `\"` are consumed by\n    // the first pattern and we never fall through here for a quoted\n    // secret.\n    pattern: /(?<![A-Za-z0-9_])(?:api[_-]?key|apikey|secret|password|token)\"?\\s*[:=]\\s*[^\\s,;}\\]\"]+/gi,\n  },\n];\n\n/**\n * Applies redaction patterns to `body`, returning a new string. The original\n * is never mutated. If no pattern matches, the input is returned unchanged\n * (reference-equal where possible — `String.replace` returns the same\n * string instance when no replacement is applied).\n */\nexport function sanitizeErrorResponseBody(body: string): string {\n  let out = body;\n  for (const { pattern } of REDACTION_PATTERNS) {\n    out = out.replace(pattern, REDACTED);\n  }\n  return out;\n}\n\n/**\n * Truncates `body` to at most {@link ERROR_RESPONSE_BODY_MAX_BYTES} bytes\n * when encoded as UTF-8. Bodies already within the budget are returned\n * unchanged. When truncation fires, the result is the longest valid\n * UTF-8 prefix that fits within the budget, followed by the truncation\n * marker. The marker is appended in JS-string form and is NOT counted\n * toward the byte budget so consumers always see a clear \"partial\"\n * signal even at the worst case.\n *\n * The implementation uses `TextEncoder` / `TextDecoder` rather than\n * `Buffer` because `String.prototype.slice` operates on UTF-16 code\n * units; a naive slice can split a 4-byte codepoint at a surrogate pair\n * or a multi-byte UTF-8 sequence at a non-leading byte. We slice the\n * encoded byte array on a UTF-8 codepoint boundary by walking the\n * cut backward past any continuation bytes (`10xxxxxx`) before\n * decoding, so we never present a body that ends in a synthesized\n * U+FFFD. A real U+FFFD in the original body is encoded as the\n * 3-byte sequence `EF BF BD` and is preserved unchanged.\n *\n * `TextEncoder` and `TextDecoder` are globals on every supported runtime\n * (Node ≥18, all edge runtimes, all modern browsers), so this helper\n * does not pin the enclosing module to the Node-only side of the\n * F003 runtime gate by itself.\n */\nexport function truncateErrorResponseBody(body: string): string {\n  const encoder = new TextEncoder();\n  const encoded = encoder.encode(body);\n  if (encoded.byteLength <= ERROR_RESPONSE_BODY_MAX_BYTES) {\n    return body;\n  }\n\n  // Adjust `cut` so the slice lands on a UTF-8 codepoint boundary.\n  // UTF-8 byte classes:\n  //   0xxxxxxx — ASCII (1-byte codepoint).\n  //   10xxxxxx — continuation byte (0x80–0xBF).\n  //   110xxxxx — leading byte of a 2-byte codepoint.\n  //   1110xxxx — leading byte of a 3-byte codepoint.\n  //   11110xxx — leading byte of a 4-byte codepoint.\n  // Strategy: walk backward from `cut - 1` past continuation bytes\n  // until we find a leading or ASCII byte; that is the start of the\n  // codepoint that may straddle the boundary. If the codepoint's\n  // expected length runs past `cut`, drop it (set `cut` to the\n  // leading byte's index). Otherwise leave `cut` alone — the\n  // codepoint is fully contained and the slice is clean.\n  let cut = ERROR_RESPONSE_BODY_MAX_BYTES;\n  let scan = cut - 1;\n  while (scan >= 0 && (encoded[scan] & 0xc0) === 0x80) {\n    scan -= 1;\n  }\n  if (scan >= 0) {\n    const leading = encoded[scan];\n    let expected = 1;\n    if ((leading & 0x80) === 0) {\n      expected = 1; // ASCII\n    } else if ((leading & 0xe0) === 0xc0) {\n      expected = 2;\n    } else if ((leading & 0xf0) === 0xe0) {\n      expected = 3;\n    } else if ((leading & 0xf8) === 0xf0) {\n      expected = 4;\n    }\n    if (scan + expected > cut) {\n      // Codepoint runs past the cut — drop it entirely.\n      cut = scan;\n    }\n  }\n\n  const decoder = new TextDecoder(\"utf-8\", { fatal: false });\n  const sliced = encoded.subarray(0, cut);\n  const decoded = decoder.decode(sliced);\n\n  return decoded + ERROR_RESPONSE_BODY_TRUNCATION_MARKER;\n}\n\n/**\n * End-to-end pipeline: sanitize, then truncate. Returns the string ready\n * to attach as `glasstrace.error.response_body`, or `null` if the body\n * is unsuitable for capture (empty or whitespace-only after redaction).\n *\n * The empty-after-sanitize guard is conservative: a body that consists\n * entirely of a redacted secret yields `[REDACTED]` and IS still\n * captured (it tells the operator that *something* error-shaped came\n * back). Only literal empty string / whitespace returns `null`.\n */\nexport function prepareErrorResponseBody(body: string): string | null {\n  if (body.length === 0) return null;\n  if (body.trim().length === 0) return null;\n  const sanitized = sanitizeErrorResponseBody(body);\n  return truncateErrorResponseBody(sanitized);\n}\n","/**\n * Helpers for the `glasstrace.error.stack` span attribute.\n *\n * The exporter promotes an OTel `exception.stacktrace` (read from a span\n * event or, as a fallback, a span attribute) to the public\n * `glasstrace.error.stack` attribute. Before promotion the stack is:\n *\n *   1. Sanitized to redact absolute local paths, URL query strings and\n *      fragments, and well-known credential patterns. The same\n *      credential redactor as `error-response-body.ts` is reused so a\n *      stack-trace frame echoing a `Bearer …` header is treated\n *      identically to a response-body fragment carrying the same value.\n *   2. Truncated to a hard byte budget. Sanitization runs BEFORE\n *      truncation so a credential straddling the truncation boundary is\n *      still removed from the visible portion. Truncation respects\n *      UTF-8 codepoint boundaries via the same `TextEncoder` /\n *      `TextDecoder` walk used by `error-response-body.ts`.\n *\n * Two sibling boolean attributes accompany every emitted stack:\n *\n *   - `glasstrace.error.stack.truncated` — `true` iff truncation fired.\n *   - `glasstrace.error.stack.redacted` — `true` iff at least one\n *     sanitization rule (path normalization, URL query stripping, or\n *     credential redaction) produced a change.\n *\n * Design constraints (mirrored from `error-response-body.ts`):\n *   - Zero new runtime dependencies. Inline regex only.\n *   - Pure functions: easy to unit-test without span mocks.\n *   - Conservative: when in doubt, redact. False positives that\n *     replace an unusual abs path with a normalized form are\n *     acceptable; false negatives that leak a `/Users/<name>/` home\n *     prefix or an unredacted Bearer token are not.\n *\n * Out of scope for v1:\n *   - Parsed `StackFrameSummary[]` structured attribute output. The\n *     v1 contract is bounded `exception.stacktrace` input for the\n *     product-side stack-summary parser.\n *   - Source-map resolution to original source paths. The SDK already\n *     emits the top user-relevant frame's source via\n *     `glasstrace.source.{file,line,mapped}` on `captureError()` span\n *     events; that path is unchanged.\n *\n * @drift-check ../../glasstrace-product/docs/component-designs/agent-evidence-sdk-attribute-contract.md §5.5 (Error Evidence)\n */\n\nimport { sanitizeErrorResponseBody } from \"./error-response-body.js\";\n\n/**\n * Maximum byte length for the captured stack.\n *\n * Set to 8192 bytes. Stacks are longer than typical error-response\n * bodies (each V8 frame is ~80–200 bytes; a 30-frame stack is\n * comfortably under 8 KB while a 100-frame deep async stack runs\n * past). Most agent-facing consumers care about the top 10–30 frames;\n * truncation past the budget is acceptable when accompanied by the\n * `truncated: true` sibling attribute so consumers do not interpret\n * the absence of a frame as proof it was not on the stack.\n */\nexport const ERROR_STACK_MAX_BYTES = 8192;\n\n/**\n * Marker appended when the stack was truncated to fit the byte budget.\n * Distinct token from `error-response-body.ts`'s marker so consumers\n * can tell at a glance which evidence class produced the partial.\n */\nexport const ERROR_STACK_TRUNCATION_MARKER = \"...[stack truncated]\";\n\n/**\n * Replacement token written in place of any normalized abs path.\n */\nconst PATH_REDACTED = \"<path>\";\n\n/**\n * Path-prefix markers we keep when stripping abs paths. The first\n * occurrence of any marker (matched as `/<marker>/`) anchors the\n * relative form; everything before it is replaced with the\n * {@link PATH_REDACTED} sentinel. Order matters: the LAST marker we\n * see in left-to-right scan would normally win, but we anchor to the\n * RIGHTMOST occurrence so a path like\n * `/Users/erik/proj/node_modules/.pnpm/.../node_modules/foo/index.js`\n * keeps both `node_modules` segments — which is the structural truth\n * (the inner one is where the actual frame lives).\n *\n * Additions / removals here change agent-facing stack readability;\n * keep this set conservative and in sync with `tests/unit/sdk/error-stack.test.ts`.\n */\nconst PATH_KEEP_MARKERS: readonly string[] = [\n  \"node_modules\",\n  \".next\",\n  \".glasstrace\",\n  \"src\",\n  \"dist\",\n  \"build\",\n  \"lib\",\n  \"app\",\n  \"pages\",\n];\n\n/**\n * Single-frame path candidate. Captures the entire path token plus\n * the trailing `:line[:col]` if present. The path body is permissive\n * (anything but whitespace, paren, and angle brackets) so we catch:\n *\n *   - POSIX abs:    `/Users/erik/proj/src/file.ts:10:5`\n *   - Windows abs:  `C:\\Users\\erik\\proj\\src\\file.ts:10:5`\n *   - file:// URI:  `file:///Users/erik/proj/src/file.ts:10:5`\n *   - webpack:      `webpack-internal:///./src/file.ts:10:5`\n *   - node:         `node:internal/process/main_thread_only:75:7`\n *\n * The leading anchors `(?<=^|[\\s(])` ensure we only match path tokens\n * preceded by whitespace, line start, or `(` (the V8 frame open paren).\n * That keeps us from over-matching inside arbitrary text that happens\n * to contain a path-shaped substring.\n */\nconst PATH_TOKEN_RE = /(?<=^|[\\s(])(\\/[^\\s()<>]+|[A-Za-z]:\\\\[^\\s()<>]+|file:\\/\\/\\/[^\\s()<>]+|webpack-internal:\\/\\/[^\\s()<>]+|node:[^\\s()<>]+)/g;\n\n/**\n * URL with query/fragment. Strips `?...` and `#...` from URLs that\n * appear inside stack frames (rare, but happens for source maps\n * served behind tokens or Next.js route URLs echoed in errors).\n *\n * The capture group keeps the URL-prefix-up-to-`?-or-#` so a\n * replacement substitutes only the suffix.\n */\nconst URL_QUERY_FRAGMENT_RE = /(\\bhttps?:\\/\\/[^\\s?#()<>]+)([?#][^\\s()<>]*)/g;\n\n/**\n * Normalize a single path token. Returns the original if no\n * normalization was needed; otherwise returns the rewritten form.\n * The boolean second tuple element tells the caller whether a change\n * happened (for the `redacted: true` sibling attribute).\n */\nfunction normalizePathToken(token: string): { token: string; changed: boolean } {\n  // file:// URI prefix: drop the scheme so the underlying abs path\n  // can be processed by the same logic.\n  let work = token;\n  if (work.startsWith(\"file:///\")) {\n    work = work.slice(\"file://\".length);\n  }\n\n  // webpack-internal and node: schemes are already non-abs and\n  // non-secret; pass through unchanged.\n  if (work.startsWith(\"webpack-internal:\") || work.startsWith(\"node:\")) {\n    return { token, changed: false };\n  }\n\n  // Detect abs (POSIX or Windows). Anything else is already relative\n  // or non-path-shaped; leave alone.\n  const isPosixAbs = work.startsWith(\"/\");\n  const isWinAbs = /^[A-Za-z]:\\\\/.test(work);\n  if (!isPosixAbs && !isWinAbs) {\n    return { token, changed: false };\n  }\n\n  // Find the rightmost `/<marker>/` anchor. We walk markers in\n  // priority order but pick the highest start-index across all\n  // matches so an inner package's frame (deepest under\n  // node_modules) wins.\n  const sep = isWinAbs ? \"\\\\\" : \"/\";\n  // Walk markers in priority order; the FIRST marker with a match\n  // wins. Within that marker, anchor at its rightmost occurrence so\n  // deep paths like\n  // `node_modules/.pnpm/.../node_modules/@trpc/server/dist/...`\n  // keep the inner package's `node_modules/` (the structural truth\n  // for where the frame lives) rather than getting truncated to\n  // some lower-priority marker that happens to appear further right\n  // (e.g. `/dist/`).\n  let bestIdx = -1;\n  for (const marker of PATH_KEEP_MARKERS) {\n    const needle = `${sep}${marker}${sep}`;\n    const idx = work.lastIndexOf(needle);\n    if (idx >= 0) {\n      bestIdx = idx;\n      break;\n    }\n  }\n\n  if (bestIdx >= 0) {\n    // Keep from `<marker>/...` onward, prefixed with the redaction\n    // sentinel so consumers can spot that a prefix was elided.\n    const kept = work.slice(bestIdx + sep.length); // starts with marker\n    const rebuilt = `${PATH_REDACTED}/${kept.replace(/\\\\/g, \"/\")}`;\n    return { token: rebuilt, changed: true };\n  }\n\n  // No known marker — fall back to basename only. The colon-prefixed\n  // tail (e.g. `:10:5`) is preserved because it is not part of the\n  // path; PATH_TOKEN_RE matches the whole `path:line:col`, and we\n  // split here on the LAST occurrence of `:` that's followed by a\n  // digit to find the path body.\n  const colonLineRe = /:\\d+(?::\\d+)?$/;\n  const lineMatch = colonLineRe.exec(work);\n  const pathBody = lineMatch ? work.slice(0, lineMatch.index) : work;\n  const lineSuffix = lineMatch ? work.slice(lineMatch.index) : \"\";\n  const lastSep = Math.max(pathBody.lastIndexOf(\"/\"), pathBody.lastIndexOf(\"\\\\\"));\n  const basename = lastSep >= 0 ? pathBody.slice(lastSep + 1) : pathBody;\n  const rebuilt = `${PATH_REDACTED}/${basename}${lineSuffix}`;\n  return { token: rebuilt, changed: true };\n}\n\n/**\n * Sanitizes the stack: normalizes abs paths, strips URL query/fragments,\n * and applies the credential-redaction patterns from\n * `error-response-body.ts`.\n *\n * Returns the sanitized string and a boolean `redacted` indicating\n * whether at least one rule produced a change. Reference-equality is\n * not preserved when no change is made (the path-token replace runs\n * unconditionally and may reconstruct the same string), so the\n * `redacted` flag — not a `===` check — is the authoritative signal.\n */\nexport function sanitizeStack(stack: string): { stack: string; redacted: boolean } {\n  let changed = false;\n\n  // Step 1: normalize abs paths. The replace callback inspects each\n  // token and reports back through `changed`.\n  const pathNormalized = stack.replace(PATH_TOKEN_RE, (token) => {\n    const out = normalizePathToken(token);\n    if (out.changed) changed = true;\n    return out.token;\n  });\n\n  // Step 2: strip URL query strings + fragments.\n  const urlStripped = pathNormalized.replace(URL_QUERY_FRAGMENT_RE, (match, prefix: string) => {\n    if (match !== prefix) changed = true;\n    return prefix;\n  });\n\n  // Step 3: credential redaction (reuse the response-body redactor;\n  // its rule set covers Bearer, JWT, gt_dev/anon keys, AWS access\n  // keys, and key=value secrets). The redactor returns a new string\n  // when a match fires but does not signal change, so we compare\n  // refs to detect.\n  const credentialRedacted = sanitizeErrorResponseBody(urlStripped);\n  if (credentialRedacted !== urlStripped) changed = true;\n\n  return { stack: credentialRedacted, redacted: changed };\n}\n\n/**\n * Truncates `stack` to at most {@link ERROR_STACK_MAX_BYTES} bytes\n * when encoded as UTF-8. Returns `{ stack, truncated }` so the caller\n * can set the sibling `glasstrace.error.stack.truncated` attribute.\n *\n * The truncation algorithm is the same UTF-8-codepoint-boundary walk\n * used by `truncateErrorResponseBody`. Marker is appended in\n * JS-string form and is NOT counted toward the byte budget so\n * consumers always see a clear \"partial\" signal at the worst case.\n */\nexport function truncateStack(stack: string): { stack: string; truncated: boolean } {\n  const encoder = new TextEncoder();\n  const encoded = encoder.encode(stack);\n  if (encoded.byteLength <= ERROR_STACK_MAX_BYTES) {\n    return { stack, truncated: false };\n  }\n\n  let cut = ERROR_STACK_MAX_BYTES;\n  let scan = cut - 1;\n  while (scan >= 0 && (encoded[scan] & 0xc0) === 0x80) {\n    scan -= 1;\n  }\n  if (scan >= 0) {\n    const leading = encoded[scan];\n    let expected = 1;\n    if ((leading & 0x80) === 0) {\n      expected = 1;\n    } else if ((leading & 0xe0) === 0xc0) {\n      expected = 2;\n    } else if ((leading & 0xf0) === 0xe0) {\n      expected = 3;\n    } else if ((leading & 0xf8) === 0xf0) {\n      expected = 4;\n    }\n    if (scan + expected > cut) {\n      cut = scan;\n    }\n  }\n\n  const decoder = new TextDecoder(\"utf-8\", { fatal: false });\n  const sliced = encoded.subarray(0, cut);\n  const decoded = decoder.decode(sliced);\n\n  return { stack: decoded + ERROR_STACK_TRUNCATION_MARKER, truncated: true };\n}\n\n/**\n * End-to-end pipeline: sanitize, then truncate. Returns the\n * structured result ready for emission as the\n * `glasstrace.error.stack` family of attributes, or `null` if the\n * stack is unsuitable for capture (empty or whitespace-only after\n * the input check).\n *\n * Conservative empty-input guard: a stack that consists entirely of\n * a redacted secret yields `[REDACTED]` and IS still emitted (it\n * tells the operator that *something* stack-shaped came back). Only\n * literal empty / whitespace input returns `null`.\n */\nexport function prepareStack(stack: string): {\n  stack: string;\n  truncated: boolean;\n  redacted: boolean;\n} | null {\n  if (stack.length === 0) return null;\n  if (stack.trim().length === 0) return null;\n  const sanitized = sanitizeStack(stack);\n  const truncated = truncateStack(sanitized.stack);\n  return {\n    stack: truncated.stack,\n    truncated: truncated.truncated,\n    redacted: sanitized.redacted,\n  };\n}\n","/**\n * Export-Path Circuit Breaker\n *\n * Three-state machine — CLOSED → OPEN → HALF_OPEN — that bounds wasted\n * traffic from the OTLP export path when the backend is rejecting\n * batches (invalid credentials, server errors, network failures, rate\n * limits). The breaker counts consecutive failures, trips OPEN when it\n * crosses the configured threshold, drops spans during the open window\n * (incrementing the existing `recordSpansDropped` health surface),\n * permits a single probe batch after the backoff timer expires, and\n * either closes (probe succeeds) or doubles the timer back to OPEN\n * (probe fails). Credential rotation resets the breaker to CLOSED with\n * a generation counter that invalidates any in-flight probe.\n *\n * **Pure logic, no I/O:** the module owns no sockets, no files, no\n * direct logger access. Lifecycle event emission and health-collector\n * recording are wired in via {@link createExportCircuitBreaker}'s\n * `events` and `recordDropped` callbacks so the module is unit-\n * testable with mock collaborators and zero side effects per test.\n *\n * **Design memo:** glasstrace-product\n * `docs/task-briefs/SDK-circuit-breaker-design.md` (private). All\n * eight decisions in that memo are encoded as constants below; the\n * memo is the source of truth for the numbers (T₀ = 30s, threshold = 5,\n * doubling = 2×, T_MAX = 30 min, etc.).\n */\n\n/**\n * Closed enum of failure categories that can trip the breaker. Surfaced\n * verbatim in the `otel:circuit_opened` lifecycle payload and on\n * {@link RuntimeStateLastError.exportCircuitCategory}; CLI consumers\n * may render the value, so renaming or removing a member is a public-\n * contract change.\n */\nexport type ExportCircuitFailureCategory =\n  | \"auth\"          // 401, 403\n  | \"client_error\"  // 4xx other than 401/403/429\n  | \"rate_limit\"    // 429 surfaced by export layer\n  | \"server_error\"  // 5xx\n  | \"network\";      // socket / DNS / TLS / timeout\n\n/** Three-state machine per the Wave 15C design memo. */\nexport type ExportCircuitState = \"CLOSED\" | \"OPEN\" | \"HALF_OPEN\";\n\n// ---------------------------------------------------------------------------\n// Per-trace boundary-masked error tracking\n//\n// The descendant boundary-masked-error detection in `enriching-exporter.ts`\n// needs to correlate an exception recorded on a transitive child span with\n// the HTTP server span that rendered it — and the two can arrive in\n// different export batches. The breaker singleton hosts this per-trace\n// state so it survives multiple `createGlasstraceSpanProcessor()` calls in\n// one process and shares the singleton's key-rotation lifecycle.\n//\n// Memory is bounded three ways: per-trace caps on the recorded parent links\n// (`MAX_LINKS_PER_TRACE`) and the recorded exception entries\n// (`MAX_EXCEPTIONS_PER_TRACE`), plus a process-wide cap on tracked traces\n// (`MAX_TRACKED_TRACES`) with TTL-then-LRU eviction. Every bound degrades\n// to a documented detection miss (the parent stays at its original status),\n// never a false promotion: a dropped link, dropped exception entry, or evicted\n// entry can only *prevent* a promotion, never fabricate one.\n// ---------------------------------------------------------------------------\n\n/**\n * One exception-bearing span recorded in a trace, used to confirm a\n * candidate is a transitive descendant of an HTTP server span and to pick\n * the deterministic earliest-exception span.\n */\nexport interface ExceptionLineageEntry {\n  /** The descendant span that recorded the exception. */\n  spanId: string;\n  /** Parent span id for the ancestor walk; undefined for a trace root. */\n  parentSpanId?: string;\n  /** hrTime → ms; used for the deterministic earliest-exception tie-break. */\n  startTimeMs: number;\n  /** First 256 chars of the exception message, pre-truncated at write time. */\n  message?: string;\n  /** The exception type string, when present. */\n  type?: string;\n  /** The descendant's `next.span_type` attribute, when present (render-route detection). */\n  nextSpanType?: string;\n  /**\n   * True when the descendant span carried `glasstrace.error.expected === true`.\n   * An expected boundary is never promotable — the escape hatch must be honored\n   * on the exception-bearer itself, not only on the HTTP server span.\n   */\n  expected?: boolean;\n}\n\n/**\n * Aggregated per-trace state used by descendant boundary-masked detection.\n */\nexport interface TraceErrorState {\n  /**\n   * All exception-bearing spans in this trace, keyed by spanId for O(1)\n   * lineage lookup. Capped at {@link MAX_EXCEPTIONS_PER_TRACE}; overflow drops\n   * further entries and sets {@link lineageOverflow} (a documented miss).\n   */\n  lineageBySpanId: Map<string, ExceptionLineageEntry>;\n  /**\n   * parentSpanId for EVERY span seen in this trace (error AND non-error),\n   * keyed by spanId, so the ancestor walk can bridge a non-error\n   * intermediate span that ended in an earlier batch. Capped at\n   * {@link MAX_LINKS_PER_TRACE}.\n   */\n  parentLinks: Map<string, string | undefined>;\n  /** spanId of the earliest exception span (smallest startTimeMs; tie-break smallest spanId). */\n  firstExceptionSpanId?: string;\n  /** Start time (ms) of the earliest exception span — the tie-break key. */\n  firstExceptionStartMs?: number;\n  /** Message of the earliest exception span, pre-truncated to 256 chars at write time. */\n  firstExceptionMessage?: string;\n  /** Whether the per-trace parentLinks cap has been hit (a documented miss). */\n  parentLinkOverflow: boolean;\n  /** Whether the per-trace lineage cap has been hit (a documented miss). */\n  lineageOverflow: boolean;\n  createdAtMs: number;\n  lastAccessedAtMs: number;\n}\n\n/** Counters exposed for observability and tests. */\nexport interface TraceErrorCounters {\n  evictions: number;\n  keyValidationFailures: number;\n  parentLinkOverflow: number;\n  lineageOverflow: number;\n}\n\n/**\n * Per-trace boundary-masked error store hosted on the breaker singleton.\n * Pure in-memory logic (no I/O); shares the singleton's lifecycle so a\n * credential rotation drops stale `${traceId}#${sessionId}` entries.\n */\nexport interface TraceErrorStore {\n  /** Records a span's parent link (every span — error and non-error). */\n  recordParentLink(key: string, spanId: string, parentSpanId: string | undefined, nowMs: number): void;\n  /** Records an exception-bearing span and updates the earliest-exception bookkeeping. */\n  recordException(key: string, entry: ExceptionLineageEntry, nowMs: number): void;\n  /** Reads a trace's state, touching its LRU timestamp. Returns undefined if absent. */\n  consult(key: string, nowMs: number): TraceErrorState | undefined;\n  /** Empties the whole store (key rotation / test reset). */\n  clear(): void;\n  /** Current number of tracked traces. */\n  size(): number;\n  /** Reads (without touching LRU) for tests/observability. */\n  peek(key: string): TraceErrorState | undefined;\n  /** Increments the key-validation-failure counter. */\n  recordKeyValidationFailure(): void;\n  /** Snapshot of the counters. */\n  getCounters(): TraceErrorCounters;\n}\n\n/**\n * Maximum number of `parentLinks` entries kept per trace. Bounds worst-case\n * per-trace link memory; covers normal page-route depths\n * (SERVER → route/component → ORM exception is depth 3). Overflow drops\n * further links and increments the `parentLinkOverflow` counter — a dropped\n * link can only suppress a promotion, never cause one.\n */\nexport const MAX_LINKS_PER_TRACE = 512;\n\n/**\n * Maximum number of exception-lineage entries kept per trace. Bounds worst-case\n * per-trace exception memory independently of {@link MAX_LINKS_PER_TRACE}\n * (a trace can record far more parent links than exceptions). Overflow drops\n * further exception entries and increments the `exceptionOverflow` counter\n * while preserving the earliest-exception bookkeeping — a dropped entry can\n * only suppress a promotion, never cause one.\n */\nexport const MAX_EXCEPTIONS_PER_TRACE = 256;\n\n/**\n * Maximum number of distinct traces tracked at once. Sized to the concurrent\n * in-flight trace cardinality. On overflow the store evicts by TTL first,\n * then LRU (tie-broken by oldest-inserted) — both deterministic.\n */\nexport const MAX_TRACKED_TRACES = 1024;\n\n/**\n * How long (ms) a trace's error state is retained before it ages out. Generous\n * enough that a normal late descendant is still present when the parent server\n * span is consulted, while error-only traces with no server span age out.\n */\nexport const TRACE_ERROR_TTL_MS = 300_000;\n\n/** Message-storage cap shared with the lifecycle emit boundary. */\nconst MAX_EXCEPTION_MESSAGE_CHARS = 256;\n\nfunction createTraceErrorStore(): TraceErrorStore {\n  const traces = new Map<string, TraceErrorState>();\n  let evictions = 0;\n  let keyValidationFailures = 0;\n  let parentLinkOverflow = 0;\n  let lineageOverflow = 0;\n\n  function isStale(state: TraceErrorState, nowMs: number): boolean {\n    return nowMs - state.createdAtMs > TRACE_ERROR_TTL_MS;\n  }\n\n  function makeFreshState(nowMs: number): TraceErrorState {\n    return {\n      lineageBySpanId: new Map(),\n      parentLinks: new Map(),\n      parentLinkOverflow: false,\n      lineageOverflow: false,\n      createdAtMs: nowMs,\n      lastAccessedAtMs: nowMs,\n    };\n  }\n\n  function expireAndEvict(nowMs: number): void {\n    // TTL sweep first: drop entries older than the TTL regardless of size.\n    for (const [key, state] of traces) {\n      if (isStale(state, nowMs)) {\n        traces.delete(key);\n        evictions += 1;\n      }\n    }\n    // LRU eviction if still over the cap: evict least-recently-accessed,\n    // tie-broken by oldest-inserted (smallest createdAtMs) so the order is\n    // deterministic and tests cannot flake.\n    while (traces.size > MAX_TRACKED_TRACES) {\n      let victimKey: string | undefined;\n      let victim: TraceErrorState | undefined;\n      for (const [key, state] of traces) {\n        if (\n          victim === undefined ||\n          state.lastAccessedAtMs < victim.lastAccessedAtMs ||\n          (state.lastAccessedAtMs === victim.lastAccessedAtMs &&\n            state.createdAtMs < victim.createdAtMs)\n        ) {\n          victim = state;\n          victimKey = key;\n        }\n      }\n      if (victimKey === undefined) break;\n      traces.delete(victimKey);\n      evictions += 1;\n    }\n  }\n\n  function getOrCreate(key: string, nowMs: number): TraceErrorState {\n    const existing = traces.get(key);\n    if (existing !== undefined && !isStale(existing, nowMs)) {\n      existing.lastAccessedAtMs = nowMs;\n      return existing;\n    }\n    // Either no entry, or the existing one has aged past the TTL but was not\n    // yet swept (TTL eviction runs lazily, on new-key inserts). Reusing the\n    // same `${traceId}#${sessionId}` after the TTL — a traceId collision, a\n    // long-delayed retry, or a deterministic fixture — must NOT resurrect a\n    // stale descendant exception to promote a fresh server span (a false 500).\n    // Evict the aged entry and start fresh so old lineage can only be dropped,\n    // never reused (fail-open).\n    if (existing !== undefined) {\n      evictions += 1;\n    }\n    const state = makeFreshState(nowMs);\n    traces.set(key, state);\n    expireAndEvict(nowMs);\n    // expireAndEvict cannot drop the entry just inserted (createdAtMs === nowMs\n    // so it is not stale, and it is the most-recently-accessed so never the LRU\n    // victim). Re-read to stay correct if that invariant ever changes.\n    return traces.get(key) ?? state;\n  }\n\n  return {\n    recordParentLink(key, spanId, parentSpanId, nowMs): void {\n      const state = getOrCreate(key, nowMs);\n      if (state.parentLinks.has(spanId)) return;\n      if (state.parentLinks.size >= MAX_LINKS_PER_TRACE) {\n        if (!state.parentLinkOverflow) {\n          state.parentLinkOverflow = true;\n        }\n        parentLinkOverflow += 1;\n        return;\n      }\n      state.parentLinks.set(spanId, parentSpanId);\n    },\n\n    recordException(key, entry, nowMs): void {\n      const state = getOrCreate(key, nowMs);\n      const stored: ExceptionLineageEntry = {\n        ...entry,\n        message:\n          entry.message !== undefined\n            ? entry.message.slice(0, MAX_EXCEPTION_MESSAGE_CHARS)\n            : undefined,\n      };\n      // Per-trace lineage cap: a new spanId past the cap is dropped (and the\n      // overflow counter bumped) rather than admitted. Re-recording an already\n      // tracked spanId always overwrites in place — it never counts against the\n      // cap. A dropped entry can only suppress a promotion, never cause one.\n      if (\n        !state.lineageBySpanId.has(entry.spanId) &&\n        state.lineageBySpanId.size >= MAX_EXCEPTIONS_PER_TRACE\n      ) {\n        if (!state.lineageOverflow) state.lineageOverflow = true;\n        lineageOverflow += 1;\n        return;\n      }\n      state.lineageBySpanId.set(entry.spanId, stored);\n      // Also record its parent link so the walk can traverse it.\n      if (!state.parentLinks.has(entry.spanId)) {\n        if (state.parentLinks.size < MAX_LINKS_PER_TRACE) {\n          state.parentLinks.set(entry.spanId, entry.parentSpanId);\n        } else {\n          if (!state.parentLinkOverflow) state.parentLinkOverflow = true;\n          parentLinkOverflow += 1;\n        }\n      }\n      // Update earliest-exception bookkeeping (smallest startTimeMs, tie-break\n      // smallest spanId lexicographically) — deterministic across runs.\n      const isEarlier =\n        state.firstExceptionStartMs === undefined ||\n        entry.startTimeMs < state.firstExceptionStartMs ||\n        (entry.startTimeMs === state.firstExceptionStartMs &&\n          (state.firstExceptionSpanId === undefined ||\n            entry.spanId < state.firstExceptionSpanId));\n      if (isEarlier) {\n        state.firstExceptionSpanId = entry.spanId;\n        state.firstExceptionStartMs = entry.startTimeMs;\n        state.firstExceptionMessage = stored.message;\n      }\n    },\n\n    consult(key, nowMs): TraceErrorState | undefined {\n      const state = traces.get(key);\n      if (state === undefined) return undefined;\n      // Evict-on-access: an entry aged past the TTL but not yet swept must not\n      // promote a fresh server span from stale lineage (a false 500). Drop it\n      // and report no lineage (fail-open) rather than returning stale state.\n      if (isStale(state, nowMs)) {\n        traces.delete(key);\n        evictions += 1;\n        return undefined;\n      }\n      state.lastAccessedAtMs = nowMs;\n      return state;\n    },\n\n    clear(): void {\n      traces.clear();\n    },\n\n    size(): number {\n      return traces.size;\n    },\n\n    peek(key): TraceErrorState | undefined {\n      return traces.get(key);\n    },\n\n    recordKeyValidationFailure(): void {\n      keyValidationFailures += 1;\n    },\n\n    getCounters(): TraceErrorCounters {\n      return { evictions, keyValidationFailures, parentLinkOverflow, lineageOverflow };\n    },\n  };\n}\n\n/**\n * Initial backoff timer applied on the first OPEN transition. Doubled\n * on each successive HALF_OPEN→OPEN transition until {@link MAX_BACKOFF_MS}.\n *\n * @drift-check ../glasstrace-product/docs/task-briefs/SDK-circuit-breaker-design.md §Decision 3 (T₀ = 30s)\n */\nexport const INITIAL_BACKOFF_MS = 30_000;\n\n/**\n * Backoff doubling factor between successive OPEN states. Pure\n * exponential — no jitter (single-process probe rate poses no\n * thundering-herd risk; jitter can be added if observability shows\n * synchronized retries from many SDK instances).\n *\n * @drift-check ../glasstrace-product/docs/task-briefs/SDK-circuit-breaker-design.md §Decision 3 (factor = 2.0)\n */\nexport const BACKOFF_FACTOR = 2;\n\n/**\n * Maximum backoff timer; capped after six doublings\n * (30s → 60s → 120s → 240s → 480s → 960s → 1800s). After this point a\n * persistently broken key produces one probe per 30 minutes.\n *\n * @drift-check ../glasstrace-product/docs/task-briefs/SDK-circuit-breaker-design.md §Decision 3 (T_MAX = 30 min)\n */\nexport const MAX_BACKOFF_MS = 30 * 60 * 1000; // 1_800_000\n\n/**\n * Number of consecutive non-success export results required to trip\n * the breaker from CLOSED to OPEN. Successive successes reset the\n * counter; no sliding window — see memo §Decision 2 for the rationale.\n *\n * @drift-check ../glasstrace-product/docs/task-briefs/SDK-circuit-breaker-design.md §Decision 2 (threshold = 5)\n */\nexport const FAILURE_THRESHOLD = 5;\n\n/**\n * Lifecycle-event payload shapes the breaker hands back to the caller\n * via the `events` callback. Each shape mirrors the corresponding\n * entry in `SdkLifecycleEvents` exactly (see `lifecycle.ts`). The\n * indirection keeps the breaker module free of a direct lifecycle\n * import so it remains pure-logic.\n */\nexport interface ExportCircuitOpenedPayload {\n  category: ExportCircuitFailureCategory;\n  message: string;\n  timestamp: string;\n  consecutiveFailures: number;\n  nextProbeMs: number;\n}\n\nexport interface ExportCircuitHalfOpenPayload {\n  timestamp: string;\n  previousTimerMs: number;\n}\n\nexport interface ExportCircuitClosedPayload {\n  timestamp: string;\n  outageDurationMs: number;\n}\n\n/** Sink for the breaker's three lifecycle events. */\nexport interface ExportCircuitEventSink {\n  emitOpened(payload: ExportCircuitOpenedPayload): void;\n  emitHalfOpen(payload: ExportCircuitHalfOpenPayload): void;\n  emitClosed(payload: ExportCircuitClosedPayload): void;\n}\n\n/** Optional FSM-coupling hooks invoked on circuit transitions. */\nexport interface ExportCircuitFsmHooks {\n  /**\n   * Called when the breaker trips OPEN. Implementations should set\n   * `CoreState.ACTIVE_DEGRADED` (no-op when the SDK is already\n   * degraded by another source).\n   */\n  onCircuitOpened(): void;\n  /**\n   * Called when the breaker recovers to CLOSED. Implementations\n   * should re-evaluate whether the SDK can return to `CoreState.ACTIVE`\n   * without clobbering an unrelated degradation source (e.g.,\n   * `OtelState.COEXISTENCE_FAILED`).\n   */\n  onCircuitClosed(): void;\n}\n\n/** Failure shape passed into {@link ExportCircuitBreaker.recordFailure}. */\nexport interface ExportFailureInfo {\n  /** HTTP status code if the underlying transport surfaced one. */\n  status?: number;\n  /**\n   * Free-form error object from the export pipeline. Inspected only\n   * for shape signals (status property, error name) that drive\n   * category classification.\n   */\n  error?: unknown;\n}\n\n/** Options accepted by {@link createExportCircuitBreaker}. */\nexport interface ExportCircuitBreakerOptions {\n  /** Lifecycle event sink. Required. */\n  events: ExportCircuitEventSink;\n  /**\n   * Health-collector hook. Called every time spans are dropped while\n   * the breaker is OPEN. Required so the existing health surface\n   * (`recordSpansDropped`) reflects circuit-induced drops without the\n   * module taking a direct import on the collector.\n   */\n  recordDropped: (count: number) => void;\n  /** Optional FSM-coupling hooks. */\n  fsm?: ExportCircuitFsmHooks;\n  /**\n   * Time source override for tests. Defaults to {@link Date.now}.\n   */\n  now?: () => number;\n  /**\n   * Timer factory override for tests. Defaults to `setTimeout`.\n   * Returns a handle accepted by the matching {@link ExportCircuitBreakerOptions.clearTimer}.\n   */\n  setTimer?: (fn: () => void, delayMs: number) => unknown;\n  /** Timer disposal counterpart to {@link ExportCircuitBreakerOptions.setTimer}. */\n  clearTimer?: (handle: unknown) => void;\n}\n\n/**\n * The public-facing breaker handle. Returned by\n * {@link createExportCircuitBreaker}. Methods are documented at the\n * factory call site.\n */\nexport interface ExportCircuitBreaker {\n  /**\n   * Returns true when the breaker permits a real export attempt.\n   * `false` when OPEN; the caller MUST drop the spans (call\n   * {@link onSpansDropped}) and complete the BSP callback with a\n   * success result so the BSP does not retry.\n   */\n  shouldExport(): boolean;\n  /** Records a successful export result. Resets the failure counter to zero. */\n  recordSuccess(): void;\n  /** Records a failed export result. Trips OPEN on the Nth consecutive failure. */\n  recordFailure(info: ExportFailureInfo): void;\n  /**\n   * Counts dropped spans while OPEN. Forwards to the\n   * {@link ExportCircuitBreakerOptions.recordDropped} hook the caller\n   * provided.\n   */\n  onSpansDropped(count: number): void;\n  /** Read-only snapshot of internal state for tests and observability. */\n  getState(): ExportCircuitState;\n  /**\n   * Resets the breaker to CLOSED, clears the failure counter and the\n   * pending probe timer, and emits `otel:circuit_closed` if the\n   * breaker was non-CLOSED. Bumps the generation counter so any\n   * in-flight HALF_OPEN probe completion handler is observed as\n   * stale and discarded. Also clears the per-trace boundary-masked\n   * error store — key rotation changes the session id, so stale\n   * `${traceId}#${sessionId}` entries must drop (an old-session\n   * descendant error must not promote a new-context server span).\n   *\n   * Called on credential rotation per memo §Decision 7.\n   */\n  resetForKeyRotation(): void;\n  /**\n   * The per-trace boundary-masked error store used by descendant\n   * status inference. Hosted on the breaker singleton so it survives\n   * multiple span-processor constructions in one process and shares\n   * this breaker's key-rotation lifecycle.\n   */\n  readonly traceErrors: TraceErrorStore;\n  /** Empties the per-trace boundary-masked error store. */\n  clearTraceErrors(): void;\n  /**\n   * Returns the current generation counter. The HALF_OPEN probe\n   * captures this value at probe-issue time and compares it on\n   * completion to detect a credential rotation that fired mid-probe\n   * (memo §Decision 7 edge case).\n   */\n  getGeneration(): number;\n}\n\n/**\n * Maps a transport result into a {@link ExportCircuitFailureCategory}\n * using the precedence in memo §Decision 1: explicit auth status (401,\n * 403) → rate limit (429) → server error (5xx) → other client error\n * (4xx) → network. Unknown shapes default to `\"network\"` since the\n * OTLP exporter surfaces transport-layer failures (DNS, TCP, TLS,\n * timeout) without a status code.\n */\nexport function classifyExportFailure(info: ExportFailureInfo): ExportCircuitFailureCategory {\n  const status = readStatus(info);\n  if (status === 401 || status === 403) return \"auth\";\n  if (status === 429) return \"rate_limit\";\n  if (typeof status === \"number\" && status >= 500 && status <= 599) return \"server_error\";\n  if (typeof status === \"number\" && status >= 400 && status <= 499) return \"client_error\";\n  return \"network\";\n}\n\n/**\n * Best-effort extraction of an HTTP status code from the failure\n * shape. The OTLP exporter wraps responses through several layers and\n * different OTel SDK versions surface the status via slightly\n * different property paths; we probe the well-known shapes without\n * dereferencing untrusted data.\n */\nfunction readStatus(info: ExportFailureInfo): number | undefined {\n  if (typeof info.status === \"number\") return info.status;\n  const err = info.error;\n  if (!err || typeof err !== \"object\") return undefined;\n  const record = err as Record<string, unknown>;\n\n  const direct = record.status;\n  if (typeof direct === \"number\") return direct;\n\n  // OTLP exporter surfaces status as a string in some Node versions\n  // (e.g. `\"401\"`); coerce defensively. The same coercion applies to\n  // the nested `response.status` path (Copilot review 2026-05-08;\n  // discovered by inspection; no in-the-wild repro yet but the cost\n  // of the extra check is negligible).\n  if (typeof direct === \"string\") {\n    const parsed = Number.parseInt(direct, 10);\n    if (Number.isFinite(parsed)) return parsed;\n  }\n\n  const nested = record.response;\n  if (nested && typeof nested === \"object\") {\n    const nestedStatus = (nested as Record<string, unknown>).status;\n    if (typeof nestedStatus === \"number\") return nestedStatus;\n    if (typeof nestedStatus === \"string\") {\n      const parsed = Number.parseInt(nestedStatus, 10);\n      if (Number.isFinite(parsed)) return parsed;\n    }\n  }\n\n  return undefined;\n}\n\n/**\n * Builds a fixed-template, PII-safe summary string for the\n * `otel:circuit_opened` payload. Mirrors the `otel:failed`\n * contract: no URLs, no headers, no payload bodies — only the closed\n * category enum and the consecutive-failure count.\n */\nfunction buildOpenedMessage(category: ExportCircuitFailureCategory, count: number): string {\n  return (\n    `[glasstrace] Export circuit opened after ${count} consecutive failures ` +\n    `(category: ${category}). Subsequent spans dropped until probe succeeds.`\n  );\n}\n\n/**\n * Module-level singleton for the production export pipeline. Lazily\n * constructed on first {@link getExportCircuitBreaker} call so module\n * loading remains side-effect-free (matching the broader SDK\n * convention).\n *\n * Tests must call {@link _resetExportCircuitBreakerForTesting} in\n * `afterEach` to drop the singleton; alternative tests that need an\n * isolated breaker can call {@link createExportCircuitBreaker}\n * directly with their own sinks.\n */\nlet _singleton: ExportCircuitBreaker | null = null;\n\n/**\n * Returns the production export circuit breaker singleton, lazily\n * constructing it on first call with the supplied options. Subsequent\n * calls return the same instance regardless of the options passed —\n * the production pipeline owns a single breaker for the OTLP export\n * path.\n */\nexport function getExportCircuitBreaker(\n  options: ExportCircuitBreakerOptions,\n): ExportCircuitBreaker {\n  if (_singleton === null) {\n    _singleton = createExportCircuitBreaker(options);\n  }\n  return _singleton;\n}\n\n/**\n * Returns the current singleton without constructing it. Used by call\n * sites that need to reset the breaker on credential rotation (e.g.,\n * `init-client.ts`'s `_setCurrentConfig`) — they should not construct\n * a breaker with stale options just to call `resetForKeyRotation()`.\n */\nexport function peekExportCircuitBreaker(): ExportCircuitBreaker | null {\n  return _singleton;\n}\n\n/**\n * Reset the production singleton. **Test-only.** Mirrors\n * `_resetConfigForTesting()` in init-client.ts.\n */\nexport function _resetExportCircuitBreakerForTesting(): void {\n  _singleton = null;\n}\n\n/**\n * Factory: builds a breaker bound to the provided sinks and hooks.\n * Returned object encapsulates all mutable state — the module itself\n * holds none, so multiple breakers can coexist (e.g., tests run in\n * parallel with isolated instances).\n */\nexport function createExportCircuitBreaker(\n  options: ExportCircuitBreakerOptions,\n): ExportCircuitBreaker {\n  const events = options.events;\n  const recordDropped = options.recordDropped;\n  const fsm = options.fsm;\n  const now = options.now ?? (() => Date.now());\n  // Default timer wiring uses globalThis.setTimeout. We unref() the\n  // returned handle when supported so a pending probe timer never\n  // prevents process exit (the breaker is best-effort recovery — if\n  // the host process is exiting, an outstanding probe must not keep\n  // the event loop alive).\n  const setTimer =\n    options.setTimer ??\n    ((fn: () => void, delayMs: number) => {\n      const handle = setTimeout(fn, delayMs);\n      if (typeof handle === \"object\" && handle && \"unref\" in handle) {\n        (handle as { unref: () => void }).unref();\n      }\n      return handle;\n    });\n  const clearTimer =\n    options.clearTimer ??\n    ((handle: unknown) => clearTimeout(handle as ReturnType<typeof setTimeout>));\n\n  // ---- Internal mutable state ----------------------------------------------\n  const traceErrors = createTraceErrorStore();\n  let state: ExportCircuitState = \"CLOSED\";\n  let consecutiveFailures = 0;\n  let currentBackoffMs = INITIAL_BACKOFF_MS;\n  let openedAtMs: number | null = null;\n  let pendingTimer: unknown = null;\n  /**\n   * HALF_OPEN single-probe gate. The contract is that exactly one\n   * batch is admitted while the circuit is HALF_OPEN; if multiple\n   * concurrent `export()` callers arrived in the same tick they would\n   * all see `state === \"HALF_OPEN\"` and `shouldExport()` would return\n   * `true` for each, sending parallel probes that race the recorded\n   * outcome (Codex P1 + Copilot, 2026-05-08). The flag is set when\n   * `shouldExport()` admits a HALF_OPEN probe and cleared by\n   * `recordSuccess()` / `recordFailure()` (or any state transition).\n   */\n  let halfOpenProbeInFlight = false;\n  /**\n   * Generation counter. Incremented on every credential rotation\n   * (memo §Decision 7) so a HALF_OPEN probe completion handler that\n   * captured the previous generation can detect the rotation and\n   * become a no-op.\n   */\n  let generation = 0;\n\n  // ---- Helpers -------------------------------------------------------------\n\n  function clearPendingTimer(): void {\n    if (pendingTimer !== null) {\n      clearTimer(pendingTimer);\n      pendingTimer = null;\n    }\n  }\n\n  function scheduleHalfOpen(delayMs: number): void {\n    clearPendingTimer();\n    pendingTimer = setTimer(() => {\n      pendingTimer = null;\n      // The breaker may have transitioned out of OPEN since the timer\n      // was scheduled (e.g., credential rotation). Only HALF_OPEN if\n      // we are still OPEN.\n      if (state !== \"OPEN\") return;\n      transitionToHalfOpen(delayMs);\n    }, delayMs);\n  }\n\n  function transitionToOpen(category: ExportCircuitFailureCategory): void {\n    const wasNonOpen = state !== \"OPEN\";\n    state = \"OPEN\";\n    halfOpenProbeInFlight = false;\n    if (openedAtMs === null) {\n      openedAtMs = now();\n    }\n    if (wasNonOpen) {\n      const timestamp = new Date(now()).toISOString();\n      const message = buildOpenedMessage(category, consecutiveFailures);\n      // Lifecycle event first, FSM coupling second. Listeners may\n      // observe the OPEN transition via the lifecycle bus\n      // independently of the FSM.\n      try {\n        events.emitOpened({\n          category,\n          message,\n          timestamp,\n          consecutiveFailures,\n          nextProbeMs: currentBackoffMs,\n        });\n      } catch {\n        // event sink errors must not block the state machine\n      }\n      try {\n        fsm?.onCircuitOpened();\n      } catch {\n        // FSM hook errors must not block the state machine\n      }\n    }\n    scheduleHalfOpen(currentBackoffMs);\n  }\n\n  function transitionToHalfOpen(previousTimerMs: number): void {\n    state = \"HALF_OPEN\";\n    halfOpenProbeInFlight = false;\n    try {\n      events.emitHalfOpen({\n        timestamp: new Date(now()).toISOString(),\n        previousTimerMs,\n      });\n    } catch {\n      // best-effort\n    }\n  }\n\n  /**\n   * Transition the breaker to CLOSED and emit `otel:circuit_closed`\n   * with `outageDurationMs` measured from the original OPEN moment.\n   * Resets failure counter, backoff timer, and pending probe timer.\n   */\n  function transitionToClosed(): void {\n    const startedAt = openedAtMs;\n    state = \"CLOSED\";\n    consecutiveFailures = 0;\n    currentBackoffMs = INITIAL_BACKOFF_MS;\n    openedAtMs = null;\n    halfOpenProbeInFlight = false;\n    clearPendingTimer();\n    try {\n      events.emitClosed({\n        timestamp: new Date(now()).toISOString(),\n        outageDurationMs: startedAt === null ? 0 : Math.max(0, now() - startedAt),\n      });\n    } catch {\n      // best-effort\n    }\n    try {\n      fsm?.onCircuitClosed();\n    } catch {\n      // best-effort\n    }\n  }\n\n  // ---- Public API ----------------------------------------------------------\n\n  return {\n    shouldExport(): boolean {\n      if (state === \"OPEN\") return false;\n      if (state === \"HALF_OPEN\") {\n        // Single-probe gate: only the first concurrent caller is\n        // admitted while a probe is in flight. Subsequent callers see\n        // `false` and their spans are dropped (same as OPEN). The flag\n        // clears on probe-result record or any state transition.\n        if (halfOpenProbeInFlight) return false;\n        halfOpenProbeInFlight = true;\n        return true;\n      }\n      return true; // CLOSED\n    },\n\n    recordSuccess(): void {\n      if (state === \"HALF_OPEN\") {\n        // Probe succeeded → close. Counter and backoff reset inside\n        // transitionToClosed; the in-flight gate also clears.\n        halfOpenProbeInFlight = false;\n        transitionToClosed();\n        return;\n      }\n      // CLOSED or OPEN-without-permission (defensive). Reset counter\n      // — a 2xx mid-streak indicates the backend is healthy again.\n      consecutiveFailures = 0;\n    },\n\n    recordFailure(info: ExportFailureInfo): void {\n      const category = classifyExportFailure(info);\n\n      if (state === \"HALF_OPEN\") {\n        // Probe failed → re-open with doubled timer (capped at T_MAX).\n        currentBackoffMs = Math.min(currentBackoffMs * BACKOFF_FACTOR, MAX_BACKOFF_MS);\n        // consecutiveFailures stays at THRESHOLD-or-above; we do not\n        // re-emit `otel:circuit_opened` for the same outage. The\n        // caller's lifecycle stream sees a single open / many half-\n        // open / one close.\n        halfOpenProbeInFlight = false;\n        state = \"OPEN\";\n        scheduleHalfOpen(currentBackoffMs);\n        return;\n      }\n\n      if (state === \"CLOSED\") {\n        consecutiveFailures += 1;\n        if (consecutiveFailures >= FAILURE_THRESHOLD) {\n          // First trip → backoff is INITIAL_BACKOFF_MS (set above).\n          transitionToOpen(category);\n        }\n        return;\n      }\n\n      // state === \"OPEN\" — should not normally happen because\n      // shouldExport() returns false in OPEN, but if a caller routes a\n      // failure through the breaker anyway (e.g., a stale callback\n      // arriving after a probe timer scheduled the next half-open),\n      // we keep the counter monotonic without re-tripping.\n    },\n\n    onSpansDropped(count: number): void {\n      if (!Number.isFinite(count) || count <= 0) return;\n      try {\n        recordDropped(count);\n      } catch {\n        // health collector errors must not block the export path\n      }\n    },\n\n    getState(): ExportCircuitState {\n      return state;\n    },\n\n    resetForKeyRotation(): void {\n      generation += 1;\n      const wasNonClosed = state !== \"CLOSED\";\n      // Always reset counters on rotation regardless of state.\n      consecutiveFailures = 0;\n      currentBackoffMs = INITIAL_BACKOFF_MS;\n      clearPendingTimer();\n      // Drop stale per-trace boundary-masked entries: rotation changes\n      // the session id, so an old-session descendant error must not\n      // promote a new-context server span.\n      traceErrors.clear();\n      if (wasNonClosed) {\n        transitionToClosed();\n      }\n    },\n\n    getGeneration(): number {\n      return generation;\n    },\n\n    traceErrors,\n\n    clearTraceErrors(): void {\n      traceErrors.clear();\n    },\n  };\n}\n","declare const __SDK_VERSION__: string;\n\nimport type { GlasstraceOptions, AnonApiKey } from \"@glasstrace/protocol\";\nimport { resolveConfig, isProductionDisabled, isAnonymousMode } from \"./env-detection.js\";\nimport type { ResolvedConfig } from \"./env-detection.js\";\nimport { SessionManager } from \"./session.js\";\nimport { getOrCreateAnonKey, readAnonKey } from \"./anon-key.js\";\nimport { loadCachedConfig, performInit, _setCurrentConfig, getActiveConfig, getLinkedAccountId, getClaimResult, didLastInitSucceed } from \"./init-client.js\";\nimport { createDiscoveryHandler } from \"./discovery-endpoint.js\";\nimport { configureOtel, setResolvedApiKey, getResolvedApiKey, notifyApiKeyResolved, resetOtelConfigForTesting } from \"./otel-config.js\";\nimport { installContextManager } from \"./context-manager.js\";\nimport * as otelApi from \"@opentelemetry/api\";\nimport { installConsoleCapture, uninstallConsoleCapture, sdkLog } from \"./console-capture.js\";\nimport { collectHealthReport, _resetHealthForTesting } from \"./health-collector.js\";\nimport { startHeartbeat, _resetHeartbeatForTesting } from \"./heartbeat.js\";\nimport { initLifecycle, setCoreState, CoreState, getCoreState, initAuthState, AuthState, setAuthState, emitLifecycleEvent, registerSignalHandlers, resetLifecycleForTesting } from \"./lifecycle.js\";\nimport { setCoexistenceState } from \"./signal-handler.js\";\nimport { setSideEffectVerboseFlag } from \"./side-effect/index.js\";\nimport { startRuntimeStateWriter, _resetRuntimeStateForTesting } from \"./runtime-state.js\";\nimport { isProxyTracerProvider, isProxyTracer } from \"./proxy-detection.js\";\nimport { maybeWarnStaleAgentInstructions, _resetUpgradeNoticeForTesting } from \"./agent-detection/upgrade-notice.js\";\nimport { maskKey } from \"./mask-key.js\";\nimport {\n  decisionTrace,\n  decisionTraceEnabled,\n  setDecisionTraceFlag,\n  _resetDecisionTraceForTesting,\n} from \"./decision-trace.js\";\n\n/** Whether console capture has been installed in this registration cycle. */\nlet consoleCaptureInstalled = false;\n\n/** Module-level state tracking for the registered discovery handler. */\nlet discoveryHandler: ((request: Request) => Promise<Response | null>) | null = null;\n\n/** Generation counter to invalidate stale background promises after reset. */\nlet registrationGeneration = 0;\n\n/** Module-level session manager, shared with createGlasstraceSpanProcessor(). */\nlet _sessionManager: SessionManager | null = null;\n\n/** Returns the shared SessionManager. Creates a new one if registerGlasstrace() hasn't run yet. */\nexport function getSessionManager(): SessionManager {\n  if (!_sessionManager) {\n    _sessionManager = new SessionManager();\n  }\n  return _sessionManager;\n}\n\n/**\n * The primary SDK entry point called by developers in their `instrumentation.ts`.\n * Orchestrates OTel setup, span processor, init client, anon key, and discovery endpoint.\n *\n * This function is synchronous and MUST NOT throw. The developer's server is never blocked.\n * Background work (key resolution, init call) happens via fire-and-forget promises.\n *\n * @param options - Optional SDK configuration. Environment variables are used as fallbacks.\n *\n * @example\n * ```ts\n * // instrumentation.ts\n * import { registerGlasstrace } from \"@glasstrace/sdk\";\n * registerGlasstrace(); // uses env vars\n * ```\n */\nexport function registerGlasstrace(options?: GlasstraceOptions): void {\n  try {\n    // Prevent double registration (lifecycle state check replaces isRegistered flag)\n    if (getCoreState() !== CoreState.IDLE) {\n      return;\n    }\n\n    // Initialize lifecycle state machine before any state transitions.\n    initLifecycle({ logger: sdkLog });\n\n    // Guard: SDK requires Node.js runtime. Some environments (e.g. Bun,\n    // Deno with partial Node compat) resolve node: imports but lack full\n    // Node.js APIs. This guard prevents cryptic failures deeper in the\n    // SDK by detecting these environments early and returning a no-op.\n    //\n    // Note: environments that cannot resolve node: imports at all (pure\n    // Edge Runtime, Cloudflare Workers) will fail at module evaluation\n    // before this guard runs. Those cases are mitigated by the package's\n    // `sideEffects: false` flag and bundler externalization of node: modules.\n    if (typeof process === \"undefined\" || typeof process.versions?.node !== \"string\") {\n      console.warn(\n        \"[glasstrace] SDK requires a Node.js runtime. \" +\n        \"Edge Runtime, browser, and Deno without Node compat are not supported. \" +\n        \"Glasstrace is disabled in this environment.\",\n      );\n      return;\n    }\n\n    setCoreState(CoreState.REGISTERING);\n\n    // SDK-050 / DISC-1592: emit a one-time stderr warning if the project's\n    // agent instruction file (any of AGENTS.md / CLAUDE.md / GEMINI.md /\n    // .cursor/rules/glasstrace.mdc / .windsurf/rules/glasstrace.md /\n    // .cursorrules / codex.md / .windsurfrules — Wave 18 expanded set\n    // per DISC-1782) carries a managed-section stamp older than the\n    // running SDK version. The\n    // helper is best-effort, never throws, never mutates files, and\n    // respects the GLASSTRACE_DISABLE_UPGRADE_NOTICE opt-out. Placed after\n    // the Node-runtime guard above so it cannot fire in non-Node contexts.\n    maybeWarnStaleAgentInstructions({\n      projectRoot: process.cwd(),\n      sdkVersion: __SDK_VERSION__,\n    });\n\n    // Start runtime state writer — writes lifecycle state to\n    // .glasstrace/runtime-state.json for CLI status reporting (SDK-026).\n    // Must be after initLifecycle() and Node.js guard.\n    startRuntimeStateWriter({\n      projectRoot: process.cwd(),\n      sdkVersion: __SDK_VERSION__,\n    });\n\n    // Resolve config\n    const config = resolveConfig(options);\n    setSideEffectVerboseFlag(config.verbose);\n    // Decision tracing folds in `verbose`: a verbose session gets the\n    // decision lines for free, while a narrow `decisionTrace`/env opt-in\n    // shows only the decision lines without the full init firehose.\n    setDecisionTraceFlag(config.decisionTrace || config.verbose);\n    if (config.verbose) {\n      console.info(\"[glasstrace] Config resolved.\");\n    }\n\n    // Production check\n    const productionDisabled = isProductionDisabled(config);\n    // Decision trace: how the production gate resolved, keyed on whether\n    // force-enable actually changed the outcome:\n    //   - `forced` — a production env was detected AND force-enable overrode the\n    //     block (the gate would have disabled the SDK without it);\n    //   - `production_disabled` — a production env disabled the SDK, not\n    //     overridden;\n    //   - `normal` — not a production env, so force-enable was irrelevant / a\n    //     no-op.\n    // Keyed by the closed outcome (three values). Guarded so nothing is built\n    // when OFF. The decision-trace flag was set just above, so the threaded\n    // gate governs.\n    if (decisionTraceEnabled()) {\n      // Whether a production env was detected, independent of force-enable —\n      // i.e. whether the gate WOULD have blocked without the override.\n      const productionEnvDetected =\n        config.nodeEnv === \"production\" || config.vercelEnv === \"production\";\n      const outcome = productionDisabled\n        ? \"production_disabled\"\n        : productionEnvDetected && config.forceEnable\n          ? \"forced\"\n          : \"normal\";\n      decisionTrace(\"env.forceEnable\", outcome, {\n        oneShotKey: `env.forceEnable:${outcome}`,\n      });\n    }\n    if (productionDisabled) {\n      setCoreState(CoreState.PRODUCTION_DISABLED);\n      console.warn(\n        \"[glasstrace] Disabled in production. Set GLASSTRACE_FORCE_ENABLE=true to override.\",\n      );\n      return;\n    }\n    if (config.verbose) {\n      console.info(\"[glasstrace] Not production-disabled.\");\n    }\n\n    // Synchronous probe for an existing OTel provider. Used to gate\n    // context manager installation below. If another tracing tool (Datadog,\n    // Sentry, New Relic) has already registered a provider, the SDK must\n    // NOT claim the global context manager slot — doing so would break\n    // the other tool's context propagation.\n    //\n    // DISC-1556: classification is structural rather than constructor-name\n    // based. Next.js 16's production bundler renames `@opentelemetry/api`'s\n    // `ProxyTracerProvider` / `ProxyTracer` to short minified identifiers\n    // (`eN`/`ek`/etc.), which previously caused the SDK's own bundled proxy\n    // to be misidentified as an external provider — see\n    // `/tmp/recon-option-A-DISC-1556.md` and {@link isProxyTracerProvider}.\n    //\n    // OR-ordering edge case: if a third party extends a real provider\n    // (e.g. `BasicTracerProvider`) and stamps the four `getDelegate*`\n    // method names onto the subclass, `isProxyTracerProvider` returns\n    // `true`, but the probe tracer (returned by the subclass's real\n    // `getTracer()`) is a real `Tracer`, not a `ProxyTracer` —\n    // `isProxyTracer` returns `false`. The OR short-circuit then sets\n    // `anotherProviderRegistered = true`, which is the correct behavior\n    // for a real provider with a custom shape.\n    const existingTracerProvider = otelApi.trace.getTracerProvider();\n    const existingProbe = existingTracerProvider.getTracer(\"glasstrace-probe\");\n    const anotherProviderRegistered =\n      !isProxyTracerProvider(existingTracerProvider) ||\n      !isProxyTracer(existingProbe, existingTracerProvider);\n\n    // When another provider is already present, set coexistenceState BEFORE\n    // installing the signal handler. Without this, the handler would see\n    // \"unknown\" during the configureOtel() async tick/probe window and would\n    // re-raise the signal — terminating the process before the existing\n    // provider's async flush completes (Codex review on #168).\n    //\n    // configureOtel() calls setCoexistenceState() again after its own async\n    // probe for precision (e.g. a new provider appears in that tick window),\n    // but the synchronous probe is authoritative for any signal arriving\n    // between registerGlasstrace() returning and configureOtel() completing.\n    if (anotherProviderRegistered) {\n      setCoexistenceState(\"coexisting\");\n    }\n\n    // Register SIGTERM/SIGINT handlers BEFORE any async work (DISC-1249).\n    // configureOtel() yields a tick and awaits the @vercel/otel probe;\n    // without an early handler a signal arriving in that window would find\n    // no coordinator and silently drop buffered spans.\n    //\n    // The handler is now always installed regardless of whether another\n    // provider exists (DISC-1265). Whether the signal is re-raised after our\n    // hooks drain is decided at delivery time by checking coexistenceState:\n    //   - \"unknown\"     → re-raise (safe default during the startup window)\n    //   - \"sole-owner\"  → re-raise (Glasstrace owns the provider)\n    //   - \"coexisting\"  → do NOT re-raise (existing provider owns shutdown)\n    //\n    // Registered AFTER the production check so PRODUCTION_DISABLED processes\n    // don't retain a handler that would log invalid-transition warnings if\n    // signaled.\n    registerSignalHandlers();\n\n    // Determine auth mode\n    const anonymous = isAnonymousMode(config);\n    let effectiveKey: string | undefined = config.apiKey;\n\n    // Set initial auth lifecycle state based on configuration\n    initAuthState(anonymous ? AuthState.ANONYMOUS : AuthState.AUTHENTICATED);\n\n    if (effectiveKey) {\n      setResolvedApiKey(effectiveKey);\n      emitLifecycleEvent(\"auth:key_resolved\", {\n        key: maskKey(effectiveKey),\n        mode: anonymous ? \"anonymous\" : \"dev\",\n      });\n    }\n\n    if (config.verbose) {\n      console.info(\n        `[glasstrace] Auth mode = ${anonymous ? \"anonymous\" : \"dev-key\"}.`,\n      );\n    }\n\n    // Load cached config and apply to in-memory store. Tag it with the `cache`\n    // origin so the decision-trace `config.tier` gate reports `cached` (not\n    // `served`) until a live init response replaces it.\n    const cachedInitResponse = loadCachedConfig();\n    if (cachedInitResponse) {\n      _setCurrentConfig(cachedInitResponse, \"cache\");\n    }\n    if (config.verbose) {\n      console.info(\n        `[glasstrace] Cached config ${cachedInitResponse ? \"loaded and applied\" : \"not found\"}.`,\n      );\n    }\n\n    // Create or reuse SessionManager (shared with createGlasstraceSpanProcessor)\n    const sessionManager = getSessionManager();\n    if (config.verbose) {\n      console.info(\"[glasstrace] SessionManager created.\");\n    }\n\n    setCoreState(CoreState.KEY_PENDING);\n    const currentGeneration = registrationGeneration;\n\n    if (anotherProviderRegistered) {\n      if (config.verbose) {\n        console.info(\"[glasstrace] Another OTel provider detected — using existing context manager.\");\n      }\n    } else {\n      // Register the context manager SYNCHRONOUSLY before any spans are\n      // created. Without this, each span starts a new root trace with a\n      // fresh traceId because there's no parent context to inherit from.\n      // Must happen before configureOtel (which is async) — Next.js may\n      // create spans between registerGlasstrace() returning and\n      // configureOtel() completing (DISC-1183).\n      const contextManagerInstalled = installContextManager();\n      if (config.verbose) {\n        console.info(\n          contextManagerInstalled\n            ? \"[glasstrace] Context manager installed.\"\n            : \"[glasstrace] Context manager not available — trace context propagation disabled.\",\n        );\n      }\n    }\n\n    // Configure OTel IMMEDIATELY in all modes.\n    // OTel is registered before the anon key resolves so that\n    // spans are captured from cold start. GlasstraceExporter buffers spans\n    // while the key is \"pending\" and flushes them once notifyApiKeyResolved()\n    // is called after anonymous key resolution.\n    // This is fire-and-forget -- OTel failure must not block init.\n    void configureOtel(config, sessionManager).then(\n      () => {\n        // Check cached config for consoleErrors (may be stale or absent).\n        // Re-checked after performInit completes with the authoritative config.\n        maybeInstallConsoleCapture();\n\n        if (config.verbose) {\n          console.info(\"[glasstrace] OTel configured.\");\n        }\n      },\n      (err: unknown) => {\n        console.warn(\n          `[glasstrace] Failed to configure OTel: ${err instanceof Error ? err.message : String(err)}`,\n        );\n      },\n    );\n\n    // Background work: anonymous key resolution, discovery endpoint, init\n    if (anonymous) {\n      // Register discovery endpoint IMMEDIATELY with async key resolution\n      const discoveryEnabled = isDiscoveryEnabled(config);\n      // Decision trace: whether the browser-extension discovery endpoint is\n      // registered for this environment. Keyed by the closed outcome (two\n      // values). Guarded so nothing is built when OFF.\n      if (decisionTraceEnabled()) {\n        const outcome = discoveryEnabled ? \"enabled\" : \"disabled\";\n        decisionTrace(\"feature.discovery\", outcome, {\n          oneShotKey: `feature.discovery:${outcome}`,\n        });\n      }\n      if (discoveryEnabled) {\n        let resolvedAnonKey: AnonApiKey | null = null;\n        const anonKeyPromise = getOrCreateAnonKey();\n\n        // Derive claim state from the init response.\n        // Called on every discovery request so it reflects the latest state.\n        // Two sources indicate a claimed account:\n        //   1. linkedAccountId — key was already linked to an account\n        //   2. claimResult — a claim just completed during this init call\n        const getClaimState = () => {\n          if (getLinkedAccountId()) return { claimed: true as const };\n          if (getClaimResult()) return { claimed: true as const };\n          return null;\n        };\n\n        // Use getResolvedApiKey() for session ID instead of\n        // capturing the mutable effectiveKey closure variable.\n        //\n        // Internal compatibility only — see `packages/sdk/README.md`\n        // \"Browser-extension discovery\". The runtime handler is not part\n        // of the supported discovery contract; the supported surface is\n        // the static file written by `glasstrace init`.\n        discoveryHandler = createDiscoveryHandler(\n          async () => resolvedAnonKey,\n          () => sessionManager.getSessionId(getResolvedApiKey()),\n          getClaimState,\n        );\n\n        if (config.verbose) {\n          console.info(\"[glasstrace] Discovery endpoint registered (key pending).\");\n        }\n\n        // Background: resolve key, update API key, then init\n        void (async () => {\n          try {\n            if (currentGeneration !== registrationGeneration) return;\n\n            const anonKey = await anonKeyPromise;\n            resolvedAnonKey = anonKey;\n            setResolvedApiKey(anonKey);\n            notifyApiKeyResolved();\n            emitLifecycleEvent(\"auth:key_resolved\", { key: maskKey(anonKey), mode: \"anonymous\" });\n            effectiveKey = anonKey;\n\n            if (currentGeneration !== registrationGeneration) return;\n\n            // Update the discovery handler to serve the resolved key.\n            // Use getResolvedApiKey() for canonical key state.\n            //\n            // Internal compatibility only — see `packages/sdk/README.md`\n            // \"Browser-extension discovery\". The runtime handler is not\n            // part of the supported discovery contract.\n            discoveryHandler = createDiscoveryHandler(\n              () => Promise.resolve(anonKey),\n              () => sessionManager.getSessionId(getResolvedApiKey()),\n              getClaimState,\n            );\n\n            await backgroundInit(config, anonKey, currentGeneration);\n          } catch (err) {\n            console.warn(\n              `[glasstrace] Background init failed: ${err instanceof Error ? err.message : String(err)}`,\n            );\n          }\n        })();\n      } else {\n        // Anonymous + non-dev: no discovery endpoint, just background init\n        void (async () => {\n          try {\n            if (currentGeneration !== registrationGeneration) return;\n\n            const anonKey = await getOrCreateAnonKey();\n            setResolvedApiKey(anonKey);\n            notifyApiKeyResolved();\n            emitLifecycleEvent(\"auth:key_resolved\", { key: maskKey(anonKey), mode: \"anonymous\" });\n            effectiveKey = anonKey;\n\n            if (currentGeneration !== registrationGeneration) return;\n\n            await backgroundInit(config, anonKey, currentGeneration);\n          } catch (err) {\n            console.warn(\n              `[glasstrace] Background init failed: ${err instanceof Error ? err.message : String(err)}`,\n            );\n          }\n        })();\n      }\n    } else {\n      // Dev key mode: read straggler anon key, then fire init\n      void (async () => {\n        try {\n          if (currentGeneration !== registrationGeneration) return;\n\n          let anonKeyForInit: AnonApiKey | null = null;\n          try {\n            anonKeyForInit = await readAnonKey();\n          } catch {\n            // Expected when no prior anon key file exists on disk (first run).\n          }\n\n          if (currentGeneration !== registrationGeneration) return;\n\n          await backgroundInit(config, anonKeyForInit, currentGeneration);\n        } catch (err) {\n          console.warn(\n            `[glasstrace] Background init failed: ${err instanceof Error ? err.message : String(err)}`,\n          );\n        }\n      })();\n    }\n\n    // Import graph (coverageMapEnabled) -- placeholder\n    if (config.coverageMapEnabled && config.verbose) {\n      console.info(\"[glasstrace] Import graph building skipped.\");\n    }\n  } catch (err) {\n    setCoreState(CoreState.REGISTRATION_FAILED);\n    console.warn(\n      `[glasstrace] Registration failed: ${err instanceof Error ? err.message : String(err)}`,\n    );\n  }\n}\n\n/**\n * Shared background init logic for all auth modes.\n *\n * Fires the init request, handles account claim transitions (updating\n * the exporter key), and re-checks console capture config. The anonymous\n * paths pass the anon key as `anonKeyForInit`; the dev-key path passes\n * the straggler anon key (or null).\n */\nasync function backgroundInit(\n  config: ResolvedConfig,\n  anonKeyForInit: AnonApiKey | null,\n  generation: number,\n): Promise<void> {\n  if (config.verbose) {\n    console.info(\"[glasstrace] Background init firing.\");\n  }\n\n  const healthReport = collectHealthReport(__SDK_VERSION__);\n  const initResult = await performInit(config, anonKeyForInit, __SDK_VERSION__, healthReport);\n\n  if (generation !== registrationGeneration) return;\n\n  // Bail if shutdown was initiated while backgroundInit was in flight.\n  const currentState = getCoreState();\n  if (currentState === CoreState.SHUTTING_DOWN || currentState === CoreState.SHUTDOWN) {\n    return;\n  }\n\n  // Advance core lifecycle: KEY_PENDING → KEY_RESOLVED → ACTIVE/ACTIVE_DEGRADED.\n  // In the full lifecycle (SDK-024), KEY_RESOLVED is triggered by auth:key_resolved.\n  // For now, drive both transitions here since the auth layer isn't wired yet.\n  if (currentState === CoreState.KEY_PENDING) {\n    setCoreState(CoreState.KEY_RESOLVED);\n  }\n  if (getCoreState() === CoreState.KEY_RESOLVED) {\n    setCoreState(didLastInitSucceed() ? CoreState.ACTIVE : CoreState.ACTIVE_DEGRADED);\n  }\n\n  // Decision trace (cold path, once per init): record the capture posture\n  // the SDK actually applied. On success, read the backend-authoritative\n  // applied config via getActiveConfig() — NOT the pre-init `config`\n  // param, which predates the fetched account config. On failure, emit a\n  // distinct fail-closed line so a capture failure is one-run localizable:\n  // it answers \"did the in-app SDK ever receive sideEffectEvidence=true?\".\n  if (decisionTraceEnabled()) {\n    // Fenced so a throwing config read can never alter the control flow\n    // that follows (claim handling, heartbeat) — this stays observational\n    // even with the toggle ON.\n    try {\n      if (didLastInitSucceed()) {\n        const applied = getActiveConfig();\n        const outcome = applied.sideEffectEvidence === true ? \"enabled\" : \"disabled\";\n        decisionTrace(\"capture.sideEffectEvidence\", outcome, {\n          reason: \"config_applied\",\n          inputs: {\n            surface: \"configApply\",\n            captureFidelity: applied.captureFidelity ?? \"strict\",\n          },\n          oneShotKey: `capture.sideEffectEvidence:configApply:${outcome}`,\n        });\n      } else {\n        // Init failed. A cached init response loaded before backgroundInit\n        // stays active, so capture can still be ON from the cache even\n        // though the fresh init failed — report the real posture rather\n        // than unconditionally claiming fail-closed. Only when no usable\n        // cached config keeps capture enabled is the gate truly fail-closed.\n        const active = getActiveConfig();\n        if (active.sideEffectEvidence === true) {\n          decisionTrace(\"capture.sideEffectEvidence\", \"enabled\", {\n            reason: \"init_failed_cached_config_active\",\n            inputs: {\n              surface: \"configApply\",\n              captureFidelity: active.captureFidelity ?? \"strict\",\n            },\n            oneShotKey: \"capture.sideEffectEvidence:configApply:init_failed_cached\",\n          });\n        } else {\n          decisionTrace(\"capture.sideEffectEvidence\", \"disabled\", {\n            reason: \"init_failed_fail_closed\",\n            inputs: { surface: \"configApply\" },\n            oneShotKey: \"capture.sideEffectEvidence:configApply:init_failed\",\n          });\n        }\n      }\n    } catch {\n      // Diagnostic deliverability is best-effort; never disrupt init.\n    }\n  }\n\n  // If the backend reported an account claim, update the exporter\n  // key so subsequent span exports authenticate with the dev key.\n  if (initResult?.claimResult) {\n    const { newApiKey, accountId } = initResult.claimResult;\n    setAuthState(AuthState.CLAIMING);\n    emitLifecycleEvent(\"auth:claim_started\", { accountId });\n    setResolvedApiKey(newApiKey);\n    notifyApiKeyResolved();\n    setAuthState(AuthState.CLAIMED);\n    emitLifecycleEvent(\"auth:claim_completed\", { newKey: maskKey(newApiKey), accountId });\n  }\n\n  // Re-check consoleErrors with the authoritative init response config. This\n  // is the post-init pass, so it emits the `feature.consoleErrors` decision.\n  maybeInstallConsoleCapture(true);\n\n  // Start the periodic health heartbeat if init succeeded.\n  // The heartbeat re-calls performInit every 5 minutes to report health\n  // metrics and refresh config. Only starts after first successful init.\n  if (didLastInitSucceed()) {\n    startHeartbeat(config, anonKeyForInit, __SDK_VERSION__, generation, (newApiKey, accountId) => {\n      setAuthState(AuthState.CLAIMING);\n      emitLifecycleEvent(\"auth:claim_started\", { accountId });\n      setResolvedApiKey(newApiKey);\n      notifyApiKeyResolved();\n      setAuthState(AuthState.CLAIMED);\n      emitLifecycleEvent(\"auth:claim_completed\", { newKey: maskKey(newApiKey), accountId });\n    });\n  }\n}\n\n/**\n * Returns the registered discovery handler, or null if not registered.\n */\nexport function getDiscoveryHandler(): ((request: Request) => Promise<Response | null>) | null {\n  return discoveryHandler;\n}\n\n/**\n * Checks the active config and installs console capture if enabled.\n * Idempotent — safe to call multiple times (after OTel config, after init).\n * This ensures console capture is installed whenever authoritative config\n * becomes available, whether from the file cache or the init response.\n *\n * `emitDecision` gates the `feature.consoleErrors` decision trace. The\n * pre-init call (right after OTel configures) reads the cached/absent config\n * and passes `false`, so it never emits a transient — possibly wrong —\n * `disabled` line before the backend config lands. Only the post-init call\n * passes `true`, and it reports the authoritative install posture from the\n * resolved config exactly once. The decision is emitted BEFORE the\n * already-installed early return so it always lands on the authoritative pass,\n * even when the pre-init call already installed capture (the install state must\n * not swallow the authoritative decision line).\n */\nfunction maybeInstallConsoleCapture(emitDecision = false): void {\n  // Read the authoritative config and emit the decision first, independent of\n  // the install state. A pre-init call may already have installed capture, but\n  // the post-init pass must still report the authoritative posture exactly once.\n  const consoleErrorsEnabled = getActiveConfig().consoleErrors === true;\n  if (emitDecision && decisionTraceEnabled()) {\n    const outcome = consoleErrorsEnabled ? \"enabled\" : \"disabled\";\n    decisionTrace(\"feature.consoleErrors\", outcome, {\n      oneShotKey: `feature.consoleErrors:${outcome}`,\n    });\n  }\n  if (consoleCaptureInstalled) return;\n  if (consoleErrorsEnabled) {\n    consoleCaptureInstalled = true;\n    void installConsoleCapture();\n  }\n}\n\n/**\n * Returns `true` if the discovery endpoint should be enabled for this environment.\n *\n * Tightened from \"not production\" to explicit development conditions:\n * 1. `GLASSTRACE_DISCOVERY_ENABLED=true` -- explicit override (highest priority)\n * 2. `GLASSTRACE_DISCOVERY_ENABLED=false` -- explicit disable (highest priority)\n * 3. `NODE_ENV` is `\"development\"` or unset, AND `VERCEL_ENV` is not `\"production\"`\n *\n * Environments like `staging`, `test`, and `ci` do not expose the discovery\n * endpoint by default, since it serves the anonymous API key over CORS.\n *\n * @param config - The resolved SDK configuration.\n * @returns Whether the discovery endpoint should be registered.\n */\nfunction isDiscoveryEnabled(config: ResolvedConfig): boolean {\n  // Explicit flag takes precedence\n  if (process.env.GLASSTRACE_DISCOVERY_ENABLED === \"true\") return true;\n  if (process.env.GLASSTRACE_DISCOVERY_ENABLED === \"false\") return false;\n\n  // Block production environments\n  if (config.nodeEnv === \"production\") return false;\n  if (config.vercelEnv === \"production\") return false;\n\n  // Only allow in development or when NODE_ENV is unset\n  if (config.nodeEnv === \"development\" || config.nodeEnv === undefined) return true;\n\n  return false;\n}\n\n/**\n * Resets registration state. For testing only.\n */\nexport function _resetRegistrationForTesting(): void {\n  discoveryHandler = null;\n  consoleCaptureInstalled = false;\n  registrationGeneration++;\n  _resetHealthForTesting();\n  _resetHeartbeatForTesting();\n  uninstallConsoleCapture();\n  resetOtelConfigForTesting(); // also resets coexistenceState via signal-handler\n  _resetRuntimeStateForTesting();\n  _resetUpgradeNoticeForTesting();\n  _sessionManager = null;\n  resetLifecycleForTesting();\n  _resetDecisionTraceForTesting();\n}\n","import type { AnonApiKey, SessionId } from \"@glasstrace/protocol\";\n\n/**\n * Checks whether the given Origin header is allowed for CORS access.\n *\n * Allowed origins:\n * - `chrome-extension://*` — any Chrome extension\n * - `moz-extension://*` — any Firefox extension\n * - `safari-web-extension://*` — any Safari extension\n * - Absent origin (same-origin / non-browser request)\n *\n * Replaced wildcard `*` to prevent arbitrary websites from\n * reading the anonymous API key from localhost.\n */\nfunction isAllowedOrigin(origin: string | null): boolean {\n  if (origin === null) return true;\n  if (origin.startsWith(\"chrome-extension://\")) return true;\n  if (origin.startsWith(\"moz-extension://\")) return true;\n  if (origin.startsWith(\"safari-web-extension://\")) return true;\n  return false;\n}\n\n/**\n * Builds CORS headers for a given request origin.\n * Returns headers with `Access-Control-Allow-Origin` set to the origin\n * if allowed, otherwise omits that header entirely.\n */\nfunction buildCorsHeaders(origin: string | null): Record<string, string> {\n  const headers: Record<string, string> = {\n    \"Content-Type\": \"application/json\",\n    Vary: \"Origin\",\n  };\n\n  if (origin && isAllowedOrigin(origin)) {\n    headers[\"Access-Control-Allow-Origin\"] = origin;\n  }\n\n  return headers;\n}\n\n/**\n * @internal Claim state returned by the `getClaimState` callback.\n *\n * - `claimed` — `true` when the anonymous key has been linked to an account.\n * - `accountHint` — optional masked identifier (e.g. `\"er***@example.com\"`)\n *   for the browser extension to display to the user.\n */\nexport interface ClaimState {\n  claimed: boolean;\n  accountHint?: string;\n}\n\n/**\n * @internal Creates a request handler for the `/__glasstrace/config`\n * discovery endpoint.\n *\n * Called from {@link registerGlasstrace} when the SDK runs in anonymous +\n * development mode. The supported discovery contract is the static file\n * served at `/.well-known/glasstrace.json` (written by\n * `glasstrace init` under the framework's static root — `public/`\n * for Next.js and most frameworks, `static/` for SvelteKit). The runtime\n * handler here is internal compatibility for older consumer integrations\n * during local development and is not part of the supported discovery\n * contract (removed from the root barrel in v1.0.0; may be removed\n * without deprecation in a future release). See `packages/sdk/README.md`\n * \"Browser-extension discovery\" for the canonical statement.\n *\n * The returned handler checks if the request URL path is\n * `/__glasstrace/config`. If not, returns `null` (pass-through). If it\n * matches, returns a `DiscoveryResponse` with the anonymous key and\n * current session ID.\n *\n * When `getClaimState` returns a non-null value with `claimed: true`, the\n * response includes `claimed` and (optionally) `accountHint` so the\n * browser extension can prompt the user to sign in.\n *\n * The triple guard (anonymous + dev + active) is enforced by the caller,\n * not by this module. If the handler is registered, it serves.\n */\nexport function createDiscoveryHandler(\n  getAnonKey: () => Promise<AnonApiKey | null>,\n  getSessionId: () => SessionId,\n  getClaimState?: () => ClaimState | null,\n): (request: Request) => Promise<Response | null> {\n  return async (request: Request): Promise<Response | null> => {\n    // Check path match\n    let url: URL;\n    try {\n      url = new URL(request.url);\n    } catch {\n      return null;\n    }\n\n    if (url.pathname !== \"/__glasstrace/config\") {\n      return null;\n    }\n\n    // Restrict CORS to known extension origins instead of wildcard\n    const origin = request.headers.get(\"Origin\");\n    const corsHeaders = buildCorsHeaders(origin);\n\n    // Handle CORS preflight\n    if (request.method === \"OPTIONS\") {\n      return new Response(null, {\n        status: 204,\n        headers: {\n          ...corsHeaders,\n          \"Access-Control-Allow-Methods\": \"GET, OPTIONS\",\n          \"Access-Control-Allow-Headers\": \"Content-Type\",\n        },\n      });\n    }\n\n    // Only allow GET requests\n    if (request.method !== \"GET\") {\n      return new Response(\n        JSON.stringify({ error: \"method_not_allowed\" }),\n        {\n          status: 405,\n          headers: corsHeaders,\n        },\n      );\n    }\n\n    try {\n      // Get the anonymous key\n      const anonKey = await getAnonKey();\n\n      if (anonKey === null) {\n        return new Response(\n          JSON.stringify({ error: \"not_ready\" }),\n          {\n            status: 503,\n            headers: corsHeaders,\n          },\n        );\n      }\n\n      // Get the current session ID\n      const sessionId = getSessionId();\n\n      // Build response body, conditionally including claim fields\n      const responseBody: Record<string, unknown> = { key: anonKey, sessionId };\n      const claimState = getClaimState?.();\n      if (claimState?.claimed) {\n        responseBody.claimed = true;\n        if (claimState.accountHint) {\n          responseBody.accountHint = claimState.accountHint;\n        }\n      }\n\n      return new Response(\n        JSON.stringify(responseBody),\n        {\n          status: 200,\n          headers: corsHeaders,\n        },\n      );\n    } catch {\n      return new Response(\n        JSON.stringify({ error: \"internal_error\" }),\n        {\n          status: 500,\n          headers: corsHeaders,\n        },\n      );\n    }\n  };\n}\n\n// Exported for testing\nexport { isAllowedOrigin, buildCorsHeaders };\n","/*\n * Copyright The OpenTelemetry Authors\n * SPDX-License-Identifier: Apache-2.0\n */\n\nimport type { ExportResult } from '@opentelemetry/core';\nimport type { IOtlpExportDelegate } from './otlp-export-delegate';\n\nexport class OTLPExporterBase<Internal> {\n  private _delegate: IOtlpExportDelegate<Internal>;\n  constructor(delegate: IOtlpExportDelegate<Internal>) {\n    this._delegate = delegate;\n  }\n\n  /**\n   * Export items.\n   * @param items\n   * @param resultCallback\n   */\n  export(\n    items: Internal,\n    resultCallback: (result: ExportResult) => void\n  ): void {\n    this._delegate.export(items, resultCallback);\n  }\n\n  forceFlush(): Promise<void> {\n    return this._delegate.forceFlush();\n  }\n\n  shutdown(): Promise<void> {\n    return this._delegate.shutdown();\n  }\n}\n","/*\n * Copyright The OpenTelemetry Authors\n * SPDX-License-Identifier: Apache-2.0\n */\n\n/**\n * Interface for handling error\n */\nexport class OTLPExporterError extends Error {\n  readonly code?: number;\n  override readonly name: string = 'OTLPExporterError';\n  readonly data?: string;\n\n  constructor(message?: string, code?: number, data?: string) {\n    super(message);\n    this.data = data;\n    this.code = code;\n  }\n}\n\n/**\n * Interface for handling export service errors\n */\nexport interface ExportServiceError {\n  name: string;\n  code: number;\n  details: string;\n  metadata: { [key: string]: unknown };\n  message: string;\n  stack: string;\n}\n","/*\n * Copyright The OpenTelemetry Authors\n * SPDX-License-Identifier: Apache-2.0\n */\n\nimport type { HeadersFactory } from './otlp-http-configuration';\n\n/**\n * Configuration shared across all OTLP exporters\n *\n * Implementation note: anything added here MUST be\n * - platform-agnostic\n * - signal-agnostic\n * - transport-agnostic\n */\nexport interface OtlpSharedConfiguration {\n  timeoutMillis: number;\n  concurrencyLimit: number;\n  compression: 'gzip' | 'none';\n}\n\nexport function validateTimeoutMillis(timeoutMillis: number) {\n  if (Number.isFinite(timeoutMillis) && timeoutMillis > 0) {\n    return timeoutMillis;\n  }\n  throw new Error(\n    `Configuration: timeoutMillis is invalid, expected number greater than 0 (actual: '${timeoutMillis}')`\n  );\n}\n\nexport function wrapStaticHeadersInFunction(\n  headers: Record<string, string> | undefined\n): HeadersFactory | undefined {\n  if (headers == null) {\n    return undefined;\n  }\n\n  return async () => headers;\n}\n\n/**\n * @param userProvidedConfiguration  Configuration options provided by the user in code.\n * @param fallbackConfiguration Fallback to use when the {@link userProvidedConfiguration} does not specify an option.\n * @param defaultConfiguration The defaults as defined by the exporter specification\n */\nexport function mergeOtlpSharedConfigurationWithDefaults(\n  userProvidedConfiguration: Partial<OtlpSharedConfiguration>,\n  fallbackConfiguration: Partial<OtlpSharedConfiguration>,\n  defaultConfiguration: OtlpSharedConfiguration\n): OtlpSharedConfiguration {\n  return {\n    timeoutMillis: validateTimeoutMillis(\n      userProvidedConfiguration.timeoutMillis ??\n        fallbackConfiguration.timeoutMillis ??\n        defaultConfiguration.timeoutMillis\n    ),\n    concurrencyLimit:\n      userProvidedConfiguration.concurrencyLimit ??\n      fallbackConfiguration.concurrencyLimit ??\n      defaultConfiguration.concurrencyLimit,\n    compression:\n      userProvidedConfiguration.compression ??\n      fallbackConfiguration.compression ??\n      defaultConfiguration.compression,\n  };\n}\n\nexport function getSharedConfigurationDefaults(): OtlpSharedConfiguration {\n  return {\n    timeoutMillis: 10000,\n    concurrencyLimit: 30,\n    compression: 'none',\n  };\n}\n","/*\n * Copyright The OpenTelemetry Authors\n * SPDX-License-Identifier: Apache-2.0\n */\n\nexport interface IExportPromiseHandler {\n  pushPromise(promise: Promise<void>): void;\n  hasReachedLimit(): boolean;\n  awaitAll(): Promise<void>;\n}\n\nclass BoundedQueueExportPromiseHandler implements IExportPromiseHandler {\n  private readonly _concurrencyLimit: number;\n  private _sendingPromises: Promise<unknown>[] = [];\n\n  /**\n   * @param concurrencyLimit maximum promises allowed in a queue at the same time.\n   */\n  constructor(concurrencyLimit: number) {\n    this._concurrencyLimit = concurrencyLimit;\n  }\n\n  public pushPromise(promise: Promise<void>): void {\n    if (this.hasReachedLimit()) {\n      throw new Error('Concurrency Limit reached');\n    }\n\n    this._sendingPromises.push(promise);\n    const popPromise = () => {\n      const index = this._sendingPromises.indexOf(promise);\n      void this._sendingPromises.splice(index, 1);\n    };\n    promise.then(popPromise, popPromise);\n  }\n\n  public hasReachedLimit(): boolean {\n    return this._sendingPromises.length >= this._concurrencyLimit;\n  }\n\n  public async awaitAll(): Promise<void> {\n    await Promise.all(this._sendingPromises);\n  }\n}\n\n/**\n * Promise queue for keeping track of export promises. Finished promises will be auto-dequeued.\n * Allows for awaiting all promises in the queue.\n */\nexport function createBoundedQueueExportPromiseHandler(options: {\n  concurrencyLimit: number;\n}): IExportPromiseHandler {\n  return new BoundedQueueExportPromiseHandler(options.concurrencyLimit);\n}\n","/*\n * Copyright The OpenTelemetry Authors\n * SPDX-License-Identifier: Apache-2.0\n */\n\nimport type { Context } from '@opentelemetry/api';\nimport { createContextKey } from '@opentelemetry/api';\n\nconst SUPPRESS_TRACING_KEY = createContextKey(\n  'OpenTelemetry SDK Context Key SUPPRESS_TRACING'\n);\n\nexport function suppressTracing(context: Context): Context {\n  return context.setValue(SUPPRESS_TRACING_KEY, true);\n}\n\nexport function unsuppressTracing(context: Context): Context {\n  return context.deleteValue(SUPPRESS_TRACING_KEY);\n}\n\nexport function isTracingSuppressed(context: Context): boolean {\n  return context.getValue(SUPPRESS_TRACING_KEY) === true;\n}\n","/*\n * Copyright The OpenTelemetry Authors\n * SPDX-License-Identifier: Apache-2.0\n */\n\nexport const BAGGAGE_KEY_PAIR_SEPARATOR = '=';\nexport const BAGGAGE_PROPERTIES_SEPARATOR = ';';\nexport const BAGGAGE_ITEMS_SEPARATOR = ',';\n\n// Name of the http header used to propagate the baggage\nexport const BAGGAGE_HEADER = 'baggage';\n// Maximum number of name-value pairs allowed by w3c spec\nexport const BAGGAGE_MAX_NAME_VALUE_PAIRS = 180;\n// Maximum number of bytes per a single name-value pair allowed by w3c spec\nexport const BAGGAGE_MAX_PER_NAME_VALUE_PAIRS = 4096;\n// Maximum total length of all name-value pairs allowed by w3c spec\nexport const BAGGAGE_MAX_TOTAL_LENGTH = 8192;\n","/*\n * Copyright The OpenTelemetry Authors\n * SPDX-License-Identifier: Apache-2.0\n */\nimport type {\n  Baggage,\n  BaggageEntry,\n  BaggageEntryMetadata,\n} from '@opentelemetry/api';\nimport { baggageEntryMetadataFromString } from '@opentelemetry/api';\nimport {\n  BAGGAGE_ITEMS_SEPARATOR,\n  BAGGAGE_PROPERTIES_SEPARATOR,\n  BAGGAGE_KEY_PAIR_SEPARATOR,\n  BAGGAGE_MAX_TOTAL_LENGTH,\n  BAGGAGE_MAX_NAME_VALUE_PAIRS,\n  BAGGAGE_MAX_PER_NAME_VALUE_PAIRS,\n} from './constants';\n\ntype ParsedBaggageKeyValue = {\n  key: string;\n  value: string;\n  metadata: BaggageEntryMetadata | undefined;\n};\n\nexport function serializeKeyPairs(keyPairs: string[]): string {\n  return keyPairs.reduce((hValue: string, current: string) => {\n    const value = `${hValue}${\n      hValue !== '' ? BAGGAGE_ITEMS_SEPARATOR : ''\n    }${current}`;\n    return value.length > BAGGAGE_MAX_TOTAL_LENGTH ? hValue : value;\n  }, '');\n}\n\nexport function getKeyPairs(baggage: Baggage): string[] {\n  return baggage.getAllEntries().map(([key, value]) => {\n    let entry = `${encodeURIComponent(key)}=${encodeURIComponent(value.value)}`;\n\n    // include opaque metadata if provided\n    // NOTE: we intentionally don't URI-encode the metadata - that responsibility falls on the metadata implementation\n    if (value.metadata !== undefined) {\n      entry += BAGGAGE_PROPERTIES_SEPARATOR + value.metadata.toString();\n    }\n\n    return entry;\n  });\n}\n\nexport function parsePairKeyValue(\n  entry: string\n): ParsedBaggageKeyValue | undefined {\n  if (!entry) return;\n  const metadataSeparatorIndex = entry.indexOf(BAGGAGE_PROPERTIES_SEPARATOR);\n  const keyPairPart =\n    metadataSeparatorIndex === -1\n      ? entry\n      : entry.substring(0, metadataSeparatorIndex);\n\n  const separatorIndex = keyPairPart.indexOf(BAGGAGE_KEY_PAIR_SEPARATOR);\n  if (separatorIndex <= 0) return;\n\n  const rawKey = keyPairPart.substring(0, separatorIndex).trim();\n  const rawValue = keyPairPart.substring(separatorIndex + 1).trim();\n\n  if (!rawKey || !rawValue) return;\n  let key: string;\n  let value: string;\n  try {\n    key = decodeURIComponent(rawKey);\n    value = decodeURIComponent(rawValue);\n  } catch {\n    return;\n  }\n\n  let metadata;\n  if (\n    metadataSeparatorIndex !== -1 &&\n    metadataSeparatorIndex < entry.length - 1\n  ) {\n    const metadataString = entry.substring(metadataSeparatorIndex + 1);\n    metadata = baggageEntryMetadataFromString(metadataString);\n  }\n\n  return { key, value, metadata };\n}\n\n/**\n * Parses a single baggage header string into the provided record, applying limits defined in this package.\n * Uses indexOf/substring in a while loop to avoid allocating a full array of split entries.\n * Returns the updated pair count so callers can track totals across multiple header values.\n */\nexport function parseBaggageHeaderString(\n  value: string,\n  baggage: Record<string, BaggageEntry>,\n  count: number,\n  totalSize: number\n): [count: number, totalSize: number] {\n  let start = 0;\n  while (start < value.length && count < BAGGAGE_MAX_NAME_VALUE_PAIRS) {\n    const end = value.indexOf(BAGGAGE_ITEMS_SEPARATOR, start);\n    const entryEnd = end === -1 ? value.length : end;\n    const entryLength = entryEnd - start;\n\n    if (entryLength <= BAGGAGE_MAX_PER_NAME_VALUE_PAIRS) {\n      const keyPair = parsePairKeyValue(value.substring(start, entryEnd));\n      if (keyPair) {\n        // Comma separator is counted for every accepted entry after the first\n        const entrySize = (count === 0 ? 0 : 1) + entryLength;\n        if (totalSize + entrySize > BAGGAGE_MAX_TOTAL_LENGTH) break;\n        baggage[keyPair.key] = keyPair.metadata\n          ? { value: keyPair.value, metadata: keyPair.metadata }\n          : { value: keyPair.value };\n        count++;\n        totalSize += entrySize;\n      }\n    }\n\n    if (end === -1) break;\n    start = end + 1;\n  }\n  return [count, totalSize];\n}\n\n/**\n * Parse a string serialized in the baggage HTTP Format (without metadata):\n * https://github.com/w3c/baggage/blob/master/baggage/HTTP_HEADER_FORMAT.md\n */\nexport function parseKeyPairsIntoRecord(\n  value?: string\n): Record<string, string> {\n  const result: Record<string, string> = {};\n\n  if (typeof value === 'string' && value.length > 0) {\n    value.split(BAGGAGE_ITEMS_SEPARATOR).forEach(entry => {\n      const keyPair = parsePairKeyValue(entry);\n\n      if (keyPair !== undefined && keyPair.value.length > 0) {\n        result[keyPair.key] = keyPair.value;\n      }\n    });\n  }\n\n  return result;\n}\n","/*\n * Copyright The OpenTelemetry Authors\n * SPDX-License-Identifier: Apache-2.0\n */\n\nimport type { AttributeValue, Attributes } from '@opentelemetry/api';\nimport { diag } from '@opentelemetry/api';\n\nexport function sanitizeAttributes(attributes: unknown): Attributes {\n  const out: Attributes = {};\n\n  if (typeof attributes !== 'object' || attributes == null) {\n    return out;\n  }\n\n  for (const key in attributes) {\n    if (!Object.prototype.hasOwnProperty.call(attributes, key)) {\n      continue;\n    }\n    if (!isAttributeKey(key)) {\n      diag.warn(`Invalid attribute key: ${key}`);\n      continue;\n    }\n    const val = (attributes as Record<string, unknown>)[key];\n    if (!isAttributeValue(val)) {\n      diag.warn(`Invalid attribute value set for key: ${key}`);\n      continue;\n    }\n    if (Array.isArray(val)) {\n      out[key] = val.slice();\n    } else {\n      out[key] = val;\n    }\n  }\n\n  return out;\n}\n\nexport function isAttributeKey(key: unknown): key is string {\n  return typeof key === 'string' && key !== '';\n}\n\nexport function isAttributeValue(val: unknown): val is AttributeValue {\n  if (val == null) {\n    return true;\n  }\n\n  if (Array.isArray(val)) {\n    return isHomogeneousAttributeValueArray(val);\n  }\n\n  return isValidPrimitiveAttributeValueType(typeof val);\n}\n\nfunction isHomogeneousAttributeValueArray(arr: unknown[]): boolean {\n  let type: string | undefined;\n\n  for (const element of arr) {\n    // null/undefined elements are allowed\n    if (element == null) continue;\n    const elementType = typeof element;\n\n    if (elementType === type) {\n      continue;\n    }\n\n    if (!type) {\n      if (isValidPrimitiveAttributeValueType(elementType)) {\n        type = elementType;\n        continue;\n      }\n      // encountered an invalid primitive\n      return false;\n    }\n\n    return false;\n  }\n\n  return true;\n}\n\nfunction isValidPrimitiveAttributeValueType(valType: string): boolean {\n  switch (valType) {\n    case 'number':\n    case 'boolean':\n    case 'string':\n      return true;\n  }\n\n  return false;\n}\n","/*\n * Copyright The OpenTelemetry Authors\n * SPDX-License-Identifier: Apache-2.0\n */\n\nimport type { Exception } from '@opentelemetry/api';\nimport { diag } from '@opentelemetry/api';\nimport type { ErrorHandler } from './types';\n\n/**\n * Returns a function that logs an error using the provided logger, or a\n * console logger if one was not provided.\n */\nexport function loggingErrorHandler(): ErrorHandler {\n  return (ex: Exception) => {\n    diag.error(stringifyException(ex));\n  };\n}\n\n/**\n * Converts an exception into a string representation\n * @param {Exception} ex\n */\nfunction stringifyException(ex: Exception | string): string {\n  if (typeof ex === 'string') {\n    return ex;\n  } else {\n    return JSON.stringify(flattenException(ex));\n  }\n}\n\n/**\n * Flattens an exception into key-value pairs by traversing the prototype chain\n * and coercing values to strings. Duplicate properties will not be overwritten;\n * the first insert wins.\n */\nfunction flattenException(ex: Exception): Record<string, string> {\n  const result = {} as Record<string, string>;\n  let current = ex;\n\n  while (current !== null) {\n    Object.getOwnPropertyNames(current).forEach(propertyName => {\n      if (result[propertyName]) return;\n      const value = current[propertyName as keyof typeof current];\n      if (value) {\n        result[propertyName] = String(value);\n      }\n    });\n    current = Object.getPrototypeOf(current);\n  }\n\n  return result;\n}\n","/*\n * Copyright The OpenTelemetry Authors\n * SPDX-License-Identifier: Apache-2.0\n */\n\nimport type { Exception } from '@opentelemetry/api';\nimport { loggingErrorHandler } from './logging-error-handler';\nimport type { ErrorHandler } from './types';\n\n/** The global error handler delegate */\nlet delegateHandler = loggingErrorHandler();\n\n/**\n * Set the global error handler\n * @param {ErrorHandler} handler\n */\nexport function setGlobalErrorHandler(handler: ErrorHandler): void {\n  delegateHandler = handler;\n}\n\n/**\n * Return the global error handler\n * @param {Exception} ex\n */\nexport function globalErrorHandler(ex: Exception): void {\n  try {\n    delegateHandler(ex);\n  } catch {} // eslint-disable-line no-empty\n}\n","/*\n * Copyright The OpenTelemetry Authors\n * SPDX-License-Identifier: Apache-2.0\n */\n\nimport { diag } from '@opentelemetry/api';\nimport { inspect } from 'util';\n\n/**\n * Retrieves a number from an environment variable.\n * - Returns `undefined` if the environment variable is empty, unset, contains only whitespace, or is not a number.\n * - Returns a number in all other cases.\n *\n * @param {string} key - The name of the environment variable to retrieve.\n * @returns {number | undefined} - The number value or `undefined`.\n */\nexport function getNumberFromEnv(key: string): number | undefined {\n  const raw = process.env[key];\n  if (raw == null || raw.trim() === '') {\n    return undefined;\n  }\n\n  const value = Number(raw);\n  if (isNaN(value)) {\n    diag.warn(\n      `Unknown value ${inspect(raw)} for ${key}, expected a number, using defaults`\n    );\n    return undefined;\n  }\n\n  return value;\n}\n\n/**\n * Retrieves a string from an environment variable.\n * - Returns `undefined` if the environment variable is empty, unset, or contains only whitespace.\n *\n * @param {string} key - The name of the environment variable to retrieve.\n * @returns {string | undefined} - The string value or `undefined`.\n */\nexport function getStringFromEnv(key: string): string | undefined {\n  const raw = process.env[key];\n  if (raw == null || raw.trim() === '') {\n    return undefined;\n  }\n  return raw;\n}\n\n/**\n * Retrieves a boolean value from an environment variable.\n * - Trims leading and trailing whitespace and ignores casing.\n * - Returns `false` if the environment variable is empty, unset, or contains only whitespace.\n * - Returns `false` for strings that cannot be mapped to a boolean.\n *\n * @param {string} key - The name of the environment variable to retrieve.\n * @returns {boolean} - The boolean value or `false` if the environment variable is unset empty, unset, or contains only whitespace.\n */\nexport function getBooleanFromEnv(key: string): boolean {\n  const raw = process.env[key]?.trim().toLowerCase();\n  if (raw == null || raw === '') {\n    // NOTE: falling back to `false` instead of `undefined` as required by the specification.\n    // If you have a use-case that requires `undefined`, consider using `getStringFromEnv()` and applying the necessary\n    // normalizations in the consuming code.\n    return false;\n  }\n  if (raw === 'true') {\n    return true;\n  } else if (raw === 'false') {\n    return false;\n  } else {\n    diag.warn(\n      `Unknown value ${inspect(raw)} for ${key}, expected 'true' or 'false', falling back to 'false' (default)`\n    );\n    return false;\n  }\n}\n\n/**\n * Retrieves a list of strings from an environment variable.\n * - Uses ',' as the delimiter.\n * - Trims leading and trailing whitespace from each entry.\n * - Excludes empty entries.\n * - Returns `undefined` if the environment variable is empty or contains only whitespace.\n * - Returns an empty array if all entries are empty or whitespace.\n *\n * @param {string} key - The name of the environment variable to retrieve.\n * @returns {string[] | undefined} - The list of strings or `undefined`.\n */\nexport function getStringListFromEnv(key: string): string[] | undefined {\n  return getStringFromEnv(key)\n    ?.split(',')\n    .map(v => v.trim())\n    .filter(s => s !== '');\n}\n","/*\n * Copyright The OpenTelemetry Authors\n * SPDX-License-Identifier: Apache-2.0\n */\n\n// this is autogenerated file, see scripts/version-update.js\nexport const VERSION = '2.8.0';\n","/*\n * Copyright The OpenTelemetry Authors\n * SPDX-License-Identifier: Apache-2.0\n */\n\n//----------------------------------------------------------------------------------------------------------\n// DO NOT EDIT, this is an Auto-generated file from scripts/semconv/templates/registry/stable/attributes.ts.j2\n//----------------------------------------------------------------------------------------------------------\n\n/**\n * ASP.NET Core exception middleware handling result.\n *\n * @example handled\n * @example unhandled\n */\nexport const ATTR_ASPNETCORE_DIAGNOSTICS_EXCEPTION_RESULT = 'aspnetcore.diagnostics.exception.result' as const;\n\n/**\n * Enum value \"aborted\" for attribute {@link ATTR_ASPNETCORE_DIAGNOSTICS_EXCEPTION_RESULT}.\n *\n * Exception handling didn't run because the request was aborted.\n */\nexport const ASPNETCORE_DIAGNOSTICS_EXCEPTION_RESULT_VALUE_ABORTED = \"aborted\" as const;\n\n/**\n * Enum value \"handled\" for attribute {@link ATTR_ASPNETCORE_DIAGNOSTICS_EXCEPTION_RESULT}.\n *\n * Exception was handled by the exception handling middleware.\n */\nexport const ASPNETCORE_DIAGNOSTICS_EXCEPTION_RESULT_VALUE_HANDLED = \"handled\" as const;\n\n/**\n * Enum value \"skipped\" for attribute {@link ATTR_ASPNETCORE_DIAGNOSTICS_EXCEPTION_RESULT}.\n *\n * Exception handling was skipped because the response had started.\n */\nexport const ASPNETCORE_DIAGNOSTICS_EXCEPTION_RESULT_VALUE_SKIPPED = \"skipped\" as const;\n\n/**\n * Enum value \"unhandled\" for attribute {@link ATTR_ASPNETCORE_DIAGNOSTICS_EXCEPTION_RESULT}.\n *\n * Exception was not handled by the exception handling middleware.\n */\nexport const ASPNETCORE_DIAGNOSTICS_EXCEPTION_RESULT_VALUE_UNHANDLED = \"unhandled\" as const;\n\n/**\n * Full type name of the [`IExceptionHandler`](https://learn.microsoft.com/dotnet/api/microsoft.aspnetcore.diagnostics.iexceptionhandler) implementation that handled the exception.\n *\n * @example Contoso.MyHandler\n */\nexport const ATTR_ASPNETCORE_DIAGNOSTICS_HANDLER_TYPE = 'aspnetcore.diagnostics.handler.type' as const;\n\n/**\n * Rate limiting policy name.\n *\n * @example fixed\n * @example sliding\n * @example token\n */\nexport const ATTR_ASPNETCORE_RATE_LIMITING_POLICY = 'aspnetcore.rate_limiting.policy' as const;\n\n/**\n * Rate-limiting result, shows whether the lease was acquired or contains a rejection reason\n *\n * @example acquired\n * @example request_canceled\n */\nexport const ATTR_ASPNETCORE_RATE_LIMITING_RESULT = 'aspnetcore.rate_limiting.result' as const;\n\n/**\n * Enum value \"acquired\" for attribute {@link ATTR_ASPNETCORE_RATE_LIMITING_RESULT}.\n *\n * Lease was acquired\n */\nexport const ASPNETCORE_RATE_LIMITING_RESULT_VALUE_ACQUIRED = \"acquired\" as const;\n\n/**\n * Enum value \"endpoint_limiter\" for attribute {@link ATTR_ASPNETCORE_RATE_LIMITING_RESULT}.\n *\n * Lease request was rejected by the endpoint limiter\n */\nexport const ASPNETCORE_RATE_LIMITING_RESULT_VALUE_ENDPOINT_LIMITER = \"endpoint_limiter\" as const;\n\n/**\n * Enum value \"global_limiter\" for attribute {@link ATTR_ASPNETCORE_RATE_LIMITING_RESULT}.\n *\n * Lease request was rejected by the global limiter\n */\nexport const ASPNETCORE_RATE_LIMITING_RESULT_VALUE_GLOBAL_LIMITER = \"global_limiter\" as const;\n\n/**\n * Enum value \"request_canceled\" for attribute {@link ATTR_ASPNETCORE_RATE_LIMITING_RESULT}.\n *\n * Lease request was canceled\n */\nexport const ASPNETCORE_RATE_LIMITING_RESULT_VALUE_REQUEST_CANCELED = \"request_canceled\" as const;\n\n/**\n * Flag indicating if request was handled by the application pipeline.\n *\n * @example true\n */\nexport const ATTR_ASPNETCORE_REQUEST_IS_UNHANDLED = 'aspnetcore.request.is_unhandled' as const;\n\n/**\n * A value that indicates whether the matched route is a fallback route.\n *\n * @example true\n */\nexport const ATTR_ASPNETCORE_ROUTING_IS_FALLBACK = 'aspnetcore.routing.is_fallback' as const;\n\n/**\n * Match result - success or failure\n *\n * @example success\n * @example failure\n */\nexport const ATTR_ASPNETCORE_ROUTING_MATCH_STATUS = 'aspnetcore.routing.match_status' as const;\n\n/**\n * Enum value \"failure\" for attribute {@link ATTR_ASPNETCORE_ROUTING_MATCH_STATUS}.\n *\n * Match failed\n */\nexport const ASPNETCORE_ROUTING_MATCH_STATUS_VALUE_FAILURE = \"failure\" as const;\n\n/**\n * Enum value \"success\" for attribute {@link ATTR_ASPNETCORE_ROUTING_MATCH_STATUS}.\n *\n * Match succeeded\n */\nexport const ASPNETCORE_ROUTING_MATCH_STATUS_VALUE_SUCCESS = \"success\" as const;\n\n/**\n * A value that indicates whether the user is authenticated.\n *\n * @example true\n */\nexport const ATTR_ASPNETCORE_USER_IS_AUTHENTICATED = 'aspnetcore.user.is_authenticated' as const;\n\n/**\n * Client address - domain name if available without reverse DNS lookup; otherwise, IP address or Unix domain socket name.\n *\n * @example client.example.com\n * @example 10.1.2.80\n * @example /tmp/my.sock\n *\n * @note When observed from the server side, and when communicating through an intermediary, `client.address` **SHOULD** represent the client address behind any intermediaries,  for example proxies, if it's available.\n */\nexport const ATTR_CLIENT_ADDRESS = 'client.address' as const;\n\n/**\n * Client port number.\n *\n * @example 65123\n *\n * @note When observed from the server side, and when communicating through an intermediary, `client.port` **SHOULD** represent the client port behind any intermediaries,  for example proxies, if it's available.\n */\nexport const ATTR_CLIENT_PORT = 'client.port' as const;\n\n/**\n * The column number in `code.file.path` best representing the operation. It **SHOULD** point within the code unit named in `code.function.name`. This attribute **MUST NOT** be used on the Profile signal since the data is already captured in 'message Line'. This constraint is imposed to prevent redundancy and maintain data integrity.\n *\n * @example 16\n */\nexport const ATTR_CODE_COLUMN_NUMBER = 'code.column.number' as const;\n\n/**\n * The source code file name that identifies the code unit as uniquely as possible (preferably an absolute file path). This attribute **MUST NOT** be used on the Profile signal since the data is already captured in 'message Function'. This constraint is imposed to prevent redundancy and maintain data integrity.\n *\n * @example \"/usr/local/MyApplication/content_root/app/index.php\"\n */\nexport const ATTR_CODE_FILE_PATH = 'code.file.path' as const;\n\n/**\n * The method or function fully-qualified name without arguments. The value should fit the natural representation of the language runtime, which is also likely the same used within `code.stacktrace` attribute value. This attribute **MUST NOT** be used on the Profile signal since the data is already captured in 'message Function'. This constraint is imposed to prevent redundancy and maintain data integrity.\n *\n * @example com.example.MyHttpService.serveRequest\n * @example GuzzleHttp\\\\Client::transfer\n * @example fopen\n *\n * @note Values and format depends on each language runtime, thus it is impossible to provide an exhaustive list of examples.\n * The values are usually the same (or prefixes of) the ones found in native stack trace representation stored in\n * `code.stacktrace` without information on arguments.\n *\n * Examples:\n *\n *   - Java method: `com.example.MyHttpService.serveRequest`\n *   - Java anonymous class method: `com.mycompany.Main$1.myMethod`\n *   - Java lambda method: `com.mycompany.Main$$Lambda/0x0000748ae4149c00.myMethod`\n *   - PHP function: `GuzzleHttp\\Client::transfer`\n *   - Go function: `github.com/my/repo/pkg.foo.func5`\n *   - Elixir: `OpenTelemetry.Ctx.new`\n *   - Erlang: `opentelemetry_ctx:new`\n *   - Rust: `playground::my_module::my_cool_func`\n *   - C function: `fopen`\n */\nexport const ATTR_CODE_FUNCTION_NAME = 'code.function.name' as const;\n\n/**\n * The line number in `code.file.path` best representing the operation. It **SHOULD** point within the code unit named in `code.function.name`. This attribute **MUST NOT** be used on the Profile signal since the data is already captured in 'message Line'. This constraint is imposed to prevent redundancy and maintain data integrity.\n *\n * @example 42\n */\nexport const ATTR_CODE_LINE_NUMBER = 'code.line.number' as const;\n\n/**\n * A stacktrace as a string in the natural representation for the language runtime. The representation is identical to [`exception.stacktrace`](/docs/exceptions/exceptions-spans.md#stacktrace-representation). This attribute **MUST NOT** be used on the Profile signal since the data is already captured in 'message Location'. This constraint is imposed to prevent redundancy and maintain data integrity.\n *\n * @example \"at com.example.GenerateTrace.methodB(GenerateTrace.java:13)\\\\n at com.example.GenerateTrace.methodA(GenerateTrace.java:9)\\\\n at com.example.GenerateTrace.main(GenerateTrace.java:5)\\\\n\"\n */\nexport const ATTR_CODE_STACKTRACE = 'code.stacktrace' as const;\n\n/**\n * The name of a collection (table, container) within the database.\n *\n * @example public.users\n * @example customers\n *\n * @note It is **RECOMMENDED** to capture the value as provided by the application\n * without attempting to do any case normalization.\n *\n * The collection name **SHOULD NOT** be extracted from `db.query.text`,\n * when the database system supports query text with multiple collections\n * in non-batch operations.\n *\n * For batch operations, if the individual operations are known to have the same\n * collection name then that collection name **SHOULD** be used.\n */\nexport const ATTR_DB_COLLECTION_NAME = 'db.collection.name' as const;\n\n/**\n * The name of the database, fully qualified within the server address and port.\n *\n * @example customers\n * @example test.users\n *\n * @note If a database system has multiple namespace components, they **SHOULD** be concatenated from the most general to the most specific namespace component, using `|` as a separator between the components. Any missing components (and their associated separators) **SHOULD** be omitted.\n * Semantic conventions for individual database systems **SHOULD** document what `db.namespace` means in the context of that system.\n * It is **RECOMMENDED** to capture the value as provided by the application without attempting to do any case normalization.\n */\nexport const ATTR_DB_NAMESPACE = 'db.namespace' as const;\n\n/**\n * The number of queries included in a batch operation.\n *\n * @example 2\n * @example 3\n * @example 4\n *\n * @note Operations are only considered batches when they contain two or more operations, and so `db.operation.batch.size` **SHOULD** never be `1`.\n */\nexport const ATTR_DB_OPERATION_BATCH_SIZE = 'db.operation.batch.size' as const;\n\n/**\n * The name of the operation or command being executed.\n *\n * @example findAndModify\n * @example HMSET\n * @example SELECT\n *\n * @note It is **RECOMMENDED** to capture the value as provided by the application\n * without attempting to do any case normalization.\n *\n * The operation name **SHOULD NOT** be extracted from `db.query.text`,\n * when the database system supports query text with multiple operations\n * in non-batch operations.\n *\n * If spaces can occur in the operation name, multiple consecutive spaces\n * **SHOULD** be normalized to a single space.\n *\n * For batch operations, if the individual operations are known to have the same operation name\n * then that operation name **SHOULD** be used prepended by `BATCH `,\n * otherwise `db.operation.name` **SHOULD** be `BATCH` or some other database\n * system specific term if more applicable.\n */\nexport const ATTR_DB_OPERATION_NAME = 'db.operation.name' as const;\n\n/**\n * Low cardinality summary of a database query.\n *\n * @example SELECT wuser_table\n * @example INSERT shipping_details SELECT orders\n * @example get user by id\n *\n * @note The query summary describes a class of database queries and is useful\n * as a grouping key, especially when analyzing telemetry for database\n * calls involving complex queries.\n *\n * Summary may be available to the instrumentation through\n * instrumentation hooks or other means. If it is not available, instrumentations\n * that support query parsing **SHOULD** generate a summary following\n * [Generating query summary](/docs/db/database-spans.md#generating-a-summary-of-the-query)\n * section.\n *\n * For batch operations, if the individual operations are known to have the same query summary\n * then that query summary **SHOULD** be used prepended by `BATCH `,\n * otherwise `db.query.summary` **SHOULD** be `BATCH` or some other database\n * system specific term if more applicable.\n */\nexport const ATTR_DB_QUERY_SUMMARY = 'db.query.summary' as const;\n\n/**\n * The database query being executed.\n *\n * @example SELECT * FROM wuser_table where username = ?\n * @example SET mykey ?\n *\n * @note For sanitization see [Sanitization of `db.query.text`](/docs/db/database-spans.md#sanitization-of-dbquerytext).\n * For batch operations, if the individual operations are known to have the same query text then that query text **SHOULD** be used, otherwise all of the individual query texts **SHOULD** be concatenated with separator `; ` or some other database system specific separator if more applicable.\n * Parameterized query text **SHOULD NOT** be sanitized. Even though parameterized query text can potentially have sensitive data, by using a parameterized query the user is giving a strong signal that any sensitive data will be passed as parameter values, and the benefit to observability of capturing the static part of the query text by default outweighs the risk.\n */\nexport const ATTR_DB_QUERY_TEXT = 'db.query.text' as const;\n\n/**\n * Database response status code.\n *\n * @example 102\n * @example ORA-17002\n * @example 08P01\n * @example 404\n *\n * @note The status code returned by the database. Usually it represents an error code, but may also represent partial success, warning, or differentiate between various types of successful outcomes.\n * Semantic conventions for individual database systems **SHOULD** document what `db.response.status_code` means in the context of that system.\n */\nexport const ATTR_DB_RESPONSE_STATUS_CODE = 'db.response.status_code' as const;\n\n/**\n * The name of a stored procedure within the database.\n *\n * @example GetCustomer\n *\n * @note It is **RECOMMENDED** to capture the value as provided by the application\n * without attempting to do any case normalization.\n *\n * For batch operations, if the individual operations are known to have the same\n * stored procedure name then that stored procedure name **SHOULD** be used.\n */\nexport const ATTR_DB_STORED_PROCEDURE_NAME = 'db.stored_procedure.name' as const;\n\n/**\n * The database management system (DBMS) product as identified by the client instrumentation.\n *\n * @note The actual DBMS may differ from the one identified by the client. For example, when using PostgreSQL client libraries to connect to a CockroachDB, the `db.system.name` is set to `postgresql` based on the instrumentation's best knowledge.\n */\nexport const ATTR_DB_SYSTEM_NAME = 'db.system.name' as const;\n\n/**\n * Enum value \"mariadb\" for attribute {@link ATTR_DB_SYSTEM_NAME}.\n *\n * [MariaDB](https://mariadb.org/)\n */\nexport const DB_SYSTEM_NAME_VALUE_MARIADB = \"mariadb\" as const;\n\n/**\n * Enum value \"microsoft.sql_server\" for attribute {@link ATTR_DB_SYSTEM_NAME}.\n *\n * [Microsoft SQL Server](https://www.microsoft.com/sql-server)\n */\nexport const DB_SYSTEM_NAME_VALUE_MICROSOFT_SQL_SERVER = \"microsoft.sql_server\" as const;\n\n/**\n * Enum value \"mysql\" for attribute {@link ATTR_DB_SYSTEM_NAME}.\n *\n * [MySQL](https://www.mysql.com/)\n */\nexport const DB_SYSTEM_NAME_VALUE_MYSQL = \"mysql\" as const;\n\n/**\n * Enum value \"postgresql\" for attribute {@link ATTR_DB_SYSTEM_NAME}.\n *\n * [PostgreSQL](https://www.postgresql.org/)\n */\nexport const DB_SYSTEM_NAME_VALUE_POSTGRESQL = \"postgresql\" as const;\n\n/**\n * Name of the [deployment environment](https://wikipedia.org/wiki/Deployment_environment) (aka deployment tier).\n *\n * @example staging\n * @example production\n *\n * @note `deployment.environment.name` does not affect the uniqueness constraints defined through\n * the `service.namespace`, `service.name` and `service.instance.id` resource attributes.\n * This implies that resources carrying the following attribute combinations **MUST** be\n * considered to be identifying the same service:\n *\n *   - `service.name=frontend`, `deployment.environment.name=production`\n *   - `service.name=frontend`, `deployment.environment.name=staging`.\n */\nexport const ATTR_DEPLOYMENT_ENVIRONMENT_NAME = 'deployment.environment.name' as const;\n\n/**\n * Enum value \"development\" for attribute {@link ATTR_DEPLOYMENT_ENVIRONMENT_NAME}.\n *\n * Development environment\n */\nexport const DEPLOYMENT_ENVIRONMENT_NAME_VALUE_DEVELOPMENT = \"development\" as const;\n\n/**\n * Enum value \"production\" for attribute {@link ATTR_DEPLOYMENT_ENVIRONMENT_NAME}.\n *\n * Production environment\n */\nexport const DEPLOYMENT_ENVIRONMENT_NAME_VALUE_PRODUCTION = \"production\" as const;\n\n/**\n * Enum value \"staging\" for attribute {@link ATTR_DEPLOYMENT_ENVIRONMENT_NAME}.\n *\n * Staging environment\n */\nexport const DEPLOYMENT_ENVIRONMENT_NAME_VALUE_STAGING = \"staging\" as const;\n\n/**\n * Enum value \"test\" for attribute {@link ATTR_DEPLOYMENT_ENVIRONMENT_NAME}.\n *\n * Testing environment\n */\nexport const DEPLOYMENT_ENVIRONMENT_NAME_VALUE_TEST = \"test\" as const;\n\n/**\n * Name of the garbage collector managed heap generation.\n *\n * @example gen0\n * @example gen1\n * @example gen2\n */\nexport const ATTR_DOTNET_GC_HEAP_GENERATION = 'dotnet.gc.heap.generation' as const;\n\n/**\n * Enum value \"gen0\" for attribute {@link ATTR_DOTNET_GC_HEAP_GENERATION}.\n *\n * Generation 0\n */\nexport const DOTNET_GC_HEAP_GENERATION_VALUE_GEN0 = \"gen0\" as const;\n\n/**\n * Enum value \"gen1\" for attribute {@link ATTR_DOTNET_GC_HEAP_GENERATION}.\n *\n * Generation 1\n */\nexport const DOTNET_GC_HEAP_GENERATION_VALUE_GEN1 = \"gen1\" as const;\n\n/**\n * Enum value \"gen2\" for attribute {@link ATTR_DOTNET_GC_HEAP_GENERATION}.\n *\n * Generation 2\n */\nexport const DOTNET_GC_HEAP_GENERATION_VALUE_GEN2 = \"gen2\" as const;\n\n/**\n * Enum value \"loh\" for attribute {@link ATTR_DOTNET_GC_HEAP_GENERATION}.\n *\n * Large Object Heap\n */\nexport const DOTNET_GC_HEAP_GENERATION_VALUE_LOH = \"loh\" as const;\n\n/**\n * Enum value \"poh\" for attribute {@link ATTR_DOTNET_GC_HEAP_GENERATION}.\n *\n * Pinned Object Heap\n */\nexport const DOTNET_GC_HEAP_GENERATION_VALUE_POH = \"poh\" as const;\n\n/**\n * Describes a class of error the operation ended with.\n *\n * @example timeout\n * @example java.net.UnknownHostException\n * @example server_certificate_invalid\n * @example 500\n *\n * @note The `error.type` **SHOULD** be predictable, and **SHOULD** have low cardinality.\n *\n * When `error.type` is set to a type (e.g., an exception type), its\n * canonical class name identifying the type within the artifact **SHOULD** be used.\n *\n * If the recorded error type is a wrapper that is not meaningful for\n * failure classification, instrumentation **MAY** use the type of the inner\n * error instead. For example, in Go, errors created with `fmt.Errorf`\n * using `%w` **MAY** be unwrapped when the wrapper type does not help\n * classify the failure.\n *\n * Instrumentations **SHOULD** document the list of errors they report.\n *\n * The cardinality of `error.type` within one instrumentation library **SHOULD** be low.\n * Telemetry consumers that aggregate data from multiple instrumentation libraries and applications\n * should be prepared for `error.type` to have high cardinality at query time when no\n * additional filters are applied.\n *\n * If the operation has completed successfully, instrumentations **SHOULD NOT** set `error.type`.\n *\n * If a specific domain defines its own set of error identifiers (such as HTTP or RPC status codes),\n * it's **RECOMMENDED** to:\n *\n *   - Use a domain-specific attribute\n *   - Set `error.type` to capture all errors, regardless of whether they are defined within the domain-specific set or not.\n */\nexport const ATTR_ERROR_TYPE = 'error.type' as const;\n\n/**\n * Enum value \"_OTHER\" for attribute {@link ATTR_ERROR_TYPE}.\n *\n * A fallback error value to be used when the instrumentation doesn't define a custom value.\n */\nexport const ERROR_TYPE_VALUE_OTHER = \"_OTHER\" as const;\n\n/**\n * Indicates that the exception is escaping the scope of the span.\n *\n * @deprecated It's no longer recommended to record exceptions that are handled and do not escape the scope of a span.\n */\nexport const ATTR_EXCEPTION_ESCAPED = 'exception.escaped' as const;\n\n/**\n * The exception message.\n *\n * @example Division by zero\n * @example Can't convert 'int' object to str implicitly\n *\n * @note > [!WARNING]\n *\n * > This attribute may contain sensitive information.\n */\nexport const ATTR_EXCEPTION_MESSAGE = 'exception.message' as const;\n\n/**\n * A stacktrace as a string in the natural representation for the language runtime. The representation is to be determined and documented by each language SIG.\n *\n * @example \"Exception in thread \"main\" java.lang.RuntimeException: Test exception\\\\n at com.example.GenerateTrace.methodB(GenerateTrace.java:13)\\\\n at com.example.GenerateTrace.methodA(GenerateTrace.java:9)\\\\n at com.example.GenerateTrace.main(GenerateTrace.java:5)\\\\n\"\n */\nexport const ATTR_EXCEPTION_STACKTRACE = 'exception.stacktrace' as const;\n\n/**\n * The type of the exception (its fully-qualified class name, if applicable). The dynamic type of the exception should be preferred over the static type in languages that support it.\n *\n * @example java.net.ConnectException\n * @example OSError\n *\n * @note If the recorded exception type is a wrapper that is not meaningful for\n * failure classification, instrumentation **MAY** use the type of the inner\n * exception instead. For example, in Go, errors created with `fmt.Errorf`\n * using `%w` **MAY** be unwrapped when the wrapper type does not help\n * classify the failure.\n */\nexport const ATTR_EXCEPTION_TYPE = 'exception.type' as const;\n\n/**\n * HTTP request headers, `<key>` being the normalized HTTP Header name (lowercase), the value being the header values.\n *\n * @example [\"application/json\"]\n * @example [\"1.2.3.4\", \"1.2.3.5\"]\n *\n * @note Instrumentations **SHOULD** require an explicit configuration of which headers are to be captured.\n * Including all request headers can be a security risk - explicit configuration helps avoid leaking sensitive information.\n *\n * The `User-Agent` header is already captured in the `user_agent.original` attribute.\n * Users **MAY** explicitly configure instrumentations to capture them even though it is not recommended.\n *\n * The attribute value **MUST** consist of either multiple header values as an array of strings\n * or a single-item array containing a possibly comma-concatenated string, depending on the way\n * the HTTP library provides access to headers.\n *\n * Examples:\n *\n *   - A header `Content-Type: application/json` **SHOULD** be recorded as the `http.request.header.content-type`\n *     attribute with value `[\"application/json\"]`.\n *   - A header `X-Forwarded-For: 1.2.3.4, 1.2.3.5` **SHOULD** be recorded as the `http.request.header.x-forwarded-for`\n *     attribute with value `[\"1.2.3.4\", \"1.2.3.5\"]` or `[\"1.2.3.4, 1.2.3.5\"]` depending on the HTTP library.\n */\nexport const ATTR_HTTP_REQUEST_HEADER = (key: string) => `http.request.header.${key}`;\n\n/**\n * HTTP request method.\n *\n * @example GET\n * @example POST\n * @example HEAD\n *\n * @note HTTP request method value **SHOULD** be \"known\" to the instrumentation.\n * By default, this convention defines \"known\" methods as the ones listed in [RFC9110](https://www.rfc-editor.org/rfc/rfc9110.html#name-methods),\n * the PATCH method defined in [RFC5789](https://www.rfc-editor.org/rfc/rfc5789.html)\n * and the QUERY method defined in [httpbis-safe-method-w-body](https://datatracker.ietf.org/doc/draft-ietf-httpbis-safe-method-w-body/?include_text=1).\n *\n * If the HTTP request method is not known to instrumentation, it **MUST** set the `http.request.method` attribute to `_OTHER`.\n *\n * If the HTTP instrumentation could end up converting valid HTTP request methods to `_OTHER`, then it **MUST** provide a way to override\n * the list of known HTTP methods. If this override is done via environment variable, then the environment variable **MUST** be named\n * OTEL_INSTRUMENTATION_HTTP_KNOWN_METHODS and support a comma-separated list of case-sensitive known HTTP methods.\n *\n *\n * If this override is done via declarative configuration, then the list **MUST** be configurable via the `known_methods` property\n * (an array of case-sensitive strings with minimum items 0) under `.instrumentation/development.general.http.client` and/or\n * `.instrumentation/development.general.http.server`.\n *\n * In either case, this list **MUST** be a full override of the default known methods,\n * it is not a list of known methods in addition to the defaults.\n *\n * HTTP method names are case-sensitive and `http.request.method` attribute value **MUST** match a known HTTP method name exactly.\n * Instrumentations for specific web frameworks that consider HTTP methods to be case insensitive, **SHOULD** populate a canonical equivalent.\n * Tracing instrumentations that do so, **MUST** also set `http.request.method_original` to the original value.\n */\nexport const ATTR_HTTP_REQUEST_METHOD = 'http.request.method' as const;\n\n/**\n * Enum value \"_OTHER\" for attribute {@link ATTR_HTTP_REQUEST_METHOD}.\n *\n * Any HTTP method that the instrumentation has no prior knowledge of.\n */\nexport const HTTP_REQUEST_METHOD_VALUE_OTHER = \"_OTHER\" as const;\n\n/**\n * Enum value \"CONNECT\" for attribute {@link ATTR_HTTP_REQUEST_METHOD}.\n *\n * CONNECT method.\n */\nexport const HTTP_REQUEST_METHOD_VALUE_CONNECT = \"CONNECT\" as const;\n\n/**\n * Enum value \"DELETE\" for attribute {@link ATTR_HTTP_REQUEST_METHOD}.\n *\n * DELETE method.\n */\nexport const HTTP_REQUEST_METHOD_VALUE_DELETE = \"DELETE\" as const;\n\n/**\n * Enum value \"GET\" for attribute {@link ATTR_HTTP_REQUEST_METHOD}.\n *\n * GET method.\n */\nexport const HTTP_REQUEST_METHOD_VALUE_GET = \"GET\" as const;\n\n/**\n * Enum value \"HEAD\" for attribute {@link ATTR_HTTP_REQUEST_METHOD}.\n *\n * HEAD method.\n */\nexport const HTTP_REQUEST_METHOD_VALUE_HEAD = \"HEAD\" as const;\n\n/**\n * Enum value \"OPTIONS\" for attribute {@link ATTR_HTTP_REQUEST_METHOD}.\n *\n * OPTIONS method.\n */\nexport const HTTP_REQUEST_METHOD_VALUE_OPTIONS = \"OPTIONS\" as const;\n\n/**\n * Enum value \"PATCH\" for attribute {@link ATTR_HTTP_REQUEST_METHOD}.\n *\n * PATCH method.\n */\nexport const HTTP_REQUEST_METHOD_VALUE_PATCH = \"PATCH\" as const;\n\n/**\n * Enum value \"POST\" for attribute {@link ATTR_HTTP_REQUEST_METHOD}.\n *\n * POST method.\n */\nexport const HTTP_REQUEST_METHOD_VALUE_POST = \"POST\" as const;\n\n/**\n * Enum value \"PUT\" for attribute {@link ATTR_HTTP_REQUEST_METHOD}.\n *\n * PUT method.\n */\nexport const HTTP_REQUEST_METHOD_VALUE_PUT = \"PUT\" as const;\n\n/**\n * Enum value \"TRACE\" for attribute {@link ATTR_HTTP_REQUEST_METHOD}.\n *\n * TRACE method.\n */\nexport const HTTP_REQUEST_METHOD_VALUE_TRACE = \"TRACE\" as const;\n\n/**\n * Original HTTP method sent by the client in the request line.\n *\n * @example GeT\n * @example ACL\n * @example foo\n */\nexport const ATTR_HTTP_REQUEST_METHOD_ORIGINAL = 'http.request.method_original' as const;\n\n/**\n * The ordinal number of request resending attempt (for any reason, including redirects).\n *\n * @example 3\n *\n * @note The resend count **SHOULD** be updated each time an HTTP request gets resent by the client, regardless of what was the cause of the resending (e.g. redirection, authorization failure, 503 Server Unavailable, network issues, or any other).\n */\nexport const ATTR_HTTP_REQUEST_RESEND_COUNT = 'http.request.resend_count' as const;\n\n/**\n * HTTP response headers, `<key>` being the normalized HTTP Header name (lowercase), the value being the header values.\n *\n * @example [\"application/json\"]\n * @example [\"abc\", \"def\"]\n *\n * @note Instrumentations **SHOULD** require an explicit configuration of which headers are to be captured.\n * Including all response headers can be a security risk - explicit configuration helps avoid leaking sensitive information.\n *\n * Users **MAY** explicitly configure instrumentations to capture them even though it is not recommended.\n *\n * The attribute value **MUST** consist of either multiple header values as an array of strings\n * or a single-item array containing a possibly comma-concatenated string, depending on the way\n * the HTTP library provides access to headers.\n *\n * Examples:\n *\n *   - A header `Content-Type: application/json` header **SHOULD** be recorded as the `http.request.response.content-type`\n *     attribute with value `[\"application/json\"]`.\n *   - A header `My-custom-header: abc, def` header **SHOULD** be recorded as the `http.response.header.my-custom-header`\n *     attribute with value `[\"abc\", \"def\"]` or `[\"abc, def\"]` depending on the HTTP library.\n */\nexport const ATTR_HTTP_RESPONSE_HEADER = (key: string) => `http.response.header.${key}`;\n\n/**\n * [HTTP response status code](https://tools.ietf.org/html/rfc7231#section-6).\n *\n * @example 200\n */\nexport const ATTR_HTTP_RESPONSE_STATUS_CODE = 'http.response.status_code' as const;\n\n/**\n * The matched route template for the request. This **MUST** be low-cardinality and include all static path segments, with dynamic path segments represented with placeholders.\n *\n * @example /users/:userID?\n * @example my-controller/my-action/{id?}\n *\n * @note **MUST NOT** be populated when this is not supported by the HTTP server framework as the route attribute should have low-cardinality and the URI path can NOT substitute it.\n * **SHOULD** include the [application root](/docs/http/http-spans.md#http-server-definitions) if there is one.\n *\n * A static path segment is a part of the route template with a fixed, low-cardinality value. This includes literal strings like `/users/` and placeholders that\n * are constrained to a finite, predefined set of values, e.g. `{controller}` or `{action}`.\n *\n * A dynamic path segment is a placeholder for a value that can have high cardinality and is not constrained to a predefined list like static path segments.\n *\n * Instrumentations **SHOULD** use routing information provided by the corresponding web framework. They **SHOULD** pick the most precise source of routing information and **MAY**\n * support custom route formatting. Instrumentations **SHOULD** document the format and the API used to obtain the route string.\n */\nexport const ATTR_HTTP_ROUTE = 'http.route' as const;\n\n/**\n * Name of the garbage collector action.\n *\n * @example end of minor GC\n * @example end of major GC\n *\n * @note Garbage collector action is generally obtained via [GarbageCollectionNotificationInfo#getGcAction()](https://docs.oracle.com/en/java/javase/11/docs/api/jdk.management/com/sun/management/GarbageCollectionNotificationInfo.html#getGcAction()).\n */\nexport const ATTR_JVM_GC_ACTION = 'jvm.gc.action' as const;\n\n/**\n * Name of the garbage collector.\n *\n * @example G1 Young Generation\n * @example G1 Old Generation\n *\n * @note Garbage collector name is generally obtained via [GarbageCollectionNotificationInfo#getGcName()](https://docs.oracle.com/en/java/javase/11/docs/api/jdk.management/com/sun/management/GarbageCollectionNotificationInfo.html#getGcName()).\n */\nexport const ATTR_JVM_GC_NAME = 'jvm.gc.name' as const;\n\n/**\n * Name of the memory pool.\n *\n * @example G1 Old Gen\n * @example G1 Eden space\n * @example G1 Survivor Space\n *\n * @note Pool names are generally obtained via [MemoryPoolMXBean#getName()](https://docs.oracle.com/en/java/javase/11/docs/api/java.management/java/lang/management/MemoryPoolMXBean.html#getName()).\n */\nexport const ATTR_JVM_MEMORY_POOL_NAME = 'jvm.memory.pool.name' as const;\n\n/**\n * The type of memory.\n *\n * @example heap\n * @example non_heap\n */\nexport const ATTR_JVM_MEMORY_TYPE = 'jvm.memory.type' as const;\n\n/**\n * Enum value \"heap\" for attribute {@link ATTR_JVM_MEMORY_TYPE}.\n *\n * Heap memory.\n */\nexport const JVM_MEMORY_TYPE_VALUE_HEAP = \"heap\" as const;\n\n/**\n * Enum value \"non_heap\" for attribute {@link ATTR_JVM_MEMORY_TYPE}.\n *\n * Non-heap memory\n */\nexport const JVM_MEMORY_TYPE_VALUE_NON_HEAP = \"non_heap\" as const;\n\n/**\n * Whether the thread is daemon or not.\n */\nexport const ATTR_JVM_THREAD_DAEMON = 'jvm.thread.daemon' as const;\n\n/**\n * State of the thread.\n *\n * @example runnable\n * @example blocked\n */\nexport const ATTR_JVM_THREAD_STATE = 'jvm.thread.state' as const;\n\n/**\n * Enum value \"blocked\" for attribute {@link ATTR_JVM_THREAD_STATE}.\n *\n * A thread that is blocked waiting for a monitor lock is in this state.\n */\nexport const JVM_THREAD_STATE_VALUE_BLOCKED = \"blocked\" as const;\n\n/**\n * Enum value \"new\" for attribute {@link ATTR_JVM_THREAD_STATE}.\n *\n * A thread that has not yet started is in this state.\n */\nexport const JVM_THREAD_STATE_VALUE_NEW = \"new\" as const;\n\n/**\n * Enum value \"runnable\" for attribute {@link ATTR_JVM_THREAD_STATE}.\n *\n * A thread executing in the Java virtual machine is in this state.\n */\nexport const JVM_THREAD_STATE_VALUE_RUNNABLE = \"runnable\" as const;\n\n/**\n * Enum value \"terminated\" for attribute {@link ATTR_JVM_THREAD_STATE}.\n *\n * A thread that has exited is in this state.\n */\nexport const JVM_THREAD_STATE_VALUE_TERMINATED = \"terminated\" as const;\n\n/**\n * Enum value \"timed_waiting\" for attribute {@link ATTR_JVM_THREAD_STATE}.\n *\n * A thread that is waiting for another thread to perform an action for up to a specified waiting time is in this state.\n */\nexport const JVM_THREAD_STATE_VALUE_TIMED_WAITING = \"timed_waiting\" as const;\n\n/**\n * Enum value \"waiting\" for attribute {@link ATTR_JVM_THREAD_STATE}.\n *\n * A thread that is waiting indefinitely for another thread to perform a particular action is in this state.\n */\nexport const JVM_THREAD_STATE_VALUE_WAITING = \"waiting\" as const;\n\n/**\n * Local address of the network connection - IP address or Unix domain socket name.\n *\n * @example 10.1.2.80\n * @example /tmp/my.sock\n */\nexport const ATTR_NETWORK_LOCAL_ADDRESS = 'network.local.address' as const;\n\n/**\n * Local port number of the network connection.\n *\n * @example 65123\n */\nexport const ATTR_NETWORK_LOCAL_PORT = 'network.local.port' as const;\n\n/**\n * Peer address of the network connection - IP address or Unix domain socket name.\n *\n * @example 10.1.2.80\n * @example /tmp/my.sock\n */\nexport const ATTR_NETWORK_PEER_ADDRESS = 'network.peer.address' as const;\n\n/**\n * Peer port number of the network connection.\n *\n * @example 65123\n */\nexport const ATTR_NETWORK_PEER_PORT = 'network.peer.port' as const;\n\n/**\n * [OSI application layer](https://wikipedia.org/wiki/Application_layer) or non-OSI equivalent.\n *\n * @example amqp\n * @example http\n * @example mqtt\n *\n * @note The value **SHOULD** be normalized to lowercase.\n */\nexport const ATTR_NETWORK_PROTOCOL_NAME = 'network.protocol.name' as const;\n\n/**\n * The actual version of the protocol used for network communication.\n *\n * @example 1.1\n * @example 2\n *\n * @note If protocol version is subject to negotiation (for example using [ALPN](https://www.rfc-editor.org/rfc/rfc7301.html)), this attribute **SHOULD** be set to the negotiated version. If the actual protocol version is not known, this attribute **SHOULD NOT** be set.\n */\nexport const ATTR_NETWORK_PROTOCOL_VERSION = 'network.protocol.version' as const;\n\n/**\n * [OSI transport layer](https://wikipedia.org/wiki/Transport_layer) or [inter-process communication method](https://wikipedia.org/wiki/Inter-process_communication).\n *\n * @example tcp\n * @example udp\n *\n * @note The value **SHOULD** be normalized to lowercase.\n *\n * Consider always setting the transport when setting a port number, since\n * a port number is ambiguous without knowing the transport. For example\n * different processes could be listening on TCP port 12345 and UDP port 12345.\n */\nexport const ATTR_NETWORK_TRANSPORT = 'network.transport' as const;\n\n/**\n * Enum value \"pipe\" for attribute {@link ATTR_NETWORK_TRANSPORT}.\n *\n * Named or anonymous pipe.\n */\nexport const NETWORK_TRANSPORT_VALUE_PIPE = \"pipe\" as const;\n\n/**\n * Enum value \"quic\" for attribute {@link ATTR_NETWORK_TRANSPORT}.\n *\n * QUIC\n */\nexport const NETWORK_TRANSPORT_VALUE_QUIC = \"quic\" as const;\n\n/**\n * Enum value \"tcp\" for attribute {@link ATTR_NETWORK_TRANSPORT}.\n *\n * TCP\n */\nexport const NETWORK_TRANSPORT_VALUE_TCP = \"tcp\" as const;\n\n/**\n * Enum value \"udp\" for attribute {@link ATTR_NETWORK_TRANSPORT}.\n *\n * UDP\n */\nexport const NETWORK_TRANSPORT_VALUE_UDP = \"udp\" as const;\n\n/**\n * Enum value \"unix\" for attribute {@link ATTR_NETWORK_TRANSPORT}.\n *\n * Unix domain socket\n */\nexport const NETWORK_TRANSPORT_VALUE_UNIX = \"unix\" as const;\n\n/**\n * [OSI network layer](https://wikipedia.org/wiki/Network_layer) or non-OSI equivalent.\n *\n * @example ipv4\n * @example ipv6\n *\n * @note The value **SHOULD** be normalized to lowercase.\n */\nexport const ATTR_NETWORK_TYPE = 'network.type' as const;\n\n/**\n * Enum value \"ipv4\" for attribute {@link ATTR_NETWORK_TYPE}.\n *\n * IPv4\n */\nexport const NETWORK_TYPE_VALUE_IPV4 = \"ipv4\" as const;\n\n/**\n * Enum value \"ipv6\" for attribute {@link ATTR_NETWORK_TYPE}.\n *\n * IPv6\n */\nexport const NETWORK_TYPE_VALUE_IPV6 = \"ipv6\" as const;\n\n/**\n * Identifies the class / type of event.\n *\n * @example browser.mouse.click\n * @example device.app.lifecycle\n *\n * @note This attribute **SHOULD** be used by non-OTLP exporters when destination does not support `EventName` or equivalent field. This attribute **MAY** be used by applications using existing logging libraries so that it can be used to set the `EventName` field by Collector or SDK components.\n */\nexport const ATTR_OTEL_EVENT_NAME = 'otel.event.name' as const;\n\n/**\n * The name of the instrumentation scope - (`InstrumentationScope.Name` in OTLP).\n *\n * @example io.opentelemetry.contrib.mongodb\n */\nexport const ATTR_OTEL_SCOPE_NAME = 'otel.scope.name' as const;\n\n/**\n * The version of the instrumentation scope - (`InstrumentationScope.Version` in OTLP).\n *\n * @example 1.0.0\n */\nexport const ATTR_OTEL_SCOPE_VERSION = 'otel.scope.version' as const;\n\n/**\n * Name of the code, either \"OK\" or \"ERROR\". **MUST NOT** be set if the status code is UNSET.\n */\nexport const ATTR_OTEL_STATUS_CODE = 'otel.status_code' as const;\n\n/**\n * Enum value \"ERROR\" for attribute {@link ATTR_OTEL_STATUS_CODE}.\n *\n * The operation contains an error.\n */\nexport const OTEL_STATUS_CODE_VALUE_ERROR = \"ERROR\" as const;\n\n/**\n * Enum value \"OK\" for attribute {@link ATTR_OTEL_STATUS_CODE}.\n *\n * The operation has been validated by an Application developer or Operator to have completed successfully.\n */\nexport const OTEL_STATUS_CODE_VALUE_OK = \"OK\" as const;\n\n/**\n * Description of the Status if it has a value, otherwise not set.\n *\n * @example resource not found\n */\nexport const ATTR_OTEL_STATUS_DESCRIPTION = 'otel.status_description' as const;\n\n/**\n * Server domain name if available without reverse DNS lookup; otherwise, IP address or Unix domain socket name.\n *\n * @example example.com\n * @example 10.1.2.80\n * @example /tmp/my.sock\n *\n * @note When observed from the client side, and when communicating through an intermediary, `server.address` **SHOULD** represent the server address behind any intermediaries, for example proxies, if it's available.\n */\nexport const ATTR_SERVER_ADDRESS = 'server.address' as const;\n\n/**\n * Server port number.\n *\n * @example 80\n * @example 8080\n * @example 443\n *\n * @note When observed from the client side, and when communicating through an intermediary, `server.port` **SHOULD** represent the server port behind any intermediaries, for example proxies, if it's available.\n */\nexport const ATTR_SERVER_PORT = 'server.port' as const;\n\n/**\n * The string ID of the service instance.\n *\n * @example 627cc493-f310-47de-96bd-71410b7dec09\n *\n * @note **MUST** be unique for each instance of the same `service.namespace,service.name` pair (in other words\n * `service.namespace,service.name,service.instance.id` triplet **MUST** be globally unique). The ID helps to\n * distinguish instances of the same service that exist at the same time (e.g. instances of a horizontally scaled\n * service).\n *\n * Implementations, such as SDKs, are recommended to generate a random Version 1 or Version 4 [RFC\n * 4122](https://www.ietf.org/rfc/rfc4122.txt) UUID, but are free to use an inherent unique ID as the source of\n * this value if stability is desirable. In that case, the ID **SHOULD** be used as source of a UUID Version 5 and\n * **SHOULD** use the following UUID as the namespace: `4d63009a-8d0f-11ee-aad7-4c796ed8e320`.\n *\n * UUIDs are typically recommended, as only an opaque value for the purposes of identifying a service instance is\n * needed. Similar to what can be seen in the man page for the\n * [`/etc/machine-id`](https://www.freedesktop.org/software/systemd/man/latest/machine-id.html) file, the underlying\n * data, such as pod name and namespace should be treated as confidential, being the user's choice to expose it\n * or not via another resource attribute.\n *\n * For applications running behind an application server (like unicorn), we do not recommend using one identifier\n * for all processes participating in the application. Instead, it's recommended each division (e.g. a worker\n * thread in unicorn) to have its own instance.id.\n *\n * It's not recommended for a Collector to set `service.instance.id` if it can't unambiguously determine the\n * service instance that is generating that telemetry. For instance, creating an UUID based on `pod.name` will\n * likely be wrong, as the Collector might not know from which container within that pod the telemetry originated.\n * However, Collectors can set the `service.instance.id` if they can unambiguously determine the service instance\n * for that telemetry. This is typically the case for scraping receivers, as they know the target address and\n * port.\n */\nexport const ATTR_SERVICE_INSTANCE_ID = 'service.instance.id' as const;\n\n/**\n * Logical name of the service.\n *\n * @example shoppingcart\n *\n * @note **MUST** be the same for all instances of horizontally scaled services. If the value was not specified, SDKs **MUST** fallback to `unknown_service:` concatenated with the process executable name, e.g. `unknown_service:bash`. If the process executable name is not available, the value **MUST** be set to `unknown_service`.\n * The process executable name is the name of the process executable, the same value as described by the [`process.executable.name`](process.md) resource attribute.\n */\nexport const ATTR_SERVICE_NAME = 'service.name' as const;\n\n/**\n * A namespace for `service.name`.\n *\n * @example Shop\n *\n * @note A string value having a meaning that helps to distinguish a group of services, for example the team name that owns a group of services. `service.name` is expected to be unique within the same namespace. If `service.namespace` is not specified in the Resource then `service.name` is expected to be unique for all services that have no explicit namespace defined (so the empty/unspecified namespace is simply one more valid namespace). Zero-length namespace string is assumed equal to unspecified namespace.\n */\nexport const ATTR_SERVICE_NAMESPACE = 'service.namespace' as const;\n\n/**\n * The version string of the service component. The format is not defined by these conventions.\n *\n * @example 2.0.0\n * @example a01dbef8a\n */\nexport const ATTR_SERVICE_VERSION = 'service.version' as const;\n\n/**\n * SignalR HTTP connection closure status.\n *\n * @example app_shutdown\n * @example timeout\n */\nexport const ATTR_SIGNALR_CONNECTION_STATUS = 'signalr.connection.status' as const;\n\n/**\n * Enum value \"app_shutdown\" for attribute {@link ATTR_SIGNALR_CONNECTION_STATUS}.\n *\n * The connection was closed because the app is shutting down.\n */\nexport const SIGNALR_CONNECTION_STATUS_VALUE_APP_SHUTDOWN = \"app_shutdown\" as const;\n\n/**\n * Enum value \"normal_closure\" for attribute {@link ATTR_SIGNALR_CONNECTION_STATUS}.\n *\n * The connection was closed normally.\n */\nexport const SIGNALR_CONNECTION_STATUS_VALUE_NORMAL_CLOSURE = \"normal_closure\" as const;\n\n/**\n * Enum value \"timeout\" for attribute {@link ATTR_SIGNALR_CONNECTION_STATUS}.\n *\n * The connection was closed due to a timeout.\n */\nexport const SIGNALR_CONNECTION_STATUS_VALUE_TIMEOUT = \"timeout\" as const;\n\n/**\n * [SignalR transport type](https://github.com/dotnet/aspnetcore/blob/main/src/SignalR/docs/specs/TransportProtocols.md)\n *\n * @example web_sockets\n * @example long_polling\n */\nexport const ATTR_SIGNALR_TRANSPORT = 'signalr.transport' as const;\n\n/**\n * Enum value \"long_polling\" for attribute {@link ATTR_SIGNALR_TRANSPORT}.\n *\n * LongPolling protocol\n */\nexport const SIGNALR_TRANSPORT_VALUE_LONG_POLLING = \"long_polling\" as const;\n\n/**\n * Enum value \"server_sent_events\" for attribute {@link ATTR_SIGNALR_TRANSPORT}.\n *\n * ServerSentEvents protocol\n */\nexport const SIGNALR_TRANSPORT_VALUE_SERVER_SENT_EVENTS = \"server_sent_events\" as const;\n\n/**\n * Enum value \"web_sockets\" for attribute {@link ATTR_SIGNALR_TRANSPORT}.\n *\n * WebSockets protocol\n */\nexport const SIGNALR_TRANSPORT_VALUE_WEB_SOCKETS = \"web_sockets\" as const;\n\n/**\n * The name of the auto instrumentation agent or distribution, if used.\n *\n * @example parts-unlimited-java\n *\n * @note Official auto instrumentation agents and distributions **SHOULD** set the `telemetry.distro.name` attribute to\n * a string starting with `opentelemetry-`, e.g. `opentelemetry-java-instrumentation`.\n */\nexport const ATTR_TELEMETRY_DISTRO_NAME = 'telemetry.distro.name' as const;\n\n/**\n * The version string of the auto instrumentation agent or distribution, if used.\n *\n * @example 1.2.3\n */\nexport const ATTR_TELEMETRY_DISTRO_VERSION = 'telemetry.distro.version' as const;\n\n/**\n * The language of the telemetry SDK.\n */\nexport const ATTR_TELEMETRY_SDK_LANGUAGE = 'telemetry.sdk.language' as const;\n\n/**\n * Enum value \"cpp\" for attribute {@link ATTR_TELEMETRY_SDK_LANGUAGE}.\n */\nexport const TELEMETRY_SDK_LANGUAGE_VALUE_CPP = \"cpp\" as const;\n\n/**\n * Enum value \"dotnet\" for attribute {@link ATTR_TELEMETRY_SDK_LANGUAGE}.\n */\nexport const TELEMETRY_SDK_LANGUAGE_VALUE_DOTNET = \"dotnet\" as const;\n\n/**\n * Enum value \"erlang\" for attribute {@link ATTR_TELEMETRY_SDK_LANGUAGE}.\n */\nexport const TELEMETRY_SDK_LANGUAGE_VALUE_ERLANG = \"erlang\" as const;\n\n/**\n * Enum value \"go\" for attribute {@link ATTR_TELEMETRY_SDK_LANGUAGE}.\n */\nexport const TELEMETRY_SDK_LANGUAGE_VALUE_GO = \"go\" as const;\n\n/**\n * Enum value \"java\" for attribute {@link ATTR_TELEMETRY_SDK_LANGUAGE}.\n */\nexport const TELEMETRY_SDK_LANGUAGE_VALUE_JAVA = \"java\" as const;\n\n/**\n * Enum value \"nodejs\" for attribute {@link ATTR_TELEMETRY_SDK_LANGUAGE}.\n */\nexport const TELEMETRY_SDK_LANGUAGE_VALUE_NODEJS = \"nodejs\" as const;\n\n/**\n * Enum value \"php\" for attribute {@link ATTR_TELEMETRY_SDK_LANGUAGE}.\n */\nexport const TELEMETRY_SDK_LANGUAGE_VALUE_PHP = \"php\" as const;\n\n/**\n * Enum value \"python\" for attribute {@link ATTR_TELEMETRY_SDK_LANGUAGE}.\n */\nexport const TELEMETRY_SDK_LANGUAGE_VALUE_PYTHON = \"python\" as const;\n\n/**\n * Enum value \"ruby\" for attribute {@link ATTR_TELEMETRY_SDK_LANGUAGE}.\n */\nexport const TELEMETRY_SDK_LANGUAGE_VALUE_RUBY = \"ruby\" as const;\n\n/**\n * Enum value \"rust\" for attribute {@link ATTR_TELEMETRY_SDK_LANGUAGE}.\n */\nexport const TELEMETRY_SDK_LANGUAGE_VALUE_RUST = \"rust\" as const;\n\n/**\n * Enum value \"swift\" for attribute {@link ATTR_TELEMETRY_SDK_LANGUAGE}.\n */\nexport const TELEMETRY_SDK_LANGUAGE_VALUE_SWIFT = \"swift\" as const;\n\n/**\n * Enum value \"webjs\" for attribute {@link ATTR_TELEMETRY_SDK_LANGUAGE}.\n */\nexport const TELEMETRY_SDK_LANGUAGE_VALUE_WEBJS = \"webjs\" as const;\n\n/**\n * The name of the telemetry SDK as defined above.\n *\n * @example opentelemetry\n *\n * @note The OpenTelemetry SDK **MUST** set the `telemetry.sdk.name` attribute to `opentelemetry`.\n * If another SDK, like a fork or a vendor-provided implementation, is used, this SDK **MUST** set the\n * `telemetry.sdk.name` attribute to the fully-qualified class or module name of this SDK's main entry point\n * or another suitable identifier depending on the language.\n * The identifier `opentelemetry` is reserved and **MUST NOT** be used in this case.\n * All custom identifiers **SHOULD** be stable across different versions of an implementation.\n */\nexport const ATTR_TELEMETRY_SDK_NAME = 'telemetry.sdk.name' as const;\n\n/**\n * The version string of the telemetry SDK.\n *\n * @example 1.2.3\n */\nexport const ATTR_TELEMETRY_SDK_VERSION = 'telemetry.sdk.version' as const;\n\n/**\n * The [URI fragment](https://www.rfc-editor.org/rfc/rfc3986#section-3.5) component\n *\n * @example SemConv\n */\nexport const ATTR_URL_FRAGMENT = 'url.fragment' as const;\n\n/**\n * Absolute URL describing a network resource according to [RFC3986](https://www.rfc-editor.org/rfc/rfc3986)\n *\n * @example https://www.foo.bar/search?q=OpenTelemetry#SemConv\n * @example //localhost\n *\n * @note For network calls, URL usually has `scheme://host[:port][path][?query][#fragment]` format, where the fragment\n * is not transmitted over HTTP, but if it is known, it **SHOULD** be included nevertheless.\n *\n * `url.full` **MUST NOT** contain credentials passed via URL in form of `https://username:password@www.example.com/`.\n * In such case username and password **SHOULD** be redacted and attribute's value **SHOULD** be `https://REDACTED:REDACTED@www.example.com/`.\n *\n * `url.full` **SHOULD** capture the absolute URL when it is available (or can be reconstructed).\n *\n * Sensitive content provided in `url.full` **SHOULD** be scrubbed when instrumentations can identify it.\n *\n *\n * Query string values for the following keys **SHOULD** be redacted by default and replaced by the\n * value `REDACTED`:\n *\n *   - [`AWSAccessKeyId`](https://docs.aws.amazon.com/AmazonS3/latest/userguide/RESTAuthentication.html#RESTAuthenticationQueryStringAuth)\n *   - [`Signature`](https://docs.aws.amazon.com/AmazonS3/latest/userguide/RESTAuthentication.html#RESTAuthenticationQueryStringAuth)\n *   - [`sig`](https://learn.microsoft.com/azure/storage/common/storage-sas-overview#sas-token)\n *   - [`X-Goog-Signature`](https://cloud.google.com/storage/docs/access-control/signed-urls)\n *\n * This list is subject to change over time.\n *\n * Matching of query parameter keys against the sensitive list **SHOULD** be case-sensitive.\n *\n *\n * Instrumentation **MAY** provide a way to override this list via declarative configuration.\n * If so, it **SHOULD** use the `sensitive_query_parameters` property\n * (an array of case-sensitive strings with minimum items 0) under\n * `.instrumentation/development.general.sanitization.url`.\n * This list is a full override of the default sensitive query parameter keys,\n * it is not a list of keys in addition to the defaults.\n *\n * When a query string value is redacted, the query string key **SHOULD** still be preserved, e.g.\n * `https://www.example.com/path?color=blue&sig=REDACTED`.\n */\nexport const ATTR_URL_FULL = 'url.full' as const;\n\n/**\n * The [URI path](https://www.rfc-editor.org/rfc/rfc3986#section-3.3) component\n *\n * @example /search\n *\n * @note Sensitive content provided in `url.path` **SHOULD** be scrubbed when instrumentations can identify it.\n */\nexport const ATTR_URL_PATH = 'url.path' as const;\n\n/**\n * The [URI query](https://www.rfc-editor.org/rfc/rfc3986#section-3.4) component\n *\n * @example q=OpenTelemetry\n *\n * @note Sensitive content provided in `url.query` **SHOULD** be scrubbed when instrumentations can identify it.\n *\n *\n * Query string values for the following keys **SHOULD** be redacted by default and replaced by the value `REDACTED`:\n *\n *   - [`AWSAccessKeyId`](https://docs.aws.amazon.com/AmazonS3/latest/userguide/RESTAuthentication.html#RESTAuthenticationQueryStringAuth)\n *   - [`Signature`](https://docs.aws.amazon.com/AmazonS3/latest/userguide/RESTAuthentication.html#RESTAuthenticationQueryStringAuth)\n *   - [`sig`](https://learn.microsoft.com/azure/storage/common/storage-sas-overview#sas-token)\n *   - [`X-Goog-Signature`](https://cloud.google.com/storage/docs/access-control/signed-urls)\n *\n * This list is subject to change over time.\n *\n * Matching of query parameter keys against the sensitive list **SHOULD** be case-sensitive.\n *\n * Instrumentation **MAY** provide a way to override this list via declarative configuration.\n * If so, it **SHOULD** use the `sensitive_query_parameters` property\n * (an array of case-sensitive strings with minimum items 0) under\n * `.instrumentation/development.general.sanitization.url`.\n * This list is a full override of the default sensitive query parameter keys,\n * it is not a list of keys in addition to the defaults.\n *\n * When a query string value is redacted, the query string key **SHOULD** still be preserved, e.g.\n * `q=OpenTelemetry&sig=REDACTED`.\n */\nexport const ATTR_URL_QUERY = 'url.query' as const;\n\n/**\n * The [URI scheme](https://www.rfc-editor.org/rfc/rfc3986#section-3.1) component identifying the used protocol.\n *\n * @example https\n * @example ftp\n * @example telnet\n */\nexport const ATTR_URL_SCHEME = 'url.scheme' as const;\n\n/**\n * Value of the [HTTP User-Agent](https://www.rfc-editor.org/rfc/rfc9110.html#field.user-agent) header sent by the client.\n *\n * @example CERN-LineMode/2.15 libwww/2.17b3\n * @example Mozilla/5.0 (iPhone; CPU iPhone OS 14_7_1 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/14.1.2 Mobile/15E148 Safari/604.1\n * @example YourApp/1.0.0 grpc-java-okhttp/1.27.2\n */\nexport const ATTR_USER_AGENT_ORIGINAL = 'user_agent.original' as const;\n\n","/*\n * Copyright The OpenTelemetry Authors\n * SPDX-License-Identifier: Apache-2.0\n */\n\n/*\n * This file contains a copy of unstable semantic convention definitions\n * used by this package.\n * @see https://github.com/open-telemetry/opentelemetry-js/tree/main/semantic-conventions#unstable-semconv\n */\n\n/**\n * The name of the runtime of this process.\n *\n * @example OpenJDK Runtime Environment\n *\n * @experimental This attribute is experimental and is subject to breaking changes in minor releases of `@opentelemetry/semantic-conventions`.\n */\nexport const ATTR_PROCESS_RUNTIME_NAME = 'process.runtime.name' as const;\n","/*\n * Copyright The OpenTelemetry Authors\n * SPDX-License-Identifier: Apache-2.0\n */\n\nimport { VERSION } from '../../version';\nimport {\n  ATTR_TELEMETRY_SDK_NAME,\n  ATTR_TELEMETRY_SDK_LANGUAGE,\n  TELEMETRY_SDK_LANGUAGE_VALUE_NODEJS,\n  ATTR_TELEMETRY_SDK_VERSION,\n} from '@opentelemetry/semantic-conventions';\nimport { ATTR_PROCESS_RUNTIME_NAME } from '../../semconv';\n\n/** Constants describing the SDK in use */\nexport const SDK_INFO = {\n  [ATTR_TELEMETRY_SDK_NAME]: 'opentelemetry',\n  [ATTR_PROCESS_RUNTIME_NAME]: 'node',\n  [ATTR_TELEMETRY_SDK_LANGUAGE]: TELEMETRY_SDK_LANGUAGE_VALUE_NODEJS,\n  [ATTR_TELEMETRY_SDK_VERSION]: VERSION,\n};\n","/*\n * Copyright The OpenTelemetry Authors\n * SPDX-License-Identifier: Apache-2.0\n */\n\nexport {\n  getStringFromEnv,\n  getBooleanFromEnv,\n  getNumberFromEnv,\n  getStringListFromEnv,\n} from './environment';\nexport { _globalThis } from '../../common/globalThis';\nexport { SDK_INFO } from './sdk-info';\n\n/**\n * @deprecated Use performance directly.\n */\nexport const otperformance: { now(): number; readonly timeOrigin: number } =\n  performance;\n","/*\n * Copyright The OpenTelemetry Authors\n * SPDX-License-Identifier: Apache-2.0\n */\n\nimport type * as api from '@opentelemetry/api';\nimport { otperformance as performance } from '../platform';\n\nconst NANOSECOND_DIGITS = 9;\nconst NANOSECOND_DIGITS_IN_MILLIS = 6;\nconst MILLISECONDS_TO_NANOSECONDS = Math.pow(10, NANOSECOND_DIGITS_IN_MILLIS);\nconst SECOND_TO_NANOSECONDS = Math.pow(10, NANOSECOND_DIGITS);\n\n/**\n * Converts a number of milliseconds from epoch to HrTime([seconds, remainder in nanoseconds]).\n * @param epochMillis\n */\nexport function millisToHrTime(epochMillis: number): api.HrTime {\n  const epochSeconds = epochMillis / 1000;\n  // Decimals only.\n  const seconds = Math.trunc(epochSeconds);\n  // Round sub-nanosecond accuracy to nanosecond.\n  const nanos = Math.round((epochMillis % 1000) * MILLISECONDS_TO_NANOSECONDS);\n  return [seconds, nanos];\n}\n\n/**\n * @deprecated Use `performance.timeOrigin` directly.\n */\nexport function getTimeOrigin(): number {\n  return performance.timeOrigin;\n}\n\n/**\n * Returns an hrtime calculated via performance component.\n * @param performanceNow\n */\nexport function hrTime(performanceNow?: number): api.HrTime {\n  const timeOrigin = millisToHrTime(performance.timeOrigin);\n  const now = millisToHrTime(\n    typeof performanceNow === 'number' ? performanceNow : performance.now()\n  );\n\n  return addHrTimes(timeOrigin, now);\n}\n\n/**\n *\n * Converts a TimeInput to an HrTime, defaults to _hrtime().\n * @param time\n */\nexport function timeInputToHrTime(time: api.TimeInput): api.HrTime {\n  // process.hrtime\n  if (isTimeInputHrTime(time)) {\n    return time as api.HrTime;\n  } else if (typeof time === 'number') {\n    // Must be a performance.now() if it's smaller than process start time.\n    if (time < performance.timeOrigin) {\n      return hrTime(time);\n    } else {\n      // epoch milliseconds or performance.timeOrigin\n      return millisToHrTime(time);\n    }\n  } else if (time instanceof Date) {\n    return millisToHrTime(time.getTime());\n  } else {\n    throw TypeError('Invalid input type');\n  }\n}\n\n/**\n * Returns a duration of two hrTime.\n * @param startTime\n * @param endTime\n */\nexport function hrTimeDuration(\n  startTime: api.HrTime,\n  endTime: api.HrTime\n): api.HrTime {\n  let seconds = endTime[0] - startTime[0];\n  let nanos = endTime[1] - startTime[1];\n\n  // overflow\n  if (nanos < 0) {\n    seconds -= 1;\n    // negate\n    nanos += SECOND_TO_NANOSECONDS;\n  }\n\n  return [seconds, nanos];\n}\n\n/**\n * Convert hrTime to timestamp, for example \"2019-05-14T17:00:00.000123456Z\"\n * @param time\n */\nexport function hrTimeToTimeStamp(time: api.HrTime): string {\n  const precision = NANOSECOND_DIGITS;\n  const tmp = `${'0'.repeat(precision)}${time[1]}Z`;\n  const nanoString = tmp.substring(tmp.length - precision - 1);\n  const date = new Date(time[0] * 1000).toISOString();\n  return date.replace('000Z', nanoString);\n}\n\n/**\n * Convert hrTime to nanoseconds.\n * @param time\n */\nexport function hrTimeToNanoseconds(time: api.HrTime): number {\n  return time[0] * SECOND_TO_NANOSECONDS + time[1];\n}\n\n/**\n * Convert hrTime to microseconds.\n * @param time\n */\nexport function hrTimeToMicroseconds(time: api.HrTime): number {\n  return time[0] * 1e6 + time[1] / 1e3;\n}\n\n/**\n * Convert hrTime to milliseconds.\n * @param time\n */\nexport function hrTimeToMilliseconds(time: api.HrTime): number {\n  return time[0] * 1e3 + time[1] / 1e6;\n}\n\n/**\n * Convert hrTime to seconds.\n * @param time\n */\nexport function hrTimeToSeconds(time: api.HrTime): number {\n  return time[0] + time[1] / SECOND_TO_NANOSECONDS;\n}\n/**\n * check if time is HrTime\n * @param value\n */\nexport function isTimeInputHrTime(value: unknown): value is api.HrTime {\n  return (\n    Array.isArray(value) &&\n    value.length === 2 &&\n    typeof value[0] === 'number' &&\n    typeof value[1] === 'number'\n  );\n}\n\n/**\n * check if input value is a correct types.TimeInput\n * @param value\n */\nexport function isTimeInput(\n  value: unknown\n): value is api.HrTime | number | Date {\n  return (\n    isTimeInputHrTime(value) ||\n    typeof value === 'number' ||\n    value instanceof Date\n  );\n}\n\n/**\n * Given 2 HrTime formatted times, return their sum as an HrTime.\n */\nexport function addHrTimes(time1: api.HrTime, time2: api.HrTime): api.HrTime {\n  const out = [time1[0] + time2[0], time1[1] + time2[1]] as api.HrTime;\n\n  // Nanoseconds\n  if (out[1] >= SECOND_TO_NANOSECONDS) {\n    out[1] -= SECOND_TO_NANOSECONDS;\n    out[0] += 1;\n  }\n\n  return out;\n}\n","/*\n * Copyright The OpenTelemetry Authors\n * SPDX-License-Identifier: Apache-2.0\n */\n\nexport interface ExportResult {\n  code: ExportResultCode;\n  error?: Error;\n}\n\nexport enum ExportResultCode {\n  SUCCESS,\n  FAILED,\n}\n","/*\n * Copyright The OpenTelemetry Authors\n * SPDX-License-Identifier: Apache-2.0\n */\n\n/* eslint-disable @typescript-eslint/no-explicit-any */\n\n/**\n * based on lodash in order to support esm builds without esModuleInterop.\n * lodash is using MIT License.\n **/\n\nconst objectTag = '[object Object]';\nconst nullTag = '[object Null]';\nconst undefinedTag = '[object Undefined]';\nconst funcProto = Function.prototype;\nconst funcToString = funcProto.toString;\nconst objectCtorString = funcToString.call(Object);\nconst getPrototypeOf = Object.getPrototypeOf;\nconst objectProto = Object.prototype;\nconst hasOwnProperty = objectProto.hasOwnProperty;\nconst symToStringTag = Symbol ? Symbol.toStringTag : undefined;\nconst nativeObjectToString = objectProto.toString;\n\n/**\n * Checks if `value` is a plain object, that is, an object created by the\n * `Object` constructor or one with a `[[Prototype]]` of `null`.\n *\n * @static\n * @memberOf _\n * @since 0.8.0\n * @category Lang\n * @param {*} value The value to check.\n * @returns {boolean} Returns `true` if `value` is a plain object, else `false`.\n * @example\n *\n * function Foo() {\n *   this.a = 1;\n * }\n *\n * _.isPlainObject(new Foo);\n * // => false\n *\n * _.isPlainObject([1, 2, 3]);\n * // => false\n *\n * _.isPlainObject({ 'x': 0, 'y': 0 });\n * // => true\n *\n * _.isPlainObject(Object.create(null));\n * // => true\n */\nexport function isPlainObject(value: any) {\n  if (!isObjectLike(value) || baseGetTag(value) !== objectTag) {\n    return false;\n  }\n  const proto = getPrototypeOf(value);\n  if (proto === null) {\n    return true;\n  }\n  const Ctor = hasOwnProperty.call(proto, 'constructor') && proto.constructor;\n  return (\n    typeof Ctor == 'function' &&\n    Ctor instanceof Ctor &&\n    funcToString.call(Ctor) === objectCtorString\n  );\n}\n\n/**\n * Checks if `value` is object-like. A value is object-like if it's not `null`\n * and has a `typeof` result of \"object\".\n *\n * @static\n * @memberOf _\n * @since 4.0.0\n * @category Lang\n * @param {*} value The value to check.\n * @returns {boolean} Returns `true` if `value` is object-like, else `false`.\n * @example\n *\n * _.isObjectLike({});\n * // => true\n *\n * _.isObjectLike([1, 2, 3]);\n * // => true\n *\n * _.isObjectLike(_.noop);\n * // => false\n *\n * _.isObjectLike(null);\n * // => false\n */\nfunction isObjectLike(value: any) {\n  return value != null && typeof value == 'object';\n}\n\n/**\n * The base implementation of `getTag` without fallbacks for buggy environments.\n *\n * @private\n * @param {*} value The value to query.\n * @returns {string} Returns the `toStringTag`.\n */\nfunction baseGetTag(value: any) {\n  if (value == null) {\n    return value === undefined ? undefinedTag : nullTag;\n  }\n  return symToStringTag && symToStringTag in Object(value)\n    ? getRawTag(value)\n    : objectToString(value);\n}\n\n/**\n * A specialized version of `baseGetTag` which ignores `Symbol.toStringTag` values.\n *\n * @private\n * @param {*} value The value to query.\n * @returns {string} Returns the raw `toStringTag`.\n */\nfunction getRawTag(value: any) {\n  const isOwn = hasOwnProperty.call(value, symToStringTag as any),\n    tag = value[symToStringTag as any];\n  let unmasked = false;\n\n  try {\n    value[symToStringTag as any] = undefined;\n    unmasked = true;\n  } catch {\n    // silence\n  }\n\n  const result = nativeObjectToString.call(value);\n  if (unmasked) {\n    if (isOwn) {\n      value[symToStringTag as any] = tag;\n    } else {\n      delete value[symToStringTag as any];\n    }\n  }\n  return result;\n}\n\n/**\n * Converts `value` to a string using `Object.prototype.toString`.\n *\n * @private\n * @param {*} value The value to convert.\n * @returns {string} Returns the converted string.\n */\nfunction objectToString(value: any) {\n  return nativeObjectToString.call(value);\n}\n","/*\n * Copyright The OpenTelemetry Authors\n * SPDX-License-Identifier: Apache-2.0\n */\n\n/* eslint-disable @typescript-eslint/no-explicit-any */\n\nimport { isPlainObject } from './lodash.merge';\n\nconst MAX_LEVEL = 20;\n\ninterface ObjectInto {\n  obj: any;\n  key: string;\n}\n\n/**\n * Merges objects together\n * @param args - objects / values to be merged\n */\nexport function merge(...args: any[]): any {\n  let result: any = args.shift();\n  const objects: WeakMap<any, ObjectInto[]> | undefined = new WeakMap<\n    any,\n    ObjectInto[]\n  >();\n  while (args.length > 0) {\n    result = mergeTwoObjects(result, args.shift(), 0, objects);\n  }\n\n  return result;\n}\n\nfunction takeValue(value: any): any {\n  if (isArray(value)) {\n    return value.slice();\n  }\n  return value;\n}\n\n/**\n * Merges two objects\n * @param one - first object\n * @param two - second object\n * @param level - current deep level\n * @param objects - objects holder that has been already referenced - to prevent\n * cyclic dependency\n */\nfunction mergeTwoObjects(\n  one: any,\n  two: any,\n  level = 0,\n  objects: WeakMap<any, ObjectInto[]>\n): any {\n  let result: any;\n  if (level > MAX_LEVEL) {\n    return undefined;\n  }\n  level++;\n  if (isPrimitive(one) || isPrimitive(two) || isFunction(two)) {\n    result = takeValue(two);\n  } else if (isArray(one)) {\n    result = one.slice();\n    if (isArray(two)) {\n      for (let i = 0, j = two.length; i < j; i++) {\n        result.push(takeValue(two[i]));\n      }\n    } else if (isObject(two)) {\n      const keys = Object.keys(two);\n      for (let i = 0, j = keys.length; i < j; i++) {\n        const key = keys[i];\n        if (\n          key === '__proto__' ||\n          key === 'constructor' ||\n          key === 'prototype'\n        ) {\n          continue;\n        }\n        result[key] = takeValue(two[key]);\n      }\n    }\n  } else if (isObject(one)) {\n    if (isObject(two)) {\n      if (!shouldMerge(one, two)) {\n        return two;\n      }\n      result = Object.assign({}, one);\n      const keys = Object.keys(two);\n\n      for (let i = 0, j = keys.length; i < j; i++) {\n        const key = keys[i];\n        if (\n          key === '__proto__' ||\n          key === 'constructor' ||\n          key === 'prototype'\n        ) {\n          continue;\n        }\n        const twoValue = two[key];\n\n        if (isPrimitive(twoValue)) {\n          if (typeof twoValue === 'undefined') {\n            delete result[key];\n          } else {\n            // result[key] = takeValue(twoValue);\n            result[key] = twoValue;\n          }\n        } else {\n          const obj1 = result[key];\n          const obj2 = twoValue;\n\n          if (\n            wasObjectReferenced(one, key, objects) ||\n            wasObjectReferenced(two, key, objects)\n          ) {\n            delete result[key];\n          } else {\n            if (isObject(obj1) && isObject(obj2)) {\n              const arr1 = objects.get(obj1) || [];\n              const arr2 = objects.get(obj2) || [];\n              arr1.push({ obj: one, key });\n              arr2.push({ obj: two, key });\n              objects.set(obj1, arr1);\n              objects.set(obj2, arr2);\n            }\n\n            result[key] = mergeTwoObjects(\n              result[key],\n              twoValue,\n              level,\n              objects\n            );\n          }\n        }\n      }\n    } else {\n      result = two;\n    }\n  }\n\n  return result;\n}\n\n/**\n * Function to check if object has been already reference\n * @param obj\n * @param key\n * @param objects\n */\nfunction wasObjectReferenced(\n  obj: any,\n  key: string,\n  objects: WeakMap<any, ObjectInto[]>\n): boolean {\n  const arr = objects.get(obj[key]) || [];\n  for (let i = 0, j = arr.length; i < j; i++) {\n    const info = arr[i];\n    if (info.key === key && info.obj === obj) {\n      return true;\n    }\n  }\n  return false;\n}\n\nfunction isArray(value: any): boolean {\n  return Array.isArray(value);\n}\n\nfunction isFunction(value: any): boolean {\n  return typeof value === 'function';\n}\n\nfunction isObject(value: any): boolean {\n  return (\n    !isPrimitive(value) &&\n    !isArray(value) &&\n    !isFunction(value) &&\n    typeof value === 'object'\n  );\n}\n\nfunction isPrimitive(value: any): boolean {\n  return (\n    typeof value === 'string' ||\n    typeof value === 'number' ||\n    typeof value === 'boolean' ||\n    typeof value === 'undefined' ||\n    value instanceof Date ||\n    value instanceof RegExp ||\n    value === null\n  );\n}\n\nfunction shouldMerge(one: any, two: any): boolean {\n  if (!isPlainObject(one) || !isPlainObject(two)) {\n    return false;\n  }\n\n  return true;\n}\n","/*\n * Copyright The OpenTelemetry Authors\n * SPDX-License-Identifier: Apache-2.0\n */\n\nexport class Deferred<T> {\n  private _promise: Promise<T>;\n  private _resolve!: (val: T) => void;\n  private _reject!: (error: unknown) => void;\n  constructor() {\n    this._promise = new Promise((resolve, reject) => {\n      this._resolve = resolve;\n      this._reject = reject;\n    });\n  }\n\n  get promise() {\n    return this._promise;\n  }\n\n  resolve(val: T) {\n    this._resolve(val);\n  }\n\n  reject(err: unknown) {\n    this._reject(err);\n  }\n}\n","/*\n * Copyright The OpenTelemetry Authors\n * SPDX-License-Identifier: Apache-2.0\n */\n\nimport { Deferred } from './promise';\n\n/**\n * Bind the callback and only invoke the callback once regardless how many times `BindOnceFuture.call` is invoked.\n */\nexport class BindOnceFuture<\n  R,\n  This = unknown,\n  T extends (this: This, ...args: unknown[]) => R = () => R,\n> {\n  private _isCalled = false;\n  private _deferred = new Deferred<R>();\n  private _callback: T;\n  private _that: This;\n\n  constructor(callback: T, that: This) {\n    this._callback = callback;\n    this._that = that;\n  }\n\n  get isCalled() {\n    return this._isCalled;\n  }\n\n  get promise() {\n    return this._deferred.promise;\n  }\n\n  call(...args: Parameters<T>): Promise<R> {\n    if (!this._isCalled) {\n      this._isCalled = true;\n      try {\n        Promise.resolve(this._callback.call(this._that, ...args)).then(\n          val => this._deferred.resolve(val),\n          err => this._deferred.reject(err)\n        );\n      } catch (err) {\n        this._deferred.reject(err);\n      }\n    }\n    return this._deferred.promise;\n  }\n}\n","/*\n * Copyright The OpenTelemetry Authors\n * SPDX-License-Identifier: Apache-2.0\n */\nimport { diag } from '@opentelemetry/api';\nimport type { IOtlpResponseHandler } from './response-handler';\n\nfunction isPartialSuccessResponse(\n  response: unknown\n): response is { partialSuccess: never } {\n  return Object.prototype.hasOwnProperty.call(response, 'partialSuccess');\n}\n\n/**\n * Default response handler that logs a partial success to the console.\n */\nexport function createLoggingPartialSuccessResponseHandler<\n  T,\n>(): IOtlpResponseHandler<T> {\n  return {\n    handleResponse(response: T) {\n      // Partial success MUST never be an empty object according the specification\n      // see https://opentelemetry.io/docs/specs/otlp/#partial-success\n      if (\n        response == null ||\n        !isPartialSuccessResponse(response) ||\n        response.partialSuccess == null ||\n        Object.keys(response.partialSuccess).length === 0\n      ) {\n        return;\n      }\n      diag.warn(\n        'Received Partial Success response:',\n        JSON.stringify(response.partialSuccess)\n      );\n    },\n  };\n}\n","/*\n * Copyright The OpenTelemetry Authors\n * SPDX-License-Identifier: Apache-2.0\n */\n\nimport type { ExportResult } from '@opentelemetry/core';\nimport { ExportResultCode } from '@opentelemetry/core';\nimport type { IExporterTransport } from './exporter-transport';\nimport type { IExportPromiseHandler } from './bounded-queue-export-promise-handler';\nimport type { ISerializer } from '@opentelemetry/otlp-transformer';\nimport { OTLPExporterError } from './types';\nimport type { IOtlpResponseHandler } from './response-handler';\nimport { createLoggingPartialSuccessResponseHandler } from './logging-response-handler';\nimport type { DiagLogger } from '@opentelemetry/api';\nimport { diag } from '@opentelemetry/api';\n\n/**\n * Internally shared export logic for OTLP.\n */\nexport interface IOtlpExportDelegate<Internal> {\n  export(\n    internalRepresentation: Internal,\n    resultCallback: (result: ExportResult) => void\n  ): void;\n  forceFlush(): Promise<void>;\n  shutdown(): Promise<void>;\n}\n\nclass OTLPExportDelegate<Internal, Response>\n  implements IOtlpExportDelegate<Internal>\n{\n  private _diagLogger: DiagLogger;\n  private _transport: IExporterTransport;\n  private _serializer: ISerializer<Internal, Response>;\n  private _responseHandler: IOtlpResponseHandler<Response>;\n  private _promiseQueue: IExportPromiseHandler;\n  private _timeout: number;\n\n  constructor(\n    transport: IExporterTransport,\n    serializer: ISerializer<Internal, Response>,\n    responseHandler: IOtlpResponseHandler<Response>,\n    promiseQueue: IExportPromiseHandler,\n    timeout: number\n  ) {\n    this._transport = transport;\n    this._serializer = serializer;\n    this._responseHandler = responseHandler;\n    this._promiseQueue = promiseQueue;\n    this._timeout = timeout;\n    this._diagLogger = diag.createComponentLogger({\n      namespace: 'OTLPExportDelegate',\n    });\n  }\n\n  export(\n    internalRepresentation: Internal,\n    resultCallback: (result: ExportResult) => void\n  ): void {\n    this._diagLogger.debug('items to be sent', internalRepresentation);\n\n    // don't do any work if too many exports are in progress.\n    if (this._promiseQueue.hasReachedLimit()) {\n      resultCallback({\n        code: ExportResultCode.FAILED,\n        error: new Error('Concurrent export limit reached'),\n      });\n      return;\n    }\n\n    const serializedRequest = this._serializer.serializeRequest(\n      internalRepresentation\n    );\n\n    if (serializedRequest == null) {\n      resultCallback({\n        code: ExportResultCode.FAILED,\n        error: new Error('Nothing to send'),\n      });\n      return;\n    }\n\n    this._promiseQueue.pushPromise(\n      this._transport.send(serializedRequest, this._timeout).then(\n        response => {\n          if (response.status === 'success') {\n            if (response.data != null) {\n              try {\n                this._responseHandler.handleResponse(\n                  this._serializer.deserializeResponse(response.data)\n                );\n              } catch (e) {\n                this._diagLogger.warn(\n                  'Export succeeded but could not deserialize response - is the response specification compliant?',\n                  e,\n                  response.data\n                );\n              }\n            }\n            // No matter the response, we can consider the export still successful.\n            resultCallback({\n              code: ExportResultCode.SUCCESS,\n            });\n            return;\n          } else if (response.status === 'failure' && response.error) {\n            resultCallback({\n              code: ExportResultCode.FAILED,\n              error: response.error,\n            });\n            return;\n          } else if (response.status === 'retryable') {\n            resultCallback({\n              code: ExportResultCode.FAILED,\n              error:\n                response.error ??\n                new OTLPExporterError('Export failed with retryable status'),\n            });\n          } else {\n            resultCallback({\n              code: ExportResultCode.FAILED,\n              error: new OTLPExporterError('Export failed with unknown error'),\n            });\n          }\n        },\n        reason =>\n          resultCallback({\n            code: ExportResultCode.FAILED,\n            error: reason,\n          })\n      )\n    );\n  }\n\n  forceFlush(): Promise<void> {\n    return this._promiseQueue.awaitAll();\n  }\n\n  async shutdown(): Promise<void> {\n    this._diagLogger.debug('shutdown started');\n    await this.forceFlush();\n    this._transport.shutdown();\n  }\n}\n\n/**\n * Creates a generic delegate for OTLP exports which only contains parts of the OTLP export that are shared across all\n * signals.\n */\nexport function createOtlpExportDelegate<Internal, Response>(\n  components: {\n    transport: IExporterTransport;\n    serializer: ISerializer<Internal, Response>;\n    promiseHandler: IExportPromiseHandler;\n  },\n  settings: { timeout: number }\n): IOtlpExportDelegate<Internal> {\n  return new OTLPExportDelegate(\n    components.transport,\n    components.serializer,\n    createLoggingPartialSuccessResponseHandler(),\n    components.promiseHandler,\n    settings.timeout\n  );\n}\n","/*\n * Copyright The OpenTelemetry Authors\n * SPDX-License-Identifier: Apache-2.0\n */\n\nimport type { Attributes, AttributeValue } from '@opentelemetry/api';\nimport { diag } from '@opentelemetry/api';\nimport { SDK_INFO } from '@opentelemetry/core';\nimport {\n  ATTR_SERVICE_NAME,\n  ATTR_TELEMETRY_SDK_LANGUAGE,\n  ATTR_TELEMETRY_SDK_NAME,\n  ATTR_TELEMETRY_SDK_VERSION,\n} from '@opentelemetry/semantic-conventions';\nimport type { Resource } from './Resource';\nimport { defaultServiceName } from './default-service-name';\nimport type {\n  DetectedResource,\n  DetectedResourceAttributes,\n  MaybePromise,\n  RawResourceAttribute,\n  ResourceOptions,\n} from './types';\nimport { isPromiseLike } from './utils';\n\nclass ResourceImpl implements Resource {\n  private _rawAttributes: RawResourceAttribute[];\n  private _asyncAttributesPending = false;\n  private _schemaUrl?: string;\n\n  private _memoizedAttributes?: Attributes;\n\n  static FromAttributeList(\n    attributes: [string, MaybePromise<AttributeValue | undefined>][],\n    options?: ResourceOptions\n  ): Resource {\n    const res = new ResourceImpl({}, options);\n    res._rawAttributes = guardedRawAttributes(attributes);\n    res._asyncAttributesPending =\n      attributes.filter(([_, val]) => isPromiseLike(val)).length > 0;\n    return res;\n  }\n\n  constructor(\n    /**\n     * A dictionary of attributes with string keys and values that provide\n     * information about the entity as numbers, strings or booleans\n     * TODO: Consider to add check/validation on attributes.\n     */\n    resource: DetectedResource,\n    options?: ResourceOptions\n  ) {\n    const attributes = resource.attributes ?? {};\n    this._rawAttributes = Object.entries(attributes).map(([k, v]) => {\n      if (isPromiseLike(v)) {\n        // side-effect\n        this._asyncAttributesPending = true;\n      }\n\n      return [k, v];\n    });\n\n    this._rawAttributes = guardedRawAttributes(this._rawAttributes);\n    this._schemaUrl = validateSchemaUrl(options?.schemaUrl);\n  }\n\n  public get asyncAttributesPending(): boolean {\n    return this._asyncAttributesPending;\n  }\n\n  public async waitForAsyncAttributes(): Promise<void> {\n    if (!this.asyncAttributesPending) {\n      return;\n    }\n\n    for (let i = 0; i < this._rawAttributes.length; i++) {\n      const [k, v] = this._rawAttributes[i];\n      this._rawAttributes[i] = [k, isPromiseLike(v) ? await v : v];\n    }\n\n    this._asyncAttributesPending = false;\n  }\n\n  public get attributes(): Attributes {\n    if (this.asyncAttributesPending) {\n      diag.error(\n        'Accessing resource attributes before async attributes settled'\n      );\n    }\n\n    if (this._memoizedAttributes) {\n      return this._memoizedAttributes;\n    }\n\n    const attrs: Attributes = {};\n    for (const [k, v] of this._rawAttributes) {\n      if (isPromiseLike(v)) {\n        diag.debug(`Unsettled resource attribute ${k} skipped`);\n        continue;\n      }\n      if (v != null) {\n        attrs[k] ??= v;\n      }\n    }\n\n    // only memoize output if all attributes are settled\n    if (!this._asyncAttributesPending) {\n      this._memoizedAttributes = attrs;\n    }\n\n    return attrs;\n  }\n\n  public getRawAttributes(): RawResourceAttribute[] {\n    return this._rawAttributes;\n  }\n\n  public get schemaUrl(): string | undefined {\n    return this._schemaUrl;\n  }\n\n  public merge(resource: Resource | null): Resource {\n    if (resource == null) return this;\n\n    // Order is important\n    // Spec states incoming attributes override existing attributes\n    const mergedSchemaUrl = mergeSchemaUrl(this, resource);\n    const mergedOptions: ResourceOptions | undefined = mergedSchemaUrl\n      ? { schemaUrl: mergedSchemaUrl }\n      : undefined;\n\n    return ResourceImpl.FromAttributeList(\n      [...resource.getRawAttributes(), ...this.getRawAttributes()],\n      mergedOptions\n    );\n  }\n}\n\nexport function resourceFromAttributes(\n  attributes: DetectedResourceAttributes,\n  options?: ResourceOptions\n): Resource {\n  return ResourceImpl.FromAttributeList(Object.entries(attributes), options);\n}\n\nexport function resourceFromDetectedResource(\n  detectedResource: DetectedResource,\n  options?: ResourceOptions\n): Resource {\n  return new ResourceImpl(detectedResource, options);\n}\n\nexport function emptyResource(): Resource {\n  return resourceFromAttributes({});\n}\n\nexport function defaultResource(): Resource {\n  return resourceFromAttributes({\n    [ATTR_SERVICE_NAME]: defaultServiceName(),\n    [ATTR_TELEMETRY_SDK_LANGUAGE]: SDK_INFO[ATTR_TELEMETRY_SDK_LANGUAGE],\n    [ATTR_TELEMETRY_SDK_NAME]: SDK_INFO[ATTR_TELEMETRY_SDK_NAME],\n    [ATTR_TELEMETRY_SDK_VERSION]: SDK_INFO[ATTR_TELEMETRY_SDK_VERSION],\n  });\n}\n\nfunction guardedRawAttributes(\n  attributes: RawResourceAttribute[]\n): RawResourceAttribute[] {\n  return attributes.map(([k, v]) => {\n    if (isPromiseLike(v)) {\n      return [\n        k,\n        v.catch(err => {\n          diag.debug(\n            'promise rejection for resource attribute: %s - %s',\n            k,\n            err\n          );\n          return undefined;\n        }),\n      ];\n    }\n    return [k, v];\n  });\n}\n\nfunction validateSchemaUrl(schemaUrl?: string): string | undefined {\n  if (typeof schemaUrl === 'string' || schemaUrl === undefined) {\n    return schemaUrl;\n  }\n\n  diag.warn(\n    'Schema URL must be string or undefined, got %s. Schema URL will be ignored.',\n    schemaUrl\n  );\n\n  return undefined;\n}\n\nfunction mergeSchemaUrl(\n  old: Resource,\n  updating: Resource | null\n): string | undefined {\n  const oldSchemaUrl = old?.schemaUrl;\n  const updatingSchemaUrl = updating?.schemaUrl;\n\n  const isOldEmpty = oldSchemaUrl === undefined || oldSchemaUrl === '';\n  const isUpdatingEmpty =\n    updatingSchemaUrl === undefined || updatingSchemaUrl === '';\n\n  if (isOldEmpty) {\n    return updatingSchemaUrl;\n  }\n\n  if (isUpdatingEmpty) {\n    return oldSchemaUrl;\n  }\n\n  if (oldSchemaUrl === updatingSchemaUrl) {\n    return oldSchemaUrl;\n  }\n\n  diag.warn(\n    'Schema URL merge conflict: old resource has \"%s\", updating resource has \"%s\". Resulting resource will have undefined Schema URL.',\n    oldSchemaUrl,\n    updatingSchemaUrl\n  );\n\n  return undefined;\n}\n","/*\n * Copyright The OpenTelemetry Authors\n * SPDX-License-Identifier: Apache-2.0\n */\n\nlet serviceName: string | undefined;\n\n/**\n * Returns the default service name for OpenTelemetry resources.\n * In Node.js environments, returns \"unknown_service:<process.argv0>\".\n * In browser/edge environments, returns \"unknown_service\".\n */\nexport function defaultServiceName(): string {\n  if (serviceName === undefined) {\n    try {\n      const argv0 = globalThis.process.argv0;\n      serviceName = argv0 ? `unknown_service:${argv0}` : 'unknown_service';\n    } catch {\n      serviceName = 'unknown_service';\n    }\n  }\n  return serviceName;\n}\n\n/** @internal For testing purposes only */\nexport function _clearDefaultServiceNameCache(): void {\n  serviceName = undefined;\n}\n","/*\n * Copyright The OpenTelemetry Authors\n * SPDX-License-Identifier: Apache-2.0\n */\n\nexport const isPromiseLike = <R>(val: unknown): val is PromiseLike<R> => {\n  return (\n    val !== null &&\n    typeof val === 'object' &&\n    typeof (val as Partial<PromiseLike<R>>).then === 'function'\n  );\n};\n","/*\n * Copyright The OpenTelemetry Authors\n * SPDX-License-Identifier: Apache-2.0\n */\nimport type {\n  IAnyValue,\n  IInstrumentationScope,\n  IKeyValue,\n  Resource,\n} from './internal-types';\nimport type { InstrumentationScope } from '@opentelemetry/core';\nimport type { Resource as ISdkResource } from '@opentelemetry/resources';\nimport type { Encoder } from './utils';\nimport type { LogAttributes } from '@opentelemetry/api-logs';\n\nexport function createResource(\n  resource: ISdkResource,\n  encoder: Encoder\n): Resource {\n  const result: Resource = {\n    attributes: toAttributes(resource.attributes, encoder),\n    droppedAttributesCount: 0,\n  };\n\n  const schemaUrl = resource.schemaUrl;\n  if (schemaUrl && schemaUrl !== '') result.schemaUrl = schemaUrl;\n\n  return result;\n}\n\nexport function createInstrumentationScope(\n  scope: InstrumentationScope & {\n    attributes?: LogAttributes;\n    droppedAttributesCount?: number;\n  },\n  encoder: Encoder\n): IInstrumentationScope {\n  const result: IInstrumentationScope = {\n    name: scope.name,\n    version: scope.version,\n  };\n\n  if (scope.attributes && Object.keys(scope.attributes).length > 0) {\n    result.attributes = toAttributes(scope.attributes, encoder);\n    result.droppedAttributesCount = scope.droppedAttributesCount ?? 0;\n  }\n\n  return result;\n}\n\nexport function toAttributes(\n  attributes: LogAttributes,\n  encoder: Encoder\n): IKeyValue[] {\n  return Object.keys(attributes).map(key =>\n    toKeyValue(key, attributes[key], encoder)\n  );\n}\n\nexport function toKeyValue(\n  key: string,\n  value: unknown,\n  encoder: Encoder\n): IKeyValue {\n  return {\n    key: key,\n    value: toAnyValue(value, encoder),\n  };\n}\n\nexport function toAnyValue(value: unknown, encoder: Encoder): IAnyValue {\n  const t = typeof value;\n  if (t === 'string') return { stringValue: value as string };\n  if (t === 'number') {\n    if (!Number.isInteger(value)) return { doubleValue: value as number };\n    return { intValue: value as number };\n  }\n  if (t === 'boolean') return { boolValue: value as boolean };\n  if (value instanceof Uint8Array)\n    return { bytesValue: encoder.encodeUint8Array(value) };\n  if (Array.isArray(value)) {\n    const values: IAnyValue[] = new Array(value.length);\n    for (let i = 0; i < value.length; i++) {\n      values[i] = toAnyValue(value[i], encoder);\n    }\n    return { arrayValue: { values } };\n  }\n  if (t === 'object' && value != null) {\n    const keys = Object.keys(value);\n    const values: IKeyValue[] = new Array(keys.length);\n    for (let i = 0; i < keys.length; i++) {\n      values[i] = {\n        key: keys[i],\n        value: toAnyValue((value as Record<string, unknown>)[keys[i]], encoder),\n      };\n    }\n    return { kvlistValue: { values } };\n  }\n\n  return {};\n}\n","/*\n * Copyright The OpenTelemetry Authors\n * SPDX-License-Identifier: Apache-2.0\n */\n\nimport type { Fixed64, LongBits } from './internal-types';\nimport type { HrTime } from '@opentelemetry/api';\nimport { hrTimeToNanoseconds } from '@opentelemetry/core';\nimport { hexToBinary } from './hex-to-binary';\n\nexport function hrTimeToNanos(hrTime: HrTime): bigint {\n  const NANOSECONDS = BigInt(1_000_000_000);\n  return (\n    BigInt(Math.trunc(hrTime[0])) * NANOSECONDS + BigInt(Math.trunc(hrTime[1]))\n  );\n}\n\nexport function toLongBits(value: bigint): LongBits {\n  const low = Number(BigInt.asUintN(32, value));\n  const high = Number(BigInt.asUintN(32, value >> BigInt(32)));\n  return { low, high };\n}\n\nexport function encodeAsLongBits(hrTime: HrTime): LongBits {\n  const nanos = hrTimeToNanos(hrTime);\n  return toLongBits(nanos);\n}\n\nexport function encodeAsString(hrTime: HrTime): string {\n  const nanos = hrTimeToNanos(hrTime);\n  return nanos.toString();\n}\n\nconst encodeTimestamp =\n  typeof BigInt !== 'undefined' ? encodeAsString : hrTimeToNanoseconds;\n\nexport type HrTimeEncodeFunction = (hrTime: HrTime) => Fixed64;\nexport type SpanContextEncodeFunction = (\n  spanContext: string\n) => string | Uint8Array;\nexport type OptionalSpanContextEncodeFunction = (\n  spanContext: string | undefined\n) => string | Uint8Array | undefined;\nexport type Uint8ArrayEncodeFunction = (\n  value: Uint8Array\n) => string | Uint8Array;\n\nexport interface Encoder {\n  encodeHrTime: HrTimeEncodeFunction;\n  encodeSpanContext: SpanContextEncodeFunction;\n  encodeOptionalSpanContext: OptionalSpanContextEncodeFunction;\n  encodeUint8Array: Uint8ArrayEncodeFunction;\n}\n\nfunction identity<T>(value: T): T {\n  return value;\n}\n\nfunction optionalHexToBinary(str: string | undefined): Uint8Array | undefined {\n  if (str === undefined) return undefined;\n  return hexToBinary(str);\n}\n\n/**\n * Encoder for protobuf format.\n * Uses { high, low } timestamps and binary for span/trace IDs, leaves Uint8Array attributes as-is.\n */\nexport const PROTOBUF_ENCODER: Encoder = {\n  encodeHrTime: encodeAsLongBits,\n  encodeSpanContext: hexToBinary,\n  encodeOptionalSpanContext: optionalHexToBinary,\n  encodeUint8Array: identity,\n};\n\n/**\n * Encoder for JSON format.\n * Uses string timestamps, hex for span/trace IDs, and base64 for Uint8Array.\n */\nexport const JSON_ENCODER: Encoder = {\n  encodeHrTime: encodeTimestamp,\n  encodeSpanContext: identity,\n  encodeOptionalSpanContext: identity,\n  encodeUint8Array: (bytes: Uint8Array): string => {\n    if (typeof Buffer !== 'undefined') {\n      return Buffer.from(bytes).toString('base64');\n    }\n\n    // implementation note: not using spread operator and passing to\n    // btoa to avoid stack overflow on large Uint8Arrays\n    const chars = new Array(bytes.length);\n    for (let i = 0; i < bytes.length; i++) {\n      chars[i] = String.fromCharCode(bytes[i]);\n    }\n    return btoa(chars.join(''));\n  },\n};\n","/*\n * Copyright The OpenTelemetry Authors\n * SPDX-License-Identifier: Apache-2.0\n */\nimport type { Link } from '@opentelemetry/api';\nimport type { Resource } from '@opentelemetry/resources';\nimport type { ReadableSpan, TimedEvent } from '@opentelemetry/sdk-trace-base';\nimport type { Encoder } from '../common/utils';\nimport {\n  createInstrumentationScope,\n  createResource,\n  toAttributes,\n} from '../common/internal';\nimport type {\n  EStatusCode,\n  IEvent,\n  IExportTraceServiceRequest,\n  ILink,\n  IResourceSpans,\n  IScopeSpans,\n  ISpan,\n} from './internal-types';\n\n// Span flags constants matching the OTLP specification\nconst SPAN_FLAGS_CONTEXT_HAS_IS_REMOTE_MASK = 0x100;\nconst SPAN_FLAGS_CONTEXT_IS_REMOTE_MASK = 0x200;\n\n/**\n * Builds the 32-bit span flags value combining the low 8-bit W3C TraceFlags\n * with the HAS_IS_REMOTE and IS_REMOTE bits according to the OTLP spec.\n */\nfunction buildSpanFlagsFrom(traceFlags: number, isRemote?: boolean): number {\n  // low 8 bits are W3C TraceFlags (e.g., sampled)\n  let flags = (traceFlags & 0xff) | SPAN_FLAGS_CONTEXT_HAS_IS_REMOTE_MASK;\n  if (isRemote) {\n    flags |= SPAN_FLAGS_CONTEXT_IS_REMOTE_MASK;\n  }\n  return flags;\n}\n\nexport function sdkSpanToOtlpSpan(span: ReadableSpan, encoder: Encoder): ISpan {\n  const ctx = span.spanContext();\n  const status = span.status;\n  const parentSpanId = span.parentSpanContext?.spanId\n    ? encoder.encodeSpanContext(span.parentSpanContext?.spanId)\n    : undefined;\n  return {\n    traceId: encoder.encodeSpanContext(ctx.traceId),\n    spanId: encoder.encodeSpanContext(ctx.spanId),\n    parentSpanId: parentSpanId,\n    traceState: ctx.traceState?.serialize(),\n    name: span.name,\n    // Span kind is offset by 1 because the API does not define a value for unset\n    kind: span.kind == null ? 0 : span.kind + 1,\n    startTimeUnixNano: encoder.encodeHrTime(span.startTime),\n    endTimeUnixNano: encoder.encodeHrTime(span.endTime),\n    attributes: toAttributes(span.attributes, encoder),\n    droppedAttributesCount: span.droppedAttributesCount,\n    events: span.events.map(event => toOtlpSpanEvent(event, encoder)),\n    droppedEventsCount: span.droppedEventsCount,\n    status: {\n      // API and proto enums share the same values\n      code: status.code as unknown as EStatusCode,\n      message: status.message,\n    },\n    links: span.links.map(link => toOtlpLink(link, encoder)),\n    droppedLinksCount: span.droppedLinksCount,\n    flags: buildSpanFlagsFrom(ctx.traceFlags, span.parentSpanContext?.isRemote),\n  };\n}\n\nexport function toOtlpLink(link: Link, encoder: Encoder): ILink {\n  return {\n    attributes: link.attributes ? toAttributes(link.attributes, encoder) : [],\n    spanId: encoder.encodeSpanContext(link.context.spanId),\n    traceId: encoder.encodeSpanContext(link.context.traceId),\n    traceState: link.context.traceState?.serialize(),\n    droppedAttributesCount: link.droppedAttributesCount || 0,\n    flags: buildSpanFlagsFrom(link.context.traceFlags, link.context.isRemote),\n  };\n}\n\nexport function toOtlpSpanEvent(\n  timedEvent: TimedEvent,\n  encoder: Encoder\n): IEvent {\n  return {\n    attributes: timedEvent.attributes\n      ? toAttributes(timedEvent.attributes, encoder)\n      : [],\n    name: timedEvent.name,\n    timeUnixNano: encoder.encodeHrTime(timedEvent.time),\n    droppedAttributesCount: timedEvent.droppedAttributesCount || 0,\n  };\n}\n\nexport function createExportTraceServiceRequest(\n  spans: ReadableSpan[],\n  encoder: Encoder\n): IExportTraceServiceRequest {\n  return {\n    resourceSpans: spanRecordsToResourceSpans(spans, encoder),\n  };\n}\n\nfunction createResourceMap(readableSpans: ReadableSpan[]) {\n  const resourceMap: Map<Resource, Map<string, ReadableSpan[]>> = new Map();\n  for (const record of readableSpans) {\n    let ilsMap = resourceMap.get(record.resource);\n\n    if (!ilsMap) {\n      ilsMap = new Map();\n      resourceMap.set(record.resource, ilsMap);\n    }\n\n    // TODO this is duplicated in basic tracer. Consolidate on a common helper in core\n    const instrumentationScopeKey = `${record.instrumentationScope.name}@${\n      record.instrumentationScope.version || ''\n    }:${record.instrumentationScope.schemaUrl || ''}`;\n    let records = ilsMap.get(instrumentationScopeKey);\n\n    if (!records) {\n      records = [];\n      ilsMap.set(instrumentationScopeKey, records);\n    }\n\n    records.push(record);\n  }\n\n  return resourceMap;\n}\n\nfunction spanRecordsToResourceSpans(\n  readableSpans: ReadableSpan[],\n  encoder: Encoder\n): IResourceSpans[] {\n  const resourceMap = createResourceMap(readableSpans);\n  const out: IResourceSpans[] = [];\n\n  const entryIterator = resourceMap.entries();\n  let entry = entryIterator.next();\n  while (!entry.done) {\n    const [resource, ilmMap] = entry.value;\n    const scopeResourceSpans: IScopeSpans[] = [];\n    const ilmIterator = ilmMap.values();\n    let ilmEntry = ilmIterator.next();\n    while (!ilmEntry.done) {\n      const scopeSpans = ilmEntry.value;\n      if (scopeSpans.length > 0) {\n        const spans = scopeSpans.map(readableSpan =>\n          sdkSpanToOtlpSpan(readableSpan, encoder)\n        );\n\n        scopeResourceSpans.push({\n          scope: createInstrumentationScope(\n            scopeSpans[0].instrumentationScope,\n            encoder\n          ),\n          spans: spans,\n          schemaUrl: scopeSpans[0].instrumentationScope.schemaUrl,\n        });\n      }\n      ilmEntry = ilmIterator.next();\n    }\n    const processedResource = createResource(resource, encoder);\n    const transformedSpans: IResourceSpans = {\n      resource: processedResource,\n      scopeSpans: scopeResourceSpans,\n      schemaUrl: processedResource.schemaUrl,\n    };\n\n    out.push(transformedSpans);\n    entry = entryIterator.next();\n  }\n\n  return out;\n}\n","/*\n * Copyright The OpenTelemetry Authors\n * SPDX-License-Identifier: Apache-2.0\n */\nimport type { ISerializer } from '../../i-serializer';\nimport type { ReadableSpan } from '@opentelemetry/sdk-trace-base';\nimport type { IExportTraceServiceResponse } from '../export-response';\nimport { createExportTraceServiceRequest } from '../internal';\nimport { JSON_ENCODER } from '../../common/utils';\nimport { diag } from '@opentelemetry/api';\n\nexport const JsonTraceSerializer: ISerializer<\n  ReadableSpan[],\n  IExportTraceServiceResponse\n> = {\n  serializeRequest: (arg: ReadableSpan[]) => {\n    const request = createExportTraceServiceRequest(arg, JSON_ENCODER);\n    const encoder = new TextEncoder();\n    return encoder.encode(JSON.stringify(request));\n  },\n  deserializeResponse: (arg: Uint8Array) => {\n    if (arg.length === 0) {\n      return {};\n    }\n    const decoder = new TextDecoder();\n    try {\n      return JSON.parse(decoder.decode(arg)) as IExportTraceServiceResponse;\n    } catch (err) {\n      diag.warn(\n        `Failed to parse trace export response: ${err.message}. Returning empty response`\n      );\n      return {};\n    }\n  },\n};\n","/*\n * Copyright The OpenTelemetry Authors\n * SPDX-License-Identifier: Apache-2.0\n */\n\nimport { diag } from '@opentelemetry/api';\n\n/**\n * Parses headers from config leaving only those that have defined values\n * @param partialHeaders\n */\nexport function validateAndNormalizeHeaders(\n  partialHeaders: Record<string, string> | undefined\n): Record<string, string> {\n  const headers: Record<string, string> = {};\n  Object.entries(partialHeaders ?? {}).forEach(([key, value]) => {\n    if (typeof value !== 'undefined') {\n      headers[key] = String(value);\n    } else {\n      diag.warn(\n        `Header \"${key}\" has invalid value (${value}) and will be ignored`\n      );\n    }\n  });\n  return headers;\n}\n","/*\n * Copyright The OpenTelemetry Authors\n * SPDX-License-Identifier: Apache-2.0\n */\n\nimport type { OtlpSharedConfiguration } from './shared-configuration';\nimport {\n  getSharedConfigurationDefaults,\n  mergeOtlpSharedConfigurationWithDefaults,\n} from './shared-configuration';\nimport { validateAndNormalizeHeaders } from '../util';\n\nexport type HeadersFactory = () => Promise<Record<string, string>>;\n\nexport interface OtlpHttpConfiguration extends OtlpSharedConfiguration {\n  url: string;\n  headers: HeadersFactory;\n}\n\nfunction mergeHeaders(\n  userProvidedHeaders: HeadersFactory | undefined | null,\n  fallbackHeaders: HeadersFactory | undefined | null,\n  defaultHeaders: HeadersFactory\n): HeadersFactory {\n  return async () => {\n    const requiredHeaders = {\n      ...(await defaultHeaders()),\n    };\n    const headers = {};\n\n    // add fallback ones first\n    if (fallbackHeaders != null) {\n      Object.assign(headers, await fallbackHeaders());\n    }\n\n    // override with user-provided ones\n    if (userProvidedHeaders != null) {\n      Object.assign(\n        headers,\n        validateAndNormalizeHeaders(await userProvidedHeaders())\n      );\n    }\n\n    // override required ones.\n    return Object.assign(headers, requiredHeaders);\n  };\n}\n\nfunction validateUserProvidedUrl(url: string | undefined): string | undefined {\n  if (url == null) {\n    return undefined;\n  }\n  try {\n    // NOTE: In non-browser environments, `globalThis.location` will be `undefined`.\n    const base = globalThis.location?.href;\n    return new URL(url, base).href;\n  } catch {\n    throw new Error(\n      `Configuration: Could not parse user-provided export URL: '${url}'`\n    );\n  }\n}\n\n/**\n * @param userProvidedConfiguration  Configuration options provided by the user in code.\n * @param fallbackConfiguration Fallback to use when the {@link userProvidedConfiguration} does not specify an option.\n * @param defaultConfiguration The defaults as defined by the exporter specification\n */\nexport function mergeOtlpHttpConfigurationWithDefaults(\n  userProvidedConfiguration: Partial<OtlpHttpConfiguration>,\n  fallbackConfiguration: Partial<OtlpHttpConfiguration>,\n  defaultConfiguration: OtlpHttpConfiguration\n): OtlpHttpConfiguration {\n  return {\n    ...mergeOtlpSharedConfigurationWithDefaults(\n      userProvidedConfiguration,\n      fallbackConfiguration,\n      defaultConfiguration\n    ),\n    headers: mergeHeaders(\n      userProvidedConfiguration.headers,\n      fallbackConfiguration.headers,\n      defaultConfiguration.headers\n    ),\n    url:\n      validateUserProvidedUrl(userProvidedConfiguration.url) ??\n      fallbackConfiguration.url ??\n      defaultConfiguration.url,\n  };\n}\n\nexport function getHttpConfigurationDefaults(\n  requiredHeaders: Record<string, string>,\n  signalResourcePath: string\n): OtlpHttpConfiguration {\n  return {\n    ...getSharedConfigurationDefaults(),\n    headers: async () => requiredHeaders,\n    url: 'http://localhost:4318/' + signalResourcePath,\n  };\n}\n","/*\n * Copyright The OpenTelemetry Authors\n * SPDX-License-Identifier: Apache-2.0\n */\nimport type { OtlpHttpConfiguration } from './otlp-http-configuration';\nimport {\n  getHttpConfigurationDefaults,\n  mergeOtlpHttpConfigurationWithDefaults,\n} from './otlp-http-configuration';\n\n// NOTE: do not change these imports to be actual imports, otherwise they WILL break `@opentelemetry/instrumentation-http`\nimport type * as http from 'http';\nimport type * as https from 'https';\n\nexport type HttpAgentFactory = (\n  protocol: string\n) => http.Agent | https.Agent | Promise<http.Agent> | Promise<https.Agent>;\n\nexport interface OtlpNodeHttpConfiguration extends OtlpHttpConfiguration {\n  /**\n   * Factory function for creating agents.\n   *\n   * @remarks\n   * Prefer using {@link httpAgentFactoryFromOptions} over manually writing a factory function wherever possible.\n   * If using a factory function (`HttpAgentFactory`), **do not import `http.Agent` or `https.Agent`\n   * statically at the top of the file**.\n   * Instead, use dynamic `import()` or `require()` to load the module. This ensures that the `http` or `https`\n   * module is not loaded before `@opentelemetry/instrumentation-http` can instrument it.\n   */\n  agentFactory: HttpAgentFactory;\n  /**\n   * User agent header string to be appended to the exporter's value as a prefix.\n   * Availablie since v1.49.0 of the spec.\n   * Ref: https://opentelemetry.io/docs/specs/otel/protocol/exporter/#user-agent\n   */\n  userAgent?: string;\n}\n\nexport function httpAgentFactoryFromOptions(\n  options: http.AgentOptions | https.AgentOptions\n): HttpAgentFactory {\n  return async protocol => {\n    const isInsecure = protocol === 'http:';\n    const module = isInsecure ? import('http') : import('https');\n    const { Agent } = await module;\n\n    if (isInsecure) {\n      // eslint-disable-next-line @typescript-eslint/no-unused-vars -- these props should not be used in agent options\n      const { ca, cert, key, ...insecureOptions } =\n        options as https.AgentOptions;\n      return new Agent(insecureOptions);\n    }\n    return new Agent(options);\n  };\n}\n\n/**\n * @param userProvidedConfiguration  Configuration options provided by the user in code.\n * @param fallbackConfiguration Fallback to use when the {@link userProvidedConfiguration} does not specify an option.\n * @param defaultConfiguration The defaults as defined by the exporter specification\n */\nexport function mergeOtlpNodeHttpConfigurationWithDefaults(\n  userProvidedConfiguration: Partial<OtlpNodeHttpConfiguration>,\n  fallbackConfiguration: Partial<OtlpNodeHttpConfiguration>,\n  defaultConfiguration: OtlpNodeHttpConfiguration\n): OtlpNodeHttpConfiguration {\n  return {\n    ...mergeOtlpHttpConfigurationWithDefaults(\n      userProvidedConfiguration,\n      fallbackConfiguration,\n      defaultConfiguration\n    ),\n    agentFactory:\n      userProvidedConfiguration.agentFactory ??\n      fallbackConfiguration.agentFactory ??\n      defaultConfiguration.agentFactory,\n    userAgent: userProvidedConfiguration.userAgent,\n  };\n}\n\nexport function getNodeHttpConfigurationDefaults(\n  requiredHeaders: Record<string, string>,\n  signalResourcePath: string\n): OtlpNodeHttpConfiguration {\n  return {\n    ...getHttpConfigurationDefaults(requiredHeaders, signalResourcePath),\n    agentFactory: httpAgentFactoryFromOptions({ keepAlive: true }),\n  };\n}\n","/*\n * Copyright The OpenTelemetry Authors\n * SPDX-License-Identifier: Apache-2.0\n */\nimport type * as http from 'http';\nimport type * as https from 'https';\nimport * as zlib from 'zlib';\nimport { Readable } from 'stream';\nimport type { ExportResponse } from '../export-response';\nimport {\n  isExportHTTPErrorRetryable,\n  parseRetryAfterToMills,\n} from '../is-export-retryable';\nimport { OTLPExporterError } from '../types';\nimport { VERSION } from '../version';\n\nconst DEFAULT_USER_AGENT = `OTel-OTLP-Exporter-JavaScript/${VERSION}`;\n\n/**\n * Maximum response body size (4 MB) that the HTTP transport will read.\n * If the server sends more data the connection is destroyed and the export\n * is treated as a non-retryable error regardless of status code.\n */\nexport const MAX_RESPONSE_BODY_SIZE = 4 * 1024 * 1024;\n\n/**\n * Sends data using http\n * @param request\n * @param url\n * @param headers\n * @param compression\n * @param userAgent\n * @param agent\n * @param data\n * @param timeoutMillis\n */\nexport function sendWithHttp(\n  request: typeof https.request | typeof http.request,\n  url: string,\n  headers: Record<string, string>,\n  compression: 'gzip' | 'none',\n  userAgent: string | undefined,\n  agent: http.Agent | https.Agent,\n  data: Uint8Array,\n  timeoutMillis: number\n): Promise<ExportResponse> {\n  return new Promise<ExportResponse>(resolve => {\n    const parsedUrl = new URL(url);\n\n    if (userAgent) {\n      headers['User-Agent'] = `${userAgent} ${DEFAULT_USER_AGENT}`;\n    } else {\n      headers['User-Agent'] = DEFAULT_USER_AGENT;\n    }\n\n    const options: http.RequestOptions | https.RequestOptions = {\n      method: 'POST',\n      headers,\n      agent,\n    };\n\n    const req = request(parsedUrl, options, (res: http.IncomingMessage) => {\n      const responseData: Buffer[] = [];\n      let responseSize = 0;\n      res.on('data', (chunk: Buffer) => {\n        responseSize += chunk.length;\n        if (responseSize > MAX_RESPONSE_BODY_SIZE) {\n          const sizeError = new Error(\n            `OTLP export response body exceeded size limit of ${MAX_RESPONSE_BODY_SIZE} bytes`\n          );\n          // Oversized responses are treated as non-retryable errors\n          // regardless of status code.\n          // Resolve before destroying: res.destroy() tears down the socket which\n          // triggers ECONNRESET on req.on('error'), so, resolving first makes that\n          // a no-op. res.on('error') does not fire because destroy() is called\n          // without an error argument.\n          resolve({ status: 'failure', error: sizeError });\n          res.destroy();\n          return;\n        }\n        responseData.push(chunk);\n      });\n\n      res.on('end', () => {\n        if (res.statusCode && res.statusCode <= 299) {\n          resolve({\n            status: 'success',\n            data: Buffer.concat(responseData),\n          });\n        } else if (\n          res.statusCode &&\n          isExportHTTPErrorRetryable(res.statusCode)\n        ) {\n          resolve({\n            status: 'retryable',\n            retryInMillis: parseRetryAfterToMills(res.headers['retry-after']),\n          });\n        } else {\n          const error = new OTLPExporterError(\n            res.statusMessage,\n            res.statusCode,\n            Buffer.concat(responseData).toString()\n          );\n          resolve({\n            status: 'failure',\n            error,\n          });\n        }\n      });\n\n      res.on('error', (error: Error) => {\n        // Note: 'end' may still be emitted after 'error' on the same response object, since we're resolving a promise,\n        // the first call to resolve() will determine the final state.\n        if (res.statusCode && res.statusCode <= 299) {\n          // If the response is successful but an error occurs while reading the response,\n          // we consider it a success since the data has been sent successfully.\n          resolve({\n            status: 'success',\n          });\n        } else if (\n          res.statusCode &&\n          isExportHTTPErrorRetryable(res.statusCode)\n        ) {\n          resolve({\n            status: 'retryable',\n            error: error,\n            retryInMillis: parseRetryAfterToMills(res.headers['retry-after']),\n          });\n        } else {\n          resolve({\n            status: 'failure',\n            error,\n          });\n        }\n      });\n    });\n\n    req.setTimeout(timeoutMillis, () => {\n      req.destroy();\n      resolve({\n        status: 'retryable',\n        error: new Error('Request timed out'),\n      });\n    });\n\n    req.on('error', (error: Error) => {\n      if (isHttpTransportNetworkErrorRetryable(error)) {\n        resolve({\n          status: 'retryable',\n          error,\n        });\n      } else {\n        resolve({\n          status: 'failure',\n          error,\n        });\n      }\n    });\n\n    compressAndSend(req, compression, data, (error: Error) => {\n      resolve({\n        status: 'failure',\n        error,\n      });\n    });\n  });\n}\n\nexport function compressAndSend(\n  req: http.ClientRequest,\n  compression: 'gzip' | 'none',\n  data: Uint8Array,\n  onError: (error: Error) => void\n) {\n  let dataStream = readableFromUint8Array(data);\n\n  if (compression === 'gzip') {\n    req.setHeader('Content-Encoding', 'gzip');\n    dataStream = dataStream\n      .on('error', onError)\n      .pipe(zlib.createGzip())\n      .on('error', onError);\n  }\n\n  dataStream.pipe(req).on('error', onError);\n}\n\nfunction readableFromUint8Array(buff: string | Uint8Array): Readable {\n  const readable = new Readable();\n  readable.push(buff);\n  readable.push(null);\n\n  return readable;\n}\n\nfunction isHttpTransportNetworkErrorRetryable(error: Error): boolean {\n  const RETRYABLE_NETWORK_ERROR_CODES = new Set([\n    'ECONNRESET',\n    'ECONNREFUSED',\n    'EPIPE',\n    'ETIMEDOUT',\n    'EAI_AGAIN',\n    'ENOTFOUND',\n    'ENETUNREACH',\n    'EHOSTUNREACH',\n  ]);\n\n  if ('code' in error && typeof error.code === 'string') {\n    return RETRYABLE_NETWORK_ERROR_CODES.has(error.code);\n  }\n\n  return false;\n}\n","/*\n * Copyright The OpenTelemetry Authors\n * SPDX-License-Identifier: Apache-2.0\n */\n\nexport function isExportHTTPErrorRetryable(statusCode: number): boolean {\n  return (\n    statusCode === 429 ||\n    statusCode === 502 ||\n    statusCode === 503 ||\n    statusCode === 504\n  );\n}\n\nexport function parseRetryAfterToMills(\n  retryAfter?: string | undefined | null\n): number | undefined {\n  if (retryAfter == null) {\n    return undefined;\n  }\n\n  const seconds = Number.parseInt(retryAfter, 10);\n  if (Number.isInteger(seconds)) {\n    return seconds > 0 ? seconds * 1000 : -1;\n  }\n  // https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Retry-After#directives\n  const delay = new Date(retryAfter).getTime() - Date.now();\n\n  if (delay >= 0) {\n    return delay;\n  }\n  return 0;\n}\n","/*\n * Copyright The OpenTelemetry Authors\n * SPDX-License-Identifier: Apache-2.0\n */\n\n// this is autogenerated file, see scripts/version-update.js\nexport const VERSION = '0.219.0';\n","/*\n * Copyright The OpenTelemetry Authors\n * SPDX-License-Identifier: Apache-2.0\n */\n\n// NOTE: do not change these type imports to actual imports. Doing so WILL break `@opentelemetry/instrumentation-http`,\n// as they'd be imported before the http/https modules can be wrapped.\nimport type * as https from 'https';\nimport type * as http from 'http';\nimport type { ExportResponse } from '../export-response';\nimport type { IExporterTransport } from '../exporter-transport';\nimport { sendWithHttp } from './http-transport-utils';\nimport type { NodeHttpRequestParameters } from './node-http-transport-types';\n\ninterface Utils {\n  agent: http.Agent | https.Agent;\n  request: typeof http.request | typeof https.request;\n}\n\nclass HttpExporterTransport implements IExporterTransport {\n  private _utils: Utils | null = null;\n  private _parameters: NodeHttpRequestParameters;\n\n  constructor(parameters: NodeHttpRequestParameters) {\n    this._parameters = parameters;\n  }\n\n  async send(data: Uint8Array, timeoutMillis: number): Promise<ExportResponse> {\n    const { agent, request } = await this._loadUtils();\n    const headers = await this._parameters.headers();\n\n    return sendWithHttp(\n      request,\n      this._parameters.url,\n      headers,\n      this._parameters.compression,\n      this._parameters.userAgent,\n      agent,\n      data,\n      timeoutMillis\n    );\n  }\n\n  shutdown() {\n    // intentionally left empty, nothing to do.\n  }\n\n  private async _loadUtils(): Promise<Utils> {\n    let utils = this._utils;\n\n    if (utils === null) {\n      const protocol = new URL(this._parameters.url).protocol;\n      const [agent, request] = await Promise.all([\n        this._parameters.agentFactory(protocol),\n        requestFunctionFactory(protocol),\n      ]);\n      utils = this._utils = { agent, request };\n    }\n\n    return utils;\n  }\n}\n\nasync function requestFunctionFactory(\n  protocol: string\n): Promise<typeof http.request | typeof https.request> {\n  const module = protocol === 'http:' ? import('http') : import('https');\n  const { request } = await module;\n  return request;\n}\n\nexport function createHttpExporterTransport(\n  parameters: NodeHttpRequestParameters\n): IExporterTransport {\n  return new HttpExporterTransport(parameters);\n}\n","/*\n * Copyright The OpenTelemetry Authors\n * SPDX-License-Identifier: Apache-2.0\n */\n\nimport type { IExporterTransport } from './exporter-transport';\nimport type { ExportResponse } from './export-response';\nimport { diag } from '@opentelemetry/api';\n\nconst MAX_ATTEMPTS = 5;\nconst INITIAL_BACKOFF = 1000;\nconst MAX_BACKOFF = 5000;\nconst BACKOFF_MULTIPLIER = 1.5;\nconst JITTER = 0.2;\n\n/**\n * Get a pseudo-random jitter that falls in the range of [-JITTER, +JITTER]\n */\nfunction getJitter() {\n  return Math.random() * (2 * JITTER) - JITTER;\n}\n\nclass RetryingTransport implements IExporterTransport {\n  private _transport: IExporterTransport;\n\n  constructor(transport: IExporterTransport) {\n    this._transport = transport;\n  }\n\n  private retry(\n    data: Uint8Array,\n    timeoutMillis: number,\n    inMillis: number\n  ): Promise<ExportResponse> {\n    return new Promise((resolve, reject) => {\n      setTimeout(() => {\n        this._transport.send(data, timeoutMillis).then(resolve, reject);\n      }, inMillis);\n    });\n  }\n\n  async send(data: Uint8Array, timeoutMillis: number): Promise<ExportResponse> {\n    let attempts = MAX_ATTEMPTS;\n    let nextBackoff = INITIAL_BACKOFF;\n\n    const deadline = Date.now() + timeoutMillis;\n    let result = await this._transport.send(data, timeoutMillis);\n\n    while (result.status === 'retryable' && attempts > 0) {\n      attempts--;\n\n      // use maximum of computed backoff and 0 to avoid negative timeouts\n      const backoff = Math.max(\n        Math.min(nextBackoff * (1 + getJitter()), MAX_BACKOFF),\n        0\n      );\n      nextBackoff = nextBackoff * BACKOFF_MULTIPLIER;\n      const retryInMillis = result.retryInMillis ?? backoff;\n\n      // return when expected retry time is after the export deadline.\n      const remainingTimeoutMillis = deadline - Date.now();\n      if (retryInMillis > remainingTimeoutMillis) {\n        diag.info(\n          `Export retry time ${Math.round(retryInMillis)}ms exceeds remaining timeout ${Math.round(\n            remainingTimeoutMillis\n          )}ms, not retrying further.`\n        );\n        return result;\n      }\n\n      diag.verbose(`Scheduling export retry in ${Math.round(retryInMillis)}ms`);\n      result = await this.retry(data, remainingTimeoutMillis, retryInMillis);\n    }\n\n    if (result.status === 'success') {\n      diag.verbose(\n        `Export succeeded after ${MAX_ATTEMPTS - attempts} retry attempts.`\n      );\n    } else if (result.status === 'retryable') {\n      diag.info(\n        `Export failed after maximum retry attempts (${MAX_ATTEMPTS}).`\n      );\n    } else {\n      diag.info(`Export failed with non-retryable error: ${result.error}`);\n    }\n\n    return result;\n  }\n\n  shutdown() {\n    return this._transport.shutdown();\n  }\n}\n\n/**\n * Creates an Exporter Transport that retries on 'retryable' response.\n */\nexport function createRetryingTransport(options: {\n  // Underlying transport to wrap.\n  transport: IExporterTransport;\n}): IExporterTransport {\n  return new RetryingTransport(options.transport);\n}\n","/*\n * Copyright The OpenTelemetry Authors\n * SPDX-License-Identifier: Apache-2.0\n */\nimport type { IOtlpExportDelegate } from './otlp-export-delegate';\nimport { createOtlpExportDelegate } from './otlp-export-delegate';\nimport type { ISerializer } from '@opentelemetry/otlp-transformer';\nimport { createHttpExporterTransport } from './transport/http-exporter-transport';\nimport { createBoundedQueueExportPromiseHandler } from './bounded-queue-export-promise-handler';\nimport { createRetryingTransport } from './retrying-transport';\nimport type { OtlpNodeHttpConfiguration } from './configuration/otlp-node-http-configuration';\n\nexport function createOtlpHttpExportDelegate<Internal, Response>(\n  options: OtlpNodeHttpConfiguration,\n  serializer: ISerializer<Internal, Response>\n): IOtlpExportDelegate<Internal> {\n  return createOtlpExportDelegate(\n    {\n      transport: createRetryingTransport({\n        transport: createHttpExporterTransport(options),\n      }),\n      serializer: serializer,\n      promiseHandler: createBoundedQueueExportPromiseHandler(options),\n    },\n    { timeout: options.timeoutMillis }\n  );\n}\n","/*\n * Copyright The OpenTelemetry Authors\n * SPDX-License-Identifier: Apache-2.0\n */\nimport { getNumberFromEnv, getStringFromEnv } from '@opentelemetry/core';\nimport type { OtlpSharedConfiguration } from './shared-configuration';\nimport { diag } from '@opentelemetry/api';\n\nfunction parseAndValidateTimeoutFromEnv(\n  timeoutEnvVar: string\n): number | undefined {\n  const envTimeout = getNumberFromEnv(timeoutEnvVar);\n  if (envTimeout != null) {\n    if (Number.isFinite(envTimeout) && envTimeout > 0) {\n      return envTimeout;\n    }\n    diag.warn(\n      `Configuration: ${timeoutEnvVar} is invalid, expected number greater than 0 (actual: ${envTimeout})`\n    );\n  }\n\n  return undefined;\n}\n\nfunction getTimeoutFromEnv(signalIdentifier: string) {\n  const specificTimeout = parseAndValidateTimeoutFromEnv(\n    `OTEL_EXPORTER_OTLP_${signalIdentifier}_TIMEOUT`\n  );\n  const nonSpecificTimeout = parseAndValidateTimeoutFromEnv(\n    'OTEL_EXPORTER_OTLP_TIMEOUT'\n  );\n\n  return specificTimeout ?? nonSpecificTimeout;\n}\n\nfunction parseAndValidateCompressionFromEnv(\n  compressionEnvVar: string\n): 'none' | 'gzip' | undefined {\n  const compression = getStringFromEnv(compressionEnvVar)?.trim();\n\n  if (compression == null || compression === 'none' || compression === 'gzip') {\n    return compression;\n  }\n\n  diag.warn(\n    `Configuration: ${compressionEnvVar} is invalid, expected 'none' or 'gzip' (actual: '${compression}')`\n  );\n  return undefined;\n}\n\nfunction getCompressionFromEnv(\n  signalIdentifier: string\n): 'none' | 'gzip' | undefined {\n  const specificCompression = parseAndValidateCompressionFromEnv(\n    `OTEL_EXPORTER_OTLP_${signalIdentifier}_COMPRESSION`\n  );\n  const nonSpecificCompression = parseAndValidateCompressionFromEnv(\n    'OTEL_EXPORTER_OTLP_COMPRESSION'\n  );\n\n  return specificCompression ?? nonSpecificCompression;\n}\n\nexport function getSharedConfigurationFromEnvironment(\n  signalIdentifier: string\n): Partial<OtlpSharedConfiguration> {\n  return {\n    timeoutMillis: getTimeoutFromEnv(signalIdentifier),\n    compression: getCompressionFromEnv(signalIdentifier),\n  };\n}\n","/*\n * Copyright The OpenTelemetry Authors\n * SPDX-License-Identifier: Apache-2.0\n */\nimport type { OTLPExporterNodeConfigBase } from './legacy-node-configuration';\nimport { diag } from '@opentelemetry/api';\nimport type {\n  HttpAgentFactory,\n  OtlpNodeHttpConfiguration,\n} from './otlp-node-http-configuration';\nimport {\n  getNodeHttpConfigurationDefaults,\n  mergeOtlpNodeHttpConfigurationWithDefaults,\n} from './otlp-node-http-configuration';\nimport { httpAgentFactoryFromOptions } from '../index-node-http';\nimport { getNodeHttpConfigurationFromEnvironment } from './otlp-node-http-env-configuration';\nimport { convertLegacyHeaders } from './convert-legacy-http-options';\n\nfunction convertLegacyAgentOptions(\n  config: OTLPExporterNodeConfigBase\n): HttpAgentFactory | undefined {\n  if (typeof config.httpAgentOptions === 'function') {\n    return config.httpAgentOptions;\n  }\n\n  let legacy = config.httpAgentOptions;\n  if (config.keepAlive != null) {\n    legacy = { keepAlive: config.keepAlive, ...legacy };\n  }\n\n  if (legacy != null) {\n    return httpAgentFactoryFromOptions(legacy);\n  } else {\n    return undefined;\n  }\n}\n\n/**\n * @deprecated this will be removed in 2.0\n * @param config\n * @param signalIdentifier\n * @param signalResourcePath\n * @param requiredHeaders\n */\nexport function convertLegacyHttpOptions(\n  config: OTLPExporterNodeConfigBase,\n  signalIdentifier: string,\n  signalResourcePath: string,\n  requiredHeaders: Record<string, string>\n): OtlpNodeHttpConfiguration {\n  // eslint-disable-next-line @typescript-eslint/no-explicit-any\n  if ((config as any).metadata) {\n    diag.warn('Metadata cannot be set when using http');\n  }\n\n  return mergeOtlpNodeHttpConfigurationWithDefaults(\n    {\n      url: config.url,\n      headers: convertLegacyHeaders(config),\n      concurrencyLimit: config.concurrencyLimit,\n      timeoutMillis: config.timeoutMillis,\n      compression: config.compression,\n      agentFactory: convertLegacyAgentOptions(config),\n      userAgent: config.userAgent,\n    },\n    getNodeHttpConfigurationFromEnvironment(\n      signalIdentifier,\n      signalResourcePath\n    ),\n    getNodeHttpConfigurationDefaults(requiredHeaders, signalResourcePath)\n  );\n}\n","/*\n * Copyright The OpenTelemetry Authors\n * SPDX-License-Identifier: Apache-2.0\n */\nimport * as fs from 'fs';\nimport * as path from 'path';\nimport { getStringFromEnv, parseKeyPairsIntoRecord } from '@opentelemetry/core';\nimport { diag } from '@opentelemetry/api';\nimport { getSharedConfigurationFromEnvironment } from './shared-env-configuration';\nimport { wrapStaticHeadersInFunction } from './shared-configuration';\nimport type { OtlpNodeHttpConfiguration } from './otlp-node-http-configuration';\nimport { httpAgentFactoryFromOptions } from './otlp-node-http-configuration';\n\nfunction getStaticHeadersFromEnv(\n  signalIdentifier: string\n): Record<string, string> | undefined {\n  const signalSpecificRawHeaders = getStringFromEnv(\n    `OTEL_EXPORTER_OTLP_${signalIdentifier}_HEADERS`\n  );\n  const nonSignalSpecificRawHeaders = getStringFromEnv(\n    'OTEL_EXPORTER_OTLP_HEADERS'\n  );\n\n  const signalSpecificHeaders = parseKeyPairsIntoRecord(\n    signalSpecificRawHeaders\n  );\n  const nonSignalSpecificHeaders = parseKeyPairsIntoRecord(\n    nonSignalSpecificRawHeaders\n  );\n\n  if (\n    Object.keys(signalSpecificHeaders).length === 0 &&\n    Object.keys(nonSignalSpecificHeaders).length === 0\n  ) {\n    return undefined;\n  }\n\n  // headers are combined instead of overwritten, with the specific headers taking precedence over\n  // the non-specific ones.\n  return Object.assign(\n    {},\n    parseKeyPairsIntoRecord(nonSignalSpecificRawHeaders),\n    parseKeyPairsIntoRecord(signalSpecificRawHeaders)\n  );\n}\n\nfunction appendRootPathToUrlIfNeeded(url: string): string | undefined {\n  try {\n    const parsedUrl = new URL(url);\n    // This will automatically append '/' if there's no root path.\n    return parsedUrl.toString();\n  } catch {\n    diag.warn(\n      `Configuration: Could not parse environment-provided export URL: '${url}', falling back to undefined`\n    );\n    return undefined;\n  }\n}\n\nfunction appendResourcePathToUrl(\n  url: string,\n  path: string\n): string | undefined {\n  try {\n    // just try to parse, if it fails we catch and warn.\n    new URL(url);\n  } catch {\n    diag.warn(\n      `Configuration: Could not parse environment-provided export URL: '${url}', falling back to undefined`\n    );\n    return undefined;\n  }\n\n  if (!url.endsWith('/')) {\n    url = url + '/';\n  }\n  url += path;\n\n  try {\n    // just try to parse, if it fails we catch and warn.\n    new URL(url);\n  } catch {\n    diag.warn(\n      `Configuration: Provided URL appended with '${path}' is not a valid URL, using 'undefined' instead of '${url}'`\n    );\n    return undefined;\n  }\n\n  return url;\n}\n\nfunction getNonSpecificUrlFromEnv(\n  signalResourcePath: string\n): string | undefined {\n  const envUrl = getStringFromEnv('OTEL_EXPORTER_OTLP_ENDPOINT');\n  if (envUrl === undefined) {\n    return undefined;\n  }\n  return appendResourcePathToUrl(envUrl, signalResourcePath);\n}\n\nfunction getSpecificUrlFromEnv(signalIdentifier: string): string | undefined {\n  const envUrl = getStringFromEnv(\n    `OTEL_EXPORTER_OTLP_${signalIdentifier}_ENDPOINT`\n  );\n  if (envUrl === undefined) {\n    return undefined;\n  }\n  return appendRootPathToUrlIfNeeded(envUrl);\n}\n\nfunction readFileFromEnv(\n  signalSpecificEnvVar: string,\n  nonSignalSpecificEnvVar: string,\n  warningMessage: string\n): Buffer | undefined {\n  const signalSpecificPath = getStringFromEnv(signalSpecificEnvVar);\n  const nonSignalSpecificPath = getStringFromEnv(nonSignalSpecificEnvVar);\n  const filePath = signalSpecificPath ?? nonSignalSpecificPath;\n\n  if (filePath != null) {\n    try {\n      return fs.readFileSync(path.resolve(process.cwd(), filePath));\n    } catch {\n      diag.warn(warningMessage);\n      return undefined;\n    }\n  } else {\n    return undefined;\n  }\n}\n\nfunction getClientCertificateFromEnv(\n  signalIdentifier: string\n): Buffer | undefined {\n  return readFileFromEnv(\n    `OTEL_EXPORTER_OTLP_${signalIdentifier}_CLIENT_CERTIFICATE`,\n    'OTEL_EXPORTER_OTLP_CLIENT_CERTIFICATE',\n    'Failed to read client certificate chain file'\n  );\n}\n\nfunction getClientKeyFromEnv(signalIdentifier: string): Buffer | undefined {\n  return readFileFromEnv(\n    `OTEL_EXPORTER_OTLP_${signalIdentifier}_CLIENT_KEY`,\n    'OTEL_EXPORTER_OTLP_CLIENT_KEY',\n    'Failed to read client certificate private key file'\n  );\n}\n\nfunction getRootCertificateFromEnv(\n  signalIdentifier: string\n): Buffer | undefined {\n  return readFileFromEnv(\n    `OTEL_EXPORTER_OTLP_${signalIdentifier}_CERTIFICATE`,\n    'OTEL_EXPORTER_OTLP_CERTIFICATE',\n    'Failed to read root certificate file'\n  );\n}\n\n/**\n * Reads and returns configuration from the environment\n *\n * @param signalIdentifier all caps part in environment variables that identifies the signal (e.g.: METRICS, TRACES, LOGS)\n * @param signalResourcePath signal resource path to append if necessary (e.g.: v1/metrics, v1/traces, v1/logs)\n */\nexport function getNodeHttpConfigurationFromEnvironment(\n  signalIdentifier: string,\n  signalResourcePath: string\n): Partial<OtlpNodeHttpConfiguration> {\n  return {\n    ...getSharedConfigurationFromEnvironment(signalIdentifier),\n    url:\n      getSpecificUrlFromEnv(signalIdentifier) ??\n      getNonSpecificUrlFromEnv(signalResourcePath),\n    headers: wrapStaticHeadersInFunction(\n      getStaticHeadersFromEnv(signalIdentifier)\n    ),\n    agentFactory: httpAgentFactoryFromOptions({\n      keepAlive: true,\n      ca: getRootCertificateFromEnv(signalIdentifier),\n      cert: getClientCertificateFromEnv(signalIdentifier),\n      key: getClientKeyFromEnv(signalIdentifier),\n    }),\n  };\n}\n","/*\n * Copyright The OpenTelemetry Authors\n * SPDX-License-Identifier: Apache-2.0\n */\n\nimport type { OTLPExporterConfigBase } from './legacy-base-configuration';\nimport { wrapStaticHeadersInFunction } from './shared-configuration';\nimport type { HeadersFactory } from './otlp-http-configuration';\n\nexport function convertLegacyHeaders(\n  config: OTLPExporterConfigBase\n): HeadersFactory | undefined {\n  if (typeof config.headers === 'function') {\n    return config.headers;\n  }\n  return wrapStaticHeadersInFunction(config.headers);\n}\n","/*\n * Copyright The OpenTelemetry Authors\n * SPDX-License-Identifier: Apache-2.0\n */\n\nimport type { ReadableSpan, SpanExporter } from '@opentelemetry/sdk-trace-base';\nimport type { OTLPExporterNodeConfigBase } from '@opentelemetry/otlp-exporter-base';\nimport { OTLPExporterBase } from '@opentelemetry/otlp-exporter-base';\nimport { JsonTraceSerializer } from '@opentelemetry/otlp-transformer';\nimport {\n  convertLegacyHttpOptions,\n  createOtlpHttpExportDelegate,\n} from '@opentelemetry/otlp-exporter-base/node-http';\n\n/**\n * Collector Trace Exporter for Node\n */\nexport class OTLPTraceExporter\n  extends OTLPExporterBase<ReadableSpan[]>\n  implements SpanExporter\n{\n  constructor(config: OTLPExporterNodeConfigBase = {}) {\n    super(\n      createOtlpHttpExportDelegate(\n        convertLegacyHttpOptions(config, 'TRACES', 'v1/traces', {\n          'Content-Type': 'application/json',\n        }),\n        JsonTraceSerializer\n      )\n    );\n  }\n}\n","/*\n * Copyright The OpenTelemetry Authors\n * SPDX-License-Identifier: Apache-2.0\n */\n\nimport * as api from '@opentelemetry/api';\nimport type { InstrumentationScope } from '@opentelemetry/core';\nimport { sanitizeAttributes, isTracingSuppressed } from '@opentelemetry/core';\nimport { SpanImpl } from './Span';\nimport type { GeneralLimits, SpanLimits, TracerConfig } from './types';\nimport { mergeConfig } from './utility';\nimport type { SpanProcessor } from './SpanProcessor';\nimport type { Sampler } from './Sampler';\nimport type { IdGenerator } from './IdGenerator';\nimport { RandomIdGenerator } from './platform';\nimport type { Resource } from '@opentelemetry/resources';\nimport { TracerMetrics } from './TracerMetrics';\nimport { VERSION } from './version';\nimport type { InspectFn, InspectStylizeOptions } from './inspect';\nimport {\n  formatInspect,\n  inspectCustom,\n  settledResourceAttributes,\n} from './inspect';\n\n/**\n * This class represents a basic tracer.\n */\nexport class Tracer implements api.Tracer {\n  private readonly _sampler: Sampler;\n  private readonly _generalLimits: GeneralLimits;\n  private readonly _spanLimits: SpanLimits;\n  private readonly _idGenerator: IdGenerator;\n  readonly instrumentationScope: InstrumentationScope;\n\n  private readonly _resource: Resource;\n  private readonly _spanProcessor: SpanProcessor;\n  private readonly _tracerMetrics: TracerMetrics;\n\n  /**\n   * Constructs a new Tracer instance.\n   */\n  constructor(\n    instrumentationScope: InstrumentationScope,\n    config: TracerConfig,\n    resource: Resource,\n    spanProcessor: SpanProcessor\n  ) {\n    const localConfig = mergeConfig(config);\n    this._sampler = localConfig.sampler;\n    this._generalLimits = localConfig.generalLimits;\n    this._spanLimits = localConfig.spanLimits;\n    this._idGenerator = config.idGenerator || new RandomIdGenerator();\n    this._resource = resource;\n    this._spanProcessor = spanProcessor;\n    this.instrumentationScope = instrumentationScope;\n\n    const meter = localConfig.meterProvider\n      ? localConfig.meterProvider.getMeter('@opentelemetry/sdk-trace', VERSION)\n      : api.createNoopMeter();\n    this._tracerMetrics = new TracerMetrics(meter);\n  }\n\n  /**\n   * Starts a new Span or returns the default NoopSpan based on the sampling\n   * decision.\n   */\n  startSpan(\n    name: string,\n    options: api.SpanOptions = {},\n    context = api.context.active()\n  ): api.Span {\n    // remove span from context in case a root span is requested via options\n    if (options.root) {\n      context = api.trace.deleteSpan(context);\n    }\n    const parentSpan = api.trace.getSpan(context);\n\n    if (isTracingSuppressed(context)) {\n      api.diag.debug('Instrumentation suppressed, returning Noop Span');\n      const nonRecordingSpan = api.trace.wrapSpanContext(\n        api.INVALID_SPAN_CONTEXT\n      );\n      return nonRecordingSpan;\n    }\n\n    const parentSpanContext = parentSpan?.spanContext();\n    const spanId = this._idGenerator.generateSpanId();\n    let validParentSpanContext;\n    let traceId;\n    let traceState;\n    if (\n      !parentSpanContext ||\n      !api.trace.isSpanContextValid(parentSpanContext)\n    ) {\n      // New root span.\n      traceId = this._idGenerator.generateTraceId();\n    } else {\n      // New child span.\n      traceId = parentSpanContext.traceId;\n      traceState = parentSpanContext.traceState;\n      validParentSpanContext = parentSpanContext;\n    }\n\n    const spanKind = options.kind ?? api.SpanKind.INTERNAL;\n    const links = (options.links ?? []).map(link => {\n      return {\n        context: link.context,\n        attributes: sanitizeAttributes(link.attributes),\n      };\n    });\n    const attributes = sanitizeAttributes(options.attributes);\n    // make sampling decision\n    const samplingResult = this._sampler.shouldSample(\n      context,\n      traceId,\n      name,\n      spanKind,\n      attributes,\n      links\n    );\n\n    const recordEndMetrics = this._tracerMetrics.startSpan(\n      parentSpanContext,\n      samplingResult.decision\n    );\n\n    traceState = samplingResult.traceState ?? traceState;\n\n    const traceFlags =\n      samplingResult.decision === api.SamplingDecision.RECORD_AND_SAMPLED\n        ? api.TraceFlags.SAMPLED\n        : api.TraceFlags.NONE;\n    const spanContext = { traceId, spanId, traceFlags, traceState };\n    if (samplingResult.decision === api.SamplingDecision.NOT_RECORD) {\n      api.diag.debug(\n        'Recording is off, propagating context in a non-recording span'\n      );\n      const nonRecordingSpan = api.trace.wrapSpanContext(spanContext);\n      return nonRecordingSpan;\n    }\n\n    // Set initial span attributes. The attributes object may have been mutated\n    // by the sampler, so we sanitize the merged attributes before setting them.\n    const initAttributes = sanitizeAttributes(\n      Object.assign(attributes, samplingResult.attributes)\n    );\n\n    const span = new SpanImpl({\n      resource: this._resource,\n      scope: this.instrumentationScope,\n      context,\n      spanContext,\n      name,\n      kind: spanKind,\n      links,\n      parentSpanContext: validParentSpanContext,\n      attributes: initAttributes,\n      startTime: options.startTime,\n      spanProcessor: this._spanProcessor,\n      spanLimits: this._spanLimits,\n      recordEndMetrics,\n    });\n    return span;\n  }\n\n  /**\n   * Starts a new {@link Span} and calls the given function passing it the\n   * created span as first argument.\n   * Additionally the new span gets set in context and this context is activated\n   * for the duration of the function call.\n   *\n   * **Important**: The callback function is responsible for calling `span.end()`\n   * to finish the span. Unlike some other OpenTelemetry implementations, the span\n   * is NOT automatically ended when the callback returns. If `span.end()` is not\n   * called, the span will never be exported and will be silently lost.\n   *\n   * @param name The name of the span\n   * @param [options] SpanOptions used for span creation\n   * @param [context] Context to use to extract parent\n   * @param fn function called in the context of the span and receives the newly created span as an argument\n   * @returns return value of fn\n   * @example\n   *   const something = tracer.startActiveSpan('op', span => {\n   *     try {\n   *       do some work\n   *       span.setStatus({code: SpanStatusCode.OK});\n   *       return something;\n   *     } catch (err) {\n   *       span.setStatus({\n   *         code: SpanStatusCode.ERROR,\n   *         message: err.message,\n   *       });\n   *       throw err;\n   *     } finally {\n   *       span.end();\n   *     }\n   *   });\n   * @example\n   *   const span = tracer.startActiveSpan('op', span => {\n   *     try {\n   *       do some work\n   *       return span;\n   *     } catch (err) {\n   *       span.setStatus({\n   *         code: SpanStatusCode.ERROR,\n   *         message: err.message,\n   *       });\n   *       throw err;\n   *     }\n   *   });\n   *   do some more work\n   *   span.end();\n   */\n  startActiveSpan<F extends (span: api.Span) => ReturnType<F>>(\n    name: string,\n    fn: F\n  ): ReturnType<F>;\n  startActiveSpan<F extends (span: api.Span) => ReturnType<F>>(\n    name: string,\n    opts: api.SpanOptions,\n    fn: F\n  ): ReturnType<F>;\n  startActiveSpan<F extends (span: api.Span) => ReturnType<F>>(\n    name: string,\n    opts: api.SpanOptions,\n    ctx: api.Context,\n    fn: F\n  ): ReturnType<F>;\n  startActiveSpan<F extends (span: api.Span) => ReturnType<F>>(\n    name: string,\n    arg2?: F | api.SpanOptions,\n    arg3?: F | api.Context,\n    arg4?: F\n  ): ReturnType<F> | undefined {\n    let opts: api.SpanOptions | undefined;\n    let ctx: api.Context | undefined;\n    let fn: F;\n\n    if (arguments.length < 2) {\n      return;\n    } else if (arguments.length === 2) {\n      fn = arg2 as F;\n    } else if (arguments.length === 3) {\n      opts = arg2 as api.SpanOptions | undefined;\n      fn = arg3 as F;\n    } else {\n      opts = arg2 as api.SpanOptions | undefined;\n      ctx = arg3 as api.Context | undefined;\n      fn = arg4 as F;\n    }\n\n    const parentContext = ctx ?? api.context.active();\n    const span = this.startSpan(name, opts, parentContext);\n    const contextWithSpanSet = api.trace.setSpan(parentContext, span);\n\n    return api.context.with(contextWithSpanSet, fn, undefined, span);\n  }\n\n  /** Returns the active {@link GeneralLimits}. */\n  getGeneralLimits(): GeneralLimits {\n    return this._generalLimits;\n  }\n\n  /** Returns the active {@link SpanLimits}. */\n  getSpanLimits(): SpanLimits {\n    return this._spanLimits;\n  }\n\n  [inspectCustom](\n    depth: number,\n    options: InspectStylizeOptions | undefined,\n    inspect: InspectFn | undefined\n  ): unknown {\n    const payload = {\n      instrumentationScope: this.instrumentationScope,\n      resource: { attributes: settledResourceAttributes(this._resource) },\n      spanLimits: this._spanLimits,\n      generalLimits: this._generalLimits,\n    };\n    return formatInspect('Tracer', payload, depth, options, inspect);\n  }\n}\n","/*\n * Copyright The OpenTelemetry Authors\n * SPDX-License-Identifier: Apache-2.0\n */\n\nimport type {\n  Context,\n  Exception,\n  HrTime,\n  Link,\n  Span as APISpan,\n  SpanOptions as APISpanOptions,\n  Attributes,\n  AttributeValue,\n  SpanContext,\n  SpanKind,\n  SpanStatus,\n  TimeInput,\n} from '@opentelemetry/api';\nimport { diag, SpanStatusCode } from '@opentelemetry/api';\nimport type { InstrumentationScope } from '@opentelemetry/core';\nimport {\n  addHrTimes,\n  millisToHrTime,\n  hrTime,\n  hrTimeDuration,\n  isAttributeValue,\n  isTimeInput,\n  isTimeInputHrTime,\n  otperformance,\n  sanitizeAttributes,\n} from '@opentelemetry/core';\nimport type { Resource } from '@opentelemetry/resources';\nimport {\n  ATTR_EXCEPTION_MESSAGE,\n  ATTR_EXCEPTION_STACKTRACE,\n  ATTR_EXCEPTION_TYPE,\n} from '@opentelemetry/semantic-conventions';\nimport type { ReadableSpan } from './export/ReadableSpan';\nimport { ExceptionEventName } from './enums';\nimport type { SpanProcessor } from './SpanProcessor';\nimport type { TimedEvent } from './TimedEvent';\nimport type { SpanLimits } from './types';\nimport type { InspectFn, InspectStylizeOptions } from './inspect';\nimport {\n  formatInspect,\n  inspectCustom,\n  settledResourceAttributes,\n} from './inspect';\n\n/**\n * This type provides the properties of @link{ReadableSpan} at the same time\n * of the Span API\n */\nexport type Span = APISpan & ReadableSpan;\n\n// `root` is omitted because it is consumed by Tracer.startSpan() to strip\n// parent context but it has no meaning when constructing a Span directly.\ntype SpanOptions = Omit<APISpanOptions, 'root'> & {\n  resource: Resource;\n  scope: InstrumentationScope;\n  context: Context;\n  spanContext: SpanContext;\n  name: string;\n  // Required here to override optional `kind` from the API's SpanOptions\n  // SpanImpl assigns it unconditionally and ReadableSpan expects it to be set.\n  kind: SpanKind;\n  parentSpanContext?: SpanContext;\n  spanLimits: SpanLimits;\n  spanProcessor: SpanProcessor;\n  recordEndMetrics?: () => void;\n};\n\n/**\n * This class represents a span.\n */\nexport class SpanImpl implements Span {\n  // Below properties are included to implement ReadableSpan for export\n  // purposes but are not intended to be written-to directly.\n  private readonly _spanContext: SpanContext;\n  readonly kind: SpanKind;\n  readonly parentSpanContext?: SpanContext;\n  readonly attributes: Attributes = {};\n  readonly links: Link[] = [];\n  readonly events: TimedEvent[] = [];\n  readonly startTime: HrTime;\n  readonly resource: Resource;\n  readonly instrumentationScope: InstrumentationScope;\n\n  private _droppedAttributesCount = 0;\n  private _droppedEventsCount: number = 0;\n  private _droppedLinksCount: number = 0;\n  private _attributesCount: number = 0;\n\n  name: string;\n  status: SpanStatus = {\n    code: SpanStatusCode.UNSET,\n  };\n  endTime: HrTime = [0, 0];\n  private _ended = false;\n  private _duration: HrTime = [-1, -1];\n  private readonly _spanProcessor: SpanProcessor;\n  private readonly _spanLimits: SpanLimits;\n  private readonly _attributeValueLengthLimit: number;\n  private readonly _recordEndMetrics?: () => void;\n\n  private readonly _performanceStartTime: number;\n  private readonly _performanceOffset: number;\n  private readonly _startTimeProvided: boolean;\n\n  /**\n   * Constructs a new SpanImpl instance.\n   */\n  constructor(opts: SpanOptions) {\n    const now = Date.now();\n\n    this._spanContext = opts.spanContext;\n    this._performanceStartTime = otperformance.now();\n    this._performanceOffset =\n      now - (this._performanceStartTime + otperformance.timeOrigin);\n    this._startTimeProvided = opts.startTime != null;\n    this._spanLimits = opts.spanLimits;\n    this._attributeValueLengthLimit =\n      this._spanLimits.attributeValueLengthLimit ?? 0;\n    this._spanProcessor = opts.spanProcessor;\n\n    this.name = opts.name;\n    this.parentSpanContext = opts.parentSpanContext;\n    this.kind = opts.kind;\n    if (opts.links) {\n      for (const link of opts.links) {\n        this.addLink(link);\n      }\n    }\n    this.startTime = this._getTime(opts.startTime ?? now);\n    this.resource = opts.resource;\n    this.instrumentationScope = opts.scope;\n    this._recordEndMetrics = opts.recordEndMetrics;\n\n    if (opts.attributes != null) {\n      this.setAttributes(opts.attributes);\n    }\n\n    this._spanProcessor.onStart(this, opts.context);\n  }\n\n  spanContext(): SpanContext {\n    return this._spanContext;\n  }\n\n  setAttribute(key: string, value?: AttributeValue): this;\n  setAttribute(key: string, value: unknown): this {\n    if (value == null || this._isSpanEnded()) return this;\n    if (key.length === 0) {\n      diag.warn(`Invalid attribute key: ${key}`);\n      return this;\n    }\n    if (!isAttributeValue(value)) {\n      diag.warn(`Invalid attribute value set for key: ${key}`);\n      return this;\n    }\n\n    const { attributeCountLimit } = this._spanLimits;\n    const isNewKey = !Object.prototype.hasOwnProperty.call(\n      this.attributes,\n      key\n    );\n\n    if (\n      attributeCountLimit !== undefined &&\n      this._attributesCount >= attributeCountLimit &&\n      isNewKey\n    ) {\n      this._droppedAttributesCount++;\n      return this;\n    }\n\n    this.attributes[key] = this._truncateToSize(value);\n    if (isNewKey) {\n      this._attributesCount++;\n    }\n    return this;\n  }\n\n  setAttributes(attributes: Attributes): this {\n    for (const key in attributes) {\n      if (Object.prototype.hasOwnProperty.call(attributes, key)) {\n        this.setAttribute(key, attributes[key]);\n      }\n    }\n    return this;\n  }\n\n  /**\n   *\n   * @param name Span Name\n   * @param [attributesOrStartTime] Span attributes or start time\n   *     if type is {@type TimeInput} and 3rd param is undefined\n   * @param [timeStamp] Specified time stamp for the event\n   */\n  addEvent(\n    name: string,\n    attributesOrStartTime?: Attributes | TimeInput,\n    timeStamp?: TimeInput\n  ): this {\n    if (this._isSpanEnded()) return this;\n\n    const { eventCountLimit } = this._spanLimits;\n\n    if (eventCountLimit === 0) {\n      diag.warn('No events allowed.');\n      this._droppedEventsCount++;\n      return this;\n    }\n\n    if (\n      eventCountLimit !== undefined &&\n      this.events.length >= eventCountLimit\n    ) {\n      if (this._droppedEventsCount === 0) {\n        diag.debug('Dropping extra events.');\n      }\n      this.events.shift();\n      this._droppedEventsCount++;\n    }\n\n    if (isTimeInput(attributesOrStartTime)) {\n      if (!isTimeInput(timeStamp)) {\n        timeStamp = attributesOrStartTime;\n      }\n      attributesOrStartTime = undefined;\n    }\n\n    const sanitized = sanitizeAttributes(attributesOrStartTime);\n    const { attributePerEventCountLimit } = this._spanLimits;\n    const attributes: Attributes = {};\n    let droppedAttributesCount = 0;\n    let eventAttributesCount = 0;\n\n    for (const attr in sanitized) {\n      if (!Object.prototype.hasOwnProperty.call(sanitized, attr)) {\n        continue;\n      }\n      const attrVal = sanitized[attr];\n      if (\n        attributePerEventCountLimit !== undefined &&\n        eventAttributesCount >= attributePerEventCountLimit\n      ) {\n        droppedAttributesCount++;\n        continue;\n      }\n      attributes[attr] = this._truncateToSize(attrVal!);\n      eventAttributesCount++;\n    }\n\n    this.events.push({\n      name,\n      attributes,\n      time: this._getTime(timeStamp),\n      droppedAttributesCount,\n    });\n    return this;\n  }\n\n  addLink(link: Link): this {\n    if (this._isSpanEnded()) return this;\n\n    const { linkCountLimit } = this._spanLimits;\n\n    if (linkCountLimit === 0) {\n      this._droppedLinksCount++;\n      return this;\n    }\n\n    if (linkCountLimit !== undefined && this.links.length >= linkCountLimit) {\n      if (this._droppedLinksCount === 0) {\n        diag.debug('Dropping extra links.');\n      }\n      this.links.shift();\n      this._droppedLinksCount++;\n    }\n\n    const { attributePerLinkCountLimit } = this._spanLimits;\n    const sanitized = sanitizeAttributes(link.attributes);\n    const attributes: Attributes = {};\n    let droppedAttributesCount = 0;\n    let linkAttributesCount = 0;\n\n    for (const attr in sanitized) {\n      if (!Object.prototype.hasOwnProperty.call(sanitized, attr)) {\n        continue;\n      }\n      const attrVal = sanitized[attr];\n      if (\n        attributePerLinkCountLimit !== undefined &&\n        linkAttributesCount >= attributePerLinkCountLimit\n      ) {\n        droppedAttributesCount++;\n        continue;\n      }\n      attributes[attr] = this._truncateToSize(attrVal!);\n      linkAttributesCount++;\n    }\n\n    const processedLink: Link = { context: link.context };\n    if (linkAttributesCount > 0) {\n      processedLink.attributes = attributes;\n    }\n    if (droppedAttributesCount > 0) {\n      processedLink.droppedAttributesCount = droppedAttributesCount;\n    }\n\n    this.links.push(processedLink);\n    return this;\n  }\n\n  addLinks(links: Link[]): this {\n    for (const link of links) {\n      this.addLink(link);\n    }\n    return this;\n  }\n\n  setStatus(status: SpanStatus): this {\n    if (this._isSpanEnded()) return this;\n    if (status.code === SpanStatusCode.UNSET) return this;\n    if (this.status.code === SpanStatusCode.OK) return this;\n\n    const newStatus: SpanStatus = { code: status.code };\n\n    // When using try-catch, the caught \"error\" is of type `any`. When then assigning `any` to `status.message`,\n    // TypeScript will not error. While this can happen during use of any API, it is more common on Span#setStatus()\n    // as it's likely used in a catch-block. Therefore, we validate if `status.message` is actually a string, null, or\n    // undefined to avoid an incorrect type causing issues downstream.\n    if (status.code === SpanStatusCode.ERROR) {\n      if (typeof status.message === 'string') {\n        newStatus.message = status.message;\n      } else if (status.message != null) {\n        diag.warn(\n          `Dropping invalid status.message of type '${typeof status.message}', expected 'string'`\n        );\n      }\n    }\n\n    this.status = newStatus;\n    return this;\n  }\n\n  updateName(name: string): this {\n    if (this._isSpanEnded()) return this;\n    this.name = name;\n    return this;\n  }\n\n  end(endTime?: TimeInput): void {\n    if (this._isSpanEnded()) {\n      diag.error(\n        `${this.name} ${this._spanContext.traceId}-${this._spanContext.spanId} - You can only call end() on a span once.`\n      );\n      return;\n    }\n    this.endTime = this._getTime(endTime);\n    this._duration = hrTimeDuration(this.startTime, this.endTime);\n\n    if (this._duration[0] < 0) {\n      diag.warn(\n        'Inconsistent start and end time, startTime > endTime. Setting span duration to 0ms.',\n        this.startTime,\n        this.endTime\n      );\n      this.endTime = this.startTime.slice() as HrTime;\n      this._duration = [0, 0];\n    }\n\n    if (this._droppedEventsCount > 0) {\n      diag.warn(\n        `Dropped ${this._droppedEventsCount} events because eventCountLimit reached`\n      );\n    }\n    if (this._droppedLinksCount > 0) {\n      diag.warn(\n        `Dropped ${this._droppedLinksCount} links because linkCountLimit reached`\n      );\n    }\n    if (this._spanProcessor.onEnding) {\n      this._spanProcessor.onEnding(this);\n    }\n\n    this._recordEndMetrics?.();\n    this._ended = true;\n    this._spanProcessor.onEnd(this);\n  }\n\n  private _getTime(inp?: TimeInput): HrTime {\n    if (typeof inp === 'number' && inp <= otperformance.now()) {\n      // must be a performance timestamp\n      // apply correction and convert to hrtime\n      return hrTime(inp + this._performanceOffset);\n    }\n\n    if (typeof inp === 'number') {\n      return millisToHrTime(inp);\n    }\n\n    if (inp instanceof Date) {\n      return millisToHrTime(inp.getTime());\n    }\n\n    if (isTimeInputHrTime(inp)) {\n      return inp;\n    }\n\n    if (this._startTimeProvided) {\n      // if user provided a time for the start manually\n      // we can't use duration to calculate event/end times\n      return millisToHrTime(Date.now());\n    }\n\n    const msDuration = otperformance.now() - this._performanceStartTime;\n    return addHrTimes(this.startTime, millisToHrTime(msDuration));\n  }\n\n  isRecording(): boolean {\n    return this._ended === false;\n  }\n\n  recordException(exception: Exception, time?: TimeInput): void {\n    const attributes: Attributes = {};\n    if (typeof exception === 'string') {\n      attributes[ATTR_EXCEPTION_MESSAGE] = exception;\n    } else if (exception) {\n      if (exception.code) {\n        attributes[ATTR_EXCEPTION_TYPE] = exception.code.toString();\n      } else if (exception.name) {\n        attributes[ATTR_EXCEPTION_TYPE] = exception.name;\n      }\n      if (exception.message) {\n        attributes[ATTR_EXCEPTION_MESSAGE] = exception.message;\n      }\n      if (exception.stack) {\n        attributes[ATTR_EXCEPTION_STACKTRACE] = exception.stack;\n      }\n    }\n\n    // these are minimum requirements from spec\n    if (attributes[ATTR_EXCEPTION_TYPE] || attributes[ATTR_EXCEPTION_MESSAGE]) {\n      this.addEvent(ExceptionEventName, attributes, time);\n    } else {\n      diag.warn(`Failed to record an exception ${exception}`);\n    }\n  }\n\n  get duration(): HrTime {\n    return this._duration;\n  }\n\n  get ended(): boolean {\n    return this._ended;\n  }\n\n  get droppedAttributesCount(): number {\n    return this._droppedAttributesCount;\n  }\n\n  get droppedEventsCount(): number {\n    return this._droppedEventsCount;\n  }\n\n  get droppedLinksCount(): number {\n    return this._droppedLinksCount;\n  }\n\n  private _isSpanEnded(): boolean {\n    if (this._ended) {\n      const error = new Error(\n        `Operation attempted on ended Span {traceId: ${this._spanContext.traceId}, spanId: ${this._spanContext.spanId}}`\n      );\n\n      diag.warn(\n        `Cannot execute the operation on ended Span {traceId: ${this._spanContext.traceId}, spanId: ${this._spanContext.spanId}}`,\n        error\n      );\n    }\n    return this._ended;\n  }\n\n  // Utility function to truncate given value within size\n  // for value type of string, will truncate to given limit\n  // for type of non-string, will return same value\n  private _truncateToLimitUtil(value: string, limit: number): string {\n    if (value.length <= limit) {\n      return value;\n    }\n    return value.substring(0, limit);\n  }\n\n  /**\n   * If the given attribute value is of type string and has more characters than given {@code attributeValueLengthLimit} then\n   * return string with truncated to {@code attributeValueLengthLimit} characters\n   *\n   * If the given attribute value is array of strings then\n   * return new array of strings with each element truncated to {@code attributeValueLengthLimit} characters\n   *\n   * Otherwise return same Attribute {@code value}\n   *\n   * @param value Attribute value\n   * @returns truncated attribute value if required, otherwise same value\n   */\n  private _truncateToSize(value: AttributeValue): AttributeValue {\n    const limit = this._attributeValueLengthLimit;\n    // Check limit\n    if (limit <= 0) {\n      // Negative values are invalid, so do not truncate\n      diag.warn(`Attribute value limit must be positive, got ${limit}`);\n      return value;\n    }\n\n    // String\n    if (typeof value === 'string') {\n      return this._truncateToLimitUtil(value, limit);\n    }\n\n    // Array of strings\n    if (Array.isArray(value)) {\n      return (value as []).map(val =>\n        typeof val === 'string' ? this._truncateToLimitUtil(val, limit) : val\n      );\n    }\n\n    // Other types, no need to apply value length limit\n    return value;\n  }\n\n  [inspectCustom](\n    depth: number,\n    options: InspectStylizeOptions | undefined,\n    inspect: InspectFn | undefined\n  ): unknown {\n    const payload = {\n      name: this.name,\n      kind: this.kind,\n      spanContext: this._spanContext,\n      parentSpanContext: this.parentSpanContext,\n      status: this.status,\n      startTime: this.startTime,\n      endTime: this.endTime,\n      duration: this._duration,\n      ended: this._ended,\n      attributes: this.attributes,\n      events: this.events,\n      links: this.links,\n      droppedAttributesCount: this._droppedAttributesCount,\n      droppedEventsCount: this._droppedEventsCount,\n      droppedLinksCount: this._droppedLinksCount,\n      instrumentationScope: this.instrumentationScope,\n      resource: { attributes: settledResourceAttributes(this.resource) },\n    };\n    return formatInspect('SpanImpl', payload, depth, options, inspect);\n  }\n}\n","/*\n * Copyright The OpenTelemetry Authors\n * SPDX-License-Identifier: Apache-2.0\n */\n\n// Event name definitions\nexport const ExceptionEventName = 'exception';\n","/*\n * Copyright The OpenTelemetry Authors\n * SPDX-License-Identifier: Apache-2.0\n */\n\nimport type { Attributes, AttributeValue } from '@opentelemetry/api';\nimport type { Resource } from '@opentelemetry/resources';\n\n/**\n * Well-known symbol used by Node.js `util.inspect` (and `console.*`) to\n * render an object via a custom representation. Defined as a global Symbol\n * so it works without importing from `node:util`, keeping this module safe\n * for browser builds (where the symbol is simply never looked up).\n */\nexport const inspectCustom = Symbol.for('nodejs.util.inspect.custom');\n\n/**\n * Collect a Resource's settled attributes without touching the\n * `attributes` getter, which emits diag.error/debug entries when async\n * attribute detectors are still pending. Promise-like (unsettled)\n * entries are silently skipped so logging a Span/Tracer/Provider during\n * startup doesn't recurse through the diag pipeline.\n */\nexport function settledResourceAttributes(resource: Resource): Attributes {\n  const attrs: Attributes = {};\n  for (const [k, v] of resource.getRawAttributes()) {\n    if (typeof (v as Partial<PromiseLike<unknown>>)?.then === 'function') {\n      continue;\n    }\n    if (v != null) {\n      attrs[k] ??= v as AttributeValue;\n    }\n  }\n  return attrs;\n}\n\nexport type InspectFn = (value: unknown, options: unknown) => string;\n\nexport interface InspectStylizeOptions {\n  depth?: number | null;\n  stylize?: (text: string, styleType: string) => string;\n}\n\n/**\n * Build a class-tagged inspect representation. Returns a stub like\n * `[ClassName]` once the recursion budget is exhausted, otherwise returns\n * `ClassName <inspected payload>` so nested fields keep proper coloring,\n * indentation, and depth handling. In environments that don't supply an\n * `inspect` callback (e.g. browsers), falls back to returning the raw\n * payload object.\n */\nexport function formatInspect(\n  className: string,\n  payload: object,\n  depth: number,\n  options: InspectStylizeOptions | undefined,\n  inspect: InspectFn | undefined\n): unknown {\n  if (typeof depth === 'number' && depth < 0) {\n    const tag = `[${className}]`;\n    return options?.stylize ? options.stylize(tag, 'special') : tag;\n  }\n  if (typeof inspect !== 'function' || !options) {\n    return payload;\n  }\n  const childOptions = {\n    ...options,\n    depth: options.depth == null ? options.depth : options.depth - 1,\n  };\n  return `${className} ${inspect(payload, childOptions)}`;\n}\n","/*\n * Copyright The OpenTelemetry Authors\n * SPDX-License-Identifier: Apache-2.0\n */\n\nimport { diag } from '@opentelemetry/api';\nimport { getNumberFromEnv, getStringFromEnv } from '@opentelemetry/core';\nimport type { Sampler } from './Sampler';\nimport { AlwaysOffSampler } from './sampler/AlwaysOffSampler';\nimport { AlwaysOnSampler } from './sampler/AlwaysOnSampler';\nimport { ParentBasedSampler } from './sampler/ParentBasedSampler';\nimport { TraceIdRatioBasedSampler } from './sampler/TraceIdRatioBasedSampler';\n\nconst enum TracesSamplerValues {\n  AlwaysOff = 'always_off',\n  AlwaysOn = 'always_on',\n  ParentBasedAlwaysOff = 'parentbased_always_off',\n  ParentBasedAlwaysOn = 'parentbased_always_on',\n  ParentBasedTraceIdRatio = 'parentbased_traceidratio',\n  TraceIdRatio = 'traceidratio',\n}\n\nconst DEFAULT_RATIO = 1;\n\n/**\n * Load default configuration. For fields with primitive values, any user-provided\n * value will override the corresponding default value. For fields with\n * non-primitive values (like `spanLimits`), the user-provided value will be\n * used to extend the default value.\n */\n\n// object needs to be wrapped in this function and called when needed otherwise\n// envs are parsed before tests are ran - causes tests using these envs to fail\nexport function loadDefaultConfig() {\n  return {\n    sampler: buildSamplerFromEnv(),\n    forceFlushTimeoutMillis: 30000,\n    generalLimits: {\n      attributeValueLengthLimit:\n        getNumberFromEnv('OTEL_ATTRIBUTE_VALUE_LENGTH_LIMIT') ?? Infinity,\n      attributeCountLimit:\n        getNumberFromEnv('OTEL_ATTRIBUTE_COUNT_LIMIT') ?? 128,\n    },\n    spanLimits: {\n      attributeValueLengthLimit:\n        getNumberFromEnv('OTEL_SPAN_ATTRIBUTE_VALUE_LENGTH_LIMIT') ?? Infinity,\n      attributeCountLimit:\n        getNumberFromEnv('OTEL_SPAN_ATTRIBUTE_COUNT_LIMIT') ?? 128,\n      linkCountLimit: getNumberFromEnv('OTEL_SPAN_LINK_COUNT_LIMIT') ?? 128,\n      eventCountLimit: getNumberFromEnv('OTEL_SPAN_EVENT_COUNT_LIMIT') ?? 128,\n      attributePerEventCountLimit:\n        getNumberFromEnv('OTEL_SPAN_ATTRIBUTE_PER_EVENT_COUNT_LIMIT') ?? 128,\n      attributePerLinkCountLimit:\n        getNumberFromEnv('OTEL_SPAN_ATTRIBUTE_PER_LINK_COUNT_LIMIT') ?? 128,\n    },\n  };\n}\n\n/**\n * Based on environment, builds a sampler, complies with specification.\n */\nexport function buildSamplerFromEnv(): Sampler {\n  const sampler =\n    getStringFromEnv('OTEL_TRACES_SAMPLER') ??\n    TracesSamplerValues.ParentBasedAlwaysOn;\n  switch (sampler) {\n    case TracesSamplerValues.AlwaysOn:\n      return new AlwaysOnSampler();\n    case TracesSamplerValues.AlwaysOff:\n      return new AlwaysOffSampler();\n    case TracesSamplerValues.ParentBasedAlwaysOn:\n      return new ParentBasedSampler({\n        root: new AlwaysOnSampler(),\n      });\n    case TracesSamplerValues.ParentBasedAlwaysOff:\n      return new ParentBasedSampler({\n        root: new AlwaysOffSampler(),\n      });\n    case TracesSamplerValues.TraceIdRatio:\n      return new TraceIdRatioBasedSampler(getSamplerProbabilityFromEnv());\n    case TracesSamplerValues.ParentBasedTraceIdRatio:\n      return new ParentBasedSampler({\n        root: new TraceIdRatioBasedSampler(getSamplerProbabilityFromEnv()),\n      });\n    default:\n      diag.error(\n        `OTEL_TRACES_SAMPLER value \"${sampler}\" invalid, defaulting to \"${TracesSamplerValues.ParentBasedAlwaysOn}\".`\n      );\n      return new ParentBasedSampler({\n        root: new AlwaysOnSampler(),\n      });\n  }\n}\n\nfunction getSamplerProbabilityFromEnv(): number | undefined {\n  const probability = getNumberFromEnv('OTEL_TRACES_SAMPLER_ARG');\n  if (probability == null) {\n    diag.error(\n      `OTEL_TRACES_SAMPLER_ARG is blank, defaulting to ${DEFAULT_RATIO}.`\n    );\n    return DEFAULT_RATIO;\n  }\n\n  if (probability < 0 || probability > 1) {\n    diag.error(\n      `OTEL_TRACES_SAMPLER_ARG=${probability} was given, but it is out of range ([0..1]), defaulting to ${DEFAULT_RATIO}.`\n    );\n    return DEFAULT_RATIO;\n  }\n\n  return probability;\n}\n","/*\n * Copyright The OpenTelemetry Authors\n * SPDX-License-Identifier: Apache-2.0\n */\n\nimport type {\n  Context,\n  Link,\n  Attributes,\n  SpanKind,\n  TraceState,\n} from '@opentelemetry/api';\n\n/**\n * A sampling decision that determines how a {@link Span} will be recorded\n * and collected.\n */\nexport enum SamplingDecision {\n  /**\n   * `Span.isRecording() === false`, span will not be recorded and all events\n   * and attributes will be dropped.\n   */\n  NOT_RECORD,\n  /**\n   * `Span.isRecording() === true`, but `Sampled` flag in {@link TraceFlags}\n   * MUST NOT be set.\n   */\n  RECORD,\n  /**\n   * `Span.isRecording() === true` AND `Sampled` flag in {@link TraceFlags}\n   * MUST be set.\n   */\n  RECORD_AND_SAMPLED,\n}\n\n/**\n * A sampling result contains a decision for a {@link Span} and additional\n * attributes the sampler would like to added to the Span.\n */\nexport interface SamplingResult {\n  /**\n   * A sampling decision, refer to {@link SamplingDecision} for details.\n   */\n  decision: SamplingDecision;\n  /**\n   * The list of attributes returned by SamplingResult MUST be immutable.\n   * Caller may call {@link Sampler}.shouldSample any number of times and\n   * can safely cache the returned value.\n   */\n  attributes?: Readonly<Attributes>;\n  /**\n   * A {@link TraceState} that will be associated with the {@link Span} through\n   * the new {@link SpanContext}. Samplers SHOULD return the TraceState from\n   * the passed-in {@link Context} if they do not intend to change it. Leaving\n   * the value undefined will also leave the TraceState unchanged.\n   */\n  traceState?: TraceState;\n}\n\n/**\n * This interface represent a sampler. Sampling is a mechanism to control the\n * noise and overhead introduced by OpenTelemetry by reducing the number of\n * samples of traces collected and sent to the backend.\n */\nexport interface Sampler {\n  /**\n   * Checks whether span needs to be created and tracked.\n   *\n   * @param context Parent Context which may contain a span.\n   * @param traceId of the span to be created. It can be different from the\n   *     traceId in the {@link SpanContext}. Typically in situations when the\n   *     span to be created starts a new trace.\n   * @param spanName of the span to be created.\n   * @param spanKind of the span to be created.\n   * @param attributes Initial set of Attributes for the Span being constructed.\n   * @param links Collection of links that will be associated with the Span to\n   *     be created. Typically useful for batch operations.\n   * @returns a {@link SamplingResult}.\n   */\n  shouldSample(\n    context: Context,\n    traceId: string,\n    spanName: string,\n    spanKind: SpanKind,\n    attributes: Attributes,\n    links: Link[]\n  ): SamplingResult;\n\n  /** Returns the sampler name or short description with the configuration. */\n  toString(): string;\n}\n","/*\n * Copyright The OpenTelemetry Authors\n * SPDX-License-Identifier: Apache-2.0\n */\n\nimport type { Sampler, SamplingResult } from '../Sampler';\nimport { SamplingDecision } from '../Sampler';\n\n/** Sampler that samples no traces. */\nexport class AlwaysOffSampler implements Sampler {\n  shouldSample(): SamplingResult {\n    return {\n      decision: SamplingDecision.NOT_RECORD,\n    };\n  }\n\n  toString(): string {\n    return 'AlwaysOffSampler';\n  }\n}\n","/*\n * Copyright The OpenTelemetry Authors\n * SPDX-License-Identifier: Apache-2.0\n */\n\nimport type { Sampler, SamplingResult } from '../Sampler';\nimport { SamplingDecision } from '../Sampler';\n\n/** Sampler that samples all traces. */\nexport class AlwaysOnSampler implements Sampler {\n  shouldSample(): SamplingResult {\n    return {\n      decision: SamplingDecision.RECORD_AND_SAMPLED,\n    };\n  }\n\n  toString(): string {\n    return 'AlwaysOnSampler';\n  }\n}\n","/*\n * Copyright The OpenTelemetry Authors\n * SPDX-License-Identifier: Apache-2.0\n */\n\nimport type { Context, Link, Attributes, SpanKind } from '@opentelemetry/api';\nimport { isSpanContextValid, TraceFlags, trace } from '@opentelemetry/api';\nimport { globalErrorHandler } from '@opentelemetry/core';\nimport { AlwaysOffSampler } from './AlwaysOffSampler';\nimport { AlwaysOnSampler } from './AlwaysOnSampler';\nimport type { Sampler, SamplingResult } from '../Sampler';\n\n/**\n * A composite sampler that either respects the parent span's sampling decision\n * or delegates to `delegateSampler` for root spans.\n */\nexport class ParentBasedSampler implements Sampler {\n  private _root: Sampler;\n  private _remoteParentSampled: Sampler;\n  private _remoteParentNotSampled: Sampler;\n  private _localParentSampled: Sampler;\n  private _localParentNotSampled: Sampler;\n\n  constructor(config: ParentBasedSamplerConfig) {\n    this._root = config.root;\n\n    if (!this._root) {\n      globalErrorHandler(\n        new Error('ParentBasedSampler must have a root sampler configured')\n      );\n      this._root = new AlwaysOnSampler();\n    }\n\n    this._remoteParentSampled =\n      config.remoteParentSampled ?? new AlwaysOnSampler();\n    this._remoteParentNotSampled =\n      config.remoteParentNotSampled ?? new AlwaysOffSampler();\n    this._localParentSampled =\n      config.localParentSampled ?? new AlwaysOnSampler();\n    this._localParentNotSampled =\n      config.localParentNotSampled ?? new AlwaysOffSampler();\n  }\n\n  shouldSample(\n    context: Context,\n    traceId: string,\n    spanName: string,\n    spanKind: SpanKind,\n    attributes: Attributes,\n    links: Link[]\n  ): SamplingResult {\n    const parentContext = trace.getSpanContext(context);\n\n    if (!parentContext || !isSpanContextValid(parentContext)) {\n      return this._root.shouldSample(\n        context,\n        traceId,\n        spanName,\n        spanKind,\n        attributes,\n        links\n      );\n    }\n\n    if (parentContext.isRemote) {\n      if (parentContext.traceFlags & TraceFlags.SAMPLED) {\n        return this._remoteParentSampled.shouldSample(\n          context,\n          traceId,\n          spanName,\n          spanKind,\n          attributes,\n          links\n        );\n      }\n      return this._remoteParentNotSampled.shouldSample(\n        context,\n        traceId,\n        spanName,\n        spanKind,\n        attributes,\n        links\n      );\n    }\n\n    if (parentContext.traceFlags & TraceFlags.SAMPLED) {\n      return this._localParentSampled.shouldSample(\n        context,\n        traceId,\n        spanName,\n        spanKind,\n        attributes,\n        links\n      );\n    }\n\n    return this._localParentNotSampled.shouldSample(\n      context,\n      traceId,\n      spanName,\n      spanKind,\n      attributes,\n      links\n    );\n  }\n\n  toString(): string {\n    return `ParentBased{root=${this._root.toString()}, remoteParentSampled=${this._remoteParentSampled.toString()}, remoteParentNotSampled=${this._remoteParentNotSampled.toString()}, localParentSampled=${this._localParentSampled.toString()}, localParentNotSampled=${this._localParentNotSampled.toString()}}`;\n  }\n}\n\ninterface ParentBasedSamplerConfig {\n  /** Sampler called for spans with no parent */\n  root: Sampler;\n  /** Sampler called for spans with a remote parent which was sampled. Default AlwaysOn */\n  remoteParentSampled?: Sampler;\n  /** Sampler called for spans with a remote parent which was not sampled. Default AlwaysOff */\n  remoteParentNotSampled?: Sampler;\n  /** Sampler called for spans with a local parent which was sampled. Default AlwaysOn */\n  localParentSampled?: Sampler;\n  /** Sampler called for spans with a local parent which was not sampled. Default AlwaysOff */\n  localParentNotSampled?: Sampler;\n}\n","/*\n * Copyright The OpenTelemetry Authors\n * SPDX-License-Identifier: Apache-2.0\n */\n\nimport { isValidTraceId } from '@opentelemetry/api';\nimport type { Sampler, SamplingResult } from '../Sampler';\nimport { SamplingDecision } from '../Sampler';\n\n/** Sampler that samples a given fraction of traces based of trace id deterministically. */\nexport class TraceIdRatioBasedSampler implements Sampler {\n  private readonly _ratio;\n  private _upperBound: number;\n\n  constructor(ratio = 0) {\n    this._ratio = this._normalize(ratio);\n    this._upperBound = Math.floor(this._ratio * 0xffffffff);\n  }\n\n  shouldSample(context: unknown, traceId: string): SamplingResult {\n    return {\n      decision:\n        isValidTraceId(traceId) && this._accumulate(traceId) < this._upperBound\n          ? SamplingDecision.RECORD_AND_SAMPLED\n          : SamplingDecision.NOT_RECORD,\n    };\n  }\n\n  toString(): string {\n    return `TraceIdRatioBased{${this._ratio}}`;\n  }\n\n  private _normalize(ratio: number): number {\n    if (typeof ratio !== 'number' || isNaN(ratio)) return 0;\n    return ratio >= 1 ? 1 : ratio <= 0 ? 0 : ratio;\n  }\n\n  private _accumulate(traceId: string): number {\n    let accumulation = 0;\n    for (let i = 0; i < 32; i += 8) {\n      let part = 0;\n      for (let j = 0; j < 8; j++) {\n        const c = traceId.charCodeAt(i + j);\n        // Convert hex char code to value: '0'-'9' -> 0-9, 'a'-'f' -> 10-15, 'A'-'F' -> 10-15\n        const v = c < 58 ? c - 48 : c < 71 ? c - 55 : c - 87;\n        part = (part << 4) | v;\n      }\n      accumulation = (accumulation ^ part) >>> 0;\n    }\n    return accumulation;\n  }\n}\n","/*\n * Copyright The OpenTelemetry Authors\n * SPDX-License-Identifier: Apache-2.0\n */\n\nimport { buildSamplerFromEnv, loadDefaultConfig } from './config';\nimport type { Sampler } from './Sampler';\nimport type { SpanLimits, TracerConfig, GeneralLimits } from './types';\nimport { getNumberFromEnv } from '@opentelemetry/core';\n\nexport const DEFAULT_ATTRIBUTE_COUNT_LIMIT = 128;\nexport const DEFAULT_ATTRIBUTE_VALUE_LENGTH_LIMIT = Infinity;\n\n/**\n * Function to merge Default configuration (as specified in './config') with\n * user provided configurations.\n */\nexport function mergeConfig(userConfig: TracerConfig): TracerConfig & {\n  sampler: Sampler;\n  spanLimits: SpanLimits;\n  generalLimits: GeneralLimits;\n} {\n  const perInstanceDefaults: Partial<TracerConfig> = {\n    sampler: buildSamplerFromEnv(),\n  };\n\n  const DEFAULT_CONFIG = loadDefaultConfig();\n\n  const target = Object.assign(\n    {},\n    DEFAULT_CONFIG,\n    perInstanceDefaults,\n    userConfig\n  );\n\n  target.generalLimits = Object.assign(\n    {},\n    DEFAULT_CONFIG.generalLimits,\n    userConfig.generalLimits || {}\n  );\n\n  target.spanLimits = Object.assign(\n    {},\n    DEFAULT_CONFIG.spanLimits,\n    userConfig.spanLimits || {}\n  );\n\n  return target;\n}\n\n/**\n * When general limits are provided and model specific limits are not,\n * configures the model specific limits by using the values from the general ones.\n * @param userConfig User provided tracer configuration\n */\nexport function reconfigureLimits(userConfig: TracerConfig): TracerConfig {\n  const spanLimits = Object.assign({}, userConfig.spanLimits);\n\n  /**\n   * Reassign span attribute count limit to use first non null value defined by user or use default value\n   */\n  spanLimits.attributeCountLimit =\n    userConfig.spanLimits?.attributeCountLimit ??\n    userConfig.generalLimits?.attributeCountLimit ??\n    getNumberFromEnv('OTEL_SPAN_ATTRIBUTE_COUNT_LIMIT') ??\n    getNumberFromEnv('OTEL_ATTRIBUTE_COUNT_LIMIT') ??\n    DEFAULT_ATTRIBUTE_COUNT_LIMIT;\n\n  /**\n   * Reassign span attribute value length limit to use first non null value defined by user or use default value\n   */\n  spanLimits.attributeValueLengthLimit =\n    userConfig.spanLimits?.attributeValueLengthLimit ??\n    userConfig.generalLimits?.attributeValueLengthLimit ??\n    getNumberFromEnv('OTEL_SPAN_ATTRIBUTE_VALUE_LENGTH_LIMIT') ??\n    getNumberFromEnv('OTEL_ATTRIBUTE_VALUE_LENGTH_LIMIT') ??\n    DEFAULT_ATTRIBUTE_VALUE_LENGTH_LIMIT;\n\n  return Object.assign({}, userConfig, { spanLimits });\n}\n","/*\n * Copyright The OpenTelemetry Authors\n * SPDX-License-Identifier: Apache-2.0\n */\n\nimport type { Context } from '@opentelemetry/api';\nimport { context, diag, TraceFlags } from '@opentelemetry/api';\nimport {\n  BindOnceFuture,\n  ExportResultCode,\n  getNumberFromEnv,\n  globalErrorHandler,\n  suppressTracing,\n} from '@opentelemetry/core';\nimport type { Span } from '../Span';\nimport type { SpanProcessor } from '../SpanProcessor';\nimport type { BufferConfig } from '../types';\nimport type { ReadableSpan } from './ReadableSpan';\nimport type { SpanExporter } from './SpanExporter';\n\n/**\n * Implementation of the {@link SpanProcessor} that batches spans exported by\n * the SDK then pushes them to the exporter pipeline.\n */\nexport abstract class BatchSpanProcessorBase<T extends BufferConfig>\n  implements SpanProcessor\n{\n  private readonly _maxExportBatchSize: number;\n  private readonly _maxQueueSize: number;\n  private readonly _scheduledDelayMillis: number;\n  private readonly _exportTimeoutMillis: number;\n  private readonly _exporter: SpanExporter;\n\n  private _isExporting = false;\n  private _finishedSpans: ReadableSpan[] = [];\n  private _timer: NodeJS.Timeout | number | undefined;\n  private _shutdownOnce: BindOnceFuture<void>;\n  private _droppedSpansCount: number = 0;\n\n  constructor(exporter: SpanExporter, config?: T) {\n    this._exporter = exporter;\n    this._maxExportBatchSize =\n      typeof config?.maxExportBatchSize === 'number'\n        ? config.maxExportBatchSize\n        : (getNumberFromEnv('OTEL_BSP_MAX_EXPORT_BATCH_SIZE') ?? 512);\n    this._maxQueueSize =\n      typeof config?.maxQueueSize === 'number'\n        ? config.maxQueueSize\n        : (getNumberFromEnv('OTEL_BSP_MAX_QUEUE_SIZE') ?? 2048);\n    this._scheduledDelayMillis =\n      typeof config?.scheduledDelayMillis === 'number'\n        ? config.scheduledDelayMillis\n        : (getNumberFromEnv('OTEL_BSP_SCHEDULE_DELAY') ?? 5000);\n    this._exportTimeoutMillis =\n      typeof config?.exportTimeoutMillis === 'number'\n        ? config.exportTimeoutMillis\n        : (getNumberFromEnv('OTEL_BSP_EXPORT_TIMEOUT') ?? 30000);\n\n    this._shutdownOnce = new BindOnceFuture(this._shutdown, this);\n\n    if (this._maxExportBatchSize > this._maxQueueSize) {\n      diag.warn(\n        'BatchSpanProcessor: maxExportBatchSize must be smaller or equal to maxQueueSize, setting maxExportBatchSize to match maxQueueSize'\n      );\n      this._maxExportBatchSize = this._maxQueueSize;\n    }\n  }\n\n  forceFlush(): Promise<void> {\n    if (this._shutdownOnce.isCalled) {\n      return this._shutdownOnce.promise;\n    }\n    return this._flushAll();\n  }\n\n  // does nothing.\n  onStart(_span: Span, _parentContext: Context): void {}\n\n  onEnd(span: ReadableSpan): void {\n    if (this._shutdownOnce.isCalled) {\n      return;\n    }\n\n    if ((span.spanContext().traceFlags & TraceFlags.SAMPLED) === 0) {\n      return;\n    }\n\n    this._addToBuffer(span);\n  }\n\n  shutdown(): Promise<void> {\n    return this._shutdownOnce.call();\n  }\n\n  private _shutdown() {\n    return Promise.resolve()\n      .then(() => {\n        return this.onShutdown();\n      })\n      .then(() => {\n        return this._flushAll();\n      })\n      .then(() => {\n        return this._exporter.shutdown();\n      });\n  }\n\n  /** Add a span in the buffer. */\n  private _addToBuffer(span: ReadableSpan) {\n    if (this._finishedSpans.length >= this._maxQueueSize) {\n      // limit reached, drop span\n\n      if (this._droppedSpansCount === 0) {\n        diag.debug('maxQueueSize reached, dropping spans');\n      }\n      this._droppedSpansCount++;\n\n      return;\n    }\n\n    if (this._droppedSpansCount > 0) {\n      // some spans were dropped, log once with count of spans dropped\n      diag.warn(\n        `Dropped ${this._droppedSpansCount} spans because maxQueueSize reached`\n      );\n      this._droppedSpansCount = 0;\n    }\n\n    this._finishedSpans.push(span);\n    this._maybeStartTimer();\n  }\n\n  /**\n   * Send all spans to the exporter respecting the batch size limit\n   * This function is used only on forceFlush or shutdown,\n   * for all other cases _flush should be used\n   * */\n  private _flushAll(): Promise<void> {\n    return new Promise((resolve, reject) => {\n      const promises = [];\n      // calculate number of batches\n      const count = Math.ceil(\n        this._finishedSpans.length / this._maxExportBatchSize\n      );\n      for (let i = 0, j = count; i < j; i++) {\n        promises.push(this._flushOneBatch());\n      }\n      Promise.all(promises)\n        .then(() => {\n          resolve();\n        })\n        .catch(reject);\n    });\n  }\n\n  private _flushOneBatch(): Promise<void> {\n    this._clearTimer();\n    if (this._finishedSpans.length === 0) {\n      return Promise.resolve();\n    }\n    return new Promise((resolve, reject) => {\n      const timer = setTimeout(() => {\n        // don't wait anymore for export, this way the next batch can start\n        reject(new Error('Timeout'));\n      }, this._exportTimeoutMillis);\n      // prevent downstream exporter calls from generating spans\n      context.with(suppressTracing(context.active()), () => {\n        // Reset the finished spans buffer here because the next invocations of the _flush method\n        // could pass the same finished spans to the exporter if the buffer is cleared\n        // outside the execution of this callback.\n        let spans: ReadableSpan[];\n        if (this._finishedSpans.length <= this._maxExportBatchSize) {\n          spans = this._finishedSpans;\n          this._finishedSpans = [];\n        } else {\n          spans = this._finishedSpans.splice(0, this._maxExportBatchSize);\n        }\n\n        const doExport = () =>\n          this._exporter.export(spans, result => {\n            clearTimeout(timer);\n            if (result.code === ExportResultCode.SUCCESS) {\n              resolve();\n            } else {\n              reject(\n                result.error ??\n                  new Error('BatchSpanProcessor: span export failed')\n              );\n            }\n          });\n\n        let pendingResources: Array<Promise<void>> | null = null;\n        for (let i = 0, len = spans.length; i < len; i++) {\n          const span = spans[i];\n          if (\n            span.resource.asyncAttributesPending &&\n            span.resource.waitForAsyncAttributes\n          ) {\n            pendingResources ??= [];\n            pendingResources.push(span.resource.waitForAsyncAttributes());\n          }\n        }\n\n        // Avoid scheduling a promise to make the behavior more predictable and easier to test\n        if (pendingResources === null) {\n          doExport();\n        } else {\n          Promise.all(pendingResources).then(doExport, err => {\n            globalErrorHandler(err);\n            reject(err);\n          });\n        }\n      });\n    });\n  }\n\n  private _maybeStartTimer() {\n    if (this._isExporting) return;\n    const flush = () => {\n      this._isExporting = true;\n      this._flushOneBatch()\n        .finally(() => {\n          this._isExporting = false;\n          if (this._finishedSpans.length > 0) {\n            this._clearTimer();\n            this._maybeStartTimer();\n          }\n        })\n        .catch(e => {\n          this._isExporting = false;\n          globalErrorHandler(e);\n        });\n    };\n    // we only wait if the queue doesn't have enough elements yet\n    if (this._finishedSpans.length >= this._maxExportBatchSize) {\n      return flush();\n    }\n    if (this._timer !== undefined) return;\n    this._timer = setTimeout(() => flush(), this._scheduledDelayMillis);\n\n    // depending on runtime, this may be a 'number' or NodeJS.Timeout\n    if (typeof this._timer !== 'number') {\n      this._timer.unref();\n    }\n  }\n\n  private _clearTimer() {\n    if (this._timer !== undefined) {\n      clearTimeout(this._timer);\n      this._timer = undefined;\n    }\n  }\n\n  protected abstract onShutdown(): void;\n}\n","/*\n * Copyright The OpenTelemetry Authors\n * SPDX-License-Identifier: Apache-2.0\n */\n\nimport { BatchSpanProcessorBase } from '../../../export/BatchSpanProcessorBase';\nimport type { BufferConfig } from '../../../types';\n\nexport class BatchSpanProcessor extends BatchSpanProcessorBase<BufferConfig> {\n  protected onShutdown(): void {}\n}\n","/*\n * Copyright The OpenTelemetry Authors\n * SPDX-License-Identifier: Apache-2.0\n */\n\nimport type { IdGenerator } from '../../IdGenerator';\n\nconst SPAN_ID_BYTES = 8;\nconst TRACE_ID_BYTES = 16;\n\nexport class RandomIdGenerator implements IdGenerator {\n  /**\n   * Returns a random 16-byte trace ID formatted/encoded as a 32 lowercase hex\n   * characters corresponding to 128 bits.\n   */\n  generateTraceId = getIdGenerator(TRACE_ID_BYTES);\n\n  /**\n   * Returns a random 8-byte span ID formatted/encoded as a 16 lowercase hex\n   * characters corresponding to 64 bits.\n   */\n  generateSpanId = getIdGenerator(SPAN_ID_BYTES);\n}\n\nconst SHARED_BUFFER = Buffer.allocUnsafe(TRACE_ID_BYTES);\nfunction getIdGenerator(bytes: number): () => string {\n  return function generateId() {\n    for (let i = 0; i < bytes / 4; i++) {\n      // unsigned right shift drops decimal part of the number\n      // it is required because if a number between 2**32 and 2**32 - 1 is generated, an out of range error is thrown by writeUInt32BE\n      SHARED_BUFFER.writeUInt32BE((Math.random() * 2 ** 32) >>> 0, i * 4);\n    }\n\n    // If buffer is all 0, set the last byte to 1 to guarantee a valid w3c id is generated\n    for (let i = 0; i < bytes; i++) {\n      if (SHARED_BUFFER[i] > 0) {\n        break;\n      } else if (i === bytes - 1) {\n        SHARED_BUFFER[bytes - 1] = 1;\n      }\n    }\n\n    return SHARED_BUFFER.toString('hex', 0, bytes);\n  };\n}\n","/*\n * Copyright The OpenTelemetry Authors\n * SPDX-License-Identifier: Apache-2.0\n */\n\n/*\n * This file contains a copy of unstable semantic convention definitions\n * used by this package.\n * @see https://github.com/open-telemetry/opentelemetry-js/tree/main/semantic-conventions#unstable-semconv\n */\n\n/**\n * Determines whether the span has a parent span, and if so, [whether it is a remote parent](https://opentelemetry.io/docs/specs/otel/trace/api/#isremote)\n *\n * @experimental This attribute is experimental and is subject to breaking changes in minor releases of `@opentelemetry/semantic-conventions`.\n */\nexport const ATTR_OTEL_SPAN_PARENT_ORIGIN = 'otel.span.parent.origin' as const;\n\n/**\n * The result value of the sampler for this span\n *\n * @experimental This attribute is experimental and is subject to breaking changes in minor releases of `@opentelemetry/semantic-conventions`.\n */\nexport const ATTR_OTEL_SPAN_SAMPLING_RESULT =\n  'otel.span.sampling_result' as const;\n\n/**\n * The number of created spans with `recording=true` for which the end operation has not been called yet.\n *\n * @experimental This metric is experimental and is subject to breaking changes in minor releases of `@opentelemetry/semantic-conventions`.\n */\nexport const METRIC_OTEL_SDK_SPAN_LIVE = 'otel.sdk.span.live' as const;\n\n/**\n * The number of created spans.\n *\n * @note Implementations **MUST** record this metric for all spans, even for non-recording ones.\n *\n * @experimental This metric is experimental and is subject to breaking changes in minor releases of `@opentelemetry/semantic-conventions`.\n */\nexport const METRIC_OTEL_SDK_SPAN_STARTED = 'otel.sdk.span.started' as const;\n","/*\n * Copyright The OpenTelemetry Authors\n * SPDX-License-Identifier: Apache-2.0\n */\nimport type {\n  Counter,\n  Meter,\n  SpanContext,\n  UpDownCounter,\n} from '@opentelemetry/api';\nimport { SamplingDecision } from './Sampler';\nimport {\n  ATTR_OTEL_SPAN_PARENT_ORIGIN,\n  ATTR_OTEL_SPAN_SAMPLING_RESULT,\n  METRIC_OTEL_SDK_SPAN_LIVE,\n  METRIC_OTEL_SDK_SPAN_STARTED,\n} from './semconv';\n\n/**\n * Generates `otel.sdk.span.*` metrics.\n * https://opentelemetry.io/docs/specs/semconv/otel/sdk-metrics/#span-metrics\n */\nexport class TracerMetrics {\n  private readonly startedSpans: Counter;\n  private readonly liveSpans: UpDownCounter;\n\n  constructor(meter: Meter) {\n    this.startedSpans = meter.createCounter(METRIC_OTEL_SDK_SPAN_STARTED, {\n      unit: '{span}',\n      description: 'The number of created spans.',\n    });\n\n    this.liveSpans = meter.createUpDownCounter(METRIC_OTEL_SDK_SPAN_LIVE, {\n      unit: '{span}',\n      description: 'The number of currently live spans.',\n    });\n  }\n\n  startSpan(\n    parentSpanCtx: SpanContext | undefined,\n    samplingDecision: SamplingDecision\n  ): () => void {\n    const samplingDecisionStr = samplingDecisionToString(samplingDecision);\n    this.startedSpans.add(1, {\n      [ATTR_OTEL_SPAN_PARENT_ORIGIN]: parentOrigin(parentSpanCtx),\n      [ATTR_OTEL_SPAN_SAMPLING_RESULT]: samplingDecisionStr,\n    });\n\n    if (samplingDecision === SamplingDecision.NOT_RECORD) {\n      return () => {};\n    }\n\n    const liveSpanAttributes = {\n      [ATTR_OTEL_SPAN_SAMPLING_RESULT]: samplingDecisionStr,\n    };\n    this.liveSpans.add(1, liveSpanAttributes);\n    return () => {\n      this.liveSpans.add(-1, liveSpanAttributes);\n    };\n  }\n}\n\nfunction parentOrigin(parentSpanContext: SpanContext | undefined): string {\n  if (!parentSpanContext) {\n    return 'none';\n  }\n  if (parentSpanContext.isRemote) {\n    return 'remote';\n  }\n  return 'local';\n}\n\nfunction samplingDecisionToString(decision: SamplingDecision): string {\n  switch (decision) {\n    case SamplingDecision.RECORD_AND_SAMPLED:\n      return 'RECORD_AND_SAMPLE';\n    case SamplingDecision.RECORD:\n      return 'RECORD_ONLY';\n    case SamplingDecision.NOT_RECORD:\n      return 'DROP';\n  }\n}\n","/*\n * Copyright The OpenTelemetry Authors\n * SPDX-License-Identifier: Apache-2.0\n */\n\n// this is autogenerated file, see scripts/version-update.js\nexport const VERSION = '2.8.0';\n","/*\n * Copyright The OpenTelemetry Authors\n * SPDX-License-Identifier: Apache-2.0\n */\n\nimport type { Context } from '@opentelemetry/api';\nimport { globalErrorHandler } from '@opentelemetry/core';\nimport type { ReadableSpan } from './export/ReadableSpan';\nimport type { Span } from './Span';\nimport type { SpanProcessor } from './SpanProcessor';\n\n/**\n * Implementation of the {@link SpanProcessor} that simply forwards all\n * received events to a list of {@link SpanProcessor}s.\n */\nexport class MultiSpanProcessor implements SpanProcessor {\n  private readonly _spanProcessors: SpanProcessor[];\n  constructor(spanProcessors: SpanProcessor[]) {\n    this._spanProcessors = spanProcessors;\n  }\n\n  forceFlush(): Promise<void> {\n    const promises: Promise<void>[] = [];\n\n    for (const spanProcessor of this._spanProcessors) {\n      promises.push(spanProcessor.forceFlush());\n    }\n    return new Promise(resolve => {\n      Promise.all(promises)\n        .then(() => {\n          resolve();\n        })\n        .catch(error => {\n          globalErrorHandler(\n            error || new Error('MultiSpanProcessor: forceFlush failed')\n          );\n          resolve();\n        });\n    });\n  }\n\n  onStart(span: Span, context: Context): void {\n    for (const spanProcessor of this._spanProcessors) {\n      spanProcessor.onStart(span, context);\n    }\n  }\n\n  onEnding(span: Span): void {\n    for (const spanProcessor of this._spanProcessors) {\n      if (spanProcessor.onEnding) {\n        spanProcessor.onEnding(span);\n      }\n    }\n  }\n\n  onEnd(span: ReadableSpan): void {\n    for (const spanProcessor of this._spanProcessors) {\n      spanProcessor.onEnd(span);\n    }\n  }\n\n  shutdown(): Promise<void> {\n    const promises: Promise<void>[] = [];\n\n    for (const spanProcessor of this._spanProcessors) {\n      promises.push(spanProcessor.shutdown());\n    }\n    return new Promise((resolve, reject) => {\n      Promise.all(promises).then(() => {\n        resolve();\n      }, reject);\n    });\n  }\n}\n","/*\n * Copyright The OpenTelemetry Authors\n * SPDX-License-Identifier: Apache-2.0\n */\n\nimport type { TracerProvider, Tracer as ApiTracer } from '@opentelemetry/api';\nimport { merge } from '@opentelemetry/core';\nimport type { Resource } from '@opentelemetry/resources';\nimport { defaultResource } from '@opentelemetry/resources';\nimport type { SpanProcessor } from './SpanProcessor';\nimport { Tracer } from './Tracer';\nimport { loadDefaultConfig } from './config';\nimport { MultiSpanProcessor } from './MultiSpanProcessor';\nimport type { TracerConfig } from './types';\nimport { reconfigureLimits } from './utility';\nimport type { InspectFn, InspectStylizeOptions } from './inspect';\nimport {\n  formatInspect,\n  inspectCustom,\n  settledResourceAttributes,\n} from './inspect';\n\nexport enum ForceFlushState {\n  'resolved',\n  'timeout',\n  'error',\n  'unresolved',\n}\n\n/**\n * This class represents a basic tracer provider which platform libraries can extend\n */\nexport class BasicTracerProvider implements TracerProvider {\n  private readonly _config: TracerConfig;\n  private readonly _tracers: Map<string, Tracer> = new Map();\n  private readonly _resource: Resource;\n  private readonly _activeSpanProcessor: MultiSpanProcessor;\n\n  constructor(config: TracerConfig = {}) {\n    const mergedConfig = merge(\n      {},\n      loadDefaultConfig(),\n      reconfigureLimits(config)\n    );\n    this._resource = mergedConfig.resource ?? defaultResource();\n\n    this._config = Object.assign({}, mergedConfig, {\n      resource: this._resource,\n    });\n\n    const spanProcessors: SpanProcessor[] = [];\n\n    if (config.spanProcessors?.length) {\n      spanProcessors.push(...config.spanProcessors);\n    }\n\n    this._activeSpanProcessor = new MultiSpanProcessor(spanProcessors);\n  }\n\n  getTracer(\n    name: string,\n    version?: string,\n    options?: { schemaUrl?: string }\n  ): ApiTracer {\n    const key = `${name}@${version || ''}:${options?.schemaUrl || ''}`;\n    if (!this._tracers.has(key)) {\n      this._tracers.set(\n        key,\n        new Tracer(\n          { name, version, schemaUrl: options?.schemaUrl },\n          this._config,\n          this._resource,\n          this._activeSpanProcessor\n        )\n      );\n    }\n\n    return this._tracers.get(key)!;\n  }\n\n  forceFlush(): Promise<void> {\n    const timeout = this._config.forceFlushTimeoutMillis;\n    const promises = this._activeSpanProcessor['_spanProcessors'].map(\n      (spanProcessor: SpanProcessor) => {\n        return new Promise(resolve => {\n          let state: ForceFlushState;\n          const timeoutInterval = setTimeout(() => {\n            resolve(\n              new Error(\n                `Span processor did not completed within timeout period of ${timeout} ms`\n              )\n            );\n            state = ForceFlushState.timeout;\n          }, timeout);\n\n          spanProcessor\n            .forceFlush()\n            .then(() => {\n              clearTimeout(timeoutInterval);\n              if (state !== ForceFlushState.timeout) {\n                state = ForceFlushState.resolved;\n                resolve(state);\n              }\n            })\n            .catch(error => {\n              clearTimeout(timeoutInterval);\n              state = ForceFlushState.error;\n              resolve(error);\n            });\n        });\n      }\n    );\n\n    return new Promise<void>((resolve, reject) => {\n      Promise.all(promises)\n        .then(results => {\n          const errors = results.filter(\n            result => result !== ForceFlushState.resolved\n          );\n          if (errors.length > 0) {\n            reject(errors);\n          } else {\n            resolve();\n          }\n        })\n        .catch(error => reject([error]));\n    });\n  }\n\n  shutdown(): Promise<void> {\n    return this._activeSpanProcessor.shutdown();\n  }\n\n  [inspectCustom](\n    depth: number,\n    options: InspectStylizeOptions | undefined,\n    inspect: InspectFn | undefined\n  ): unknown {\n    const processors = this._activeSpanProcessor[\n      '_spanProcessors'\n    ] as SpanProcessor[];\n    const payload = {\n      resource: { attributes: settledResourceAttributes(this._resource) },\n      tracers: Array.from(this._tracers.keys()),\n      spanProcessors: processors.map(\n        p => p.constructor?.name ?? 'SpanProcessor'\n      ),\n    };\n    return formatInspect(\n      'BasicTracerProvider',\n      payload,\n      depth,\n      options,\n      inspect\n    );\n  }\n}\n","import type { ResolvedConfig } from \"./env-detection.js\";\nimport type { SessionManager } from \"./session.js\";\nimport { OTLPTraceExporter } from \"@opentelemetry/exporter-trace-otlp-http\";\nimport { BasicTracerProvider, BatchSpanProcessor } from \"@opentelemetry/sdk-trace-base\";\nimport type { SpanProcessor } from \"@opentelemetry/sdk-trace-base\";\nimport * as otelApi from \"@opentelemetry/api\";\nimport { GlasstraceExporter, API_KEY_PENDING } from \"./enriching-exporter.js\";\nimport { getActiveConfig } from \"./init-client.js\";\nimport { sdkLog } from \"./console-capture.js\";\nimport { setOtelState, OtelState, emitLifecycleEvent, registerShutdownHook, registerBeforeExitTrigger, pushDegradationSource } from \"./lifecycle.js\";\nimport {\n  peekExportCircuitBreaker,\n  _resetExportCircuitBreakerForTesting,\n} from \"./export-circuit-breaker.js\";\nimport { hashApiKey } from \"./api-key-hash.js\";\nimport {\n  emitNudgeMessage,\n  emitGuidanceMessage,\n  tryAutoAttachGlasstraceProcessor,\n} from \"./coexistence.js\";\nimport { setCoexistenceState, _resetCoexistenceStateForTesting } from \"./signal-handler.js\";\nimport { isProxyTracerProvider, isProxyTracer } from \"./proxy-detection.js\";\nimport { decisionTrace, decisionTraceEnabled } from \"./decision-trace.js\";\n\n/**\n * Emit the terminal OTel-configuration decision for the chosen provider\n * scenario. Called from each `setOtelState` terminal site so an operator can\n * see which coexistence / registration path the SDK took. The outcome is a\n * closed, code-literal scenario name (five values), keyed one-shot by that\n * outcome so it stays bounded; `configureOtel` runs once per process, so this\n * is effectively one line per boot. Call-site guarded so nothing is built\n * when the toggle is OFF.\n */\nfunction traceOtelPath(outcome: string): void {\n  if (!decisionTraceEnabled()) return;\n  decisionTrace(\"otel.path\", outcome, {\n    oneShotKey: `otel.path:${outcome}`,\n  });\n}\n\n/** Module-level resolved API key, updated when the anon key resolves. */\nlet resolvedApiKey: string = API_KEY_PENDING;\n\n/** Module-level reference to the active exporter for key-resolution notification. */\nlet activeExporter: GlasstraceExporter | null = null;\n\n/** Additional exporters that need key-resolution notification (from createGlasstraceSpanProcessor). */\nconst additionalExporters: GlasstraceExporter[] = [];\n\n/** Injected processor in coexistence mode, tracked for flush on exit. */\nlet injectedProcessor: SpanProcessor | null = null;\n\n/**\n * SHA-256-derived stable identifier of the most recently resolved\n * API key. Used to detect credential rotation\n * so the export-path circuit breaker can reset to CLOSED on rotation.\n */\nlet resolvedApiKeyHash: string = \"\";\n\n/**\n * Sets the resolved API key for OTel export authentication.\n * Called once the anonymous key or dev key is available.\n *\n * On rotation (the new key's SHA-256 differs from the previously-\n * stored hash) this notifies the export-path circuit breaker so any\n * outage tied to the old credentials is cleared. The breaker is\n * peeked, not constructed — if no exporter has yet observed a batch\n * the breaker is absent and the rotation has nothing to clear.\n *\n * @param key - The resolved API key (anonymous or developer).\n */\nexport function setResolvedApiKey(key: string): void {\n  const newHash = hashApiKey(key);\n  // Skip rotation handling when this is the first key resolution\n  // (there's nothing to \"rotate from\") OR when the key is unchanged.\n  // The first-resolution check uses the stored hash being empty so\n  // the same setResolvedApiKey() call does not erroneously trip a\n  // rotation-reset on the very first key arrival from the registration\n  // path.\n  const isRotation = resolvedApiKeyHash !== \"\" && resolvedApiKeyHash !== newHash;\n  resolvedApiKey = key;\n  resolvedApiKeyHash = newHash;\n  if (isRotation) {\n    peekExportCircuitBreaker()?.resetForKeyRotation();\n  }\n}\n\n/**\n * Returns the current resolved API key.\n * Returns the {@link API_KEY_PENDING} sentinel if the key has not yet resolved.\n */\nexport function getResolvedApiKey(): string {\n  return resolvedApiKey;\n}\n\n/**\n * Notifies the active exporter that the API key has transitioned from\n * \"pending\" to a resolved value. This triggers flushing of any buffered spans.\n */\nexport function notifyApiKeyResolved(): void {\n  activeExporter?.notifyKeyResolved();\n  for (const exporter of additionalExporters) {\n    exporter.notifyKeyResolved();\n  }\n}\n\n/**\n * Register an additional exporter for key-resolution notification.\n * Used by createGlasstraceSpanProcessor() so its exporter gets notified\n * when the API key resolves (flushing buffered spans immediately rather\n * than waiting for the next BSP timer tick).\n */\nexport function registerExporterForKeyNotification(exporter: GlasstraceExporter): void {\n  additionalExporters.push(exporter);\n}\n\n/**\n * Resets OTel configuration state to initial values. For testing only.\n */\nexport function resetOtelConfigForTesting(): void {\n  resolvedApiKey = API_KEY_PENDING;\n  resolvedApiKeyHash = \"\";\n  activeExporter = null;\n  injectedProcessor = null;\n  additionalExporters.length = 0;\n  // The export circuit breaker is conceptually part of the OTel\n  // export pipeline owned by this module, so its singleton is reset\n  // here too. Test files that reset the OTel config get a fresh\n  // breaker without having to import the breaker reset directly.\n  _resetExportCircuitBreakerForTesting();\n  // Signal and beforeExit handler cleanup is handled by resetLifecycleForTesting()\n  // via the shutdown coordinator.\n  // Reset coexistence state here as well so that test suites that call\n  // resetOtelConfigForTesting() without _resetRegistrationForTesting() do\n  // not leak coexistenceState (\"coexisting\" / \"sole-owner\") between tests.\n  _resetCoexistenceStateForTesting();\n}\n\n/**\n * Dynamically imports an optional peer dependency at runtime.\n *\n * Uses `Function()` constructor to build the `import()` expression so that\n * bundlers (webpack, esbuild, turbopack) do not attempt to resolve the module\n * at compile time. This is intentional -- the SDK's peer dependencies are\n * optional, and static analysis would cause missing-module build errors for\n * users who have not installed them.\n *\n * **CSP note:** The `Function()` constructor is semantically equivalent to\n * `eval()` and will trigger Content Security Policy violations in environments\n * that disallow `unsafe-eval`. If your CSP blocks this, install the OTel peer\n * dependencies explicitly so they resolve via normal `import` statements, or\n * use the `@vercel/otel` path which does not rely on `tryImport` for its own\n * module.\n *\n * @param moduleId - The npm package name to import (e.g. \"@vercel/otel\").\n * @returns The module namespace object, or `null` if the module is not installed.\n */\nasync function tryImport(moduleId: string): Promise<Record<string, unknown> | null> {\n  try {\n    return await (Function(\"id\", \"return import(id)\")(moduleId) as Promise<Record<string, unknown>>);\n  } catch {\n    return null;\n  }\n}\n\n/**\n * Emits a verbose-only diagnostic when `@prisma/instrumentation` could not be\n * registered, so developers can see why Prisma query spans are missing instead\n * of getting a silent skip.\n *\n * Default-quiet by design: the SDK cannot know whether the consuming app uses\n * Prisma, so an unconditional warning would be noise for the majority of apps\n * that do not. It fires only when the caller opted into `verbose` mode — the\n * same gate the OTel diagnostic logger below uses.\n *\n * @param verbose - Whether verbose diagnostics are enabled (`config.verbose`).\n * @param detail - Why registration was skipped (e.g. \"could not be loaded\").\n */\nfunction warnPrismaInstrumentationUnavailable(verbose: boolean, detail: string): void {\n  if (!verbose) return;\n  sdkLog(\n    \"warn\",\n    `[glasstrace] @prisma/instrumentation ${detail}; Prisma query spans will ` +\n      `not be captured. If you use Prisma and expect database spans, add ` +\n      `@prisma/instrumentation as a direct dependency (some package managers, ` +\n      `e.g. pnpm, do not expose transitive copies).`,\n  );\n}\n\n/**\n * Configures OpenTelemetry with the GlasstraceExporter.\n *\n * Detection flow (per sdk-otel-coexistence.md v8+):\n *   1. Yield one tick (let synchronous Sentry.init() complete)\n *   2. Probe for existing provider\n *   3. If provider exists → shared coexistence path via\n *      {@link tryAutoAttachGlasstraceProcessor} (resolves the Next.js 16\n *      production pre-registration and Sentry hoisting cases)\n *   4. If no provider → registration path (Vercel or bare)\n */\nexport async function configureOtel(\n  config: ResolvedConfig,\n  sessionManager: SessionManager,\n): Promise<void> {\n  setOtelState(OtelState.CONFIGURING);\n\n  // Step 1: Yield one tick to let synchronous Sentry.init() (or other tools)\n  // complete before probing for an existing provider (DISC-1202).\n  await new Promise<void>((resolve) => {\n    if (typeof setImmediate === \"function\") {\n      setImmediate(resolve);\n    } else {\n      setTimeout(resolve, 0);\n    }\n  });\n\n  // Step 2: Probe for an existing OTel provider BEFORE the Vercel/bare split.\n  // This unified detection ensures coexistence works regardless of whether\n  // @vercel/otel is installed (sdk-otel-coexistence.md Section 2.4).\n  //\n  // DISC-1556: classification is structural rather than constructor-name\n  // based. Next.js 16's production bundler renames `@opentelemetry/api`'s\n  // `ProxyTracerProvider` / `ProxyTracer` to short minified identifiers\n  // (`eN`/`ek`/etc.), which previously caused the SDK's own bundled proxy\n  // to be misidentified as an external provider — see\n  // `/tmp/recon-option-A-DISC-1556.md` and {@link isProxyTracerProvider}.\n  //\n  // OR-ordering edge case: if a third party extends a real provider (e.g.\n  // `BasicTracerProvider`) and stamps the four `getDelegate*` method\n  // names onto the subclass, `isProxyTracerProvider` returns `true`, but\n  // the probe tracer (returned by the subclass's real `getTracer()`) is\n  // a real `Tracer`, not a `ProxyTracer` — `isProxyTracer` returns\n  // `false`. The OR short-circuit then sets\n  // `anotherProviderRegistered = true`, which is the correct behavior\n  // for a real provider with a custom shape.\n  const existingProvider = otelApi.trace.getTracerProvider();\n  const probeTracer = existingProvider.getTracer(\"glasstrace-probe\");\n  const anotherProviderRegistered =\n    !isProxyTracerProvider(existingProvider) ||\n    !isProxyTracer(probeTracer, existingProvider);\n\n  // Step 3: If another provider exists → shared coexistence path.\n  // This is the DISC-493 Issues 2 and 4 fix: instead of silently giving up\n  // when a Next.js 16 production build or a Sentry import has already\n  // registered a provider, auto-attach our span processor onto it.\n  if (anotherProviderRegistered) {\n    // Inform the signal handler that it should NOT re-raise — the existing\n    // provider owns signal-based shutdown (DISC-1265).\n    setCoexistenceState(\"coexisting\");\n    await runCoexistencePath(existingProvider, config);\n    return;\n  }\n\n  // Step 4: No existing provider → registration path.\n  // Inform the signal handler that Glasstrace owns the provider and should\n  // re-raise after draining its hooks (DISC-1265).\n  setCoexistenceState(\"sole-owner\");\n  await runRegistrationPath(config, sessionManager);\n}\n\n/**\n * Shared coexistence path for pre-registered OTel providers.\n *\n * Used whenever `configureOtel()` detects a pre-registered OTel provider.\n * Delegates processor construction to {@link tryAutoAttachGlasstraceProcessor}\n * which reuses the `createGlasstraceSpanProcessor()` public primitive, so\n * the auto-attach path and the manual integration path stay in lockstep.\n *\n * Idempotence: if a Glasstrace-branded processor is already attached (from\n * a prior `registerGlasstrace()` call or a manual `createGlasstraceSpanProcessor()`\n * wiring), the auto-attach path returns `\"already_present\"` and no second\n * processor is created.\n */\nasync function runCoexistencePath(\n  existingProvider: ReturnType<typeof otelApi.trace.getTracerProvider>,\n  config: ResolvedConfig,\n): Promise<void> {\n  // Attempt to auto-attach via the shared primitive.\n  //\n  // tryAutoAttachGlasstraceProcessor() performs its own \"already present\"\n  // check against the branded Symbol BEFORE constructing an exporter, so\n  // idempotent registration does not create a wasted exporter instance.\n  // It also reuses createGlasstraceSpanProcessor() for construction, so\n  // the processor wiring (branded exporter, key-notification registration,\n  // BSP flush interval) matches the documented manual path exactly.\n  //\n  // Pass through the subset of resolved config that `GlasstraceOptions`\n  // accepts. `environment` is not in `GlasstraceOptions` (it's derived\n  // from env vars inside `resolveConfig`), so the primitive picks it up\n  // from the same environment variables `configureOtel()` sees.\n  const result = tryAutoAttachGlasstraceProcessor(existingProvider, {\n    endpoint: config.endpoint,\n    verbose: config.verbose,\n  });\n\n  if (result === \"already_present\") {\n    if (config.verbose) {\n      sdkLog(\"info\", \"[glasstrace] Existing provider detected — Glasstrace processor already present.\");\n    }\n    setOtelState(OtelState.PROCESSOR_PRESENT);\n    traceOtelPath(\"coexist_present\");\n    emitLifecycleEvent(\"otel:configured\", { state: OtelState.PROCESSOR_PRESENT, scenario: \"B-clean\" });\n    return;\n  }\n\n  if (result !== null) {\n    // Success: processor was attached. Retain a reference for the\n    // coexistence flush hook (Section 7.2) so beforeExit drains buffered\n    // spans even if the existing provider's shutdown does not propagate.\n    injectedProcessor = result.processor;\n\n    if (config.verbose) {\n      sdkLog(\n        \"info\",\n        \"[glasstrace] Existing provider detected — auto-attached Glasstrace span processor.\",\n      );\n    }\n\n    // Register coexistence flush hook via the lifecycle coordinator, and\n    // wire the beforeExit trigger so the coordinator runs on event loop drain.\n    // The existing provider handles signal-based shutdown (its MultiSpanProcessor\n    // propagates shutdown() to our injected processor). The beforeExit trigger\n    // covers the edge case where the process exits without signals. Both\n    // triggers (signals and beforeExit) call executeShutdown() which is\n    // idempotent — if one already ran, the other is a no-op.\n    registerShutdownHook({\n      name: \"coexistence-flush\",\n      priority: 5,\n      fn: async () => {\n        if (injectedProcessor) {\n          await injectedProcessor.forceFlush();\n        }\n      },\n    });\n    registerBeforeExitTrigger();\n\n    const scenario = result.method === \"v1_public\" ? \"D1\" : \"B-auto\";\n    setOtelState(OtelState.AUTO_ATTACHED);\n    traceOtelPath(\"coexist_attached\");\n    emitLifecycleEvent(\"otel:configured\", { state: OtelState.AUTO_ATTACHED, scenario });\n    emitLifecycleEvent(\"otel:injection_succeeded\", { method: result.method });\n    emitNudgeMessage();\n    return;\n  }\n\n  // Injection failed (Scenario C/F) — emit guidance.\n  if (config.verbose) {\n    sdkLog(\"info\", \"[glasstrace] Existing provider detected — could not auto-attach.\");\n  }\n  emitGuidanceMessage();\n  setOtelState(OtelState.COEXISTENCE_FAILED);\n  traceOtelPath(\"coexist_failed\");\n  emitLifecycleEvent(\"otel:configured\", { state: OtelState.COEXISTENCE_FAILED, scenario: \"C/F\" });\n  emitLifecycleEvent(\"otel:injection_failed\", { reason: \"provider internals inaccessible\" });\n  // DISC-1556 Option C: emit a structured fail-loud diagnostic that the\n  // runtime-state CLI bridge can persist. Distinct from\n  // `otel:injection_failed` above, which carries a free-form reason for\n  // logging only.\n  //\n  // PII-safety: only `delegate.constructor.name` is read. `delegate.url`,\n  // `delegate._exporter.endpoint`, `delegate._headers`, and any other\n  // field that could carry user-app data are deliberately untouched —\n  // see `RuntimeStateLastError` in `runtime-state.ts` for the contract.\n  emitLifecycleEvent(\"otel:failed\", {\n    category: \"auto-attach-returned-null\",\n    message:\n      \"tryAutoAttachGlasstraceProcessor returned null — the existing OTel \" +\n      \"TracerProvider exposed no injection point. Spans are not reaching \" +\n      \"the Glasstrace exporter. Apply the manual createGlasstraceSpanProcessor() \" +\n      \"workaround documented in the SDK README.\",\n    timestamp: new Date().toISOString(),\n    providerClass: readProviderClass(existingProvider),\n  });\n  // Cross-layer effect: register a degradation source so the\n  // centralised `recomputeCoreFromDegradationSources()` machinery is\n  // the single source of truth for ACTIVE_DEGRADED. The push is\n  // idempotent and self-guards: registry-driven recompute only acts\n  // when core is `ACTIVE` (per DISC-1247, `KEY_PENDING` →\n  // `ACTIVE_DEGRADED` is not a valid transition; the registry will\n  // catch up at the moment core reaches `ACTIVE` via the catch-up\n  // hook in `setCoreState`).\n  //\n  // Migrated from the prior `setCoreState(ACTIVE_DEGRADED)` direct\n  // write per Copilot review of PR #260 (2026-05-08): a future\n  // `clearDegradationSource` from another subsystem (e.g., the export\n  // circuit) would otherwise have clobbered this auto-attach-failure\n  // degradation back to ACTIVE because the registry didn't know about\n  // it. Now both subsystems share the same registry semantics.\n  pushDegradationSource(\"otel-coexistence-failed\");\n}\n\n/**\n * Reads the constructor name of an existing TracerProvider's concrete\n * delegate for inclusion in the structured fail-loud diagnostic. Strict\n * PII-safety contract: this function MUST NOT read fields that could\n * carry user-app data (e.g. `delegate.url`, `delegate._exporter.endpoint`,\n * `delegate._headers`). Only the constructor name is captured.\n *\n * Returns `undefined` if the provider exposes no readable constructor\n * (defensive — a provider that throws on property access must not crash\n * the failure path).\n */\nfunction readProviderClass(\n  tracerProvider: ReturnType<typeof otelApi.trace.getTracerProvider>,\n): string | undefined {\n  try {\n    // Unwrap ProxyTracerProvider to reach the concrete delegate, the same\n    // shape `tryAutoAttachGlasstraceProcessor` introspects.\n    const proxy = tracerProvider as unknown as { getDelegate?: () => unknown };\n    const delegate = typeof proxy.getDelegate === \"function\"\n      ? proxy.getDelegate()\n      : tracerProvider;\n    const name = (delegate as { constructor?: { name?: unknown } } | null)\n      ?.constructor?.name;\n    return typeof name === \"string\" && name.length > 0 ? name : undefined;\n  } catch {\n    return undefined;\n  }\n}\n\n/**\n * Registration path when no existing OTel provider is detected.\n *\n * Tries `@vercel/otel` first (Scenario E). Falls back to constructing a\n * bare `BasicTracerProvider` (Scenario A). In both sub-scenarios,\n * Glasstrace owns the provider and installs its own shutdown hooks.\n */\nasync function runRegistrationPath(\n  config: ResolvedConfig,\n  sessionManager: SessionManager,\n): Promise<void> {\n  // Build OTLP exporter configuration\n  const exporterUrl = `${config.endpoint}/v1/traces`;\n\n  // OTLP exporter factory — always available since OTel is bundled.\n  const createOtlpExporter = (url: string, headers: Record<string, string>) =>\n    new OTLPTraceExporter({ url, headers });\n\n  // Create the GlasstraceExporter that enriches + buffers + delegates\n  const glasstraceExporter = new GlasstraceExporter({\n    getApiKey: getResolvedApiKey,\n    sessionManager,\n    getConfig: () => getActiveConfig(),\n    environment: config.environment,\n    endpointUrl: exporterUrl,\n    createDelegate: createOtlpExporter,\n    verbose: config.verbose,\n  });\n  activeExporter = glasstraceExporter;\n\n  // Try @vercel/otel first (Scenario E)\n  const vercelOtel = await tryImport(\"@vercel/otel\");\n  if (vercelOtel && typeof vercelOtel.registerOTel === \"function\") {\n    const otelConfig: Record<string, unknown> = {\n      serviceName: \"glasstrace-sdk\",\n      traceExporter: glasstraceExporter,\n    };\n\n    // Try @prisma/instrumentation\n    const prismaModule = await tryImport(\"@prisma/instrumentation\");\n    if (prismaModule) {\n      const PrismaInstrumentation = prismaModule.PrismaInstrumentation as\n        (new () => unknown) | undefined;\n      if (PrismaInstrumentation) {\n        otelConfig.instrumentations = [new PrismaInstrumentation()];\n      } else {\n        warnPrismaInstrumentationUnavailable(\n          config.verbose,\n          \"was loaded but did not export PrismaInstrumentation\",\n        );\n      }\n    } else {\n      warnPrismaInstrumentationUnavailable(config.verbose, \"could not be loaded\");\n    }\n\n    (vercelOtel.registerOTel as (opts: Record<string, unknown>) => void)(otelConfig);\n\n    // Register a shutdown hook so buffered spans are flushed on SIGTERM.\n    // @vercel/otel does not install its own signal or beforeExit handlers\n    // (verified empirically in DISC-1250 / vercel-shutdown.test.ts): it\n    // constructs an internal Sdk instance and discards the reference, making\n    // provider.shutdown() unreachable via any ambient mechanism. Without this\n    // hook, spans buffered in the BatchSpanProcessor are lost when the Vercel\n    // runtime delivers SIGTERM to the function worker (DISC-1263).\n    //\n    // Signal handlers are registered earlier in registerGlasstrace() via\n    // registerSignalHandlers() (DISC-1249). This hook plugs into the existing\n    // coordinator; registerBeforeExitTrigger() covers the event-loop-drain path.\n    // Capture the concrete provider now (registration time) rather than at hook\n    // execution time. If something replaced the global provider between now and\n    // shutdown, we still flush the correct one — matching the pattern Scenario A\n    // uses when capturing `provider` in a lexical closure.\n    // @vercel/otel wraps its provider in a ProxyTracerProvider; unwrap once\n    // to reach the concrete BasicTracerProvider that exposes shutdown().\n    const vercelProxy = otelApi.trace.getTracerProvider() as unknown as {\n      getDelegate?: () => { shutdown?: () => Promise<void> };\n    };\n    const vercelConcreteProvider = typeof vercelProxy.getDelegate === \"function\"\n      ? vercelProxy.getDelegate()\n      : (vercelProxy as { shutdown?: () => Promise<void> });\n    registerShutdownHook({\n      name: \"vercel-otel-shutdown\",\n      priority: 0,\n      fn: async () => {\n        try {\n          await vercelConcreteProvider.shutdown?.();\n        } catch {\n          // best-effort: provider may already be shut down or not support shutdown\n        }\n      },\n    });\n    registerBeforeExitTrigger();\n\n    setOtelState(OtelState.OWNS_PROVIDER);\n    traceOtelPath(\"vercel\");\n    emitLifecycleEvent(\"otel:configured\", { state: OtelState.OWNS_PROVIDER, scenario: \"E\" });\n    return;\n  }\n\n  // Bare OTel SDK fallback (Scenario A)\n\n  // Enable OTel diagnostic logging in verbose mode so OTLP exporter\n  // errors (auth failures, network issues) are surfaced to the developer.\n  // Routes through sdkLog to avoid console-capture recording OTel internals.\n  if (config.verbose) {\n    otelApi.diag.setLogger(\n      {\n        verbose: (msg) => sdkLog(\"info\", `[otel] ${msg}`),\n        debug: (msg) => sdkLog(\"info\", `[otel] ${msg}`),\n        info: (msg) => sdkLog(\"info\", `[otel] ${msg}`),\n        warn: (msg) => sdkLog(\"warn\", `[otel] ${msg}`),\n        error: (msg) => sdkLog(\"error\", `[otel] ${msg}`),\n      },\n      otelApi.DiagLogLevel.WARN,\n    );\n  }\n\n  const processor = new BatchSpanProcessor(glasstraceExporter, {\n    scheduledDelayMillis: 1000,\n  });\n  const provider = new BasicTracerProvider({\n    spanProcessors: [processor],\n  });\n\n  // Context manager is registered synchronously in registerGlasstrace()\n  // before configureOtel() is called (DISC-1183). By this point, it's\n  // already active and propagating trace context across async boundaries.\n\n  otelApi.trace.setGlobalTracerProvider(provider);\n\n  // Register OTel shutdown via lifecycle coordinator.\n  // Signal handlers are installed upfront by registerGlasstrace() so they\n  // exist during this async setup window (DISC-1249). beforeExit is still\n  // wired here because Scenario A owns the provider and the coexistence\n  // path registers its own beforeExit trigger independently.\n  registerShutdownHook({\n    name: \"otel-provider-shutdown\",\n    priority: 0,\n    fn: async () => {\n      await provider.shutdown();\n    },\n  });\n  registerBeforeExitTrigger();\n\n  // Register Prisma instrumentation on the bare path (DISC-1223).\n  // The Vercel path handles this via registerOTel({ instrumentations: [...] }).\n  // The coexistence path gets Prisma from the existing provider (e.g., Sentry).\n  // Only the bare path was missing it.\n  const prismaModule = await tryImport(\"@prisma/instrumentation\");\n  if (prismaModule) {\n    const PrismaInstrumentation = prismaModule.PrismaInstrumentation as\n      (new () => unknown & { setTracerProvider: (p: unknown) => void; enable: () => void }) | undefined;\n    if (PrismaInstrumentation) {\n      try {\n        const inst = new PrismaInstrumentation();\n        inst.setTracerProvider(provider);\n        inst.enable();\n      } catch (err) {\n        // Prisma instrumentation is optional — failure is not fatal. Surface\n        // it in verbose mode so a silent skip is debuggable (DISC-1308).\n        if (config.verbose) {\n          sdkLog(\n            \"warn\",\n            `[glasstrace] @prisma/instrumentation failed to initialize: ${\n              err instanceof Error ? err.message : String(err)\n            }. Prisma query spans will not be captured.`,\n          );\n        }\n      }\n    } else {\n      warnPrismaInstrumentationUnavailable(\n        config.verbose,\n        \"was loaded but did not export PrismaInstrumentation\",\n      );\n    }\n  } else {\n    warnPrismaInstrumentationUnavailable(config.verbose, \"could not be loaded\");\n  }\n\n  setOtelState(OtelState.OWNS_PROVIDER);\n  traceOtelPath(\"bare\");\n  emitLifecycleEvent(\"otel:configured\", { state: OtelState.OWNS_PROVIDER, scenario: \"A\" });\n}\n","/**\n * SHA-256 hash helper for API-key rotation detection.\n *\n * Memo §Decision 7 calls for a stable hash of the resolved API key\n * that can be compared on every `_setCurrentConfig` /\n * `setResolvedApiKey` call to detect rotation. We hash with SHA-256\n * and truncate to the first 16 bytes (32 hex chars). The truncation\n * is documentary — full-length collision search is computationally\n * infeasible regardless — and keeps the cached value compact.\n *\n * The hash is held in module state at the call sites (e.g.,\n * `otel-config.ts`); the raw key is already in module state in the\n * SDK, so the hash adds no new exposure surface. The hash is **not**\n * logged or surfaced in `runtime-state.json`.\n *\n * The implementation uses `node:crypto` synchronously and emits a\n * SHA-256 hex digest prefixed with `sha256:`. Falls back to an FNV-1a\n * 32-bit hash prefixed with `fnv:` if `node:crypto` is not available\n * (non-Node runtimes — Edge, Workers, browsers); the fallback is\n * intentional — detecting rotation via FNV-1a is a degraded but\n * correct equivalent (collision-resistant for the rotation-detection\n * use case, which only needs key inequality, not security). The two\n * algorithms are mutually exclusive at runtime — the same process\n * always uses the same algorithm — so a hash from one is never\n * compared against a hash from the other.\n */\n\nlet cryptoModule: typeof import(\"node:crypto\") | null | undefined;\n\nfunction loadCrypto(): typeof import(\"node:crypto\") | null {\n  if (cryptoModule !== undefined) return cryptoModule;\n  try {\n    // eslint-disable-next-line @typescript-eslint/no-require-imports, glasstrace/no-unguarded-node-require -- guarded by surrounding try/catch; non-Node runtimes (Edge, Workers) trigger the catch and fall back to identity compare. Same pattern as runtime-state.ts (DISC-1555).\n    cryptoModule = require(\"node:crypto\") as typeof import(\"node:crypto\");\n  } catch {\n    cryptoModule = null;\n  }\n  return cryptoModule;\n}\n\n/**\n * Returns a SHA-256-derived stable identifier for the supplied API\n * key, truncated to 32 hex characters (16 bytes). When `node:crypto`\n * is not available (non-Node runtime), returns a length-prefixed\n * raw-string fallback that is still stable and equality-comparable.\n *\n * Empty / non-string input returns the empty string so callers can\n * safely diff against an initial unset state.\n */\nexport function hashApiKey(key: string | undefined | null): string {\n  if (typeof key !== \"string\" || key.length === 0) return \"\";\n  const crypto = loadCrypto();\n  if (crypto !== null) {\n    return crypto.createHash(\"sha256\").update(key, \"utf8\").digest(\"hex\").slice(0, 32);\n  }\n  // Non-Node fallback: FNV-1a 32-bit hash. NOT cryptographically\n  // secure (collisions can be constructed) but adequate for the only\n  // call site that needs the hash — comparing two keys for equality\n  // — because rotation is an honest path, not an adversarial input.\n  // Importantly, the fallback never echoes raw key bytes; it returns\n  // a fixed-length hex digest that is safe to keep in module state\n  // alongside the SHA-256 path.\n  let hash = 0x811c9dc5; // FNV offset basis\n  for (let i = 0; i < key.length; i++) {\n    hash ^= key.charCodeAt(i);\n    // FNV prime 0x01000193 — multiplication via shifts and adds keeps\n    // the result inside 32-bit range without `Math.imul`-only\n    // semantics in any specific runtime.\n    hash = (hash + ((hash << 1) + (hash << 4) + (hash << 7) + (hash << 8) + (hash << 24))) >>> 0;\n  }\n  // 8-hex-char digest, prefixed with `fnv:` so the call-site debug\n  // output makes the algorithm obvious if it ever leaks into logs.\n  return `fnv:${hash.toString(16).padStart(8, \"0\")}`;\n}\n","/**\n * OTel Coexistence Public API\n *\n * Provides createGlasstraceSpanProcessor() for developers who want to\n * manually integrate Glasstrace with their existing OTel provider\n * (e.g., Sentry's openTelemetrySpanProcessors config option).\n *\n * Also provides the auto-attach path (tryAutoAttachGlasstraceProcessor)\n * that configureOtel() uses when it detects a pre-registered provider\n * at runtime (Next.js 16 production, Sentry, Datadog, New Relic). Both\n * entry points reuse the same span-processor factory so the manual and\n * automatic paths stay in lockstep.\n *\n * Design: sdk-otel-coexistence.md Sections 3, 4, 5, 6\n */\n\nimport type { SpanProcessor } from \"@opentelemetry/sdk-trace-base\";\nimport { BatchSpanProcessor } from \"@opentelemetry/sdk-trace-base\";\nimport { OTLPTraceExporter } from \"@opentelemetry/exporter-trace-otlp-http\";\nimport type * as otelApi from \"@opentelemetry/api\";\nimport type { GlasstraceOptions } from \"@glasstrace/protocol\";\nimport { GlasstraceExporter } from \"./enriching-exporter.js\";\nimport { getResolvedApiKey, registerExporterForKeyNotification } from \"./otel-config.js\";\nimport { getActiveConfig } from \"./init-client.js\";\nimport { getSessionManager } from \"./register.js\";\nimport { resolveConfig } from \"./env-detection.js\";\nimport { getOtelState, OtelState } from \"./lifecycle.js\";\nimport { sdkLog } from \"./console-capture.js\";\n\n/** Branded symbol used to identify Glasstrace's exporter across bundled copies. */\nconst GLASSTRACE_EXPORTER_BRAND = Symbol.for(\"glasstrace.exporter\");\n\n/**\n * Creates a Glasstrace span processor for manual integration with an\n * existing OTel provider.\n *\n * Use this when another tool (e.g., Sentry) owns the OTel provider and\n * you want to add Glasstrace to their processor list:\n *\n * @example\n * ```ts\n * import * as Sentry from \"@sentry/nextjs\";\n * import { createGlasstraceSpanProcessor } from \"@glasstrace/sdk\";\n *\n * Sentry.init({\n *   dsn: \"...\",\n *   openTelemetrySpanProcessors: [createGlasstraceSpanProcessor()],\n * });\n * ```\n *\n * **Important:** `registerGlasstrace()` is still required even when using\n * this function. The processor handles span transport (enrichment and\n * export). `registerGlasstrace()` handles everything else: init calls,\n * config sync, session management, anonymous key generation, discovery\n * endpoint, and health reporting.\n *\n * @param options - Optional SDK configuration. If omitted, uses the same\n *   config as registerGlasstrace() (environment variables).\n * @returns A BatchSpanProcessor wrapping a GlasstraceExporter with the\n *   branded Symbol.for('glasstrace.exporter') for coexistence detection.\n */\nexport function createGlasstraceSpanProcessor(\n  options?: GlasstraceOptions,\n): SpanProcessor {\n  const config = resolveConfig(options);\n  const exporterUrl = `${config.endpoint}/v1/traces`;\n\n  const createOtlpExporter = (url: string, headers: Record<string, string>) =>\n    new OTLPTraceExporter({ url, headers });\n\n  const exporter = new GlasstraceExporter({\n    getApiKey: getResolvedApiKey,\n    sessionManager: getSessionManager(),\n    getConfig: () => getActiveConfig(),\n    environment: config.environment,\n    endpointUrl: exporterUrl,\n    createDelegate: createOtlpExporter,\n    // Propagate verbose so exporter-level enrichment and export logs\n    // stay observable whether the processor is built automatically by\n    // the coexistence path or wired manually by the developer.\n    verbose: config.verbose,\n  });\n\n  // Register for key-resolution notification so buffered spans flush\n  // immediately when the key resolves (not waiting for BSP timer tick).\n  registerExporterForKeyNotification(exporter);\n\n  return new BatchSpanProcessor(exporter, {\n    scheduledDelayMillis: 1000,\n  });\n}\n\n/**\n * Result returned by {@link tryAutoAttachGlasstraceProcessor}.\n *\n * - `{ method, processor }` — a Glasstrace span processor was successfully\n *   injected into the existing provider's processor list. The caller MUST\n *   retain the returned processor so it can be flushed on shutdown.\n * - `\"already_present\"` — a Glasstrace-branded processor was already in\n *   the provider's list (e.g., the developer already registered one via\n *   `createGlasstraceSpanProcessor()`). No additional processor was added.\n * - `null` — injection was not possible (provider internals inaccessible\n *   or `addSpanProcessor` threw). The caller should emit guidance.\n */\nexport type AutoAttachResult =\n  | { method: \"v1_public\" | \"v2_private\"; processor: SpanProcessor }\n  | \"already_present\"\n  | null;\n\n/**\n * Checks whether a Glasstrace-branded span processor is already present\n * in the existing provider's processor list.\n *\n * Uses the branded symbol {@link GLASSTRACE_EXPORTER_BRAND} so detection\n * works across bundled copies of `@glasstrace/sdk` (hoisted vs. nested\n * `node_modules`). `Symbol.for()` uses a global registry, so every copy\n * resolves to the same symbol.\n *\n * Fully defensive — any error or missing internal structure returns\n * `false` and lets the caller fall through to injection or guidance.\n */\nexport function isGlasstraceProcessorPresent(\n  tracerProvider: otelApi.TracerProvider,\n): boolean {\n  try {\n    const proxy = tracerProvider as unknown as { getDelegate?: () => unknown };\n    const delegate = typeof proxy.getDelegate === \"function\"\n      ? proxy.getDelegate()\n      : tracerProvider;\n\n    // Path 1: v2 internal (_activeSpanProcessor._spanProcessors)\n    const v2 = delegate as unknown as {\n      _activeSpanProcessor?: {\n        _spanProcessors?: Array<{ _exporter?: unknown }>;\n      };\n    };\n    const v2Processors = v2._activeSpanProcessor?._spanProcessors;\n    if (Array.isArray(v2Processors) && hasBrandedProcessor(v2Processors)) {\n      return true;\n    }\n\n    // Path 2: v1 getActiveSpanProcessor()\n    const v1 = delegate as unknown as {\n      getActiveSpanProcessor?: () => { _spanProcessors?: Array<{ _exporter?: unknown }> };\n    };\n    if (typeof v1.getActiveSpanProcessor === \"function\") {\n      const active = v1.getActiveSpanProcessor();\n      const processors = active?._spanProcessors;\n      if (Array.isArray(processors) && hasBrandedProcessor(processors)) {\n        return true;\n      }\n    }\n\n    return false;\n  } catch {\n    return false;\n  }\n}\n\n/**\n * Attempts to inject a Glasstrace span processor into an existing\n * provider's processor pipeline.\n *\n * Tiered approach:\n *   1. Feature-detect `addSpanProcessor` (OTel v1 public API) → call it\n *   2. Feature-detect `_activeSpanProcessor._spanProcessors` (OTel v2\n *      internal) → push the processor\n *\n * The processor is constructed via {@link createGlasstraceSpanProcessor}\n * so the auto-attach path and the manual integration path share identical\n * configuration (including the branded exporter for\n * {@link isGlasstraceProcessorPresent} detection and key-notification\n * registration).\n *\n * **Idempotence:** {@link isGlasstraceProcessorPresent} is consulted\n * before construction; if a Glasstrace-branded processor is already\n * attached, this function returns `\"already_present\"` without creating\n * a second exporter.\n *\n * **Defensive:** all errors are swallowed and return `null`. The SDK\n * falls back to emitting guidance rather than crashing.\n *\n * @param tracerProvider - The existing global provider returned by\n *   `otelApi.trace.getTracerProvider()`.\n * @param options - Optional SDK configuration passed through to\n *   `createGlasstraceSpanProcessor()`.\n * @returns See {@link AutoAttachResult}.\n */\nexport function tryAutoAttachGlasstraceProcessor(\n  tracerProvider: otelApi.TracerProvider,\n  options?: GlasstraceOptions,\n): AutoAttachResult {\n  try {\n    // Short-circuit: if a Glasstrace-branded processor is already present,\n    // never create a second exporter. Covers the duplicate\n    // registerGlasstrace() case (idempotence) and the B-clean scenario\n    // where the user wired createGlasstraceSpanProcessor() into their\n    // provider config manually.\n    if (isGlasstraceProcessorPresent(tracerProvider)) {\n      return \"already_present\";\n    }\n\n    // Unwrap ProxyTracerProvider to reach the concrete delegate.\n    const proxy = tracerProvider as unknown as { getDelegate?: () => unknown };\n    const delegate = typeof proxy.getDelegate === \"function\"\n      ? proxy.getDelegate()\n      : tracerProvider;\n\n    // Attempt 1: OTel v1 public API (addSpanProcessor).\n    const withAdd = delegate as unknown as {\n      addSpanProcessor?: (p: SpanProcessor) => void;\n    };\n    if (typeof withAdd.addSpanProcessor === \"function\") {\n      const processor = createGlasstraceSpanProcessor(options);\n      withAdd.addSpanProcessor(processor);\n      return { method: \"v1_public\", processor };\n    }\n\n    // Attempt 2: OTel v2 internals (_activeSpanProcessor._spanProcessors).\n    // Accessing a private field is justified in the design doc\n    // (sdk-otel-coexistence.md Section 4). Same pattern Sentry uses.\n    const v2 = delegate as unknown as {\n      _activeSpanProcessor?: { _spanProcessors?: unknown[] };\n    };\n    const multiProcessor = v2._activeSpanProcessor;\n    if (!multiProcessor || !Array.isArray(multiProcessor._spanProcessors)) {\n      return null;\n    }\n\n    const processor = createGlasstraceSpanProcessor(options);\n    multiProcessor._spanProcessors.push(processor);\n    return { method: \"v2_private\", processor };\n  } catch {\n    return null;\n  }\n}\n\n/**\n * Emits a nudge message guiding the developer toward the clean\n * createGlasstraceSpanProcessor() integration path.\n *\n * Called by configureOtel() when auto-attach succeeds (Scenarios B-auto, D1, D2).\n * NOT called when the processor is already present (Scenario B-clean).\n */\nexport function emitNudgeMessage(): void {\n  const isSentry = detectSentry();\n\n  if (isSentry) {\n    sdkLog(\"info\",\n      `[glasstrace] Detected existing OTel provider — auto-attached Glasstrace span processor.\\n` +\n      `For a cleaner setup, add Glasstrace to your Sentry config:\\n\\n` +\n      `  import { createGlasstraceSpanProcessor } from '@glasstrace/sdk';\\n\\n` +\n      `  Sentry.init({\\n` +\n      `    dsn: '...',\\n` +\n      `    openTelemetrySpanProcessors: [createGlasstraceSpanProcessor()],\\n` +\n      `  });\\n\\n` +\n      `This message will not appear once Glasstrace is added to your provider config.`,\n    );\n  } else {\n    sdkLog(\"info\",\n      `[glasstrace] Detected existing OTel provider — auto-attached Glasstrace span processor.\\n` +\n      `For a cleaner setup, add Glasstrace to your provider config:\\n\\n` +\n      `  import { createGlasstraceSpanProcessor } from '@glasstrace/sdk';\\n\\n` +\n      `  const provider = new BasicTracerProvider({\\n` +\n      `    spanProcessors: [\\n` +\n      `      // ... your existing processors,\\n` +\n      `      createGlasstraceSpanProcessor(),\\n` +\n      `    ],\\n` +\n      `  });\\n\\n` +\n      `This message will not appear once Glasstrace is added to your provider config.`,\n    );\n  }\n}\n\n/**\n * Emits a guidance message when auto-attach fails (Scenarios C, F).\n *\n * Log level escalates to `error` under `process.env.NODE_ENV ===\n * \"production\"` so the message survives common production log-level\n * filters that suppress `warn`. Development and\n * test runs keep the `warn` level to avoid console-noise regressions\n * for local Sentry/Datadog users who routinely see this branch.\n */\nexport function emitGuidanceMessage(): void {\n  const isSentry = detectSentry();\n  // Read from process.env at call time — not module-init time — so test\n  // suites that toggle NODE_ENV per case observe the new value. Falls\n  // back gracefully if `process` is unavailable (non-Node runtimes).\n  const isProduction =\n    typeof process !== \"undefined\" &&\n    process.env?.NODE_ENV === \"production\";\n  const level: \"warn\" | \"error\" = isProduction ? \"error\" : \"warn\";\n\n  if (isSentry) {\n    sdkLog(level,\n      `[glasstrace] An existing OTel TracerProvider is registered but Glasstrace ` +\n      `could not auto-attach its span processor.\\n` +\n      `Add Glasstrace to your Sentry config:\\n\\n` +\n      `  import { createGlasstraceSpanProcessor } from '@glasstrace/sdk';\\n\\n` +\n      `  Sentry.init({\\n` +\n      `    dsn: '...',\\n` +\n      `    openTelemetrySpanProcessors: [createGlasstraceSpanProcessor()],\\n` +\n      `  });`,\n    );\n  } else {\n    sdkLog(level,\n      `[glasstrace] An existing OTel TracerProvider is registered but Glasstrace ` +\n      `could not auto-attach its span processor.\\n` +\n      `Add Glasstrace to your provider configuration:\\n\\n` +\n      `  import { createGlasstraceSpanProcessor } from '@glasstrace/sdk';\\n\\n` +\n      `  const provider = new BasicTracerProvider({\\n` +\n      `    spanProcessors: [\\n` +\n      `      // ... your existing processors,\\n` +\n      `      createGlasstraceSpanProcessor(),\\n` +\n      `    ],\\n` +\n      `  });`,\n    );\n  }\n}\n\n/**\n * Returns true if the nudge message should be shown.\n * Only show when auto-attach was used (not when the user already\n * configured the processor manually).\n */\nexport function shouldShowNudge(): boolean {\n  return getOtelState() === OtelState.AUTO_ATTACHED;\n}\n\n// ---------------------------------------------------------------------------\n// Internal\n// ---------------------------------------------------------------------------\n\n/**\n * Scans a processor list for one whose exporter carries the Glasstrace\n * brand symbol. Defensive — missing fields or non-object exporters return\n * `false`.\n */\nfunction hasBrandedProcessor(\n  processors: Array<{ _exporter?: unknown }>,\n): boolean {\n  return processors.some((p) => {\n    const exporter = p._exporter as Record<symbol, unknown> | undefined;\n    return exporter?.[GLASSTRACE_EXPORTER_BRAND] === true;\n  });\n}\n\nfunction detectSentry(): boolean {\n  try {\n    // Check if @sentry/node or @sentry/nextjs is installed\n    // Use require.resolve which checks module resolution without importing\n    require.resolve(\"@sentry/node\");\n    return true;\n  } catch {\n    try {\n      require.resolve(\"@sentry/nextjs\");\n      return true;\n    } catch {\n      return false;\n    }\n  }\n}\n","/**\n * Structural classifiers for `@opentelemetry/api`'s `ProxyTracerProvider`\n * and `ProxyTracer`. Used by the SDK's two existing-provider probe sites\n * (`otel-config.ts`, `register.ts`) to distinguish \"the SDK is looking at\n * its own bundled OTel proxy\" from \"another tool has registered a real\n * provider\".\n *\n * **Why structural rather than constructor-name based:** Next.js 16's\n * production bundler/minifier renames `@opentelemetry/api`'s\n * `ProxyTracerProvider` and `ProxyTracer` classes to short identifiers\n * (`eN` / `ew` / `ek` / `e_` in the wild). A constructor-name comparison\n * (`probeTracer.constructor.name !== \"ProxyTracer\"`) therefore returns\n * `true` against the SDK's own bundled proxy, the SDK incorrectly\n * concludes that an external provider is registered, and the\n * coexistence/auto-attach path runs against a proxy with no real\n * delegate. Spans are silently lost. The structural classifiers below\n * survive minification because they inspect prototype-method shape\n * rather than identifier names.\n *\n * **Load-bearing assumptions** (a future OTel API change that violates\n * any of these requires revisiting the structural check; the test suite\n * for these helpers is the early-warning system):\n *\n * 1. `ProxyTracerProvider`'s prototype exposes exactly four method\n *    names — `getTracer`, `getDelegate`, `setDelegate`,\n *    `getDelegateTracer` — and `ProxyTracer`'s prototype exposes\n *    exactly three — `_getTracer`, `startSpan`, `startActiveSpan`.\n *    Verified against `@opentelemetry/api` ≤ 1.x at the time of writing\n *    (recon date 2026-05-04). If a future OTel API release renames or\n *    removes any of these methods, the matching structural check\n *    breaks silently — the regression test suite catches that.\n * 2. `ProxyTracer`'s `_provider` field is a stable own data property\n *    holding a `===`-comparable reference to the owning\n *    `ProxyTracerProvider`. If a future OTel API release wraps\n *    `_provider` in a JS `Proxy` object or replaces it with a getter\n *    that returns a fresh wrapper per call, the strict-equality\n *    disambiguator below breaks and the helpers must be revisited.\n * 3. The helpers detect `@opentelemetry/api`'s canonical proxy\n *    classes only. Arbitrary third-party \"proxy\"-style tracers that\n *    coincidentally share method-name shape are not detected as\n *    proxies; the `_provider === ownerProvider` ownership check on\n *    {@link isProxyTracer} is the disambiguator that prevents\n *    misclassification.\n */\n\n/**\n * Returns `true` when `value` structurally matches an OTel\n * `ProxyTracerProvider`: an object exposing the four methods\n * `getTracer`, `getDelegate`, `setDelegate`, and `getDelegateTracer` as\n * functions. The check uses `in` + `typeof === \"function\"`, which\n * matches both prototype methods (the canonical OTel case) and own\n * properties (e.g., a hand-rolled object literal in tests). This is\n * deliberate: a structural classifier should accept any value that\n * *behaves* like a `ProxyTracerProvider`, not just instances of the\n * upstream class.\n *\n * Returns `false` for `null`, `undefined`, and non-object inputs.\n *\n * @see {@link isProxyTracer} for the matching tracer classifier.\n */\nexport function isProxyTracerProvider(value: unknown): boolean {\n  if (value === null || value === undefined || typeof value !== \"object\") {\n    return false;\n  }\n  return (\n    \"getTracer\" in value &&\n    typeof (value as { getTracer: unknown }).getTracer === \"function\" &&\n    \"getDelegate\" in value &&\n    typeof (value as { getDelegate: unknown }).getDelegate === \"function\" &&\n    \"setDelegate\" in value &&\n    typeof (value as { setDelegate: unknown }).setDelegate === \"function\" &&\n    \"getDelegateTracer\" in value &&\n    typeof (value as { getDelegateTracer: unknown }).getDelegateTracer === \"function\"\n  );\n}\n\n/**\n * Returns `true` when `value` structurally matches an OTel\n * `ProxyTracer` AND its `_provider` **own data property** is\n * referentially equal (`===`) to `ownerProvider`. The structural check\n * requires the three methods `_getTracer`, `startSpan`, and\n * `startActiveSpan` present as functions (matching prototype methods OR\n * own properties — see {@link isProxyTracerProvider} for the rationale).\n * The ownership disambiguator catches third-party tracers that\n * coincidentally share the method-name shape but whose `_provider` is\n * absent, `undefined`, or points at a different provider object.\n *\n * The `_provider` check uses `Object.hasOwn(...)` (own-property only,\n * not the prototype chain) because OTel's canonical `ProxyTracer`\n * assigns `_provider` as an own data property in its constructor —\n * `this._provider = provider`. A prototype-chain match would risk\n * false positives if a third party places a `_provider` on a shared\n * prototype rather than the instance.\n *\n * Returns `false` for `null`, `undefined`, and non-object inputs.\n *\n * @param value - the candidate tracer.\n * @param ownerProvider - the provider that produced `value` via\n *   `getTracer()`. The match is against this exact object reference.\n *\n * @see {@link isProxyTracerProvider} for the matching provider classifier.\n */\nexport function isProxyTracer(value: unknown, ownerProvider: unknown): boolean {\n  if (value === null || value === undefined || typeof value !== \"object\") {\n    return false;\n  }\n  const structurallyShaped =\n    \"_getTracer\" in value &&\n    typeof (value as { _getTracer: unknown })._getTracer === \"function\" &&\n    \"startSpan\" in value &&\n    typeof (value as { startSpan: unknown }).startSpan === \"function\" &&\n    \"startActiveSpan\" in value &&\n    typeof (value as { startActiveSpan: unknown }).startActiveSpan === \"function\";\n  if (!structurallyShaped) {\n    return false;\n  }\n  // Ownership disambiguator: a real `ProxyTracer` carries a `_provider`\n  // OWN data property (set in the ProxyTracer constructor as\n  // `this._provider = provider`) pointing at the `ProxyTracerProvider`\n  // that produced it. Use `Object.hasOwn` to reject prototype-chain\n  // matches — a third-party tracer that exposes `_provider` on a\n  // shared prototype (rather than as an own data property on the\n  // instance) is NOT one of our proxies, so the probe should treat\n  // the surrounding provider as a real external provider.\n  if (!Object.hasOwn(value, \"_provider\")) {\n    return false;\n  }\n  return (value as unknown as { _provider: unknown })._provider === ownerProvider;\n}\n","import { AsyncLocalStorage } from \"node:async_hooks\";\nimport * as otelApi from \"@opentelemetry/api\";\n\n/**\n * Branded discriminator field on the stored guard value.\n *\n * Storing the guard payload as `{ glasstraceContextManagerBrand: 1, … }`\n * lets us detect at runtime whether the value on `globalThis[GUARD]` was\n * placed there by Glasstrace or by some foreign squatter that happens to\n * collide on the well-known symbol. Foreign values are treated as\n * \"not yet attempted\" and overwritten — refusing to install indefinitely\n * because of an unknown squatter would be the worse failure mode (no\n * trace context propagation at all). The brand lets us make that\n * decision deterministically rather than guessing from value shape.\n */\nconst GLASSTRACE_BRAND = 1 as const;\n\n/**\n * Process-wide brand used to look up the prior installation result on\n * `globalThis`. The brand survives module re-evaluation (Turbopack HMR\n * rebuilds, Webpack `next dev` rebuilds, jest module isolation) because\n * it is keyed on a `Symbol.for()` global symbol — same mechanism used\n * by the exporter brand in `coexistence.ts`. Per V8 semantics\n * `globalThis` is per-isolate, so Node `worker_threads` and `vm.Context`\n * each get a fresh slot — that is the correct behavior, since a worker\n * is a logically separate process and gets its own context manager.\n */\nconst GUARD = Symbol.for(\"glasstrace.context-manager.installed\");\n\n/**\n * Well-known key under which `@opentelemetry/api` stores its global\n * registry on `globalThis`. The major version segment matches the\n * `@opentelemetry/api` peer dependency range (`^1.9.0`), so this value\n * is stable for the lifetime of the v1.x API line.\n *\n * Reading this slot lets us observe which `ContextManager` (if any) is\n * currently registered with OTel without going through the package's\n * private `_getContextManager()` accessor. We never write to it.\n */\nconst OTEL_API_KEY = Symbol.for(\"opentelemetry.js.api.1\");\n\n/**\n * Three-state record stored under `globalThis[GUARD]`.\n *\n * - `manager: ContextManager` — installation succeeded previously; reuse\n *   the same instance and short-circuit.\n * - `manager: null` — `setGlobalContextManager()` rejected previously\n *   (another tool already owns the slot). The rejection is sticky for\n *   as long as OTel's slot remains occupied by some manager; if the\n *   competing manager is later removed (e.g. via `context.disable()`),\n *   the next call retries registration.\n *\n * The \"not yet attempted\" state is encoded by the absence of the brand\n * (`globalThis[GUARD] === undefined`), not by a third record value.\n * Encoding it as a record value would require a 4-state enum and\n * complicate the foreign-collision logic for no benefit.\n */\ninterface InstallationRecord {\n  readonly glasstraceContextManagerBrand: typeof GLASSTRACE_BRAND;\n  readonly manager: otelApi.ContextManager | null;\n}\n\n/**\n * Type-narrowing predicate that identifies a value that has the shape\n * of an OTel `ContextManager` — the five-method interface defined by\n * `@opentelemetry/api`'s `context/types.ts`. Used both to validate the\n * `manager` field of an installation record and to treat foreign or\n * corrupt records as \"not yet attempted\" so they get overwritten on\n * the next call.\n */\nfunction isOtelContextManager(value: unknown): value is otelApi.ContextManager {\n  if (typeof value !== \"object\" || value === null) return false;\n  const candidate = value as Partial<otelApi.ContextManager>;\n  return (\n    typeof candidate.active === \"function\" &&\n    typeof candidate.with === \"function\" &&\n    typeof candidate.bind === \"function\" &&\n    typeof candidate.enable === \"function\" &&\n    typeof candidate.disable === \"function\"\n  );\n}\n\n/**\n * Type-narrowing predicate that identifies a payload Glasstrace itself\n * stored. Anything else (a plain string, a number, an object missing\n * the discriminator, an old Glasstrace-shaped value with a different\n * brand version, an object whose `manager` field is corrupt and not a\n * real OTel `ContextManager`) is treated as \"not yet attempted\" and\n * overwritten on the next call.\n *\n * Validating the `manager` shape — not just `typeof === \"object\"` —\n * prevents an attacker or a buggy collaborator that has corrupted the\n * brand slot to `{ glasstraceContextManagerBrand: 1, manager: {} }`\n * from short-circuiting `installContextManager()` and leaving the SDK\n * with no real context manager registered.\n */\nfunction isInstallationRecord(value: unknown): value is InstallationRecord {\n  if (typeof value !== \"object\" || value === null) return false;\n  const candidate = value as Partial<InstallationRecord>;\n  if (candidate.glasstraceContextManagerBrand !== GLASSTRACE_BRAND) return false;\n  return candidate.manager === null || isOtelContextManager(candidate.manager);\n}\n\n/**\n * Returns the `ContextManager` that OTel's global API currently has\n * registered, or `undefined` if no manager is registered (i.e. a call\n * to `otelApi.context.disable()` has cleared the slot, or no call to\n * `setGlobalContextManager()` has succeeded yet).\n *\n * Reads `globalThis[Symbol.for(\"opentelemetry.js.api.1\")].context`\n * directly rather than calling the private `_getContextManager()`\n * accessor on the API instance — the latter falls back to a singleton\n * `NoopContextManager` when nothing is registered, which we cannot\n * disambiguate from \"an unrelated tool registered the noop manager\".\n * Reading the global slot itself is the only way to observe the\n * registration state truthfully.\n */\nfunction getOtelRegisteredContextManager(): otelApi.ContextManager | undefined {\n  const otelSlot = (globalThis as Record<symbol, unknown>)[OTEL_API_KEY];\n  if (typeof otelSlot !== \"object\" || otelSlot === null) return undefined;\n  const ctx = (otelSlot as { context?: unknown }).context;\n  return isOtelContextManager(ctx) ? ctx : undefined;\n}\n\n/**\n * Internal helper used by tests to clear the `globalThis` brand between\n * cases. Not exported from the package barrel.\n *\n * @internal\n */\nexport function _resetContextManagerForTesting(): void {\n  delete (globalThis as Record<symbol, unknown>)[GUARD];\n}\n\n/**\n * Registers an AsyncLocalStorage-based context manager with the OTel API.\n *\n * This MUST be called synchronously before any spans are created —\n * otherwise, spans created before registration have no parent context\n * and each gets a fresh traceId.\n *\n * Uses a static import of `node:async_hooks` (synchronous, no race\n * condition). This means the module cannot be evaluated in non-Node\n * environments (Edge Runtime, browser) — but the SDK is a server-side\n * package and non-Node environments are guarded by the `sideEffects: false`\n * flag in package.json (browser bundlers tree-shake it) and the browser\n * import check CI step externalizes `async_hooks`.\n *\n * **Idempotency contract.** Construction is idempotent\n * across module re-evaluations within a single V8 isolate. The first\n * successful call records the installed `ContextManager` instance\n * under `globalThis[Symbol.for(\"glasstrace.context-manager.installed\")]`;\n * subsequent calls — including those that arrive after a Turbopack HMR\n * rebuild has reset the SDK's module-level `_coreState` — read the\n * recorded instance and return without constructing a fresh\n * `AsyncLocalStorage`, **so long as OTel's global slot still holds\n * that same manager instance**. This guard prevents unbounded\n * `AsyncLocalStorage` accumulation under Turbopack HMR\n * while still allowing recovery if an external caller has run\n * `otelApi.context.disable()` or replaced the manager underneath us.\n *\n * **Recovery semantics.** When the cached record disagrees with OTel's\n * actual registered manager, the SDK does the cheapest correct thing:\n *\n * - Cache says success and OTel's slot is now empty or holds a\n *   different manager → re-register the cached manager (no fresh\n *   `AsyncLocalStorage` allocation; the existing ALS continues to\n *   work).\n * - Cache says rejection and OTel's slot is now empty → drop the\n *   sticky-false state and attempt a real registration with a fresh\n *   manager. (If the slot is still occupied — by anyone — the\n *   sticky-false state remains.)\n *\n * The guard is per-V8-isolate (`globalThis` scope). `node:worker_threads`\n * and `node:vm` contexts each get a fresh slot, which is the correct\n * behavior — workers are logically separate processes and benefit from\n * their own context manager.\n *\n * @returns `true` if Glasstrace's context manager is registered with\n * OTel after this call (either still from a prior call or as a result\n * of this call); `false` if `setGlobalContextManager` rejected this\n * call or a prior rejection is still in effect.\n */\nexport function installContextManager(): boolean {\n  try {\n    const slot = globalThis as Record<symbol, unknown>;\n    const existing = slot[GUARD];\n    const otelCurrent = getOtelRegisteredContextManager();\n\n    // Fast path: a prior call already registered our manager and OTel\n    // still has it. No allocation, no API call, just return true.\n    if (\n      isInstallationRecord(existing) &&\n      existing.manager !== null &&\n      existing.manager === otelCurrent\n    ) {\n      return true;\n    }\n\n    // Cache says we previously hit a rejection. The rejection stays\n    // sticky as long as OTel's slot is occupied — by anyone. Only when\n    // the slot becomes empty do we drop the sticky-false state and\n    // attempt a fresh registration below.\n    if (\n      isInstallationRecord(existing) &&\n      existing.manager === null &&\n      otelCurrent !== undefined\n    ) {\n      return false;\n    }\n\n    // Cache says we previously succeeded but OTel's state has\n    // diverged: someone called `context.disable()` or replaced our\n    // manager. Re-register the cached manager — its underlying\n    // AsyncLocalStorage is still functional, so we avoid the\n    // allocation that would otherwise reintroduce DISC-1310 under\n    // repeated divergences.\n    if (isInstallationRecord(existing) && existing.manager !== null) {\n      const reSuccess = otelApi.context.setGlobalContextManager(existing.manager);\n      if (!reSuccess) {\n        console.warn(\n          \"[glasstrace] Another context manager is already registered. \" +\n          \"Trace context propagation may not work as expected.\",\n        );\n      }\n      const reRecord: InstallationRecord = {\n        glasstraceContextManagerBrand: GLASSTRACE_BRAND,\n        manager: reSuccess ? existing.manager : null,\n      };\n      slot[GUARD] = reRecord;\n      return reSuccess;\n    }\n\n    // Either no record exists, the existing record is foreign/corrupt,\n    // or the prior rejection has expired (OTel slot is now empty).\n    // Allocate a fresh ALS and attempt a real registration.\n    const als = new AsyncLocalStorage<otelApi.Context>();\n\n    const contextManager: otelApi.ContextManager = {\n      active: () => als.getStore() ?? otelApi.ROOT_CONTEXT,\n      with: <A extends unknown[], F extends (...args: A) => ReturnType<F>>(\n        context: otelApi.Context,\n        fn: F,\n        thisArg?: ThisParameterType<F>,\n        ...args: A\n      ): ReturnType<F> => als.run(context, () => fn.apply(thisArg, args)),\n      bind: <T>(context: otelApi.Context, target: T): T => {\n        if (typeof target === \"function\") {\n          const bound = (...fnArgs: unknown[]) =>\n            als.run(context, () => (target as (...a: unknown[]) => unknown)(...fnArgs));\n          return bound as T;\n        }\n        return target;\n      },\n      enable: () => contextManager,\n      disable: () => contextManager,\n    };\n\n    const success = otelApi.context.setGlobalContextManager(contextManager);\n    if (!success) {\n      console.warn(\n        \"[glasstrace] Another context manager is already registered. \" +\n        \"Trace context propagation may not work as expected.\",\n      );\n    }\n\n    // Record the outcome only AFTER setGlobalContextManager has returned,\n    // so a throw from the OTel API leaves the slot empty and a\n    // subsequent call may legitimately retry. A successful call records\n    // the installed manager; a rejected call records `null` so the\n    // rejection is sticky until OTel's slot is freed.\n    const record: InstallationRecord = {\n      glasstraceContextManagerBrand: GLASSTRACE_BRAND,\n      manager: success ? contextManager : null,\n    };\n    slot[GUARD] = record;\n\n    return success;\n  } catch {\n    return false;\n  }\n}\n","import type { AnonApiKey } from \"@glasstrace/protocol\";\nimport type { ResolvedConfig } from \"./env-detection.js\";\nimport { collectHealthReport } from \"./health-collector.js\";\nimport { performInit, consumeRateLimitFlag } from \"./init-client.js\";\nimport { sdkLog } from \"./console-capture.js\";\nimport { registerShutdownHook, executeShutdown } from \"./lifecycle.js\";\n\nconst HEARTBEAT_INTERVAL_MS = 5 * 60 * 1000;   // 5 minutes\nconst BACKOFF_BASE_MS = HEARTBEAT_INTERVAL_MS;   // 5 minutes\nconst BACKOFF_MAX_MS = 30 * 60 * 1000;           // 30 minutes\nconst BACKOFF_JITTER = 0.2;                       // ±20%\n\n/**\n * Shutdown hook priority for the final heartbeat report.\n *\n * Per docs/component-designs/sdk-lifecycle.md Section 8.3:\n *   0  — OTel flush (must run first so spans are exported)\n *   10 — Heartbeat final report (includes final span counts)\n *   20 — Runtime state write (terminal state persisted last)\n *\n * @drift-check ../glasstrace-product/docs/component-designs/sdk-lifecycle.md §8.3 Shutdown Sequence\n */\nconst HEARTBEAT_SHUTDOWN_PRIORITY = 10;\n\nconst SHUTDOWN_MARKER_RELPATH = \".glasstrace/shutdown-requested\";\n\n// --- Module-level state ---\n\nlet heartbeatTimer: ReturnType<typeof setInterval> | null = null;\nlet heartbeatGeneration = 0;\nlet backoffAttempts = 0;\nlet backoffUntil = 0;\nlet tickInProgress = false;\n\n/**\n * Ensures the shutdown hook is only registered once per process and that\n * the final report is only sent once even if the hook runs more than once.\n */\nlet shutdownHookRegistered = false;\nlet shutdownFired = false;\n\n// --- Public API ---\n\n/**\n * Starts the periodic health heartbeat after successful init.\n * Timer is unref()'d so it doesn't prevent process exit.\n *\n * Registers a shutdown hook with the lifecycle coordinator (priority 10)\n * so the final health report runs after OTel flush (priority 0) and before\n * runtime state write (priority 20). The hook is registered once per\n * process; subsequent `startHeartbeat` calls do not re-register.\n *\n * @param onClaimTransition - Callback for claim key rotation, avoiding\n *   circular dependency with otel-config.ts.\n */\nexport function startHeartbeat(\n  config: ResolvedConfig,\n  anonKey: AnonApiKey | null,\n  sdkVersion: string,\n  generation: number,\n  onClaimTransition: (newApiKey: string, accountId: string) => void,\n): void {\n  // Prevent double-start\n  if (heartbeatTimer !== null) return;\n\n  heartbeatGeneration = generation;\n\n  heartbeatTimer = setInterval(() => {\n    void heartbeatTick(config, anonKey, sdkVersion, generation, onClaimTransition);\n  }, HEARTBEAT_INTERVAL_MS);\n\n  // unref() so the timer doesn't prevent Node.js process exit\n  heartbeatTimer.unref();\n\n  // Register the final health-report hook with the lifecycle coordinator.\n  // Signal handling is owned by the coordinator (registerSignalHandlers in\n  // otel-config.ts), so the heartbeat module no longer attaches directly to\n  // SIGTERM/SIGINT.\n  registerHeartbeatShutdownHook(config, anonKey, sdkVersion);\n\n  if (config.verbose) {\n    sdkLog(\"info\", \"[glasstrace] Heartbeat started (5-minute interval).\");\n  }\n}\n\n/**\n * Stops the heartbeat timer.\n *\n * The shutdown hook is intentionally not unregistered — the lifecycle\n * coordinator does not expose a removal API. Stopping the heartbeat here\n * suppresses future periodic ticks by clearing the timer, but it does not\n * prevent the already-registered shutdown hook from sending its final\n * health report once during process shutdown. The hook's internal\n * `shutdownFired` guard ensures it runs at most once regardless.\n */\nexport function stopHeartbeat(): void {\n  if (heartbeatTimer !== null) {\n    clearInterval(heartbeatTimer);\n    heartbeatTimer = null;\n  }\n}\n\n/**\n * Resets all heartbeat state. For testing only.\n */\nexport function _resetHeartbeatForTesting(): void {\n  stopHeartbeat();\n  heartbeatGeneration = 0;\n  backoffAttempts = 0;\n  backoffUntil = 0;\n  tickInProgress = false;\n  shutdownHookRegistered = false;\n  shutdownFired = false;\n}\n\n/**\n * Checks for the presence of the `.glasstrace/shutdown-requested` marker\n * file and, if present, triggers the lifecycle shutdown coordinator and\n * removes the marker.\n *\n * Returns `true` when the marker was found and the shutdown coordinator\n * was scheduled, `false` otherwise. The marker is removed synchronously\n * BEFORE executeShutdown() is scheduled so a crash during shutdown does\n * not cause the marker to be re-detected on restart.\n *\n * The filesystem lookup itself is synchronous, but `node:fs`/`node:path`\n * are loaded lazily via `require()` inside this helper rather than via\n * top-level imports. This keeps the helper usable from fake-timer-driven\n * heartbeat ticks without introducing extra microtask boundaries, while\n * also avoiding unconditional top-level built-in imports on module\n * load. The downstream `executeShutdown()` call can be awaited by the\n * caller when desired.\n *\n * Self-contained so it can be called from either the heartbeat tick\n * (current location) or a dedicated lifecycle hook in the future.\n *\n * @param projectRoot - Optional project root; defaults to `process.cwd()`.\n * @returns An object describing the outcome. When `triggered` is true,\n *   `shutdown` is the promise returned by `executeShutdown()` so the\n *   caller can optionally await full shutdown completion.\n */\nexport function checkShutdownMarker(projectRoot?: string): {\n  triggered: boolean;\n  shutdown?: Promise<void>;\n} {\n  // node:fs and node:path are imported lazily via require to remain\n  // compatible with non-Node bundlers that externalize node:* modules.\n  // Errors are swallowed — a non-Node environment simply reports\n  // \"no marker\".\n  let fsSync: typeof import(\"node:fs\") | null = null;\n  let pathSync: typeof import(\"node:path\") | null = null;\n  try {\n    // eslint-disable-next-line @typescript-eslint/no-require-imports, glasstrace/no-unguarded-node-require -- guarded by the surrounding try/catch (line 152) which returns `{ triggered: false }` on the tsup `__require` throw, identical to the no-marker branch (DISC-1555).\n    fsSync = require(\"node:fs\") as typeof import(\"node:fs\");\n    // eslint-disable-next-line @typescript-eslint/no-require-imports, glasstrace/no-unguarded-node-require -- guarded by the same try/catch as the preceding `node:fs` require; throw collapses to `{ triggered: false }` (DISC-1555).\n    pathSync = require(\"node:path\") as typeof import(\"node:path\");\n  } catch {\n    return { triggered: false };\n  }\n\n  const root = projectRoot ?? (typeof process !== \"undefined\" ? process.cwd() : \".\");\n  const markerPath = pathSync.join(root, SHUTDOWN_MARKER_RELPATH);\n\n  if (!fsSync.existsSync(markerPath)) return { triggered: false };\n\n  // Remove the marker BEFORE scheduling shutdown. If we removed it\n  // afterwards, a crashed process would leave the marker in place and\n  // cause the next start to shut down immediately.\n  try {\n    fsSync.unlinkSync(markerPath);\n  } catch {\n    // Best-effort — proceed with shutdown even if removal fails.\n  }\n\n  // executeShutdown is idempotent and never throws; fire-and-track the\n  // returned promise so the caller can optionally await completion.\n  const shutdown = executeShutdown().catch(() => {\n    // executeShutdown is designed not to throw; swallow defensively.\n  });\n  return { triggered: true, shutdown };\n}\n\n// --- Internal: heartbeat tick ---\n\nasync function heartbeatTick(\n  config: ResolvedConfig,\n  anonKey: AnonApiKey | null,\n  sdkVersion: string,\n  generation: number,\n  onClaimTransition: (newApiKey: string, accountId: string) => void,\n): Promise<void> {\n  // Prevent concurrent ticks (setInterval doesn't await async callbacks)\n  if (tickInProgress) return;\n  tickInProgress = true;\n\n  try {\n    // Generation check — stop if registration was reset\n    if (generation !== heartbeatGeneration) {\n      stopHeartbeat();\n      return;\n    }\n\n    // DISC-1247 Scenario 1: check for the shutdown-requested marker at\n    // the top of each tick. If `sdk uninit` has been run, the marker\n    // exists and we trigger shutdown immediately. Moved into a dedicated\n    // lifecycle hook once DISC-1248 lands — the helper is module-exported\n    // to keep that migration mechanical.\n    //\n    // The check itself is synchronous (fs.existsSync) so fake-timer tests\n    // stay deterministic; we do await the shutdown promise once it has\n    // been scheduled so the tick does not race its own cleanup.\n    const markerResult = checkShutdownMarker();\n    if (markerResult.triggered) {\n      stopHeartbeat();\n      if (markerResult.shutdown) {\n        await markerResult.shutdown;\n      }\n      return;\n    }\n\n    // Backoff check — skip this tick if in backoff window\n    if (Date.now() < backoffUntil) {\n      if (config.verbose) {\n        sdkLog(\"info\", \"[glasstrace] Heartbeat skipped (rate-limit backoff).\");\n      }\n      return;\n    }\n\n    // Collect and send health report (same pattern as backgroundInit)\n    const healthReport = collectHealthReport(sdkVersion);\n    const initResult = await performInit(config, anonKey, sdkVersion, healthReport);\n\n    // Generation re-check after async work\n    if (generation !== heartbeatGeneration) return;\n\n    // Handle 429 backoff via consumeRateLimitFlag\n    if (initResult === null && consumeRateLimitFlag()) {\n      backoffAttempts++;\n      const delay = Math.min(\n        BACKOFF_BASE_MS * Math.pow(2, backoffAttempts - 1),\n        BACKOFF_MAX_MS,\n      );\n      const jitter = delay * BACKOFF_JITTER * (Math.random() * 2 - 1);\n      backoffUntil = Date.now() + delay + jitter;\n      if (config.verbose) {\n        sdkLog(\"info\", `[glasstrace] Heartbeat backing off for ${Math.round((delay + jitter) / 1000)}s.`);\n      }\n    } else {\n      // Success or non-429 failure — reset backoff\n      backoffAttempts = 0;\n      backoffUntil = 0;\n    }\n\n    // Handle claim transition via callback (no otel-config import needed)\n    if (initResult?.claimResult) {\n      onClaimTransition(initResult.claimResult.newApiKey, initResult.claimResult.accountId);\n    }\n\n    if (config.verbose) {\n      sdkLog(\"info\", \"[glasstrace] Heartbeat completed.\");\n    }\n  } finally {\n    tickInProgress = false;\n  }\n}\n\n// --- Internal: shutdown health report ---\n\n/**\n * Registers the heartbeat's final-report hook exactly once per process.\n *\n * The hook:\n *   - Is idempotent (`shutdownFired` guard) so a duplicate invocation by\n *     the coordinator cannot double-report.\n *   - Stops the timer first so no further ticks race with the final report.\n *   - Preserves the exact payload that the previous direct-handler code\n *     sent (`collectHealthReport` + `performInit`), so consumers observe\n *     identical shutdown telemetry before and after this refactor.\n *   - Does NOT re-raise the signal. The lifecycle coordinator's signal\n *     handler owns signal propagation and calls process.kill() after all\n *     hooks complete.\n */\nfunction registerHeartbeatShutdownHook(\n  config: ResolvedConfig,\n  anonKey: AnonApiKey | null,\n  sdkVersion: string,\n): void {\n  if (shutdownHookRegistered) return;\n  shutdownHookRegistered = true;\n\n  registerShutdownHook({\n    name: \"heartbeat-final-report\",\n    priority: HEARTBEAT_SHUTDOWN_PRIORITY,\n    fn: async () => {\n      if (shutdownFired) return;\n      shutdownFired = true;\n\n      // Stop the heartbeat timer — no more ticks after this\n      if (heartbeatTimer !== null) {\n        clearInterval(heartbeatTimer);\n        heartbeatTimer = null;\n      }\n\n      // Best-effort final report. Errors are swallowed so they don't\n      // prevent the remainder of the shutdown sequence from completing.\n      try {\n        const healthReport = collectHealthReport(sdkVersion);\n        await performInit(config, anonKey, sdkVersion, healthReport);\n      } catch {\n        // Intentionally swallow final-report failures to avoid adding\n        // shutdown noise or interrupting the remaining shutdown hooks.\n      }\n    },\n  });\n}\n","/**\n * Public side-effect evidence emission API.\n *\n * Exposes {@link recordSideEffect} as a single user-callable function\n * that attaches allowlisted, non-sensitive semantic metadata about a\n * side-effect operation (email, calendar_link, webhook, external_api,\n * queue, after_callback) to the current active OTel span.\n *\n * The behavior contract is observational only: this function never\n * executes a side effect, never retries, never delays, never throws.\n * All failure modes (no active span, ended span, NonRecordingSpan,\n * capture-config disabled, allowlist rejection, per-span budget\n * exhausted, OTel attribute slot exhaustion) silently route to a\n * no-op or to an omission-counter increment that carries no rejected\n * input.\n */\n\nimport {\n  MAX_SIDE_EFFECT_SCALARS_PER_OPERATION,\n  type SideEffectOperationKind,\n  type SideEffectOperationPhase,\n  type SideEffectOperationStatus,\n  type SideEffectSemanticFieldKey,\n} from \"@glasstrace/protocol\";\nimport {\n  checkOperationKind,\n  checkOperationLabel,\n  checkOperationPhase,\n  checkOperationStatus,\n  checkScalarField,\n  checkSemanticFieldKey,\n  checkSemanticFieldValue,\n} from \"./allowlist.js\";\nimport { type Span } from \"@opentelemetry/api\";\nimport {\n  attachField,\n  attachOperation,\n  attachScalar,\n  getRecordingActiveSpan,\n  hasExplicitFieldAttribute,\n  isRecordingSpan,\n  recordOmission,\n} from \"./emit.js\";\nimport type { SideEffectOmissionReason } from \"@glasstrace/protocol\";\nimport { getActiveConfig } from \"../init-client.js\";\nimport {\n  decisionTrace,\n  decisionTraceEnabled,\n  _resetDecisionTraceForTesting,\n} from \"../decision-trace.js\";\n\n// ---------------------------------------------------------------------------\n// Vocabulary-governance signals (DISC-1878 + DISC-1879)\n// ---------------------------------------------------------------------------\n\n/**\n * Verbose flag, set by `registerGlasstrace()` from the resolved\n * `GlasstraceOptions.verbose`. Gates the pattern-key proliferation\n * warn so it stays opt-in for operator debugging. Defaults to `false`\n * when `registerGlasstrace()` has not been called (e.g., direct\n * `recordSideEffect` calls in tests).\n */\nlet _verbose = false;\n\n/**\n * Setter for the verbose flag. Called from `registerGlasstrace()`\n * after `resolveConfig()` runs. Not exposed from the public package\n * barrel — internal coordination only.\n *\n * @internal\n */\nexport function setSideEffectVerboseFlag(verbose: boolean): void {\n  _verbose = verbose;\n}\n\n/**\n * One-shot guard for the no-recording-active-span diagnostic. The warn\n * fires at most once per process so a high-frequency call site (a tRPC\n * procedure that drops every request) does not flood the log.\n */\nlet _noActiveSpanWarned = false;\n\n/**\n * Emit a one-time, verbose-gated diagnostic when `recordSideEffect` is\n * called correctly (valid `kind`) but no recording span is available to\n * attach evidence to — the otherwise-silent drop that makes a lost\n * side effect externally undebuggable. Marked before the `console.warn`\n * (so a throwing host does not cause a retry) and fenced (so a host that\n * replaces `console.warn` cannot disrupt the behavior-neutral path).\n */\nfunction maybeWarnNoActiveSpan(): void {\n  if (!_verbose) return;\n  if (_noActiveSpanWarned) return;\n  _noActiveSpanWarned = true;\n  try {\n    console.warn(\n      `[glasstrace] recordSideEffect: no recording active span at the ` +\n        `call site — side-effect evidence was dropped. Wrap tRPC ` +\n        `procedures with @glasstrace/sdk/trpc tracedMiddleware, or pass ` +\n        `an owned span: recordSideEffect(input, { span }).`,\n    );\n  } catch {\n    // Diagnostic deliverability is best-effort; never propagate.\n  }\n}\n\n/**\n * Distinct casing-patterns observed per `*Class` / `*Role` key, used\n * to dedup the value-casing warn so a given (key, casing-pattern)\n * pair warns at most once per process lifetime.\n *\n * Bounded by `_CASING_DEDUP_MAX_KEYS` to prevent unbounded memory\n * growth when a producer emits high-cardinality pattern keys (e.g.,\n * per-provider `provider1Class`, `provider2Class`, ...). Once the\n * cap is reached, new keys are silently skipped — no warn, no map\n * growth. Existing keys in the cap continue to dedup correctly.\n * For the high-cardinality-producer scenario the proliferation warn\n * (verbose-gated) is the operator-facing signal; this\n * cap is just a memory bound.\n */\nconst _casingWarnSeen = new Map<string, Set<string>>();\n\n/**\n * Cap on the casing-warn dedup map. 100 = bounded memory budget\n * (~10KB worst case: 100 keys × 2 casing patterns × ~50 bytes\n * per entry) while leaving room for legitimate producer vocabularies\n * to warn on real deviations. Producers exceeding this cap are\n * surfaced via the proliferation warn instead.\n */\nconst _CASING_DEDUP_MAX_KEYS = 100;\n\n/**\n * Distinct pattern-admitted field keys observed this process,\n * excluding explicitly-mapped keys (stable-core or extended evidence).\n * Used as the input to the proliferation warn threshold check.\n */\nconst _patternKeysSeen = new Set<string>();\n\n/**\n * Bounded queue of the most-recent pattern-admitted keys, used to\n * name a small sample in the proliferation warn message. Capped at\n * `_RECENT_KEYS_IN_WARN` entries.\n */\nconst _recentPatternKeys: string[] = [];\n\n/**\n * Whether the proliferation warn has already fired this process. The\n * warn is one-shot — once threshold is crossed and the warn fires,\n * no further proliferation warns emit for the remainder of the\n * process lifetime.\n */\nlet _proliferationWarned = false;\n\n/**\n * Threshold for the proliferation warn: 50 distinct pattern-admitted\n * keys this process. Rationale: 5× the per-operation field cap (10),\n * leaving room for moderate vocabulary expansion across operations\n * before signaling that producer-side vocabulary review is warranted.\n */\nconst _PROLIFERATION_THRESHOLD = 50;\n\n/** Maximum number of recent keys to name in the proliferation warn. */\nconst _RECENT_KEYS_IN_WARN = 5;\n\n/**\n * Suffixes whose values follow the lowercase-kebab convention per the\n * v4 vocabulary contract. `*Count` (digit-only) and `*Kind` (no\n * casing convention enforced) are excluded.\n */\nfunction shouldCheckCasingConvention(key: string): boolean {\n  return key.endsWith(\"Class\") || key.endsWith(\"Role\");\n}\n\n/**\n * Compute a coarse casing-pattern bucket for a value. Used as the\n * dedup key for the casing warn so each distinct deviation from\n * lowercase warns once.\n */\nfunction casingPattern(value: string): \"uppercase\" | \"mixed\" {\n  return value === value.toUpperCase() ? \"uppercase\" : \"mixed\";\n}\n\n/**\n * Warn once per (`*Class`/`*Role` key, casing-pattern)\n * pair when a value deviates from the lowercase-kebab convention.\n * Emission still succeeds; the warn surfaces producer-side\n * normalization opportunities. Warn message contains the key name\n * only (no value) for PII safety. The `[glasstrace]` prefix routes\n * past the SDK's own console-capture machinery.\n */\nfunction maybeWarnMixedCasing(key: string, value: string): void {\n  if (!shouldCheckCasingConvention(key)) return;\n  if (value === value.toLowerCase()) return;\n  const pattern = casingPattern(value);\n  let seenPatterns = _casingWarnSeen.get(key);\n  if (!seenPatterns) {\n    // Cap the dedup map to prevent unbounded growth under a\n    // high-cardinality producer. Once we hit the cap, new keys are\n    // silently skipped — better to lose late-arriving warns than to\n    // grow the map without bound. Existing tracked keys continue to\n    // dedup correctly.\n    if (_casingWarnSeen.size >= _CASING_DEDUP_MAX_KEYS) return;\n    seenPatterns = new Set();\n    _casingWarnSeen.set(key, seenPatterns);\n  }\n  if (seenPatterns.has(pattern)) return;\n  seenPatterns.add(pattern);\n  console.warn(\n    `[glasstrace] side-effect field \"${key}\" value has ${pattern} casing; ` +\n      `convention is lowercase-kebab. Producer should normalize.`,\n  );\n}\n\n/**\n * Proliferation soft-cap. Counts distinct\n * pattern-admitted keys (those without an explicit\n * `FIELD_ATTRIBUTE_BY_KEY` entry) seen this process. When verbose\n * is on and the count crosses `_PROLIFERATION_THRESHOLD`, emits a\n * one-shot warn naming the most-recent `_RECENT_KEYS_IN_WARN` keys.\n * Stable-core and extended evidence keys never count.\n */\nfunction maybeWarnPatternKeyProliferation(key: string): void {\n  if (!_verbose) return;\n  if (_proliferationWarned) return;\n  if (hasExplicitFieldAttribute(key)) return;\n  if (_patternKeysSeen.has(key)) return;\n  _patternKeysSeen.add(key);\n  _recentPatternKeys.push(key);\n  if (_recentPatternKeys.length > _RECENT_KEYS_IN_WARN) {\n    _recentPatternKeys.shift();\n  }\n  if (_patternKeysSeen.size >= _PROLIFERATION_THRESHOLD) {\n    _proliferationWarned = true;\n    console.warn(\n      `[glasstrace] side-effect emission has used ${_patternKeysSeen.size} ` +\n        `distinct pattern-admitted field keys this process; recent: ` +\n        `${_recentPatternKeys.join(\", \")}. ` +\n        `Consider producer-side vocabulary review (lowercase-kebab convention; ` +\n        `Class/Count/Kind/Role suffixes).`,\n    );\n  }\n}\n\n/**\n * Test-only state reset for the vocabulary-governance counters. Not\n * exposed from the public package barrel. Tests for the warn paths\n * must call this in `beforeEach` to ensure dedup state does not leak\n * across describe blocks.\n *\n * @internal\n */\nexport function _resetSideEffectVocabState(): void {\n  _verbose = false;\n  _casingWarnSeen.clear();\n  _patternKeysSeen.clear();\n  _recentPatternKeys.length = 0;\n  _proliferationWarned = false;\n  _noActiveSpanWarned = false;\n  // Clear decision-trace toggle + dedup state so the capture-gate\n  // decision lines do not leak across describe blocks.\n  _resetDecisionTraceForTesting();\n}\n\n/**\n * Input shape for {@link recordSideEffect}.\n *\n * All fields except `kind` and `operation` are optional. The SDK\n * silently drops unknown fields and unsafe values, surfacing only an\n * integer omission count under the matching\n * `glasstrace.side_effect.omitted.*` attribute on the active span.\n */\nexport interface RecordSideEffectInput {\n  /**\n   * One of the allowlisted v1 operation kinds. Calls with any other\n   * value (typo, unsupported kind, non-string) silently drop without\n   * recording an omission, because there is no kind to attach the\n   * counter to.\n   */\n  kind: SideEffectOperationKind;\n\n  /**\n   * Compact, normalized operation label (max 96 chars). Must match\n   * `^[A-Za-z0-9][A-Za-z0-9_.:-]*$`. Free-form prose, URLs, query\n   * strings, and email-shaped values are silently dropped and routed\n   * to the matching omission counter.\n   */\n  operation: string;\n\n  /**\n   * Optional operation lifecycle status. Defaults to omitted. Values\n   * outside the v1 allowlist are silently dropped.\n   */\n  status?: SideEffectOperationStatus;\n\n  /**\n   * Optional operation execution phase (request / post_response /\n   * background / unknown). Defaults to omitted.\n   */\n  phase?: SideEffectOperationPhase;\n\n  /**\n   * Optional allowlisted semantic fields. Keys outside the v1\n   * allowlist (`templateKey`, `providerOperation`, `role`, `locale`,\n   * `timezone`, `status`, `phase`) and values matching unsafe\n   * patterns (URLs, emails, tokens, headers, prose-shaped\n   * whitespace) are silently dropped and routed to the matching\n   * omission counter.\n   */\n  fields?: Partial<Record<SideEffectSemanticFieldKey, string>>;\n\n  /**\n   * Optional value-fidelity scalars emitted on the off-summary\n   * `glasstrace.side_effect.scalar.*` channel. Keys must be camelCase\n   * ending in `Ms` / `Amount` / `Bytes` / `Ratio` / `Id` / `Value` /\n   * `Flag` (`Count` routes to the categorical `fields` channel instead).\n   * Values are native `number` / `boolean` / `string`.\n   *\n   * Under the default `strict` capture posture the SDK rejects raw\n   * wall-clock timestamps (a `Date`, or a raw epoch on a `*Ms` key) and\n   * unhashed `*Id` values at emit time — send bounded deltas as numbers,\n   * and pre-hash identifiers with `hashId` (`@glasstrace/sdk/node`). At\n   * most\n   * {@link MAX_SIDE_EFFECT_SCALARS_PER_OPERATION} scalars are recorded\n   * per call; rejected values route to the matching omission counter and\n   * the raw value never reaches the wire. The same key may also appear\n   * in `fields` — the two channels are distinct (selected by attribute\n   * prefix), so a categorical and a scalar facet can share a name.\n   */\n  scalars?: Record<string, unknown>;\n\n  /**\n   * Optional producer-asserted boolean relations (invariants) emitted on\n   * the categorical field channel. Keys must be camelCase ending in\n   * `Holds` (e.g. `timezonePreservedHolds`); values are real `boolean`s,\n   * coerced to `\"true\"`/`\"false\"` on the wire. A non-`Holds` key, a\n   * non-boolean value, or a key already attached by `fields` (a\n   * same-channel collision — `fields` wins) is dropped with the matching\n   * omission counter. Relations count against the same product-side\n   * per-operation field budget as `fields` (enforced at projection).\n   *\n   * Use {@link invariant} / {@link isNullInvariant} to compute the\n   * boolean from a comparison.\n   */\n  relations?: Record<string, boolean>;\n}\n\n/**\n * Options for {@link recordSideEffect}.\n */\nexport interface RecordSideEffectOptions {\n  /**\n   * A caller-**owned**, recording OTel span to attach the operation to,\n   * instead of the ambient active span. Use this from a passive adapter\n   * that opens its own span, or whenever the host app's OTel context may\n   * not reliably survive to the call site (so the ambient active span is\n   * unreliable). When omitted, the ambient active span is used.\n   *\n   * A supplied span that has ended or is a `NonRecordingSpan` is a silent\n   * no-op — the call does NOT fall back to the ambient span. This is the\n   * owned-span counterpart, for the categorical channel, to the `span`\n   * option on the value-fidelity `capture()` primitive.\n   */\n  span?: Span;\n}\n\n/**\n * Record allowlisted side-effect evidence on the current active OTel\n * span.\n *\n * Behavior is observational only: this function never executes,\n * retries, or duplicates a side effect. The default capture-config\n * flag `sideEffectEvidence` is `false`; callers must opt in via\n * account configuration before any attribute reaches the wire.\n *\n * Pass an owned span via `recordSideEffect(input, { span })` (see\n * {@link RecordSideEffectOptions}) to attach the operation to a span you\n * control instead of the ambient active span — use this when the host\n * app's OTel context may not reliably survive to the call site.\n *\n * Edge cases (all silent no-ops unless noted):\n *  - capture-config flag is `false` ⇒ no-op (no allowlist evaluation)\n *  - input is not a plain object ⇒ no-op\n *  - `kind` is not in the v1 allowlist ⇒ no-op\n *  - no recording span (no `{ span }` supplied and no recording active\n *    span — including an active span that has ended or is a\n *    `NonRecordingSpan`) ⇒ no-op, plus a one-time `console.warn`\n *    diagnostic when `verbose` is enabled\n *  - a supplied `{ span }` that has ended or is a `NonRecordingSpan` ⇒\n *    no-op (does NOT fall back to the ambient span)\n *  - per-span operation budget exhausted (5 ops max) ⇒ records a\n *    `value_too_long` omission count, no operation attributes\n *  - OTel attribute slot exhaustion ⇒ silently drops the attribute\n *    write\n *\n * The SDK guards only callers of this function. Direct\n * `span.setAttribute(\"glasstrace.side_effect.<...>\", ...)` writes\n * bypass the SDK and rely on the receiver's storage filter as the\n * second defense layer; this is intentional defense-in-depth, not a\n * gap.\n *\n * @example Recording a successful cancellation email\n * ```ts\n * import { recordSideEffect } from \"@glasstrace/sdk\";\n *\n * await mailer.send({ to: recipient, template: \"EventCanceledEmail\" });\n * recordSideEffect({\n *   kind: \"email\",\n *   operation: \"email.send\",\n *   status: \"succeeded\",\n *   phase: \"request\",\n *   fields: {\n *     templateKey: \"EventCanceledEmail\",\n *     role: \"invitee\",\n *     locale: \"en-US\",\n *     timezone: \"Europe/Paris\",\n *   },\n *   scalars: {\n *     // Bounded delta (not a wall-clock epoch) and a boolean flag.\n *     renderMs: 42,\n *     hadAttachmentFlag: false,\n *   },\n * });\n * ```\n */\nexport function recordSideEffect(\n  input: RecordSideEffectInput,\n  options?: RecordSideEffectOptions,\n): void {\n  try {\n    runRecordSideEffect(input, options);\n  } catch {\n    // Defense-in-depth: any unexpected throw inside the function\n    // (e.g., a host shim mis-implementing OTel API) must not\n    // propagate to the user's code path. Behavior-neutrality requires\n    // recordSideEffect to be observationally invisible.\n  }\n}\n\n/**\n * Record a field/scalar omission on the target span and, when decision\n * tracing is on, emit a `sideEffect.fieldRejected` decision keyed by the\n * closed omission reason. This is the hot-path rejection site, so the key\n * is the reason ONLY — never the rejected field key or value — which bounds\n * the one-shot cardinality to the fixed omission-reason set and keeps unsafe\n * input off the decision channel. The decision emit is call-site guarded so\n * no detail is built when the toggle is OFF, and it never alters the\n * omission bookkeeping.\n */\nfunction recordRejection(span: Span, reason: SideEffectOmissionReason): void {\n  recordOmission(span, reason);\n  if (decisionTraceEnabled()) {\n    decisionTrace(\"sideEffect.fieldRejected\", reason, {\n      oneShotKey: `sideEffect.fieldRejected:${reason}`,\n    });\n  }\n}\n\nfunction runRecordSideEffect(\n  input: unknown,\n  options?: RecordSideEffectOptions,\n): void {\n  if (!input || typeof input !== \"object\") return;\n\n  // Capture-config gate: read at every call so config rotation takes\n  // effect on the next emission without restart. The disk read is\n  // cached inside getActiveConfig() so this stays cheap on the hot\n  // path.\n  let captureEnabled: boolean;\n  try {\n    captureEnabled = getActiveConfig().sideEffectEvidence === true;\n  } catch {\n    captureEnabled = false;\n  }\n  // Decision trace (hot path): record which branch this call-site gate\n  // took. Call-site guarded so the detail object is not built when the\n  // toggle is OFF. Keyed by surface AND outcome so the `recordSideEffect`\n  // surface stays distinct from the `capture()` / `prismaAdapter` value\n  // paths, and an enabled→disabled rotation re-emits once.\n  if (decisionTraceEnabled()) {\n    const outcome = captureEnabled ? \"enabled\" : \"disabled\";\n    decisionTrace(\"capture.sideEffectEvidence\", outcome, {\n      inputs: { surface: \"recordSideEffect\" },\n      oneShotKey: `capture.sideEffectEvidence:recordSideEffect:${outcome}`,\n    });\n  }\n  if (!captureEnabled) {\n    // Note: we deliberately do NOT increment a `capture_disabled`\n    // omission counter for every call. With the flag off, the SDK's\n    // contract is \"no allowlist evaluation runs and no allocation\n    // happens\" — surfacing a per-call counter would require attaching\n    // to a span and would defeat that goal. The\n    // `capture_disabled` reason exists for the receiver-side path\n    // where ingestion drops attributes due to product-side flag\n    // changes after the SDK emitted them.\n    return;\n  }\n\n  const candidate = input as Partial<RecordSideEffectInput>;\n\n  if (!checkOperationKind(candidate.kind)) {\n    // No `kind` to attach a counter under — silent drop.\n    return;\n  }\n\n  // Resolve the target span up front and route everything onto it. A\n  // caller-supplied span is used only when it is recording (a dead /\n  // NonRecordingSpan supplied span is caller misuse — silent no-op, no\n  // ambient fallback, mirroring `capture`). Otherwise the ambient active\n  // span is used; when none is recording a valid call would otherwise\n  // drop invisibly, so emit the one-time verbose diagnostic.\n  let targetSpan: Span | undefined;\n  if (options?.span !== undefined) {\n    if (!isRecordingSpan(options.span)) return;\n    targetSpan = options.span;\n  } else {\n    targetSpan = getRecordingActiveSpan();\n    if (!targetSpan) {\n      maybeWarnNoActiveSpan();\n      return;\n    }\n  }\n\n  const labelOutcome = checkOperationLabel(candidate.operation);\n  if (!labelOutcome.accepted) {\n    recordRejection(targetSpan, labelOutcome.reason);\n    return;\n  }\n\n  let acceptedStatus: SideEffectOperationStatus | undefined;\n  if (candidate.status !== undefined) {\n    if (checkOperationStatus(candidate.status)) {\n      acceptedStatus = candidate.status;\n    } else {\n      recordRejection(targetSpan, \"unsupported_key\");\n    }\n  }\n\n  let acceptedPhase: SideEffectOperationPhase | undefined;\n  if (candidate.phase !== undefined) {\n    if (checkOperationPhase(candidate.phase)) {\n      acceptedPhase = candidate.phase;\n    } else {\n      recordRejection(targetSpan, \"unsupported_key\");\n    }\n  }\n\n  const outcome = attachOperation(targetSpan, {\n    kind: candidate.kind,\n    operation: labelOutcome.value,\n    status: acceptedStatus,\n    phase: acceptedPhase,\n  });\n\n  if (outcome.kind === \"over_budget\") {\n    recordRejection(targetSpan, \"value_too_long\");\n    return;\n  }\n\n  // Process semantic fields. Each rejection routes to an omission\n  // count on the same span; accepted values become field attributes.\n  // `attachedFieldKeys` records the keys that actually reached the wire,\n  // so the relations loop below can detect a genuine same-channel\n  // collision (a rejected field does not suppress a valid relation).\n  const attachedFieldKeys = new Set<string>();\n  const fields = candidate.fields;\n  if (fields && typeof fields === \"object\") {\n    for (const [rawKey, rawValue] of Object.entries(fields)) {\n      if (!checkSemanticFieldKey(rawKey)) {\n        recordRejection(targetSpan, \"unsupported_key\");\n        continue;\n      }\n      const valueOutcome = checkSemanticFieldValue(rawKey, rawValue);\n      if (!valueOutcome.accepted) {\n        recordRejection(targetSpan, valueOutcome.reason);\n        continue;\n      }\n      // Vocabulary-governance signals are diagnostic-only. Wrap in a\n      // try/catch so a host that replaces `console.warn` with a\n      // throwing implementation cannot disrupt the emission path —\n      // the contract is \"emission still succeeds even when the\n      // governance signal can't be delivered\".\n      try {\n        maybeWarnMixedCasing(rawKey, valueOutcome.value);\n        maybeWarnPatternKeyProliferation(rawKey);\n      } catch {\n        // Intentionally silent — warn deliverability is best-effort.\n      }\n      attachField(targetSpan, rawKey, valueOutcome.value);\n      attachedFieldKeys.add(rawKey);\n    }\n  }\n\n  // Process boolean `*Holds` relations on the categorical field channel.\n  // A real boolean is coerced to `\"true\"`/`\"false\"` and routed through\n  // the same field validator/emitter as `fields`. A key already attached\n  // by `fields` collides on the same channel — `fields` wins and the\n  // relation is dropped (a *rejected* field key is not a collision).\n  // (`scalars` is a separate attribute channel, so a `*Holds` name there\n  // is unrelated — and is independently rejected as a non-scalar key.)\n  // Relations count against the same product-side per-operation field\n  // budget as `fields`, enforced at projection.\n  const relations = candidate.relations;\n  if (relations && typeof relations === \"object\") {\n    for (const [rawKey, rawValue] of Object.entries(relations)) {\n      if (attachedFieldKeys.has(rawKey)) {\n        recordRejection(targetSpan, \"unsupported_key\");\n        continue;\n      }\n      if (!rawKey.endsWith(\"Holds\") || !checkSemanticFieldKey(rawKey)) {\n        recordRejection(targetSpan, \"unsupported_key\");\n        continue;\n      }\n      if (typeof rawValue !== \"boolean\") {\n        // Relations must be real booleans; a non-boolean is malformed.\n        recordRejection(targetSpan, \"raw_payload\");\n        continue;\n      }\n      const valueOutcome = checkSemanticFieldValue(\n        rawKey,\n        rawValue ? \"true\" : \"false\",\n      );\n      if (!valueOutcome.accepted) {\n        recordRejection(targetSpan, valueOutcome.reason);\n        continue;\n      }\n      // Same diagnostic governance as `fields` (the casing warn no-ops\n      // for `*Holds`; the proliferation warn counts the pattern key).\n      try {\n        maybeWarnMixedCasing(rawKey, valueOutcome.value);\n        maybeWarnPatternKeyProliferation(rawKey);\n      } catch {\n        // Intentionally silent — warn deliverability is best-effort.\n      }\n      attachField(targetSpan, rawKey, valueOutcome.value);\n      attachedFieldKeys.add(rawKey);\n    }\n  }\n\n  // Process value-fidelity scalars on the off-summary `scalar.*`\n  // channel. Enforced in `strict` mode at emit: raw wall-clock\n  // timestamps and unhashed `*Id` values never reach the wire. The\n  // `full` relaxation (which lets raw values through) requires the\n  // server-pushed `captureFidelity` AND a producer opt-in, and the\n  // ingestion-side sanitizer that re-enforces it — none of which ship in\n  // this slice — so the emitter is unconditionally `strict` here and the\n  // raw path stays unreachable until that co-wave lands (fail-closed).\n  const scalars = candidate.scalars;\n  if (scalars && typeof scalars === \"object\") {\n    let scalarCount = 0;\n    for (const [rawKey, rawValue] of Object.entries(scalars)) {\n      if (scalarCount >= MAX_SIDE_EFFECT_SCALARS_PER_OPERATION) {\n        // Per-operation scalar budget exhausted. Record a single\n        // count (mirroring the operation over-budget path) and stop;\n        // no rejected value is echoed.\n        recordRejection(targetSpan, \"scalar_cap_exceeded\");\n        break;\n      }\n      scalarCount += 1;\n      const scalarOutcome = checkScalarField(rawKey, rawValue);\n      if (!scalarOutcome.accepted) {\n        recordRejection(targetSpan, scalarOutcome.reason);\n        continue;\n      }\n      attachScalar(targetSpan, rawKey, scalarOutcome.value);\n    }\n  }\n}\n","/**\n * Runtime State Bridge\n *\n * Writes the SDK's lifecycle state to `.glasstrace/runtime-state.json`\n * so that CLI commands (`glasstrace status`) can report runtime\n * state without a live process connection.\n *\n * Design: sdk-lifecycle.md Section 14 (Runtime State File)\n */\n\nimport {\n  getSdkState,\n  onLifecycleEvent,\n  CoreState,\n} from \"./lifecycle.js\";\nimport { sdkLog } from \"./console-capture.js\";\nimport { atomicWriteFileSync, isSyncFsAvailable } from \"./atomic-write.js\";\n\n// node:fs and node:path are loaded lazily via require() so the module\n// remains loadable in non-Node runtimes that do not shim Node builtins\n// (some browser bundlers, Vercel Edge, Cloudflare Workers, Deno without\n// Node-compat). Wave 8 8D guarded the runtime call sites with the\n// isSyncFsAvailable() probe, but the previous top-of-file ESM imports\n// still failed at module-evaluation time before the probe could run\n// (DISC-377 §Item 1). The require()s are wrapped in try/catch and the\n// cached references are consumed only inside the isSyncFsAvailable()\n// gated path, mirroring the precedent at heartbeat.ts:150-159.\nlet fsSync: typeof import(\"node:fs\") | null = null;\nlet pathSync: typeof import(\"node:path\") | null = null;\ntry {\n  // eslint-disable-next-line @typescript-eslint/no-require-imports, glasstrace/no-unguarded-node-require -- guarded by the surrounding try/catch (line 31): a non-Node runtime cannot resolve `node:fs` and the throw collapses to `fsSync = null`; downstream writes are skipped by the existing isSyncFsAvailable() gate, identical to the no-Node-fs branch (DISC-1555 precedent in heartbeat.ts:154; DISC-377 §Item 1 closes the residual top-of-file import gap).\n  fsSync = require(\"node:fs\") as typeof import(\"node:fs\");\n  // eslint-disable-next-line @typescript-eslint/no-require-imports, glasstrace/no-unguarded-node-require -- guarded by the same try/catch as the preceding `node:fs` require (line 31); throw collapses to `pathSync = null` and is gated by isSyncFsAvailable() (DISC-1555 precedent in heartbeat.ts:156; DISC-377 §Item 1).\n  pathSync = require(\"node:path\") as typeof import(\"node:path\");\n} catch {\n  // Non-Node runtime — null BOTH refs even on partial-load. If\n  // `node:fs` resolves but `node:path` throws, leaving fsSync\n  // populated would let the isSyncFsAvailable() probe return true and\n  // writeStateNow() would later NPE on `pathSync!.join(...)`. Clearing\n  // both keeps the silent-skip contract intact: any failure during\n  // loader init treats the runtime as non-Node and disables the\n  // writer entirely.\n  fsSync = null;\n  pathSync = null;\n}\n\n/** Schema for the runtime state file. */\nexport interface RuntimeState {\n  updatedAt: string;\n  pid: number;\n  sdkVersion: string;\n  core: { state: string };\n  auth: { state: string };\n  otel: { state: string; scenario?: string };\n  /**\n   * Most recent structured failure observed by the SDK. Optional and\n   * additive — absent on successful runs and on consumers that wrote\n   * the file before this field existed. Surfaces SDK self-diagnostics\n   * only; never user request URLs, headers, payloads, or credentials.\n   *\n   * Currently emitted by the OTel coexistence path when\n   * `tryAutoAttachGlasstraceProcessor` returns `null` under a non-\n   * inert pre-registered provider (the Next 16 production failure\n   * mode). Additional structured failures may\n   * extend the `category` enum in future revisions.\n   *\n   * **PII-safety constraint (load-bearing):** populated values must\n   * not include the existing OTel provider's `delegate.url`,\n   * `delegate._exporter.endpoint`, `delegate._headers`, or any field\n   * that could carry user-app data. `providerClass` captures only\n   * the constructor name (e.g., `\"BasicTracerProvider\"`).\n   */\n  lastError?: RuntimeStateLastError;\n}\n\n/**\n * Structured failure record stored on {@link RuntimeState.lastError}.\n *\n * Extending the `category` enum is non-breaking; renaming or removing\n * a member is a public-contract change because CLI consumers may\n * surface the value verbatim.\n */\nexport interface RuntimeStateLastError {\n  /**\n   * Discriminator identifying the failure class.\n   *\n   * - `\"auto-attach-returned-null\"`: the OTel coexistence path detected\n   *   a pre-registered provider but could not inject the Glasstrace\n   *   span processor. Spans flowing through the existing\n   *   provider will not reach the Glasstrace exporter; the documented\n   *   manual `createGlasstraceSpanProcessor()` workaround applies.\n   * - `\"export-circuit-open\"`: the export-path circuit breaker tripped\n   *   after {@link FAILURE_THRESHOLD} consecutive non-success export\n   *   results. Spans are dropped via\n   *   `recordSpansDropped` until the next probe succeeds or\n   *   credentials rotate. The `exportCircuitCategory` field\n   *   disambiguates the underlying failure class (auth, rate_limit,\n   *   server_error, etc.).\n   */\n  category:\n    | \"auto-attach-returned-null\"\n    | \"export-circuit-open\";\n  /** Human-readable summary built from a fixed template — no user data. */\n  message: string;\n  /** ISO 8601 timestamp of the failure. */\n  timestamp: string;\n  /**\n   * Sanitized constructor name of the existing provider's delegate\n   * (e.g., `\"BasicTracerProvider\"`, `\"NextTracerProvider\"`). Reflects\n   * `delegate.constructor.name` only — never URLs, headers, or\n   * credentials. Absent if the provider exposes no readable\n   * constructor. Applies only to `category === \"auto-attach-returned-null\"`.\n   */\n  providerClass?: string;\n  /**\n   * Failure category that tripped the export-path circuit when\n   * `category === \"export-circuit-open\"`. Closed enum;\n   * extending the set is non-breaking, removing or renaming a member\n   * is a public-contract change because CLI consumers may render the\n   * value verbatim.\n   */\n  exportCircuitCategory?:\n    | \"auth\"\n    | \"client_error\"\n    | \"rate_limit\"\n    | \"server_error\"\n    | \"network\";\n}\n\n// ---------------------------------------------------------------------------\n// Module State\n// ---------------------------------------------------------------------------\n\nlet _projectRoot: string | null = null;\nlet _sdkVersion: string = \"unknown\";\nlet _lastScenario: string | undefined;\nlet _lastError: RuntimeStateLastError | undefined;\nlet _debounceTimer: ReturnType<typeof setTimeout> | null = null;\nlet _started = false;\n\n// ---------------------------------------------------------------------------\n// Public API\n// ---------------------------------------------------------------------------\n\n/**\n * Start writing runtime state to disk on every lifecycle state transition.\n * Must be called after initLifecycle() and after the project root is known.\n *\n * Writes are debounced to max once per second. The final SHUTDOWN state\n * bypasses debounce to ensure it's always persisted.\n *\n * Probes synchronous `node:fs` availability once before registering any\n * listeners. When the probe fails — for example, when the SDK is loaded as\n * an ESM module under a Next.js dev/start server, where tsup's bundled\n * `__require` shim cannot resolve `require(\"node:fs\")` from an ESM scope\n * — registration is skipped silently. The runtime-state file\n * is a best-effort CLI bridge; trace capture continues unaffected. A\n * later `glasstrace status` call falls back to its existing\n * \"no runtime state available\" path, matching the behavior on a project\n * that has not yet run the SDK. The skip is intentional and not surfaced\n * even under `verbose` because \"synchronous node:fs is unreachable here\"\n * is not an actionable debug signal in production.\n */\nexport function startRuntimeStateWriter(options: {\n  projectRoot: string;\n  sdkVersion: string;\n}): void {\n  if (_started) return;\n\n  // Probe synchronous `node:fs` availability once. atomicWriteFileSync()\n  // calls the same loader internally; calling it here lets a single\n  // probe gate every subsequent write without paying for repeated\n  // try/catch on each lifecycle event. The cache is shared with\n  // atomic-write, so the probe also primes the loader for downstream\n  // CLI sites in the rare case they run in the same process.\n  //\n  // Also verify the module-scope `fsSync` and `pathSync` cached refs\n  // populated correctly. atomic-write's `isSyncFsAvailable()` only\n  // checks `node:fs`; a partial-compat runtime where `node:fs`\n  // resolves but `node:path` does not (or where the two probes\n  // disagree for any other reason) would otherwise pass the gate and\n  // later NPE inside `writeStateNow()`. Treating any null ref as\n  // \"non-Node\" keeps the silent-skip contract intact across all\n  // partial-load shapes.\n  if (!isSyncFsAvailable() || fsSync === null || pathSync === null) {\n    _started = true;\n    return;\n  }\n\n  _started = true;\n\n  _projectRoot = options.projectRoot;\n  _sdkVersion = options.sdkVersion;\n\n  // Listen for state changes across all layers\n  onLifecycleEvent(\"core:state_changed\", ({ to }) => {\n    if (to === CoreState.SHUTDOWN) {\n      // Bypass debounce for terminal state — write immediately\n      writeStateNow();\n    } else {\n      debouncedWrite();\n    }\n  });\n\n  onLifecycleEvent(\"otel:configured\", ({ scenario }) => {\n    _lastScenario = scenario;\n    debouncedWrite();\n  });\n\n  // DISC-1556 Option C: persist structured fail-loud diagnostics so the\n  // CLI bridge can surface auto-attach failures that today emit only a\n  // log line. Snapshot-by-value semantics preserve the failure across\n  // subsequent writes (including the SHUTDOWN bypass) without coupling\n  // to the lifecycle emitter for read-back.\n  onLifecycleEvent(\"otel:failed\", (payload) => {\n    _lastError = { ...payload };\n    debouncedWrite();\n  });\n\n  // DISC-1568 / Wave 15C: persist the export-path circuit breaker's\n  // OPEN transition the same way. Close events clear the field only\n  // when the previous error was an export-circuit-open record — we\n  // must not clobber an unrelated `auto-attach-returned-null` error\n  // that may already be set (memo §Decision 5).\n  onLifecycleEvent(\"otel:circuit_opened\", (payload) => {\n    _lastError = {\n      category: \"export-circuit-open\",\n      message: payload.message,\n      timestamp: payload.timestamp,\n      exportCircuitCategory: payload.category,\n    };\n    debouncedWrite();\n  });\n  onLifecycleEvent(\"otel:circuit_closed\", () => {\n    if (_lastError?.category === \"export-circuit-open\") {\n      _lastError = undefined;\n      debouncedWrite();\n    }\n  });\n\n  // Auth events — write when key resolves or claim transitions occur\n  onLifecycleEvent(\"auth:key_resolved\", () => debouncedWrite());\n  onLifecycleEvent(\"auth:claim_started\", () => debouncedWrite());\n  onLifecycleEvent(\"auth:claim_completed\", () => debouncedWrite());\n\n  // No shutdown hook needed — the SHUTDOWN bypass in the core:state_changed\n  // listener writes the final state synchronously during setCoreState(SHUTDOWN).\n  // A hook would write SHUTTING_DOWN (before SHUTDOWN) and be immediately\n  // overwritten by the listener. The listener is simpler and correct.\n\n  // Write initial state immediately\n  writeStateNow();\n}\n\n/**\n * Reset runtime state writer. For testing only.\n */\nexport function _resetRuntimeStateForTesting(): void {\n  if (_debounceTimer) {\n    clearTimeout(_debounceTimer);\n    _debounceTimer = null;\n  }\n  _projectRoot = null;\n  _sdkVersion = \"unknown\";\n  _lastScenario = undefined;\n  _lastError = undefined;\n  _started = false;\n}\n\n// ---------------------------------------------------------------------------\n// Internal\n// ---------------------------------------------------------------------------\n\nfunction debouncedWrite(): void {\n  if (_debounceTimer) return; // Already scheduled\n\n  _debounceTimer = setTimeout(() => {\n    _debounceTimer = null;\n    writeStateNow();\n  }, 1000);\n\n  // unref so the timer doesn't prevent process exit\n  if (typeof _debounceTimer === \"object\" && \"unref\" in _debounceTimer) {\n    _debounceTimer.unref();\n  }\n}\n\nfunction writeStateNow(): void {\n  if (!_projectRoot) return;\n\n  try {\n    const state = getSdkState();\n    const runtimeState: RuntimeState = {\n      updatedAt: new Date().toISOString(),\n      pid: process.pid,\n      sdkVersion: _sdkVersion,\n      core: { state: state.core },\n      auth: { state: state.auth },\n      otel: { state: state.otel, scenario: _lastScenario },\n    };\n    // Only set `lastError` when the SDK has observed a structured\n    // failure. Omitting the field on success keeps the JSON compact\n    // and lets typed CLI consumers branch on `hasOwnProperty`.\n    if (_lastError) {\n      runtimeState.lastError = _lastError;\n    }\n\n    // Non-null assertions are safe: every path that reaches\n    // writeStateNow() is downstream of the gate in\n    // startRuntimeStateWriter(), which short-circuits when\n    // isSyncFsAvailable() reports false OR when either cached ref is\n    // null. Listeners are only registered after the gate passes, so\n    // by the time writeStateNow() is invoked both refs are guaranteed\n    // populated.\n    const dir = pathSync!.join(_projectRoot, \".glasstrace\");\n    const filePath = pathSync!.join(dir, \"runtime-state.json\");\n\n    // Ensure directory exists (may not if uninit deleted it)\n    fsSync!.mkdirSync(dir, { recursive: true, mode: 0o700 });\n\n    // Atomic write per SDK 2.0 §4.3: tmp + fsync(tmp) + rename +\n    // fsync(parent). The sync variant is used because this writer\n    // runs from a signal handler that cannot await.\n    atomicWriteFileSync(filePath, JSON.stringify(runtimeState, null, 2) + \"\\n\", {\n      mode: 0o600,\n    });\n  } catch (err) {\n    // Fire-and-forget — never block state transitions for a file write failure\n    sdkLog(\n      \"warn\",\n      `[glasstrace] Failed to write runtime state: ${\n        err instanceof Error ? err.message : String(err)\n      }`,\n    );\n  }\n}\n","import * as fs from \"node:fs\";\nimport * as path from \"node:path\";\nimport { isEndMarkerLine, parseStartMarkerLine } from \"./inject.js\";\nimport { decisionTrace, decisionTraceEnabled } from \"../decision-trace.js\";\n\n/**\n * Stale-managed-section warning.\n *\n * Detects a project whose agent instruction file (CLAUDE.md /\n * .cursorrules / codex.md) was rendered by an older `@glasstrace/sdk`\n * and emits a single stderr warning at SDK init pointing the user at\n * the upgrade command.\n *\n * Constraints:\n *   - Stderr only; never stdout. Must not affect tracing behaviour.\n *   - At most once per process boot, even when `registerGlasstrace()`\n *     is invoked more than once in the same process (test runners,\n *     hot-reload, multiple register calls).\n *   - Node.js runtime only — no-op when `process` / `fs` / stderr are\n *     unavailable. Never throws and never writes to `console`.\n *   - Must not mutate any file at runtime. The warning is decided\n *     locally from the on-disk stamp and the SDK's own version\n *     constant (no network I/O).\n *   - Respects `GLASSTRACE_DISABLE_UPGRADE_NOTICE` (truthy values\n *     `\"1\"`, `\"true\"`, `\"yes\"`, case-insensitive).\n *   - Warning text contains no user-controlled content. File names\n *     come from a hardcoded set; the on-disk stamp is parsed for\n *     comparison only and is never echoed back into the warning\n *     (defends against terminal-escape-sequence injection via a\n *     hand-edited stamp).\n *\n * Only version-stamped sections participate. Legacy unstamped\n * sections trigger no warning by spec — those users\n * receive the upgraded text on their next app-local `glasstrace mcp add`\n * or `glasstrace upgrade-instructions` run.\n */\n\n/**\n * Module-level guard that enforces \"at most one warning per process\n * boot.\" Reset only via {@link _resetUpgradeNoticeForTesting} so that\n * unit tests can exercise the warning path repeatedly.\n */\nlet warningEmitted = false;\n\n/**\n * Hardcoded set of agent instruction filenames to inspect, relative\n * to the supplied project root. The canonical set follows the 2026\n * cross-tool standard:\n *\n *   - `AGENTS.md`: universal cross-tool fallback (canonical 2026)\n *   - `CLAUDE.md`: Claude Code primary (canonical, unchanged)\n *   - `GEMINI.md`: Gemini CLI primary (canonical 2026)\n *   - `.cursor/rules/glasstrace.mdc`: Cursor canonical 2026\n *   - `.windsurf/rules/glasstrace.md`: Windsurf workspace-rules\n *     directory (canonical 2026)\n *   - `.cursorrules`: Cursor legacy single-file (still scanned to\n *     surface stale sections from older installs; written\n *     unconditionally as a transitional fallback)\n *   - `codex.md`: Codex legacy (no longer the canonical destination;\n *     scanned to surface stale sections from older installs)\n *   - `.windsurfrules`: Windsurf legacy single-file (no longer\n *     written by the SDK; scanned for the same stale-section reason)\n *\n * Restricting the scan to this hardcoded set keeps the warning fast\n * and ensures the warning text never interpolates a user-supplied or\n * attacker-supplied filename. Order: canonical 2026 destinations\n * first, legacy destinations last.\n */\nconst AGENT_INSTRUCTION_FILES = [\n  \"AGENTS.md\",\n  \"CLAUDE.md\",\n  \"GEMINI.md\",\n  \".cursor/rules/glasstrace.mdc\",\n  \".windsurf/rules/glasstrace.md\",\n  \".cursorrules\",\n  \"codex.md\",\n  \".windsurfrules\",\n] as const;\n\n/**\n * Strict semver parser. Splits the optional build-metadata suffix\n * (`+build`) per semver spec — build metadata is ignored for\n * precedence — then extracts MAJOR / MINOR / PATCH and an optional\n * dot-separated prerelease tail. Returns null when the input is not\n * a valid semver, which the caller maps to \"stamp present but\n * unknown\" (future-format tolerance).\n */\ninterface ParsedSemver {\n  major: number;\n  minor: number;\n  patch: number;\n  prerelease: string | null;\n}\n\nfunction parseSemver(input: string): ParsedSemver | null {\n  // Strip build metadata (`+...`) — ignored for precedence per semver spec.\n  const plusIdx = input.indexOf(\"+\");\n  const core = plusIdx === -1 ? input : input.slice(0, plusIdx);\n\n  const m = /^(\\d+)\\.(\\d+)\\.(\\d+)(?:-([0-9A-Za-z.-]+))?$/.exec(core);\n  if (m === null) return null;\n\n  return {\n    major: Number(m[1]),\n    minor: Number(m[2]),\n    patch: Number(m[3]),\n    prerelease: m[4] ?? null,\n  };\n}\n\n/**\n * Compares two prerelease strings per semver §11. Each is split into\n * dot-separated identifiers; numeric identifiers compare numerically,\n * alphanumeric identifiers compare lexicographically, numeric < alpha\n * when the kinds differ. A shorter prerelease (with all leading\n * identifiers equal) is older.\n */\nfunction comparePrerelease(a: string, b: string): number {\n  const ap = a.split(\".\");\n  const bp = b.split(\".\");\n  const len = Math.min(ap.length, bp.length);\n  for (let i = 0; i < len; i++) {\n    const x = ap[i];\n    const y = bp[i];\n    const xNumeric = /^\\d+$/.test(x);\n    const yNumeric = /^\\d+$/.test(y);\n    if (xNumeric && yNumeric) {\n      const xv = Number(x);\n      const yv = Number(y);\n      if (xv !== yv) return xv < yv ? -1 : 1;\n    } else if (xNumeric) {\n      return -1;\n    } else if (yNumeric) {\n      return 1;\n    } else if (x !== y) {\n      return x < y ? -1 : 1;\n    }\n  }\n  return ap.length - bp.length;\n}\n\n/**\n * Compares two semver strings. Returns a negative number when `a < b`,\n * positive when `a > b`, zero when equal, or null when either input\n * is not a parseable semver. The null return is what implements the\n * \"stamp present but unknown — skip the stale-warning rather than\n * crash\" tolerance.\n */\nexport function compareSemver(a: string, b: string): number | null {\n  const pa = parseSemver(a);\n  const pb = parseSemver(b);\n  if (pa === null || pb === null) return null;\n  if (pa.major !== pb.major) return pa.major - pb.major;\n  if (pa.minor !== pb.minor) return pa.minor - pb.minor;\n  if (pa.patch !== pb.patch) return pa.patch - pb.patch;\n  if (pa.prerelease === null && pb.prerelease === null) return 0;\n  // A version without prerelease has higher precedence than one with.\n  if (pa.prerelease === null) return 1;\n  if (pb.prerelease === null) return -1;\n  return comparePrerelease(pa.prerelease, pb.prerelease);\n}\n\n/**\n * Reads the truthy-state of `GLASSTRACE_DISABLE_UPGRADE_NOTICE`. The\n * accepted truthy values are `\"1\"`, `\"true\"`, `\"yes\"`\n * (case-insensitive); any other value (including unset or whitespace)\n * leaves the warning enabled.\n */\nfunction isOptedOut(): boolean {\n  const raw = process.env.GLASSTRACE_DISABLE_UPGRADE_NOTICE;\n  if (typeof raw !== \"string\") return false;\n  const trimmed = raw.trim().toLowerCase();\n  return trimmed === \"1\" || trimmed === \"true\" || trimmed === \"yes\";\n}\n\n/**\n * Optional heuristic suppression in non-interactive CI runs. The\n * design allows — but does\n * not require — suppressing the warning when stderr is not a TTY AND\n * `CI=true` is set in the environment. The combination indicates an\n * automated build (`next build` evaluating `instrumentation.ts`,\n * GitHub Actions matrix runs, etc.) where the warning is noise; an\n * interactive developer run still sees it because either condition\n * fails (TTY present, or CI unset).\n *\n * Implementation notes:\n *   - `process.stderr.isTTY` is `true | undefined`. Coerce to boolean\n *     with `=== true` so non-TTY stderr (piped / redirected / CI) is\n *     classified consistently.\n *   - `CI=true` is the GitHub Actions / many-CI convention; we accept\n *     only the literal `\"true\"` rather than any truthy value because\n *     the brief named that exact form.\n */\nfunction isQuietCiContext(): boolean {\n  const stderrIsTty = process.stderr.isTTY === true;\n  if (stderrIsTty) return false;\n  return process.env.CI === \"true\";\n}\n\n/**\n * Per-file inspection result. The caller aggregates these and emits\n * one warning if any file is `\"stale\"`.\n */\ntype FileState =\n  | \"absent\" // file does not exist or is unreadable\n  | \"no-section\" // file exists but has no managed marker pair\n  | \"no-stamp\" // managed section exists with legacy unstamped marker\n  | \"current\" // managed section exists with stamp >= running SDK\n  | \"stale\" // managed section exists with stamp < running SDK\n  | \"unknown-stamp\"; // stamp present but unparseable as semver\n\n/**\n * Maximum file size (bytes) we will read at SDK init for stale-stamp\n * detection. Realistic agent instruction files are well under 100 KB;\n * 5 MB is generous headroom while bounding the worst-case sync read at\n * `registerGlasstrace()` time. Pathologically large files are treated\n * as `\"absent\"` — the warning cannot be decided locally, but the SDK\n * will not block on a multi-second sync read either.\n */\nconst MAX_AGENT_FILE_BYTES = 5 * 1024 * 1024;\n\n/**\n * Synchronously inspects a single agent instruction file and reports\n * its state. Best-effort and silent — never throws. Reads only the\n * first marker line by scanning the whole file (small text files\n * make a streaming reader unnecessary; the typical agent-instruction\n * file is well under 100 KB).\n */\nfunction inspectFile(filePath: string, runningSdkVersion: string): FileState {\n  let content: string;\n  try {\n    const stat = fs.statSync(filePath);\n    if (!stat.isFile()) return \"absent\";\n    if (stat.size > MAX_AGENT_FILE_BYTES) return \"absent\";\n    content = fs.readFileSync(filePath, \"utf-8\");\n  } catch {\n    return \"absent\";\n  }\n\n  const lines = content.split(\"\\n\");\n\n  // Walk the file looking for a COMPLETE marker pair (start followed\n  // by end). An orphaned/quoted start marker without a matching end\n  // is treated as no-section so a hand-edited or truncated file\n  // cannot trigger a false stale warning.\n  //\n  // When multiple start markers appear before the first end marker\n  // (e.g. an earlier quoted-example marker line followed by the real\n  // managed block), classify based on the MOST RECENT start preceding\n  // the end — same anchoring as `findMarkerBoundaries` in inject.ts,\n  // so detection here mirrors what the upgrade command will actually\n  // replace.\n  let lastStart: { stamp: string | null } | null = null;\n  let foundEnd = false;\n  for (const line of lines) {\n    const parsed = parseStartMarkerLine(line);\n    if (parsed !== null) {\n      lastStart = parsed;\n      continue;\n    }\n    if (lastStart !== null && isEndMarkerLine(line)) {\n      foundEnd = true;\n      break;\n    }\n  }\n\n  if (lastStart === null || !foundEnd) {\n    return \"no-section\";\n  }\n\n  if (lastStart.stamp === null) {\n    return \"no-stamp\";\n  }\n  const cmp = compareSemver(lastStart.stamp, runningSdkVersion);\n  if (cmp === null) {\n    // Stamp present but unparseable (hand-edited, future format).\n    // SDK-050 future-format tolerance: skip the warning rather than\n    // crash. Upgrade still re-renders correctly via inject.ts.\n    return \"unknown-stamp\";\n  }\n  return cmp < 0 ? \"stale\" : \"current\";\n}\n\n/**\n * Inputs for {@link maybeWarnStaleAgentInstructions}.\n */\nexport interface UpgradeNoticeOptions {\n  /**\n   * Project root to scan for agent instruction files. Typically\n   * `process.cwd()` from the SDK runtime. The hardcoded set of\n   * filenames in {@link AGENT_INSTRUCTION_FILES} is joined against\n   * this directory.\n   */\n  projectRoot: string;\n  /**\n   * The SDK's own version constant (`__SDK_VERSION__`). Compared\n   * against the on-disk stamp. Must be a parseable semver; if not,\n   * the warning is suppressed (a misbuilt SDK should not emit\n   * spurious notices).\n   */\n  sdkVersion: string;\n  /**\n   * Test seam — overrides `process.stderr.write` so unit tests can\n   * capture the emitted line without touching the real stderr.\n   */\n  stderrWrite?: (chunk: string) => void;\n}\n\n/**\n * Best-effort stale-section check. Emits at most one stderr warning\n * per process boot when any inspected agent instruction file carries\n * a stamp strictly older than the running SDK version.\n *\n * Never throws. No-op in non-Node runtimes (browser / edge), when\n * the opt-out env var is set, when no stamped sections are found,\n * when no stale section is detected, or when this function has\n * already emitted in the current process.\n */\nexport function maybeWarnStaleAgentInstructions(\n  options: UpgradeNoticeOptions,\n): void {\n  try {\n    if (warningEmitted) return;\n\n    // Defensive Node-runtime guard. The module is only imported by\n    // `register.ts`, which the F003 edge gate excludes from the edge\n    // bundle — but a future re-export change must not regress this\n    // contract. Bail silently in any environment lacking the Node\n    // basics (process / process.env / stderr).\n    if (\n      typeof process === \"undefined\" ||\n      typeof process.versions?.node !== \"string\" ||\n      typeof process.env !== \"object\" ||\n      process.env === null\n    ) {\n      return;\n    }\n\n    if (isOptedOut()) {\n      // Decision trace: the stale-instruction upgrade notice was suppressed by\n      // the opt-out env var. Keyed by the closed outcome (`suppressed` /\n      // `shown`) AND the code-literal reason so each suppression branch keeps\n      // its own one-shot slot. Guarded so nothing is built when OFF. (This is\n      // an early-bootstrap point — it runs before the programmatic decision\n      // flag is threaded, so it is reachable via the GLASSTRACE_DECISION_TRACE\n      // env var.)\n      if (decisionTraceEnabled()) {\n        decisionTrace(\"env.upgradeNoticeSuppressed\", \"suppressed\", {\n          reason: \"opted_out\",\n          oneShotKey: \"env.upgradeNoticeSuppressed:suppressed:opted_out\",\n        });\n      }\n      return;\n    }\n    if (isQuietCiContext()) {\n      // Decision trace: suppressed in a non-interactive CI context.\n      if (decisionTraceEnabled()) {\n        decisionTrace(\"env.upgradeNoticeSuppressed\", \"suppressed\", {\n          reason: \"quiet_ci\",\n          oneShotKey: \"env.upgradeNoticeSuppressed:suppressed:quiet_ci\",\n        });\n      }\n      return;\n    }\n\n    // Misbuilt SDK guard: an unparseable running version means we\n    // cannot meaningfully decide staleness. Stay silent rather than\n    // emit a confusing warning.\n    if (parseSemver(options.sdkVersion) === null) {\n      // Decision trace: suppressed because the running SDK version is not\n      // parseable as semver, so staleness cannot be decided.\n      if (decisionTraceEnabled()) {\n        decisionTrace(\"env.upgradeNoticeSuppressed\", \"suppressed\", {\n          reason: \"unparseable_version\",\n          oneShotKey:\n            \"env.upgradeNoticeSuppressed:suppressed:unparseable_version\",\n        });\n      }\n      return;\n    }\n\n    const staleFiles: string[] = [];\n    for (const fileName of AGENT_INSTRUCTION_FILES) {\n      const fullPath = path.join(options.projectRoot, fileName);\n      const state = inspectFile(fullPath, options.sdkVersion);\n      if (state === \"stale\") {\n        staleFiles.push(fileName);\n      }\n    }\n\n    if (staleFiles.length === 0) return;\n\n    // Single-line warning. The text mentions the upgrade command and\n    // the opt-out env var. File names come from the hardcoded set —\n    // never from the on-disk stamp value — so there is no path for\n    // arbitrary user content (or terminal escape sequences from a\n    // hand-edited stamp) to reach stderr. Phrasing is grammatical\n    // for both 1-file and multi-file lists (\"section in X\" / \"section\n    // in X, Y\" both read cleanly).\n    const fileList = staleFiles.join(\", \");\n    const message =\n      `[glasstrace] Glasstrace managed MCP section in ${fileList} was rendered by an older ` +\n      `@glasstrace/sdk; from the app package run \\`npm exec -- glasstrace upgrade-instructions\\` ` +\n      `(pnpm: \\`pnpm exec glasstrace upgrade-instructions\\`) to refresh ` +\n      `(silence with GLASSTRACE_DISABLE_UPGRADE_NOTICE=1).\\n`;\n\n    warningEmitted = true;\n\n    // Decision trace: a stale managed section was found and the upgrade notice\n    // is being shown.\n    if (decisionTraceEnabled()) {\n      decisionTrace(\"env.upgradeNoticeSuppressed\", \"shown\", {\n        oneShotKey: \"env.upgradeNoticeSuppressed:shown\",\n      });\n    }\n\n    if (options.stderrWrite !== undefined) {\n      options.stderrWrite(message);\n      return;\n    }\n\n    // process.stderr is always present on Node, but defend against\n    // an exotic embedding where it's been replaced with a non-callable\n    // value. Catch any rare write error so the warning path can never\n    // throw out of registerGlasstrace().\n    try {\n      process.stderr.write(message);\n    } catch {\n      // Swallow — the warning is best-effort.\n    }\n  } catch {\n    // Top-level safety net. Any unexpected error in the upgrade-notice\n    // path is suppressed so it cannot affect SDK init or tracing.\n  }\n}\n\n/**\n * Test-only — clears the once-per-process guard so unit tests can\n * exercise multiple emissions in sequence. Not exported from the\n * public barrel.\n */\nexport function _resetUpgradeNoticeForTesting(): void {\n  warningEmitted = false;\n}\n","import { chmod, mkdir, readFile, writeFile } from \"node:fs/promises\";\nimport { dirname, isAbsolute, join } from \"node:path\";\nimport type { DetectedAgent } from \"./detect.js\";\n\n/**\n * HTML start-marker regex used in markdown files (.md). Matches both\n * legacy unstamped markers and version-stamped markers.\n *\n * Two shapes:\n *   - Legacy: `<!-- glasstrace:mcp:start -->`\n *   - Stamped: `<!-- glasstrace:mcp:start v=1.4.0 -->`\n *\n * The optional `v=<semver>` capture group is the version stamp.\n * Recognising the legacy form is\n * load-bearing for the backward-compatibility constraint: an\n * upgrading user's first re-render must replace the existing block in\n * place rather than appending a duplicate. Subsequent re-renders write\n * the stamped form.\n *\n * The stamp character class\n * `[^\\s>]+` deliberately excludes whitespace and `>` so a hand-edited\n * malformed marker cannot terminate the comment early or smuggle a\n * line break into the file. The end marker (`...mcp:end`) is unstamped.\n */\nconst HTML_START_RE =\n  /^<!--\\s*glasstrace:mcp:start(?:\\s+v=([^\\s>]+))?\\s*-->$/;\nconst HTML_END = \"<!-- glasstrace:mcp:end -->\";\n\n/**\n * Hash-prefixed start-marker regex used in plain text files (e.g.\n * `.cursorrules`). Same legacy/stamped shape model as the HTML form,\n * with the constraint that the captured stamp is non-whitespace\n * (`\\S+`) — the line ends at end-of-line, so there is no closing\n * delimiter to escape.\n */\nconst HASH_START_RE = /^#\\s*glasstrace:mcp:start(?:\\s+v=(\\S+))?$/;\nconst HASH_END = \"# glasstrace:mcp:end\";\n\n/**\n * Parsed start marker — its kind (HTML vs hash) and, when present, the\n * `v=<sdkVersion>` stamp. `stamp === null` means the marker matched the\n * legacy unstamped form.\n */\nexport interface ParsedStartMarker {\n  kind: \"html\" | \"hash\";\n  stamp: string | null;\n}\n\n/**\n * Parses a single line as a Glasstrace start marker.\n *\n * Accepts both legacy unstamped markers and version-stamped\n * markers. Returns `null` if the line is not a start\n * marker. Trims whitespace before matching so leading/trailing spaces\n * in user-edited files do not defeat detection.\n *\n * Exported so the upgrade-notice module (which checks the start\n * marker line directly) can share the regex, keeping a single source\n * of truth for the marker shape.\n */\nexport function parseStartMarkerLine(\n  line: string,\n): ParsedStartMarker | null {\n  const trimmed = line.trim();\n  const html = HTML_START_RE.exec(trimmed);\n  if (html !== null) {\n    return { kind: \"html\", stamp: html[1] ?? null };\n  }\n  const hash = HASH_START_RE.exec(trimmed);\n  if (hash !== null) {\n    return { kind: \"hash\", stamp: hash[1] ?? null };\n  }\n  return null;\n}\n\nfunction isEndMarker(line: string): boolean {\n  const trimmed = line.trim();\n  return trimmed === HTML_END || trimmed === HASH_END;\n}\n\n/**\n * Public alias for {@link isEndMarker}, used by the upgrade-notice\n * module to confirm that a stamped start marker has a matching end\n * before classifying the file as having a managed section. Exported\n * only for cross-module reuse within `agent-detection/`; not part of\n * the public SDK surface.\n */\nexport function isEndMarkerLine(line: string): boolean {\n  return isEndMarker(line);\n}\n\n/**\n * Determines whether an error is a filesystem permission or read-only error.\n * Covers EACCES (permission denied), EPERM (operation not permitted), and\n * EROFS (read-only filesystem) to handle containerized/mounted environments.\n */\nfunction isPermissionError(err: unknown): boolean {\n  const code = (err as NodeJS.ErrnoException).code;\n  return code === \"EACCES\" || code === \"EPERM\" || code === \"EROFS\";\n}\n\n/**\n * Writes MCP configuration content to an agent's config file path.\n *\n * Creates parent directories as needed and sets file permissions to 0o600\n * (owner read/write only) since config files may contain auth tokens.\n *\n * Fails gracefully: logs a warning to stderr on permission errors instead\n * of throwing.\n *\n * @param agent - The detected agent whose config path to write to.\n * @param content - The full configuration file content.\n * @param projectRoot - The project root (reserved for future use).\n */\nexport async function writeMcpConfig(\n  agent: DetectedAgent,\n  content: string,\n  // eslint-disable-next-line @typescript-eslint/no-unused-vars\n  projectRoot: string,\n): Promise<void> {\n  if (agent.mcpConfigPath === null) {\n    return;\n  }\n\n  const configPath = agent.mcpConfigPath;\n  const parentDir = dirname(configPath);\n\n  try {\n    await mkdir(parentDir, { recursive: true });\n  } catch (err: unknown) {\n    if (isPermissionError(err)) {\n      process.stderr.write(\n        `Warning: cannot create directory ${parentDir}: permission denied\\n`,\n      );\n      return;\n    }\n    throw err;\n  }\n\n  try {\n    await writeFile(configPath, content, { mode: 0o600 });\n  } catch (err: unknown) {\n    if (isPermissionError(err)) {\n      process.stderr.write(\n        `Warning: cannot write config file ${configPath}: permission denied\\n`,\n      );\n      return;\n    }\n    throw err;\n  }\n\n  // Ensure permissions are set even if the file already existed\n  // (writeFile mode only applies to newly created files on some platforms)\n  try {\n    await chmod(configPath, 0o600);\n  } catch {\n    // Best-effort; the writeFile mode should have handled this\n  }\n}\n\n/**\n * Finds existing marker boundaries in file content.\n *\n * Recognises both the legacy unstamped marker form and\n * the version-stamped form for both HTML-comment and hash-prefix\n * conventions. Returns the start and end line indices, or `null` if no\n * complete marker pair is found. The `v=<sdkVersion>` stamp itself is\n * only inspected by the upgrade-notice module via\n * {@link parseStartMarkerLine}; in-place replacement only needs the\n * line indices.\n *\n * When multiple start markers appear before the first end marker\n * (e.g. a quoted example of the marker shape earlier in the file\n * followed by the real managed block), the boundary anchors to the\n * MOST RECENT start preceding the end. This matches the legacy\n * behaviour of `findMarkerBoundaries` and avoids the \"swallow the\n * user's example into the replacement\" failure mode that anchoring\n * to the FIRST start would produce.\n */\nexport function findMarkerBoundaries(\n  lines: string[],\n): { startIdx: number; endIdx: number } | null {\n  let startIdx = -1;\n\n  for (let i = 0; i < lines.length; i++) {\n    if (parseStartMarkerLine(lines[i]) !== null) {\n      // Track the most recent start so a quoted/example marker earlier\n      // in the file does not capture the replacement window.\n      startIdx = i;\n    } else if (startIdx !== -1 && isEndMarker(lines[i])) {\n      return { startIdx, endIdx: i };\n    }\n  }\n\n  return null;\n}\n\n/**\n * Injects an informational section into an agent's instruction file.\n *\n * Uses marker comments to enable idempotent updates:\n * - If the file contains marker pairs, replaces content between them.\n * - If the file exists but has no markers, appends the section.\n * - If the file does not exist, creates it with the section content.\n *\n * The boundary detector recognises both legacy unstamped markers\n * and version-stamped markers, so an upgrading user's first\n * re-render replaces the existing block in place rather than\n * appending a duplicate (the backward-compatibility\n * constraint). Subsequent re-renders write the stamped form.\n *\n * Fails gracefully: logs a warning to stderr on read-only files instead\n * of throwing.\n *\n * @param agent - The detected agent whose info file to update.\n * @param content - The section content (including markers).\n * @param projectRoot - The project root (reserved for future use).\n */\nexport async function injectInfoSection(\n  agent: DetectedAgent,\n  content: string,\n  // eslint-disable-next-line @typescript-eslint/no-unused-vars\n  projectRoot: string,\n): Promise<void> {\n  if (agent.infoFilePath === null) {\n    return;\n  }\n\n  // Empty content means nothing to inject (e.g., agents without info sections)\n  if (content === \"\") {\n    return;\n  }\n\n  const filePath = agent.infoFilePath;\n\n  let existingContent: string | null = null;\n  try {\n    existingContent = await readFile(filePath, \"utf-8\");\n  } catch (err: unknown) {\n    const code = (err as NodeJS.ErrnoException).code;\n    if (code !== \"ENOENT\") {\n      if (isPermissionError(err)) {\n        process.stderr.write(\n          `Warning: cannot read info file ${filePath}: permission denied\\n`,\n        );\n        return;\n      }\n      throw err;\n    }\n  }\n\n  // File does not exist — create with section content\n  if (existingContent === null) {\n    try {\n      await mkdir(dirname(filePath), { recursive: true });\n      await writeFile(filePath, content, \"utf-8\");\n    } catch (err: unknown) {\n      if (isPermissionError(err)) {\n        process.stderr.write(\n          `Warning: cannot write info file ${filePath}: permission denied\\n`,\n        );\n        return;\n      }\n      throw err;\n    }\n    return;\n  }\n\n  // File exists — check for markers\n  const lines = existingContent.split(\"\\n\");\n  const boundaries = findMarkerBoundaries(lines);\n\n  let newContent: string;\n  if (boundaries !== null) {\n    // Replace everything from start marker through end marker (inclusive)\n    const before = lines.slice(0, boundaries.startIdx);\n    const after = lines.slice(boundaries.endIdx + 1);\n    // content already includes markers and trailing newline\n    const contentWithoutTrailingNewline = content.endsWith(\"\\n\")\n      ? content.slice(0, -1)\n      : content;\n    newContent = [...before, contentWithoutTrailingNewline, ...after].join(\"\\n\");\n  } else {\n    // No markers found — append with a blank line separator\n    const separator = existingContent.endsWith(\"\\n\") ? \"\\n\" : \"\\n\\n\";\n    newContent = existingContent + separator + content;\n  }\n\n  try {\n    await writeFile(filePath, newContent, \"utf-8\");\n  } catch (err: unknown) {\n    if (isPermissionError(err)) {\n      process.stderr.write(\n        `Warning: cannot write info file ${filePath}: permission denied\\n`,\n      );\n      return;\n    }\n    throw err;\n  }\n}\n\n/**\n * Returns true when the file at `filePath` contains a complete\n * Glasstrace managed section (marker pair). Matches both legacy\n * unstamped markers and version-stamped markers. Used by the\n * upgrade-instructions CLI to decide which detected agent files\n * actually have a managed section to refresh.\n *\n * Returns `false` for the genuine \"file does not exist\" case\n * (`ENOENT`). Any other read error — permission denied (`EACCES`),\n * not-permitted (`EPERM`), read-only (`EROFS`), I/O error, etc. — is\n * re-thrown so the caller can surface it to the user. Swallowing\n * those would let `upgrade-instructions` report an inaccessible file\n * as \"skipped (no managed section present)\" and silently mask a real\n * permission problem (Codex review on PR #247).\n */\nexport async function hasManagedSection(filePath: string): Promise<boolean> {\n  let content: string;\n  try {\n    content = await readFile(filePath, \"utf-8\");\n  } catch (err: unknown) {\n    const code = (err as NodeJS.ErrnoException).code;\n    if (code === \"ENOENT\") return false;\n    throw err;\n  }\n  return findMarkerBoundaries(content.split(\"\\n\")) !== null;\n}\n\n/**\n * Ensures that the given paths are listed in the project's `.gitignore`.\n *\n * Only adds entries for paths that are not already present. Creates the\n * `.gitignore` file if it does not exist. Skips absolute paths (e.g.,\n * Windsurf's global config) since those are outside the project tree.\n *\n * Fails gracefully: logs a warning to stderr on permission errors.\n *\n * @param paths - Relative paths to ensure are gitignored.\n * @param projectRoot - The project root directory.\n */\nexport async function updateGitignore(\n  paths: string[],\n  projectRoot: string,\n): Promise<void> {\n  const gitignorePath = join(projectRoot, \".gitignore\");\n\n  // Filter out absolute paths — they reference locations outside the project\n  // Uses isAbsolute() to handle both POSIX and Windows path formats\n  const relativePaths = paths.filter((p) => !isAbsolute(p));\n\n  if (relativePaths.length === 0) {\n    return;\n  }\n\n  let existingContent = \"\";\n  try {\n    existingContent = await readFile(gitignorePath, \"utf-8\");\n  } catch (err: unknown) {\n    const code = (err as NodeJS.ErrnoException).code;\n    if (code !== \"ENOENT\") {\n      if (isPermissionError(err)) {\n        process.stderr.write(\n          `Warning: cannot read .gitignore: permission denied\\n`,\n        );\n        return;\n      }\n      throw err;\n    }\n  }\n\n  // Parse existing entries, trimming whitespace for comparison\n  const existingLines = existingContent\n    .split(\"\\n\")\n    .map((line) => line.trim())\n    .filter((line) => line !== \"\");\n\n  const existingSet = new Set(existingLines);\n\n  // Normalize entries: trim whitespace, convert backslashes to forward slashes\n  // (git ignore patterns use / as separator; backslash is an escape character),\n  // drop empties, and deduplicate against existing entries.\n  const toAdd = relativePaths\n    .map((p) => p.trim().replace(/\\\\/g, \"/\"))\n    .filter((p) => p !== \"\" && !existingSet.has(p));\n\n  if (toAdd.length === 0) {\n    return;\n  }\n\n  // Ensure file ends with newline before appending\n  let updatedContent = existingContent;\n  if (updatedContent.length > 0 && !updatedContent.endsWith(\"\\n\")) {\n    updatedContent += \"\\n\";\n  }\n\n  updatedContent += toAdd.join(\"\\n\") + \"\\n\";\n\n  try {\n    await writeFile(gitignorePath, updatedContent, \"utf-8\");\n  } catch (err: unknown) {\n    if (isPermissionError(err)) {\n      process.stderr.write(\n        `Warning: cannot write .gitignore: permission denied\\n`,\n      );\n      return;\n    }\n    throw err;\n  }\n}\n","/**\n * Mask an API key for safe inclusion in logs and lifecycle events —\n * shows a short prefix and the last 4 characters, never the full secret.\n *\n * Keys longer than 12 characters render as `prefix(8) + \"...\" + last4`;\n * shorter keys collapse to `prefix(4) + \"...\"` so the tail of a short key\n * is never disclosed. This is the single masking implementation shared by\n * every SDK surface that needs to reference a key (the register flow and\n * the decision-trace emitter), so the masking contract stays consistent.\n *\n * @internal\n */\nexport function maskKey(key: string): string {\n  if (key.length <= 12) return key.slice(0, 4) + \"...\";\n  return key.slice(0, 8) + \"...\" + key.slice(-4);\n}\n","import { isBuiltin as isNodeBuiltin } from \"node:module\";\n\n/**\n * Structural view of Next.js's `NextConfig`. The SDK does not import Next's\n * type directly because Next is not a peer dependency — this wrapper must\n * type-check regardless of which Next.js version the consumer has installed.\n *\n * The constraint is `object` rather than `Record<string, unknown>` because\n * Next's actual `NextConfig` is an interface *without* a string index\n * signature. Requiring `[key: string]: unknown` would fail the assignability\n * check, reported by Next 16 consumers as:\n *   > Argument of type 'NextConfig' is not assignable to parameter of type\n *   > 'NextConfig'. Index signature for type 'string' is missing in type\n *   > 'NextConfig'.\n *\n * `object` accepts every non-primitive value, which is what the wrapper\n * actually handles at runtime (it shallow-copies the input and reads a few\n * known properties defensively). Combined with the generic signature on\n * `withGlasstraceConfig`, callers preserve their exact config subtype.\n */\ntype NextConfig = object;\ntype WebpackConfigFn = (config: Record<string, unknown>, context: Record<string, unknown>) => Record<string, unknown>;\n\n/** Subset of the webpack context object passed by Next.js to the webpack config function. */\ninterface WebpackContext {\n  isServer: boolean;\n  dev: boolean;\n  [key: string]: unknown;\n}\n\n/** Minimal webpack compiler shape for the afterEmit hook. */\ninterface WebpackCompiler {\n  hooks?: {\n    afterEmit?: {\n      tapPromise?: (name: string, fn: (compilation: unknown) => Promise<void>) => void;\n    };\n  };\n}\n\n/**\n * Detects whether the current `next build` invocation is using Turbopack.\n *\n * Next 16 made Turbopack the default bundler for `next build`. We detect it\n * via `process.argv` (the `--turbopack` flag or the absence of `--webpack`\n * on Next 16) and the `TURBOPACK` environment variable that Next sets\n * internally. Falls back to `false` in non-Node environments.\n */\nfunction isTurbopackBuild(): boolean {\n  if (typeof process === \"undefined\") return false;\n\n  const argv = Array.isArray(process.argv) ? process.argv : [];\n  if (argv.includes(\"--webpack\")) return false;\n  if (argv.includes(\"--turbopack\")) return true;\n\n  // Next sets TURBOPACK=1 when running its Turbopack pipeline.\n  if (process.env?.TURBOPACK === \"1\") return true;\n\n  return false;\n}\n\n/**\n * Package name the wrapper adds to Next's server-external-packages list.\n * Kept as a module-level constant so tests can reference the exact string\n * without risk of drift between implementation and assertion.\n */\nconst SDK_PACKAGE_NAME = \"@glasstrace/sdk\";\n\n/**\n * Signature of a webpack 5 externals function in the array-of-entries form.\n * The `data` argument carries the import request; the `callback` signals\n * either an externalization decision (`\"commonjs <specifier>\"`) or a\n * pass-through (no second argument).\n *\n * Typed structurally rather than importing from `webpack` to keep the SDK\n * free of a webpack peer dependency.\n */\ntype WebpackExternalsFn = (\n  data: { request?: string; context?: string; contextInfo?: unknown; getResolve?: unknown },\n  callback: (err: Error | null, result?: string) => void,\n) => void;\n\n/**\n * Appends an externals entry to a webpack config that rewrites every\n * Node.js built-in import into a runtime CommonJS `require()`. This is\n * the piece that actually fixes `next dev --webpack`:\n * webpack dev-mode ships no default handler for the `node:` URI scheme\n * AND does not auto-externalize bare built-ins pulled through transitive\n * SDK dependencies (e.g. `import * as zlib from \"zlib\"` inside an OTel\n * exporter). Either form crashes the first render — `UnhandledSchemeError`\n * for `node:*`, `Can't resolve 'zlib'` for bare built-ins — unless the\n * wrapper tells webpack to treat them as runtime externals.\n *\n * Membership is decided by Node's own `isBuiltin` helper\n * (`node:module`, available since Node 18.6; SDK `engines` floor is\n * Node >= 20), so the list of built-ins stays authoritative across\n * Node versions — no hand-maintained allowlist to drift out of date.\n *\n * Webpack 5 accepts externals as a string, RegExp, object, function, or\n * array of any mixture of those. Next.js itself uses the array form. The\n * helper preserves whatever the user (or Next) already supplied:\n * - Array: append the new entry, user entries keep their positions.\n * - Function or object: wrap in an array with the user entry first so it\n *   takes precedence over the SDK's handler.\n * - Missing / nullish: initialise as a single-entry array.\n *\n * The emitted `commonjs <request>` form preserves whichever specifier the\n * caller used (prefixed or bare), which Node resolves natively on Node\n * >= 14.18 — well below the SDK's `engines` floor of Node >= 20.\n */\nfunction appendNodeSchemeExternal(webpackConfig: Record<string, unknown>): void {\n  const nodeBuiltinExternal: WebpackExternalsFn = (data, callback) => {\n    const request = data.request;\n    if (typeof request === \"string\" && isNodeBuiltin(request)) {\n      callback(null, \"commonjs \" + request);\n      return;\n    }\n    callback(null);\n  };\n\n  const existing = webpackConfig.externals;\n  if (Array.isArray(existing)) {\n    webpackConfig.externals = [...existing, nodeBuiltinExternal];\n  } else if (existing == null) {\n    webpackConfig.externals = [nodeBuiltinExternal];\n  } else {\n    // Function, object-map, RegExp, or string form — preserve as the first\n    // array entry so user/Next externals resolve before the SDK's fallback.\n    webpackConfig.externals = [existing, nodeBuiltinExternal];\n  }\n}\n\n/**\n * Pushes `@glasstrace/sdk` onto Next.js's `serverExternalPackages` list so\n * the package is loaded via Node's `require()` at runtime instead of\n * bundled through webpack/Turbopack.\n *\n * Only the Next 15+ stable top-level key is written. The Next 14 legacy\n * `experimental.serverComponentsExternalPackages` key was dropped because\n * Next 16 logs a deprecation warning for it on every build. Next 14 is\n * EOL; webpack-dev users on Next 14 are covered by the companion\n * `node:*` externals function installed below, and Turbopack users on\n * Next 14 were already unaffected.\n *\n * Dedupe is intentional: if the user already added `@glasstrace/sdk` to\n * the array, the entry is not duplicated. User entries are preserved in\n * their original order; the SDK entry is appended.\n *\n * Note that `serverExternalPackages` only affects RSC and Route Handler\n * bundling — it does NOT externalize the instrumentation path under\n * `next dev --webpack` (see vercel/next.js#58003, #28774). The full fix\n * pairs this write with the `node:*` externals function.\n *\n * Mutates the `config` bag in place; callers pass the shallow-copied bag\n * owned by `withGlasstraceConfig`, so the user's original reference is not\n * affected.\n */\nfunction ensureServerExternal(config: Record<string, unknown>): void {\n  // Next 15+ stable key: top-level `serverExternalPackages`.\n  const existingStable = config.serverExternalPackages;\n  const stable: string[] = Array.isArray(existingStable)\n    ? // Clone so we never mutate a caller-owned array in place.\n      existingStable.filter((entry): entry is string => typeof entry === \"string\")\n    : [];\n  if (!stable.includes(SDK_PACKAGE_NAME)) {\n    stable.push(SDK_PACKAGE_NAME);\n  }\n  config.serverExternalPackages = stable;\n}\n\n/**\n * Wraps the developer's Next.js config to enable source map generation\n * and upload .map files to the ingestion API at build time.\n *\n * The build NEVER fails because of Glasstrace — all errors are caught\n * and logged as warnings.\n *\n * ## What the wrapper configures for you\n *\n * - `experimental.serverSourceMaps: true` — enables server-side source maps\n *   so Glasstrace can resolve stack traces back to your source.\n * - `serverExternalPackages: [\"@glasstrace/sdk\"]` — tells Next to load the\n *   SDK via Node's `require()` at runtime instead of bundling it through\n *   webpack or Turbopack on the RSC / Route Handler paths. This is the same\n *   pattern Prisma, `@vercel/otel`, Sentry, `sharp`, and `bcrypt` ship with.\n * - A webpack `externals` entry that marks every Node.js built-in import\n *   (both `node:*` and bare forms like `zlib` or `stream`) as a runtime\n *   `commonjs` require. `serverExternalPackages` does not apply to the\n *   instrumentation path under `next dev --webpack`\n *   (vercel/next.js#58003, #28774), so any bundled SDK chunk that imports\n *   `node:child_process` or the bare `zlib` specifier used by\n *   `@opentelemetry/otlp-exporter-base` would otherwise crash with\n *   `UnhandledSchemeError` or `Can't resolve 'zlib'`. This entry is the\n *   authoritative fix for the dev-webpack path. Turbopack is\n *   unaffected — it ignores `config.webpack` and resolves Node built-ins\n *   natively.\n * - An empty `turbopack: {}` when none is set, so Next 16 does not reject\n *   the config for setting `webpack` without a companion `turbopack` key.\n * - A `webpack` hook that collects and uploads `.map` files on client-side\n *   production builds.\n *\n * ## Turbopack\n *\n * Next.js 16 made Turbopack the default bundler for `next build`, and Next\n * rejects configs that set `webpack` without also setting `turbopack`. This\n * wrapper therefore seeds an empty `turbopack: {}` when the user has not set\n * one themselves, preserving existing behaviour for explicit Turbopack configs.\n *\n * **Source-map upload is currently webpack-only.** Under Turbopack the build\n * succeeds, but the afterEmit hook that collects and uploads `.map` files does\n * not fire. Run `next build --webpack` to get source-map uploads, or wait for\n * a follow-up release that ports the plugin to Turbopack.\n *\n * @param nextConfig - The developer's existing Next.js configuration object.\n * @returns A new config object with source map generation and upload enabled.\n *   The return type mirrors the input type so that caller-side config\n *   properties are preserved. The `object` constraint (rather than\n *   `Record<string, unknown>`) is what makes the wrapper accept Next's\n *   real `NextConfig` interface.\n */\nexport function withGlasstraceConfig<T extends NextConfig>(nextConfig: T): T {\n  // Guard: config wrapper requires Node.js for source map instrumentation.\n  // In non-Node environments (Edge Runtime, browser), return config unchanged.\n  if (typeof process === \"undefined\" || typeof process.versions?.node !== \"string\") {\n    return (nextConfig != null ? { ...nextConfig } : ({} as T));\n  }\n\n  // Handle null/undefined gracefully\n  const config: T = nextConfig != null ? { ...nextConfig } : ({} as T);\n  // Mutable bag-of-props view of the same object. Using `object` as the\n  // constraint (see the `NextConfig` type alias above) means `T` does not\n  // declare the keys we touch — `experimental`, `turbopack`, `distDir`,\n  // `webpack` — so we interact with them through this looser view while the\n  // public return type stays faithfully `T`.\n  const bag = config as Record<string, unknown>;\n\n  // Enable server-side source map generation for Glasstrace uploads.\n  // Intentionally does NOT set productionBrowserSourceMaps — that exposes\n  // full source code publicly via browser DevTools. Users who want public\n  // browser source maps can set it explicitly in their Next.js config.\n\n  // Enable server-side source maps (Next.js experimental feature)\n  const existingExperimental = (bag.experimental as Record<string, unknown>) ?? {};\n  bag.experimental = {\n    ...existingExperimental,\n    serverSourceMaps: true,\n  };\n\n  // Mark the SDK as a server-external package (DISC-1257). This covers the\n  // RSC and Route Handler bundlers on Next 15+. The companion `node:*`\n  // externals entry inside the `config.webpack` hook below is what actually\n  // unblocks `next dev --webpack`.\n  ensureServerExternal(bag);\n\n  // Seed an empty Turbopack config when the user has not set one. Next 16\n  // refuses builds that set `webpack` without a companion `turbopack` key\n  // (DISC-1256). Merging preserves any existing Turbopack config the user\n  // supplied — we only fill in the default.\n  if (bag.turbopack == null) {\n    bag.turbopack = {};\n  }\n\n  // One-time warning: source-map upload does not run under Turbopack yet.\n  // Log at most once per process to avoid spamming repeated builds (dev mode,\n  // watch mode). The warning goes to stderr via console.warn — intentionally\n  // not using sdkLog so the message surfaces during the build even if SDK\n  // logging is otherwise suppressed.\n  if (isTurbopackBuild()) {\n    warnTurbopackLimitationOnce();\n  }\n\n  // Capture distDir for source map collection (default: .next)\n  const distDir = typeof bag.distDir === \"string\" ? bag.distDir : \".next\";\n\n  // Capture existing webpack config if any\n  const existingWebpack = bag.webpack as WebpackConfigFn | undefined;\n\n  // Register webpack config modifier\n  bag.webpack = (\n    webpackConfig: Record<string, unknown>,\n    context: Record<string, unknown>,\n  ): Record<string, unknown> => {\n    // Call existing webpack config first\n    let result = webpackConfig;\n    if (typeof existingWebpack === \"function\") {\n      result = existingWebpack(webpackConfig, context);\n    }\n\n    // DISC-1257: externalize Node.js built-in imports for the webpack path.\n    const webpackContext = context as WebpackContext;\n\n    // Next's `serverExternalPackages` only influences RSC / Route Handler\n    // bundling; the instrumentation path under `next dev --webpack` still\n    // runs transitive SDK imports through the dev bundler, which crashes\n    // on any built-in module — `UnhandledSchemeError` for `node:*` and\n    // `Can't resolve 'zlib'` / `'stream'` / etc. for bare specifiers used\n    // by OTel's exporter dependencies (vercel/next.js#58003, #28774).\n    //\n    // Telling webpack to externalize every Node built-in as a runtime\n    // CommonJS require resolves the crash on every SERVER webpack code\n    // path — production build, dev server, instrumentation hook. We\n    // scope it to `webpackContext.isServer` so client-side compilations\n    // (where Next applies browser polyfills / fallbacks for things like\n    // `buffer` / `stream` / `crypto`) are not affected. Emitting\n    // `commonjs` externals on the client would bypass those fallbacks\n    // and inject `require(...)` at runtime, which fails in the browser.\n    // Turbopack ignores this field and resolves Node built-ins natively\n    // on both client and server.\n    if (webpackContext.isServer) {\n      appendNodeSchemeExternal(result);\n    }\n\n    // Only run source map upload on client-side production builds (not server, not dev)\n    if (!webpackContext.isServer && webpackContext.dev === false) {\n      // Register a plugin to collect and upload source maps after compilation\n      const plugins = (result.plugins as Array<Record<string, unknown>>) ?? [];\n      plugins.push({\n        apply(compiler: Record<string, unknown>) {\n          const typedCompiler = compiler as WebpackCompiler;\n          if (typedCompiler.hooks?.afterEmit?.tapPromise) {\n            typedCompiler.hooks.afterEmit.tapPromise(\n              \"GlasstraceSourceMapUpload\",\n              async () => {\n                await handleSourceMapUpload(distDir);\n              },\n            );\n          }\n        },\n      });\n      result.plugins = plugins;\n    }\n\n    return result;\n  };\n\n  return config;\n}\n\nlet _turbopackWarningEmitted = false;\nfunction warnTurbopackLimitationOnce(): void {\n  if (_turbopackWarningEmitted) return;\n  _turbopackWarningEmitted = true;\n  console.warn(\n    \"[glasstrace] Turbopack detected. Source-map upload currently runs only under webpack — \" +\n      \"run `next build --webpack` to upload source maps, or wait for the Turbopack port in a future SDK release.\",\n  );\n}\n\n/**\n * Resets the one-shot Turbopack warning flag. For test use only.\n *\n * @internal\n */\nexport function _resetTurbopackWarningForTesting(): void {\n  _turbopackWarningEmitted = false;\n}\n\n/**\n * Collects source map files from the build output directory and uploads\n * them to the Glasstrace ingestion API. Never throws — all errors are\n * caught and logged as warnings so the build is never blocked.\n *\n * Exported for testing only; not part of the public API.\n *\n * @param distDir - The Next.js build output directory (e.g. \".next\").\n */\nexport async function handleSourceMapUpload(distDir: string): Promise<void> {\n  try {\n    const apiKey = process.env.GLASSTRACE_API_KEY;\n    const endpoint =\n      process.env.GLASSTRACE_ENDPOINT ?? \"https://api.glasstrace.dev\";\n\n    // Anonymous mode: skip upload\n    if (!apiKey || apiKey.trim() === \"\") {\n      console.info(\n        \"[glasstrace] Source map upload skipped (no API key). Stack traces will show compiled locations.\",\n      );\n      return;\n    }\n\n    // Dynamic import: source-map-uploader uses node:fs, node:path, node:crypto,\n    // and node:child_process. Deferring the import avoids a module-evaluation\n    // crash when config-wrapper.ts is loaded in a non-Node bundler context.\n    const { discoverSourceMapFiles, computeBuildHash, uploadSourceMaps } =\n      await import(\"./source-map-uploader.js\");\n\n    const files = await discoverSourceMapFiles(distDir);\n\n    if (files.length === 0) {\n      console.info(\"[glasstrace] No source map files found. Skipping upload.\");\n      return;\n    }\n\n    const buildHash = await computeBuildHash(files);\n\n    await uploadSourceMaps(apiKey, endpoint, buildHash, files);\n    console.info(\n      `[glasstrace] Uploaded ${String(files.length)} source map(s) for build ${buildHash}.`,\n    );\n  } catch (error: unknown) {\n    // Build must NEVER fail because of Glasstrace\n    const message =\n      error instanceof Error ? error.message : \"Unknown error\";\n    console.warn(\n      `[glasstrace] Source map upload failed: ${message}. Build continues normally.`,\n    );\n  }\n}\n","/**\n * Manual error capture API.\n *\n * Provides a simple function for developers to manually record errors\n * as span events, independent of the `consoleErrors` config flag.\n */\n\nimport * as otelApi from \"@opentelemetry/api\";\nimport { GLASSTRACE_ATTRIBUTE_NAMES } from \"@glasstrace/protocol\";\nimport { maybeShowMcpNudge } from \"./nudge/error-nudge.js\";\nimport { parseTopStackFrame } from \"./stack-frame.js\";\n\n/**\n * Records an error as a span event on the currently active OTel span.\n *\n * Works regardless of the `consoleErrors` configuration — this is an\n * explicit, opt-in API for manual error reporting. If no span is active\n * or OTel is not available, the call is silently ignored.\n *\n * On the first captured error, may display a one-time diagnostic nudge\n * to stderr if the MCP connection marker is absent (dev environments only).\n *\n * @param error - The error to capture. Accepts `Error` objects, strings, or any value.\n *\n * @example\n * ```ts\n * import { captureError } from \"@glasstrace/sdk\";\n *\n * try {\n *   await riskyOperation();\n * } catch (err) {\n *   captureError(err);\n *   // handle error normally...\n * }\n * ```\n */\nexport function captureError(error: unknown): void {\n  try {\n    const span = otelApi.trace.getSpan(otelApi.context.active());\n    if (!span) return;\n\n    const attributes: Record<string, string | number> = {\n      \"error.message\": String(error),\n    };\n\n    if (error instanceof Error) {\n      attributes[\"error.type\"] = error.constructor.name;\n      if (error.stack) {\n        attributes[\"error.stack\"] = error.stack;\n\n        // Stamp the top user-attributable frame as glasstrace.source.file\n        // and glasstrace.source.line. Errors are the only span signal\n        // for which a single canonical source location exists; emitting\n        // these attributes lets ingestion's source-map resolver\n        // (packages/ingestion/src/services/source-map-resolver.ts) map\n        // the compiled-output path back to the original source via the\n        // build-time uploaded sourcemap, surfacing mapped frames in the\n        // dashboard and the enrichment LLM prompt (DISC-1543, SDK-040).\n        //\n        // parseTopStackFrame returns null on any parse failure so a\n        // future V8 stack-format change cannot break error capture —\n        // the attributes are simply omitted.\n        const frame = parseTopStackFrame(error.stack);\n        if (frame) {\n          attributes[GLASSTRACE_ATTRIBUTE_NAMES.SOURCE_FILE] = frame.file;\n          attributes[GLASSTRACE_ATTRIBUTE_NAMES.SOURCE_LINE] = frame.line;\n        }\n      }\n    }\n\n    span.addEvent(\"glasstrace.error\", attributes);\n\n    // Show one-time MCP connection nudge on first captured error\n    maybeShowMcpNudge(String(error));\n  } catch {\n    // Silently ignore failures\n  }\n}\n\n/**\n * Eagerly loads the OTel API module. Previously required for async resolution;\n * now a no-op since OTel is statically imported. Retained for test compatibility.\n *\n * @internal\n */\nexport async function _preloadOtelApi(): Promise<void> {\n  // No-op: OTel API is now statically imported and always available.\n}\n\n/**\n * Resets internal state. For testing only.\n * @internal\n */\nexport function _resetCaptureErrorForTesting(): void {\n  // No-op: OTel API is now statically imported and always available.\n  // Kept for backward compatibility with existing tests.\n}\n","/**\n * V8 stack-frame parsing for error-source attribution.\n *\n * The SDK stamps `glasstrace.source.file` and `glasstrace.source.line`\n * on the `glasstrace.error` span event recorded by `captureError()`.\n * Both values come from the top user-relevant frame of the captured\n * `Error.stack` string. Ingestion's source-map resolver then maps the\n * compiled-output `file:line` back to the original source via the\n * pre-uploaded source map manifest.\n *\n * V8 is the only stack format we parse. Node uses V8 (the SDK's\n * `engines.node` is `>=20`); the brief explicitly scopes Firefox /\n * Safari formats out for now (browser error capture is a separate\n * concern, and this module is Node-only via `capture-error.ts`'s\n * placement outside `edge-entry.ts`'s curated subset).\n *\n * @remarks\n * Pure module. No `process`, no `node:*`, no I/O. Safe to import from\n * any context, but practical use is gated to the Node bundle by\n * `capture-error.ts`'s placement. The parsing helpers live in their\n * own module so they can be unit-tested against synthetic stack\n * strings without faking the OTel mocks the `captureError` test\n * harness already needs.\n */\n\n/**\n * A parsed top stack frame. `file` is the compiled-output path the V8\n * engine reported — exactly what the ingestion source-map resolver\n * expects, so we deliberately do not strip CWD or bundler prefixes.\n *\n * @public\n */\nexport interface ParsedStackFrame {\n  /** Source file path as reported by V8 (compiled-output path). */\n  readonly file: string;\n  /** 1-based line number reported by V8. */\n  readonly line: number;\n}\n\n/**\n * Match a V8 frame in the parenthesized form:\n * `    at <funcName> (file:line:col)`\n *\n * The function name segment is consumed but discarded; we only need\n * the location. Capture groups: file, line, col.\n *\n * Anchored to the start of the trimmed line via the `at ` literal.\n * Allows but does not require a function name before the parens\n * (a bare `    at (file:line:col)` is unusual but valid).\n *\n * The file-path capture group accepts:\n *\n *   1. Plain non-paren / non-whitespace characters — the common case\n *      (`/abs/path.ts`, `file:///url`, `C:\\\\win32\\\\path`, `node:fs`).\n *      Colons are allowed inside the path; the trailing\n *      `:(\\d+):(\\d+)\\)` anchor in the regex relies on greedy\n *      backtracking to split the final `:line:col)` off the path\n *      tail, which is how the original parser already handled\n *      paths like `node:internal/timers:512:7`.\n *   2. Embedded `(<segment>)` markers — the Next.js App Router\n *      bundler emits paths like\n *      `webpack-internal:///(rsc)/./src/app/page.tsx`,\n *      `webpack-internal:///(middleware)/middleware.js`, and similar\n *      forms with `(api)`, `(client)`, `(server)`, `(action)`, etc.\n *      The same shape also appears for App Router *route groups*\n *      authored by users — folders like `app/(marketing)/page.tsx`\n *      or `app/(v2)/page.tsx` — and for *intercepting-route*\n *      markers `(.)`, `(..)`, `(...)` documented by Next. The\n *      marker alphabet `[A-Za-z0-9_.-]` covers the published Next\n *      layer set, webpack-internal markers like `(__SLOT__)`,\n *      digit-bearing route-group folders the user may name\n *      themselves, and the dotted intercepting-route shapes.\n *\n * The leading negative lookahead `(?!eval\\s+\\(eval\\s+at\\b)` rejects\n * V8's nested eval frame shape —\n * `at eval (eval at <anonymous> (/file:1:1), <anonymous>:1:1)` —\n * which would otherwise greedy-match the whole inner expression and\n * stamp a non-resolvable pseudo-path as `glasstrace.source.file`.\n * Eval-origin frames have no real source location to report; the\n * parser skips them rather than emit a misleading attribute.\n *\n * Backtracking posture: the file capture is structured so each\n * inner alternation is anchored on a literal `(` and never overlaps\n * with the plain-character segment. There is no `(a*)*`-style\n * nesting, so the regex runs in linear time on adversarial inputs.\n */\nconst PAREN_FRAME =\n  /^\\s*at\\s+(?!eval\\s+\\(eval\\s+at\\b)(?:[^()]+\\s+)?\\(([^()\\s]+(?:\\([A-Za-z0-9_.-]+\\)[^()\\s]*)*):(\\d+):(\\d+)\\)\\s*$/;\n\n/**\n * Match a V8 frame in the bare anonymous form:\n * `    at file:line:col`\n * `    at async file:line:col`\n *\n * V8 emits the bare shape when the frame has no function name to print\n * (top-level module evaluation, an anonymous arrow, a Promise rejection\n * handler that V8 cannot name). The optional `async` keyword appears\n * for top-level async frames inside an awaited Promise chain. After\n * the optional `async` token the next whitespace-delimited token is\n * the file path; line and column trail it.\n *\n * The file-path capture mirrors {@link PAREN_FRAME}'s embedded\n * `(<segment>)` marker support so a top-level evaluated module\n * loaded via webpack-internal also resolves correctly. A malformed\n * truncated frame like `    at fn (file:line:col` is rejected by\n * both patterns rather than being misparsed because the bare shape\n * has no leading `\\(` wrapper.\n */\nconst BARE_FRAME =\n  /^\\s*at\\s+(?:async\\s+)?([^()\\s]+(?:\\([A-Za-z0-9_.-]+\\)[^()\\s]*)*):(\\d+):(\\d+)\\s*$/;\n\n/**\n * V8 internal-frame prefixes that should be skipped when looking for\n * the user's top frame. These are emitted for frames inside Node's\n * built-in modules (`node:internal/...`) and frames inside the SDK\n * itself when `captureError()` was reached via SDK code (the SDK\n * stack walker should report the *caller* of `captureError`, not\n * the call inside `captureError` itself).\n *\n * The SDK-self patterns target two on-disk shapes: the published\n * package path `node_modules/@glasstrace/sdk/` (where the SDK lives\n * inside a consumer project) and the in-repo source path\n * `packages/sdk/src/{capture-error,stack-frame}.{ts,js,...}` (used by\n * dogfooding and in-tree tests). Together they cover both the\n * consumed-as-published path and the in-tree development path.\n * Tightening the second to the two specific source files (rather\n * than the directory) keeps the matcher narrow: a user-side file\n * happening to live at `packages/sdk/src/...` in their own project\n * would not be incorrectly skipped.\n */\nconst INTERNAL_FRAME_PATTERNS: readonly RegExp[] = [\n  /^node:/,\n  /^node:internal\\//,\n  /[/\\\\]node_modules[/\\\\]@glasstrace[/\\\\]sdk[/\\\\]/,\n  /[/\\\\]packages[/\\\\]sdk[/\\\\]src[/\\\\]capture-error\\./,\n  /[/\\\\]packages[/\\\\]sdk[/\\\\]src[/\\\\]stack-frame\\./,\n];\n\n/**\n * Returns true when the candidate file path looks like an internal\n * frame the SDK should skip while walking the stack.\n */\nfunction isInternalFrame(file: string): boolean {\n  return INTERNAL_FRAME_PATTERNS.some((re) => re.test(file));\n}\n\n/**\n * Parses a V8 `Error.stack` string and returns the topmost\n * user-attributable `{ file, line }` pair, or `null` when no frame\n * matches. The first line of the stack — the `Error: <message>`\n * preamble — is discarded; subsequent `at` lines are scanned in order\n * and the first non-internal match wins.\n *\n * Robustness posture: on any malformed input (empty string, missing\n * frames, non-numeric line, frames that are all internal) the function\n * returns `null` so the caller can silently skip stamping rather than\n * propagating a parse error to the OTel span. The caller in\n * `capture-error.ts` further wraps the call in its own `try/catch` so\n * even an unexpected input shape (e.g., a future engine version\n * changing the stack format) cannot crash the export pipeline.\n *\n * @param stack - The raw `Error.stack` string. May include the\n *   `Error: <message>` first line (V8 default) or omit it (some\n *   engines / custom serializers).\n * @returns The first user-attributable `{ file, line }`, or `null`.\n *\n * @public\n */\nexport function parseTopStackFrame(stack: string): ParsedStackFrame | null {\n  if (typeof stack !== \"string\" || stack.length === 0) return null;\n\n  // Walk lines without an explicit split so a 50-frame stack does not\n  // pay the O(n) cost of building an intermediate array. `\\n` is the\n  // V8-emitted separator on every supported platform; `\\r\\n` (Windows)\n  // is normalized by Node before reaching here, but we tolerate it\n  // anyway by treating `\\r` as whitespace at the regex anchor level.\n  let cursor = 0;\n  while (cursor < stack.length) {\n    const newlineAt = stack.indexOf(\"\\n\", cursor);\n    const lineEnd = newlineAt === -1 ? stack.length : newlineAt;\n    const line = stack.slice(cursor, lineEnd);\n    cursor = lineEnd + 1;\n\n    // Skip the leading `Error: ...` preamble and any other lines that\n    // do not look like a frame.\n    if (!/^\\s*at\\s/.test(line)) continue;\n\n    let file: string | undefined;\n    let lineStr: string | undefined;\n\n    const parenMatch = PAREN_FRAME.exec(line);\n    if (parenMatch) {\n      file = parenMatch[1];\n      lineStr = parenMatch[2];\n    } else {\n      const bareMatch = BARE_FRAME.exec(line);\n      if (bareMatch) {\n        file = bareMatch[1];\n        lineStr = bareMatch[2];\n      }\n    }\n\n    if (!file || !lineStr) continue;\n    if (isInternalFrame(file)) continue;\n\n    const lineNum = Number.parseInt(lineStr, 10);\n    if (!Number.isFinite(lineNum) || lineNum <= 0) continue;\n\n    return { file, line: lineNum };\n  }\n\n  return null;\n}\n","import * as fs from \"node:fs/promises\";\nimport * as fsSync from \"node:fs\";\nimport * as path from \"node:path\";\nimport * as crypto from \"node:crypto\";\nimport { createBuildHash, type ImportGraphPayload } from \"@glasstrace/protocol\";\n\n/** Maximum number of test files to process to prevent runaway in large projects */\nconst MAX_TEST_FILES = 5000;\n\n/** Directories to exclude from test file discovery */\nconst EXCLUDED_DIRS = new Set([\"node_modules\", \".next\", \".git\", \"dist\", \".turbo\"]);\n\n/** Conventional test file patterns */\nconst DEFAULT_TEST_PATTERNS = [\n  /\\.test\\.tsx?$/,\n  /\\.spec\\.tsx?$/,\n];\n\n/**\n * Converts a glob pattern (e.g. \"e2e/**\\/*.ts\") to an anchored RegExp.\n * Uses a placeholder to avoid `*` replacement corrupting the `**\\/` output.\n *\n * @param glob - A file glob pattern such as \"src/**\\/*.test.ts\".\n * @returns A RegExp that matches paths against the glob from start to end.\n */\nfunction globToRegExp(glob: string): RegExp {\n  const DOUBLE_STAR_PLACEHOLDER = \"\\0DSTAR\\0\";\n  const regexStr = glob\n    .replace(/\\*\\*\\//g, DOUBLE_STAR_PLACEHOLDER) // protect **/ first\n    .replace(/[.+?^${}()|[\\]\\\\]/g, \"\\\\$&\") // escape all regex metacharacters (except *)\n    .replace(/\\*/g, \"[^/]+\")\n    .replace(new RegExp(DOUBLE_STAR_PLACEHOLDER.replace(/\\0/g, \"\\\\0\"), \"g\"), \"(?:.+/)?\");\n  return new RegExp(\"^\" + regexStr + \"$\");\n}\n\n/**\n * Attempts to read include patterns from vitest.config.*, vite.config.*,\n * or jest.config.* files. Returns additional RegExp patterns extracted\n * from the config, or an empty array if no config is found or parsing fails.\n * This is best-effort — it reads the config as text and extracts patterns\n * via regex, without evaluating the JS.\n *\n * For Vitest/Vite configs, looks for `test.include` arrays.\n * For Jest configs, looks for `testMatch` arrays.\n * Does not support `testRegex` (string-based Jest pattern) — that is\n * left as future work.\n */\nfunction loadCustomTestPatterns(projectRoot: string): RegExp[] {\n  const configNames = [\n    \"vitest.config.ts\",\n    \"vitest.config.js\",\n    \"vitest.config.mts\",\n    \"vitest.config.mjs\",\n    \"vite.config.ts\",\n    \"vite.config.js\",\n    \"vite.config.mts\",\n    \"vite.config.mjs\",\n    \"jest.config.ts\",\n    \"jest.config.js\",\n    \"jest.config.mts\",\n    \"jest.config.mjs\",\n  ];\n\n  for (const name of configNames) {\n    const configPath = path.join(projectRoot, name);\n    let content: string;\n    try {\n      content = fsSync.readFileSync(configPath, \"utf-8\");\n    } catch {\n      // Config file does not exist at this path — try next candidate\n      continue;\n    }\n\n    try {\n      const isJest = name.startsWith(\"jest.\");\n      let includeMatch: RegExpExecArray | null = null;\n\n      if (isJest) {\n        // Jest: look for testMatch: [...]\n        includeMatch = /testMatch\\s*:\\s*\\[([^\\]]*)\\]/s.exec(content);\n      } else {\n        // Vitest/Vite: look for `test` block's `include` to avoid\n        // matching `coverage.include` or other unrelated arrays.\n        // Strategy: find `test` property, then look for `include` within\n        // the next ~500 chars (heuristic to stay within the test block).\n        const testBlockMatch = /\\btest\\s*[:{]\\s*/s.exec(content);\n        if (testBlockMatch) {\n          const afterTest = content.slice(testBlockMatch.index, testBlockMatch.index + 500);\n          includeMatch = /include\\s*:\\s*\\[([^\\]]*)\\]/s.exec(afterTest);\n        }\n      }\n\n      if (!includeMatch) {\n        continue;\n      }\n\n      const arrayContent = includeMatch[1];\n      const stringRegex = /['\"]([^'\"]+)['\"]/g;\n      const patterns: RegExp[] = [];\n      let match: RegExpExecArray | null;\n      match = stringRegex.exec(arrayContent);\n      while (match !== null) {\n        patterns.push(globToRegExp(match[1]));\n        match = stringRegex.exec(arrayContent);\n      }\n\n      if (patterns.length > 0) {\n        return patterns;\n      }\n    } catch {\n      // Regex-based config parsing failed — fall through to next config file\n      continue;\n    }\n  }\n\n  return [];\n}\n\n/**\n * Discovers test files by scanning the project directory for conventional\n * test file patterns. Also reads vitest/jest config files for custom include\n * patterns and merges them with the defaults. Excludes node_modules/ and .next/.\n *\n * @param projectRoot - Absolute path to the project root directory.\n * @returns Relative POSIX paths from projectRoot, capped at {@link MAX_TEST_FILES}.\n *\n * @remarks\n * Node-only. Walks the filesystem with `node:fs/promises`\n * (`readdir`), reads vitest/jest config files with `node:fs`\n * (`readFileSync`), and resolves paths with `node:path`. No edge-safe\n * alternative — call from a Node context (build script, CI job,\n * Next.js `next.config.ts`).\n */\nexport async function discoverTestFiles(\n  projectRoot: string,\n): Promise<string[]> {\n  const customPatterns = loadCustomTestPatterns(projectRoot);\n  const testPatterns = [...DEFAULT_TEST_PATTERNS, ...customPatterns];\n  const results: string[] = [];\n\n  try {\n    await walkForTests(projectRoot, projectRoot, results, testPatterns);\n  } catch {\n    // Project root directory does not exist or is unreadable — return empty\n    return [];\n  }\n\n  return results.slice(0, MAX_TEST_FILES);\n}\n\n/** Recursively walks directories, collecting test file paths into `results`. */\nasync function walkForTests(\n  baseDir: string,\n  currentDir: string,\n  results: string[],\n  testPatterns: RegExp[],\n): Promise<void> {\n  if (results.length >= MAX_TEST_FILES) {\n    return;\n  }\n\n  let entries: import(\"node:fs\").Dirent[];\n  try {\n    entries = await fs.readdir(currentDir, { withFileTypes: true });\n  } catch {\n    // Directory is unreadable (permissions, broken symlink) — skip subtree\n    return;\n  }\n\n  for (const entry of entries) {\n    if (results.length >= MAX_TEST_FILES) {\n      return;\n    }\n\n    const fullPath = path.join(currentDir, entry.name);\n\n    if (entry.isDirectory()) {\n      if (EXCLUDED_DIRS.has(entry.name)) {\n        continue;\n      }\n      await walkForTests(baseDir, fullPath, results, testPatterns);\n    } else if (entry.isFile()) {\n      const relativePath = path.relative(baseDir, fullPath).replace(/\\\\/g, \"/\");\n\n      // Check if it matches test patterns or is in __tests__\n      const isTestFile =\n        testPatterns.some((p) => p.test(entry.name) || p.test(relativePath)) ||\n        relativePath.includes(\"__tests__\");\n\n      if (isTestFile && (entry.name.endsWith(\".ts\") || entry.name.endsWith(\".tsx\"))) {\n        results.push(relativePath);\n      }\n    }\n  }\n}\n\n/**\n * Extracts import paths from file content using regex.\n * Handles ES module imports, CommonJS requires, and dynamic imports.\n *\n * @param fileContent - The full text content of a TypeScript/JavaScript file.\n * @returns An array of import path strings as written in the source (e.g. \"./foo\", \"react\").\n *\n * @remarks\n * Node-only. The function body itself is pure string processing and\n * would run anywhere, but it is exported through `@glasstrace/sdk/node`\n * alongside {@link discoverTestFiles} and {@link buildImportGraph} —\n * the practical consumers all pair it with those Node-only helpers.\n * Kept under the `/node` subpath for API cohesion; call from a Node\n * context (build script, CI job, Next.js `next.config.ts`).\n */\nexport function extractImports(fileContent: string): string[] {\n  const seen = new Set<string>();\n  const imports: string[] = [];\n\n  /** Adds a path to the result if not already present. */\n  const addUnique = (importPath: string): void => {\n    if (!seen.has(importPath)) {\n      seen.add(importPath);\n      imports.push(importPath);\n    }\n  };\n\n  // ES module imports — split into two simple patterns to avoid\n  // catastrophic backtracking (CodeQL ReDoS). The original single regex\n  // used [\\w*{}\\s,]+ which overlapped with the surrounding \\s+, causing\n  // polynomial backtracking. These replacements use [^'\"]+ which has\n  // only one quantifier before the anchor, ensuring linear-time matching.\n  // The [^'\"]+ class supports multiline destructured imports (e.g.,\n  // import {\\n  foo,\\n  bar\\n} from 'path') since it does not exclude \\n.\n  //\n  // 1. Named/default/namespace: import { x } from 'path'\n  const esFromImportRegex = /\\bimport\\b[^'\"]+\\bfrom\\s+['\"]([^'\"]+)['\"]/g;\n  // 2. Side-effect: import 'path'\n  const esSideEffectRegex = /\\bimport\\s+['\"]([^'\"]+)['\"]/g;\n\n  let match: RegExpExecArray | null;\n\n  match = esFromImportRegex.exec(fileContent);\n  while (match !== null) {\n    addUnique(match[1]);\n    match = esFromImportRegex.exec(fileContent);\n  }\n\n  match = esSideEffectRegex.exec(fileContent);\n  while (match !== null) {\n    addUnique(match[1]);\n    match = esSideEffectRegex.exec(fileContent);\n  }\n\n  // CommonJS: require('path')\n  const requireRegex = /require\\s*\\(\\s*['\"]([^'\"]+)['\"]\\s*\\)/g;\n  match = requireRegex.exec(fileContent);\n  while (match !== null) {\n    addUnique(match[1]);\n    match = requireRegex.exec(fileContent);\n  }\n\n  // Dynamic import: import('path')\n  const dynamicImportRegex = /import\\s*\\(\\s*['\"]([^'\"]+)['\"]\\s*\\)/g;\n  match = dynamicImportRegex.exec(fileContent);\n  while (match !== null) {\n    addUnique(match[1]);\n    match = dynamicImportRegex.exec(fileContent);\n  }\n\n  return imports;\n}\n\n/**\n * Builds an import graph mapping test file paths to their imported module paths.\n *\n * Discovers test files, reads each, extracts imports, and builds a graph.\n * Computes a deterministic buildHash from the serialized graph content.\n * Individual file read failures are silently skipped.\n *\n * @param projectRoot - Absolute path to the project root directory.\n * @returns An {@link ImportGraphPayload} containing the graph and a deterministic buildHash.\n *\n * @remarks\n * Node-only. Walks the project with `node:fs/promises`, reads each\n * test file from disk, resolves paths with `node:path`, and hashes\n * the serialized graph with `node:crypto` (`createHash(\"sha256\")`).\n * No edge-safe alternative — call from a Node context (build script,\n * CI job, Next.js `next.config.ts`).\n */\nexport async function buildImportGraph(\n  projectRoot: string,\n): Promise<ImportGraphPayload> {\n  const testFiles = await discoverTestFiles(projectRoot);\n  const graph: Record<string, string[]> = {};\n\n  for (const testFile of testFiles) {\n    const fullPath = path.join(projectRoot, testFile);\n    try {\n      const content = await fs.readFile(fullPath, \"utf-8\");\n      const imports = extractImports(content);\n      graph[testFile] = imports;\n    } catch {\n      // File is unreadable (permissions, deleted between discovery and read) — skip\n      continue;\n    }\n  }\n\n  // Compute deterministic build hash from graph content\n  const sortedKeys = Object.keys(graph).sort();\n  const serialized = sortedKeys\n    .map((key) => `${key}:${JSON.stringify(graph[key])}`)\n    .join(\"\\n\");\n  const hashHex = crypto\n    .createHash(\"sha256\")\n    .update(serialized)\n    .digest(\"hex\");\n  const buildHash = createBuildHash(hashHex);\n\n  return { buildHash, graph };\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AA6BO,SAAS,cAAiC;AAC/C,SAAO;AAAA,IACL,oBAAoB,QAAQ,IAAI,oBAAoB,KAAK,KAAK;AAAA,IAC9D,yBAAyB,QAAQ,IAAI;AAAA,IACrC,gBAAgB,QAAQ,IAAI;AAAA,IAC5B,yBAAyB,QAAQ,IAAI;AAAA,IACrC,2BAA2B,QAAQ,IAAI;AAAA,IACvC,UAAU,QAAQ,IAAI;AAAA,IACtB,YAAY,QAAQ,IAAI;AAAA,EAC1B;AACF;AAMO,SAAS,cAAc,SAA6C;AACzE,QAAM,MAAM,YAAY;AAExB,SAAO;AAAA,IACL,QAAQ,SAAS,UAAU,IAAI;AAAA,IAC/B,UAAU,SAAS,YAAY;AAAA,IAC/B,aAAa,SAAS,eAAe,IAAI,4BAA4B;AAAA,IACrE,SAAS,SAAS,WAAW;AAAA;AAAA;AAAA;AAAA,IAI7B,eAAe,SAAS,iBAAiB,IAAI,8BAA8B;AAAA,IAC3E,aAAa,IAAI;AAAA,IACjB,oBAAoB,IAAI,4BAA4B;AAAA,IACpD,SAAS,IAAI;AAAA,IACb,WAAW,IAAI;AAAA,EACjB;AACF;AAUO,SAAS,qBAAqBA,SAAiC;AACpE,MAAIA,QAAO,aAAa;AACtB,WAAO;AAAA,EACT;AACA,MAAIA,QAAO,YAAY,cAAc;AACnC,WAAO;AAAA,EACT;AACA,MAAIA,QAAO,cAAc,cAAc;AACrC,WAAO;AAAA,EACT;AACA,SAAO;AACT;AAMO,SAAS,gBAAgBA,SAAiC;AAC/D,MAAIA,QAAO,WAAW,QAAW;AAC/B,WAAO;AAAA,EACT;AACA,MAAI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f,QAAM,YAAY,gBAAgB,OAAO;AAEzC,SAAO,EAAE,WAAW,MAAM;AAC5B;","names":["config","initializer","_a","array","set","object","path","Class","_a","config","base64","base64url","hex","error","issue","path","_a","time","version","_a","inst","result","base64","r","_a","checks","checkResult","canary","result","_","url","isObject","allowsEval","results","map","left","right","keyResult","valueResult","output","issue","error","issue","error","issue","error","issue","error","issue","error","issue","error","issue","error","issue","error","issue","error","issue","error","issue","error","issue","error","issue","error","issue","error","issue","error","issue","error","issue","error","issue","error","issue","error","issue","error","issue","error","issue","error","issue","error","issue","error","issue","error","issue","error","issue","number","error","issue","error","issue","error","issue","error","issue","error","issue","error","issue","error","issue","error","issue","error","issue","error","issue","error","issue","error","issue","error","issue","error","issue","error","issue","error","issue","error","issue","error","issue","error","issue","error","issue","error","issue","error","issue","error","issue","_a","meta","Class","_emoji","_undefined","_null","issue","codec","process","_a","meta","id","schema","registry","ctx","process","json","file","process","core_exports","_emoji","_null","_undefined","process","init_core","checks_exports","init_checks","init_core","date","datetime","duration","time","init_core","init_schemas","initializer","init_errors","init_core","issue","issues","parse","parseAsync","safeParse","safeParseAsync","encode","decode","encodeAsync","decodeAsync","safeEncode","safeDecode","safeEncodeAsync","safeDecodeAsync","init_parse","init_core","init_errors","schemas_exports","_default","base64","base64url","bigint","boolean","_catch","cidrv4","cidrv6","cuid","cuid2","date","describe","e164","email","emoji","_enum","guid","hex","hostname","ipv4","ipv6","ksuid","mac","meta","nanoid","_null","nullish","number","string","ulid","_undefined","uuid","_void","xid","installed","_emoji","codec","init_schemas","init_core","init_checks","init_parse","parse","safeParse","parseAsync","safeParseAsync","encode","decode","encodeAsync","decodeAsync","safeEncode","safeDecode","safeEncodeAsync","safeDecodeAsync","def","check","json","datetime","time","duration","issue","output","map","init_core","ZodFirstPartyTypeKind","path","zodSchema","objectSchema","version","init_checks","init_schemas","schemas_exports","checks_exports","bigint","boolean","date","number","string","init_core","init_schemas","_default","base64","base64url","bigint","boolean","_catch","cidrv4","cidrv6","core_exports","cuid","cuid2","date","decode","decodeAsync","describe","e164","email","emoji","encode","encodeAsync","_enum","guid","hex","hostname","ipv4","ipv6","ksuid","mac","meta","nanoid","_null","nullish","number","parse","parseAsync","safeDecode","safeDecodeAsync","safeEncode","safeEncodeAsync","safeParse","safeParseAsync","string","ulid","_undefined","uuid","_void","xid","init_core","init_schemas","init_checks","init_errors","init_parse","hash","date","z","url","isCompatible","diag","_a","DiagLogLevel","self","_a","self","context","ValueType","API_NAME","init_context","context","TraceFlags","context","_a","init_context","init_context","context","version","context","version","_a","SamplingDecision","SpanKind","SpanStatusCode","init_utils","init_context","diag","API_NAME","version","context","context","init_context","API_NAME","context","API_NAME","success","version","diag","init_utils","fs","path","config","resolve","sanitize","hash","file","stat","hash","json","url","fs","path","crypto","cachedPort","url","hostname","cachedPort","_sessionManager","fs","path","cached","resolve","url","httpsRequest","httpRequest","resolve","fs","fs","fsPathCache","loadFsPath","fs","path","loadFsPath","GLASSTRACE_DIR","version","hash","loadFsPath","GLASSTRACE_DIR","config","GLASSTRACE_DIR","fs","path","config","cached","url","error","config","rebuilt","record","ATTR","eventDetails","httpUrl","url","hrTime","path","url","promise","context","context","diag","diag","import_util","diag","VERSION","VERSION","time","time2","ExportResultCode","isPlainObject","merge","isObject","isPlainObject","resolve","diag","diag","diag","diag","hrTime","hrTime","record","diag","diag","url","module","VERSION","VERSION","url","resolve","error","module","resolve","diag","diag","url","diag","path","config","config","diag","config","inspect","diag","time","error","inspect","SamplingDecision","SamplingDecision","SamplingDecision","config","context","context","SamplingDecision","TracesSamplerValues","diag","config","diag","resolve","SamplingDecision","VERSION","config","VERSION","context","diag","inspect","resolve","error","context","ForceFlushState","config","merge","version","resolve","error","inspect","crypto","hash","config","url","processor","config","resolve","url","prismaModule","diag","GLASSTRACE_BRAND","GLASSTRACE_BRAND","context","success","record","config","fsSync","pathSync","config","fs","path","hash","stat","config","isNodeBuiltin","config","context","discoverSourceMapFiles","computeBuildHash","uploadSourceMaps","error","file","re","error","fs","fsSync","path","crypto"]}