{"version":3,"sources":["../src/errors/BaseError.ts","../src/errors/defaults.ts","../src/errors/StructuredError.ts","../src/errors/match.ts","../src/errors/match-thrown.ts","../src/errors/error-class-set.ts","../src/errors/catalog.ts","../src/errors/coerce.ts","../src/errors/validation.ts","../src/utils/guard.ts","../src/utils/redact.ts","../src/errors/guards.ts","../src/traversal/guards.ts","../src/traversal/cause-chain.ts","../src/traversal/retryability.ts"],"names":["_a","guard"],"mappings":";;;;;;;;;;;;AAAA,IAAA,SAAA,EAAA,YAAA,EAAA,QAAA,EAAA,iBAAA,EAAA,iBAAA,EAAA,cAAA,EAAA,mBAAA,EAAA,iBAAA,EAAA,YAAA,EAAA,aAAA,EAAA,aAAA,EAAA,cAAA,EAAA,iBAAA,EAAA,oBAAA,EAAA,gBAAA,EAAA,WAAA,EAAA,gBAAA,EAAA,iBAAA,EAAA,eAAA,EAAA,0BAAA,EAAA,mBAAA,EAAA,uBAAA;AA+CO,IAAM,UAAA,GAAN,MAAM,UAAA,SAAoC,KAAA,CAAM;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EA8DhC,WAAA,CACnB,OAAA,EACA,KAAA,EACA,OAAA,GAA4B,EAAC,EAC7B;AAEA,IAAA,KAAA,CAAM,OAAO,CAAA;AApEV,IAAA,YAAA,CAAA,IAAA,EAAA,oBAAA,CAAA;AA8BL;AAAA,IAAA,IAAA,CAAgB,SAAA,GAAoB,KAAK,GAAA,EAAI;AAO7C;AAAA;AAAA;AAAA;AAAA;AAAA,IAAA,IAAA,CAAgB,eAAuB,IAAI,IAAA,CAAK,IAAA,CAAK,SAAS,EAAE,WAAA,EAAY;AAK5E,IAAA,YAAA,CAAA,IAAA,EAAA,SAAA,CAAA;AAUA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,IAAA,YAAA,CAAA,IAAA,EAAA,YAAA,CAAA;AAsBE,IAAA,MAAM,YAAA,GAAe,OAAA,CAAQ,IAAA,IAAQ,IAAA,CAAK,WA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GAC9B;AACF","file":"index.cjs","sourcesContent":["// This avoids polluting the global scope\ninterface V8ErrorConstructor {\n  captureStackTrace?(\n    targetObject: object,\n    constructorOpt?: (...args: unknown[]) => unknown,\n  ): void;\n}\n\nexport type BaseErrorOptions = {\n  /** Override the runtime error name. Intended for framework errors with stable codes. */\n  name?: string;\n};\n\n/**\n * Replacement used by {@link BaseError.redact}/{@link BaseError.redactAllow}.\n * Either a fixed value, or a function of the original `(value, key)`: useful\n * for partial masking (`****6789`) or preserving the value's type.\n */\nexport type RedactMask = string | ((value: unknown, key: string) => unknown);\n\n/**\n * Where a node sits in the log tree, for `redactAllow`'s structure-vs-data\n * decision: `\"root\"` (the top level, where only the library's own envelope\n * keys are kept), `\"cause\"` (a cause's top level, structural envelope keys\n * kept, the rest data), `\"data\"` (a `details` subtree, a cause's foreign\n * subtree, or a subclass-added top-level subtree, where every leaf is data).\n * The deny-list (`redact`) ignores it.\n */\ntype RedactRegion = \"root\" | \"cause\" | \"data\";\n\n/**\n * Application-specific base error that works across full Node.js, isolate \"edge\"\n * runtimes (Cloudflare Workers, Deno Deploy, Vercel Edge Functions) and modern\n * browsers. It preserves the native `cause` field where available, falls back\n * gracefully where it is not, and produces the richest stack trace the host\n * can provide.\n *\n * @example\n * ```ts\n * // Using automatic name inference\n * class UserNotFoundError extends BaseError<'UserNotFoundError'> {\n * constructor(userId: string) {\n * super(`User with id ${userId} not found in database lookup`); // Technical message\n * }\n * }\n * ```\n */\nexport class BaseError<T extends string> extends Error {\n  /**\n   * Nominal type brand - makes each subclass structurally distinct at compile time.\n   * Using 'this' ensures every subclass gets its own unique type identity.\n   * @internal - This property is for type-checking only, never use it directly.\n   */\n  protected readonly __brand!: this;\n\n  /**\n   * Discriminant tag for type narrowing. Derived from the resolved error name\n   * (an explicit `name` option, otherwise the constructor name), so it never\n   * diverges from {@link name}.\n   *\n   * Because the fallback is `constructor.name`, a build that minifies class\n   * names will mangle it. For a stable discriminant either pass an explicit\n   * `name`, or override `_tag` with a literal, which also narrows the\n   * type:\n   *\n   * @example\n   * ```ts\n   * class MyError extends BaseError<'MyError'> {\n   *   readonly _tag = 'MyError' as const; // stable + strictly typed\n   * }\n   * ```\n   */\n  public readonly _tag: string;\n\n  public override readonly name: T;\n\n  /** Epoch-ms timestamp (numeric) */\n  public readonly timestamp: number = Date.now();\n\n  /**\n   * ISO-8601 timestamp (string) for log aggregators that prefer text. Derived\n   * from {@link timestamp} (one clock read), so the two can never disagree\n   * across a millisecond boundary.\n   */\n  public readonly timestampIso: string = new Date(this.timestamp).toISOString();\n\n  /** Rich, filtered stack where the host supports it. */\n  public override readonly stack?: string;\n\n  #redactor?: (log: Record<string, unknown>) => Record<string, unknown>;\n\n  /**\n   * Mask for the technical `message` in {@link toString}, set only by a\n   * deny-list {@link redact} whose keys include `\"message\"`. `toString` (unlike\n   * `toLogObject`) cannot run an arbitrary redactor, but a denied `message` is\n   * an explicit statement that the text is sensitive, so the one string\n   * rendering the library controls honors it. Follows the redactor's\n   * last-wins semantics: `redactAllow`/`redactWith` clear it.\n   */\n  #messageMask?: RedactMask;\n\n  /**\n   * Creates a new BaseError instance with automatic name inference.\n   *\n   * @param message – Human-readable explanation (name will be inferred from constructor)\n   * @param cause   – Optional underlying error or extra context\n   * @param options – Optional runtime name settings\n   */\n  // The /*#__PURE__*/ pragma lets tree-shakers know the constructor is side-effect free\n  public /*#__PURE__*/ constructor(\n    message: string,\n    cause?: unknown,\n    options: BaseErrorOptions = {},\n  ) {\n    // Always call super with just message for TypeScript compatibility\n    super(message);\n\n    // Resolve the error's stable identity once. An explicit `name` wins;\n    // otherwise fall back to the constructor name. Both `name` and `_tag`\n    // derive from it so they can never diverge. Passing an explicit\n    // `name` stabilizes the discriminant under class-name minification.\n    const resolvedName = options.name ?? this.constructor.name;\n    this.name = resolvedName as T;\n    this._tag = resolvedName;\n\n    // Handle cause with native support when available, fallback otherwise\n    if (cause !== undefined) {\n      this.#setCause(cause);\n    }\n\n    // Preserve prototype chain for `instanceof` checks after transpilation.\n    // Guarded: under native class semantics the prototype is already correct,\n    // and an unconditional setPrototypeOf would deopt every construction (V8\n    // hidden-class transition) for nothing.\n    if (Object.getPrototypeOf(this) !== new.target.prototype) {\n      Object.setPrototypeOf(this, new.target.prototype);\n    }\n\n    // Cross-runtime best-effort stack collection, deferred: capturing is\n    // cheap, symbolizing/filtering is not, so both happen on first read.\n    this.#installLazyStack();\n  }\n\n  /**\n   * Redacts the given keys (deep, at any depth) from the **log** output\n   * (`toLogObject`/`toJSON`). Sticky on the instance, so it also applies when a\n   * logger auto-serializes the error via `JSON.stringify`.\n   *\n   * ⚠️ Scope: redaction rewrites the **log object**, not every string render.\n   * When `keys` includes `\"message\"`, {@link toString} masks the technical\n   * message too; everything else (`err.stack`, whose header carries the raw\n   * message, and Node's `console.log(err)` inspection, which prints the stack)\n   * stays unredacted. When redaction matters, log errors only through a\n   * structured serializer that hits `toJSON`, never via string interpolation.\n   *\n   * @param keys - Property names to mask wherever they appear in the log object.\n   * @param options - `mask` defaults to `\"[REDACTED]\"`.\n   */\n  public redact(keys: string[], options?: { mask?: RedactMask }): this {\n    const mask = options?.mask ?? \"[REDACTED]\";\n    const denied = new Set(keys);\n    this.#messageMask = denied.has(\"message\") ? mask : undefined;\n    this.#redactor = (log) =>\n      BaseError.#redactWalk(\n        log,\n        (key, value) =>\n          denied.has(key)\n            ? BaseError.#applyMask(mask, value, key)\n            : BaseError.#RECURSE,\n        \"root\",\n      ) as Record<string, unknown>;\n    return this;\n  }\n\n  /**\n   * Allow-list redaction (higher assurance than {@link redact}): within any\n   * **data** region (a `details` subtree at any depth, the data-bearing\n   * fields of a `cause`, and any subclass-added top-level field): masks every\n   * leaf whose key is **not** listed, so a newly-added field leaks nothing by\n   * default. Container objects are recursed so nested allowed leaves survive.\n   * Only the library's own structural envelope is kept: the fixed top-level\n   * fields ({@link BaseError.#ROOT_ENVELOPE_KEYS}: `name`/`message`/`stack`/\n   * `code`/`category`/`retryable`/`timestamp`/`timestampIso`/`cause`/`details`)\n   * and a cause's top-level structural envelope keys (`name`/`message`/`stack`/\n   * `code`/`category`/`retryable`). Any other top-level field (e.g. one a\n   * subclass adds via `buildLogObject`) is data: its leaves are masked unless\n   * allow-listed. A cause's foreign fields (anything outside that fixed set,\n   * and everything nested beneath them) are treated as data, so a plain object\n   * that merely *looks* like a structured error cannot smuggle siblings (or\n   * envelope-named keys buried in foreign subtrees) through. Sticky; last\n   * redactor wins.\n   *\n   * ⚠️ Scope: rewrites the **log object** only. The technical `message` is part\n   * of the kept structural envelope, so `toString`, `err.stack`, and Node's\n   * `console.log(err)` inspection carry it unchanged; see {@link redact} for\n   * masking the message itself.\n   *\n   * @param keys - Data leaf keys allowed to survive in the log.\n   * @param options - `mask` defaults to `\"[REDACTED]\"`.\n   */\n  public redactAllow(keys: string[], options?: { mask?: RedactMask }): this {\n    const mask = options?.mask ?? \"[REDACTED]\";\n    const allow = new Set(keys);\n    this.#messageMask = undefined;\n    this.#redactor = (log) =>\n      BaseError.#redactWalk(\n        log,\n        (key, value, region: RedactRegion) => {\n          // Always recurse into containers so nested allowed leaves survive.\n          if (Array.isArray(value) || BaseError.#isWalkable(value)) {\n            return BaseError.#RECURSE;\n          }\n          // Leaf. Keep iff the region permits this key.\n          const kept =\n            (region === \"root\" && BaseError.#ROOT_ENVELOPE_KEYS.has(key)) ||\n            allow.has(key) ||\n            (region === \"cause\" && BaseError.#ENVELOPE_KEYS.has(key));\n          return kept ? value : BaseError.#applyMask(mask, value, key);\n        },\n        \"root\",\n      ) as Record<string, unknown>;\n    return this;\n  }\n\n  /** Sentinel returned by a redaction decision to mean \"descend / keep as-is\". */\n  static readonly #RECURSE: unique symbol = Symbol(\"redact.recurse\");\n\n  /**\n   * Largest **data** nesting depth the redaction walker descends into. Bounded\n   * so a pathologically deep `details` tree degrades to a marker at the deep end\n   * (shallow fields survive) instead of overflowing the stack and tripping the\n   * fail-closed path, which would drop the whole log. The cap is host-stack\n   * independent, so behavior is identical on small isolate stacks (edge\n   * runtimes). The cause chain is its own separately bounded spine ({@link\n   * BaseError.#MAX_CAUSE_DEPTH}) and is **exempt** from this budget, so a deep\n   * chain cannot marker-truncate a shallow `details` on a deep cause.\n   */\n  static readonly #MAX_REDACT_DEPTH = 100;\n\n  /**\n   * Total-node budget for one redaction walk. The depth cap bounds depth, not\n   * width: shared (DAG) references are cloned once per reference, so a small\n   * `details` value can legally expand exponentially. Past the budget any\n   * further container degrades to a marker (like the depth cap), keeping the\n   * logging path fail-safe instead of walking a blowup to completion.\n   */\n  static readonly #MAX_REDACT_NODES = 100_000;\n\n  /**\n   * Structural fields of an error envelope that survive an allow-list at the\n   * **top level of a cause**. Everything else under a cause (foreign siblings\n   * and anything nested beneath them, plus `details`) is treated as data, so a\n   * plain object mimicking the structured shape cannot smuggle sensitive\n   * siblings (or envelope-named keys buried in foreign subtrees) past\n   * `redactAllow`. Private: it must not become a process-wide redaction toggle.\n   */\n  static readonly #ENVELOPE_KEYS: ReadonlySet<string> = new Set([\n    \"name\",\n    \"message\",\n    \"stack\",\n    \"code\",\n    \"category\",\n    \"retryable\",\n  ]);\n\n  /**\n   * The library's own **top-level** structural fields, the only root keys an\n   * allow-list keeps (and, for containers, the only root keys that stay in the\n   * root/cause regions). Everything else at the top level (a field a subclass\n   * adds via `buildLogObject`) is data, so a subclass-added field leaks nothing\n   * through `redactAllow` by default. Private for the same reason as\n   * {@link BaseError.#ENVELOPE_KEYS}.\n   */\n  static readonly #ROOT_ENVELOPE_KEYS: ReadonlySet<string> = new Set([\n    ...BaseError.#ENVELOPE_KEYS,\n    \"timestamp\",\n    \"timestampIso\",\n    \"cause\",\n    \"details\",\n  ]);\n\n  /*#__PURE__*/ static #applyMask(\n    mask: RedactMask,\n    value: unknown,\n    key: string,\n  ): unknown {\n    return typeof mask === \"function\" ? mask(value, key) : mask;\n  }\n\n  /**\n   * Whether the walker should descend into `value`. A **plain object**\n   * (`{}` / `Object.create(null)`) is always a container, even when empty, so\n   * it is preserved as `{}` rather than masked or collapsed. Any **other**\n   * object is a container only if it carries its own enumerable keys: a class\n   * instance with own fields *is* descended (so a deny/allow list reaches keys\n   * nested inside it), while `Date`/`Map`/`Set`/`RegExp` (no own enumerable\n   * keys) stay preserved leaves rather than collapsing to `{}`.\n   */\n  /*#__PURE__*/ static #isWalkable(\n    value: unknown,\n  ): value is Record<string, unknown> {\n    if (value === null || typeof value !== \"object\" || Array.isArray(value)) {\n      return false;\n    }\n    const proto = Object.getPrototypeOf(value) as unknown;\n    if (proto === Object.prototype || proto === null) return true;\n    return Object.keys(value).length > 0;\n  }\n\n  /**\n   * Single deep-clone walker for redaction. Recurses into arrays and objects\n   * that carry own enumerable keys (see {@link BaseError.#isWalkable}); every\n   * other value (string, `Date`, `Map`, empty object, …) is a leaf.\n   * `decide(key, value, region)` returns the replacement for a key, or\n   * `#RECURSE` to descend into a container / keep a leaf unchanged.\n   *\n   * `region` classifies where we are, so the allow-list can distinguish the\n   * structural envelope from data:\n   * - `\"root\"`: the top-level error envelope (kept verbatim by the allow-list);\n   * - `\"cause\"`: at a `cause`'s top level; the structural envelope keys\n   *   (`#ENVELOPE_KEYS`) are kept, all other leaves are data;\n   * - `\"data\"`: inside a `details` subtree or a cause's foreign subtree; every\n   *   leaf is data.\n   *\n   * The transition is by key name only, not duck-typing, so a cause that\n   * merely resembles a structured error cannot reclassify its data as envelope.\n   * The deny-list ignores `region`.\n   */\n  /*#__PURE__*/ static #redactWalk(\n    value: unknown,\n    decide: (key: string, value: unknown, region: RedactRegion) => unknown,\n    region: RedactRegion,\n    depth = 0,\n    state: { nodes: number } = { nodes: 0 },\n  ): unknown {\n    // Past a cap, replace any container with a marker rather than recursing.\n    // Leaves are unaffected (they never recurse), so shallow data is intact.\n    // The node budget bounds total work (shared references expand per\n    // reference); the depth cap bounds the stack.\n    if (Array.isArray(value) || BaseError.#isWalkable(value)) {\n      if (depth >= BaseError.#MAX_REDACT_DEPTH) {\n        return \"[Max redaction depth exceeded]\";\n      }\n      if (++state.nodes > BaseError.#MAX_REDACT_NODES) {\n        return \"[Max redaction size exceeded]\";\n      }\n    }\n    if (Array.isArray(value)) {\n      return value.map((item) =>\n        BaseError.#redactWalk(item, decide, region, depth + 1, state),\n      );\n    }\n    if (BaseError.#isWalkable(value)) {\n      // Null-prototype target so an own `__proto__`/`constructor` key from\n      // untrusted details is copied as ordinary data (and masked/recursed like\n      // any other key) instead of routing through a prototype setter. Matches\n      // the null-prototype clones used by the public-error catalog and transport\n      // stage. (OWASP Prototype Pollution Prevention.)\n      const out = Object.create(null) as Record<string, unknown>;\n      for (const [key, val] of Object.entries(value)) {\n        // A leaf's keep/mask decision is made in the region it *lives in* (the\n        // parent); the child region only governs recursion. Conflating the two\n        // wrongly masks a region-transition key that holds a leaf (e.g. a\n        // top-level `cause: undefined`).\n        const decision = decide(key, val, region);\n        if (decision === BaseError.#RECURSE) {\n          if (Array.isArray(val) || BaseError.#isWalkable(val)) {\n            const childRegion = BaseError.#childRegion(region, key);\n            // The cause chain is its own bounded spine (see #serializeCause), so\n            // descending it must not consume the data-depth budget; otherwise a\n            // deep chain would marker-truncate a shallow `details` on a deep\n            // cause. The cap stays for genuinely deep data trees.\n            const childDepth = childRegion === \"cause\" ? depth : depth + 1;\n            out[key] = BaseError.#redactWalk(\n              val,\n              decide,\n              childRegion,\n              childDepth,\n              state,\n            );\n          } else {\n            out[key] = val;\n          }\n        } else {\n          out[key] = decision;\n        }\n      }\n      return out;\n    }\n    return value;\n  }\n\n  /**\n   * Region a child key enters. `details` → data (data is sticky for the whole\n   * subtree); `cause` → cause. Inside a `cause`, only the structural envelope\n   * keys stay `cause`; every other (foreign) child, and therefore everything\n   * nested beneath it, drops to data, so envelope-named keys buried in a\n   * cause's foreign subtrees cannot be mistaken for the cause's own envelope.\n   * At the root, the same rule applies against {@link\n   * BaseError.#ROOT_ENVELOPE_KEYS}: a foreign top-level key (one a subclass\n   * added via `buildLogObject`) drops to data, so its whole subtree gets\n   * allow-list protection instead of the root region's keep-everything.\n   */\n  /*#__PURE__*/ static #childRegion(\n    region: RedactRegion,\n    key: string,\n  ): RedactRegion {\n    if (region === \"data\") return \"data\";\n    if (key === \"details\") return \"data\";\n    if (key === \"cause\") return \"cause\";\n    if (region === \"cause\") {\n      return BaseError.#ENVELOPE_KEYS.has(key) ? \"cause\" : \"data\";\n    }\n    return BaseError.#ROOT_ENVELOPE_KEYS.has(key) ? \"root\" : \"data\";\n  }\n\n  /**\n   * Sets a custom redactor applied to the full log object. Use for allow-lists\n   * or scrubbing the technical `message`. Sticky; the last redactor wins.\n   *\n   * ⚠️ Scope: applies to the **log object** only. A custom redactor cannot be\n   * mapped onto the one-line {@link toString} render, so `toString`,\n   * `err.stack`, and `console.log(err)` inspection keep the raw technical\n   * message even when the redactor scrubs it from the log.\n   */\n  public redactWith(\n    redactor: (log: Record<string, unknown>) => Record<string, unknown>,\n  ): this {\n    this.#messageMask = undefined;\n    this.#redactor = redactor;\n    return this;\n  }\n\n  /**\n   * Assembles the raw log object (no redaction). Subclasses override this to\n   * add their own fields; the public {@link toLogObject} applies redaction to\n   * the complete assembled object.\n   */\n  protected buildLogObject(): Record<string, unknown> {\n    const { name, message, timestamp, timestampIso, stack } = this;\n    const cause = (this as unknown as Record<string, unknown>).cause;\n\n    const json: Record<string, unknown> = {\n      name,\n      message, // The original technical message\n      timestamp,\n      timestampIso,\n      stack,\n      cause: this.#serializeCause(cause, new Set(), 0),\n    };\n\n    return json;\n  }\n\n  /**\n   * Serialises the error for logs. Includes technical message, stack and cause,\n   * with the instance redactor applied (see {@link redact} / {@link redactWith}).\n   *\n   * ⚠️ This is a **log** serialization: it carries the technical message, stack,\n   * cause chain and raw `details`. **Never return it to a client.** Anything that\n   * auto-serializes the error (`JSON.stringify`, `res.json(err)`, `Response.json`,\n   * `return err`) reaches {@link toJSON}, which is an alias of this method, and\n   * leaks the same payload. For client-safe output use the `public-error`\n   * subpath (`@shirudo/base-error/public-error`, `project`), which projects only\n   * an allow-listed, message-free public view.\n   */\n  public toLogObject(): Record<string, unknown> {\n    const raw = this.buildLogObject();\n    if (!this.#redactor) {\n      return raw;\n    }\n    try {\n      return this.#redactor(raw);\n    } catch {\n      // Fail-closed: a broken redactor must neither crash the logging path nor\n      // leak the unredacted payload (message/details/stack/cause are dropped).\n      // Keep only the non-sensitive structural fields needed for triage.\n      const safe: Record<string, unknown> = {\n        message: \"[log redaction failed]\",\n      };\n      for (const key of BaseError.#SAFE_TRIAGE_KEYS) {\n        if (key in raw) {\n          safe[key] = raw[key];\n        }\n      }\n      return safe;\n    }\n  }\n\n  /**\n   * Non-sensitive structural fields preserved in the fail-closed redaction\n   * marker. Only those a given error's `buildLogObject()` actually emits are\n   * copied (guarded by `key in raw`), so `code`/`category`/`retryable` appear\n   * for a `StructuredError` but are simply absent for a plain `BaseError`.\n   */\n  static readonly #SAFE_TRIAGE_KEYS = [\n    \"name\",\n    \"code\",\n    \"category\",\n    \"retryable\",\n    \"timestamp\",\n    \"timestampIso\",\n  ] as const;\n\n  /**\n   * JSON serialization for logging-oriented consumers. Alias of\n   * {@link toLogObject}, so it returns the same **log** shape: technical message,\n   * stack, cause chain and raw `details`.\n   *\n   * ⚠️ Because `JSON.stringify(err)`, `res.json(err)`, `Response.json(err)` and\n   * `return err` all route through `toJSON`, sending an error down any of those\n   * paths leaks the full technical payload to the client. **Never serialize an\n   * error straight into a response.** Produce a client payload through the\n   * `public-error` subpath (`project` / `toProblem`) instead. This shape is also\n   * the input that {@link StructuredError.fromJSON} reconstructs, which is why it\n   * intentionally retains the stack and cause chain.\n   */\n  public toJSON(): Record<string, unknown> {\n    return this.toLogObject();\n  }\n\n  /**\n   * Readable one-liner plus full nested cause chain. Honors a deny-listed\n   * `\"message\"` (see {@link redact}) per BaseError in the chain; other\n   * redaction shapes rewrite only the log object.\n   */\n  public override toString(): string {\n    const parts: string[] = [];\n    let current: unknown = this as unknown;\n    const seen = new Set<unknown>();\n\n    while (current != null) {\n      if (seen.has(current)) {\n        parts.push(\"[Circular cause chain]\");\n        break;\n      }\n      seen.add(current);\n\n      if (current instanceof BaseError) {\n        parts.push(`[${current.name}] ${current.#renderMessage()}`);\n      } else if (current instanceof Error) {\n        parts.push(`${current.name}: ${current.message}`);\n      } else {\n        parts.push(String(current));\n      }\n\n      current =\n        typeof current === \"object\" && current !== null && \"cause\" in current\n          ? (current as Record<string, unknown>).cause\n          : undefined;\n    }\n\n    return parts.join(\"\\nCaused by: \");\n  }\n\n  // ----------------------------------------------------------------\n  // Internal helpers\n  // ----------------------------------------------------------------\n\n  /**\n   * The message as {@link toString} renders it: masked when a deny-list\n   * covers `\"message\"`, verbatim otherwise. Fail-closed: a throwing function\n   * mask yields the default marker, never the raw message.\n   */\n  /*#__PURE__*/ #renderMessage(): string {\n    if (this.#messageMask === undefined) {\n      return this.message;\n    }\n    try {\n      return String(\n        BaseError.#applyMask(this.#messageMask, this.message, \"message\"),\n      );\n    } catch {\n      return \"[REDACTED]\";\n    }\n  }\n\n  /**\n   * Sets the cause property as non-enumerable (like native Error.cause).\n   *\n   * Uses Object.defineProperty instead of native `new Error(msg, { cause })`\n   * for universal compatibility. This approach works across all runtimes\n   * (Node.js 14+, Deno, Cloudflare Workers, browsers) without version detection,\n   * since Object.defineProperty is ES5 and universally supported.\n   */\n  /*#__PURE__*/ #setCause(cause: unknown): void {\n    try {\n      Object.defineProperty(this, \"cause\", {\n        value: cause,\n        configurable: true,\n        writable: true,\n        enumerable: false,\n      });\n    } catch {\n      // Fallback for environments where defineProperty fails\n      (this as unknown as Record<string, unknown>).cause = cause;\n    }\n  }\n\n  /**\n   * Largest cause-chain depth serialized into a log object. Matches the cap used\n   * by `StructuredError.fromJSON` and the traversal helpers, so a pathologically\n   * deep (but acyclic) chain can never overflow the stack while logging.\n   */\n  static readonly #MAX_CAUSE_DEPTH = 100;\n\n  /**\n   * Intelligently serializes the cause for JSON output.\n   * Preserves stack traces, StructuredError fields, and nested data.\n   * Uses a seen set to detect circular cause chains, and a depth bound so an\n   * acyclic-but-very-deep chain is capped instead of recursing unbounded.\n   */\n  /*#__PURE__*/ #serializeCause(\n    cause: unknown,\n    seen: Set<unknown>,\n    depth: number,\n  ): unknown {\n    if (cause === undefined || cause === null) {\n      return cause;\n    }\n\n    if (depth >= BaseError.#MAX_CAUSE_DEPTH) {\n      return \"[Max cause depth exceeded]\";\n    }\n\n    if (cause instanceof Error) {\n      if (seen.has(cause)) {\n        return \"[Circular cause chain]\";\n      }\n      seen.add(cause);\n\n      const serialized: Record<string, unknown> = {\n        name: cause.name,\n        message: cause.message,\n        stack: cause.stack,\n      };\n\n      // Preserve StructuredError fields if present (duck-typing)\n      // This avoids circular dependency between BaseError and StructuredError\n      const errorRecord = cause as unknown as Record<string, unknown>;\n      if (\"code\" in cause) serialized.code = errorRecord.code;\n      if (\"category\" in cause) serialized.category = errorRecord.category;\n      if (\"retryable\" in cause) serialized.retryable = errorRecord.retryable;\n      if (\"details\" in cause) serialized.details = errorRecord.details;\n\n      // Recursively serialize nested causes\n      if (\"cause\" in cause && errorRecord.cause !== undefined) {\n        serialized.cause = this.#serializeCause(\n          errorRecord.cause,\n          seen,\n          depth + 1,\n        );\n      }\n\n      return serialized;\n    }\n\n    if (typeof cause === \"object\" && cause !== null) {\n      try {\n        // For plain objects, serialize with native JSON semantics (preserves\n        // structured data useful for debugging). The counting replacer bounds\n        // the total node count: JSON.stringify duplicates shared (DAG)\n        // references per reference, so a small hostile payload could expand\n        // exponentially; past the budget it degrades to the fallback marker.\n        // Kept as the native stringify/parse round-trip on purpose: it\n        // measures ~40% faster than an equivalent JS walker.\n        let nodes = 0;\n        const json = JSON.stringify(cause, (_key, value: unknown) => {\n          if (++nodes > BaseError.#MAX_JSON_NODES) {\n            throw new Error(\"payload exceeds serialization bounds\");\n          }\n          return value;\n        });\n        if (json === undefined) {\n          // A top-level toJSON returning undefined has no JSON form.\n          return this.#serializeCircularObject(cause);\n        }\n        return JSON.parse(json);\n      } catch {\n        // If JSON.stringify fails (circular references, BigInt, a size\n        // blowup, ...), create a more useful representation\n        return this.#serializeCircularObject(cause);\n      }\n    }\n\n    // For primitives (string, number, boolean), return as-is\n    return cause;\n  }\n\n  /**\n   * Total-node budget for one plain-object cause payload, enforced by a\n   * counting replacer so a shared-reference (DAG) blowup degrades to the\n   * fallback marker instead of exhausting CPU. Matches the redaction and\n   * wire-clone budgets.\n   */\n  static readonly #MAX_JSON_NODES = 100_000;\n\n  /**\n   * Creates a more useful representation of circular objects for debugging.\n   * Instead of just \"[object Object]\", it extracts key information.\n   */\n  /*#__PURE__*/ #serializeCircularObject(obj: object): string {\n    const type = obj.constructor?.name || \"Object\";\n    const keys = Object.keys(obj).slice(0, 5); // Show first 5 keys\n    const keyInfo = keys.length > 0 ? ` with keys: [${keys.join(\", \")}]` : \"\";\n    const moreKeys = Object.keys(obj).length > 5 ? \"...\" : \"\";\n\n    return `[Circular ${type}${keyInfo}${moreKeys}]`;\n  }\n\n  /**\n   * Captures the stack now but defers symbolization and filtering to the\n   * first read. V8 formats stacks lazily (via `Error.prepareStackTrace`) only\n   * when `stack` is accessed; reading it in the constructor would force that\n   * work for every error, including ones that are caught and never logged. So\n   * the raw capture lands on a side holder, and `this.stack` becomes a\n   * memoizing accessor: the first get symbolizes, filters, and replaces\n   * itself with a plain writable data property; a set before the first get\n   * (a rehydrated or user-assigned stack) wins unfiltered.\n   */\n  /*#__PURE__*/ #installLazyStack(): void {\n    // Cast Error to our local interface for type-safe access.\n    const V8Error = Error as V8ErrorConstructor;\n\n    let readRawStack: () => string | undefined;\n    if (typeof V8Error.captureStackTrace === \"function\") {\n      // V8: capture onto a plain holder, not `this`, so the engine-lazy stack\n      // stays unformatted until our getter reads it. The holder's own header\n      // is discarded by #filterInternalFrames, which writes `name: message`.\n      const holder: { stack?: string } = {};\n      V8Error.captureStackTrace(\n        holder,\n        this.constructor as (...args: unknown[]) => unknown,\n      );\n      readRawStack = () => holder.stack;\n    } else {\n      // Non-V8 engines build the stack string eagerly at throw; only the\n      // filtering is deferrable here.\n      let tempStack: string | undefined;\n      try {\n        throw new Error();\n      } catch (e) {\n        tempStack = (e as Error).stack;\n      }\n      readRawStack = () => tempStack;\n    }\n\n    const install = (value: string | undefined): void => {\n      Object.defineProperty(this, \"stack\", {\n        value,\n        writable: true,\n        configurable: true,\n        enumerable: false,\n      });\n    };\n    Object.defineProperty(this, \"stack\", {\n      configurable: true,\n      enumerable: false,\n      get: (): string | undefined => {\n        const filtered = this.#filterInternalFrames(readRawStack());\n        install(filtered);\n        return filtered;\n      },\n      set: install,\n    });\n  }\n\n  /**\n   * Filters out internal BaseError frames and updates the error header.\n   * This provides cleaner stack traces by removing implementation details.\n   */\n  /*#__PURE__*/ #filterInternalFrames(\n    stack: string | undefined,\n  ): string | undefined {\n    if (!stack) {\n      return undefined;\n    }\n\n    const lines = stack.split(\"\\n\");\n    const filteredLines: string[] = [];\n\n    // Update the header with proper error name and message\n    filteredLines.push(`${this.name}: ${this.message}`);\n\n    // Filter out internal frames\n    for (let i = 1; i < lines.length; i++) {\n      const line = lines[i];\n\n      // Skip undefined lines (shouldn't happen, but satisfy TypeScript)\n      if (!line) {\n        continue;\n      }\n\n      // Skip internal BaseError frames\n      if (\n        line.includes(\"#installLazyStack\") ||\n        line.includes(\"#filterInternalFrames\") ||\n        line.includes(\"BaseError.constructor\") ||\n        line.includes(\"new BaseError\") ||\n        line.includes(\"installLazyStack_fn\") || // Compiled private method name\n        line.includes(\"filterInternalFrames_fn\") || // Compiled private method name\n        // Skip the temporary error creation frame\n        (line.includes(\"Object.<anonymous>\") &&\n          line.includes(\"installLazyStack\"))\n      ) {\n        continue;\n      }\n\n      filteredLines.push(line);\n    }\n\n    return filteredLines.join(\"\\n\");\n  }\n}\n","/**\n * Canonical fallback identity for an unclassified or unrecognized error.\n *\n * Shared by {@link toStructuredError} (coercing a caught value) and\n * `StructuredError.fromJSON` (reconstructing a malformed payload) so the two\n * paths can never drift on what the library's default error looks like.\n */\nexport const UNKNOWN_ERROR_DEFAULTS = {\n  /** Internal code used when none is known. */\n  code: \"UNKNOWN_ERROR\",\n  /** Internal category used when none is known. */\n  category: \"INTERNAL\",\n  /** Unknown errors are not retryable by default. */\n  retryable: false,\n  /** Technical message used when none can be derived. */\n  message: \"Unknown error\",\n} as const;\n","import { BaseError } from \"./BaseError.js\";\nimport type { ErrorOptions } from \"./ErrorOptions.js\";\nimport { UNKNOWN_ERROR_DEFAULTS } from \"./defaults.js\";\n\n/**\n * A structured error class that extends BaseError with enhanced error metadata.\n *\n * StructuredError provides a standardized way to create errors with:\n * - Error codes for programmatic error handling\n * - Categories for grouping related errors\n * - Retryability flags for automatic retry logic\n * - Structured details for additional context\n *\n * All BaseError features are preserved, including timestamps, cause chains, and\n * log serialization.\n *\n * @example\n * ```ts\n * // Basic usage with type inference\n * const error = new StructuredError({\n *   code: \"USER_NOT_FOUND\",\n *   category: \"NOT_FOUND\",\n *   retryable: false,\n *   message: \"User with id 123 not found\",\n *   details: { userId: \"123\" }\n * });\n *\n * // Error handling\n * if (error.code === \"USER_NOT_FOUND\") {\n *   console.log(\"User does not exist\");\n * }\n * ```\n *\n * @example\n * ```ts\n * // Creating a domain-specific error class\n * type DatabaseErrorCode = \"CONNECTION_FAILED\" | \"QUERY_TIMEOUT\" | \"DEADLOCK\";\n * type DatabaseErrorCategory = \"CONNECTION\" | \"EXECUTION\" | \"CONCURRENCY\";\n *\n * interface DatabaseErrorDetails {\n *   query?: string;\n *   duration?: number;\n *   connectionId?: string;\n * }\n *\n * class DatabaseError extends StructuredError<\n *   DatabaseErrorCode,\n *   DatabaseErrorCategory,\n *   DatabaseErrorDetails\n * > {\n *   constructor(\n *     code: DatabaseErrorCode,\n *     message: string,\n *     details?: DatabaseErrorDetails,\n *     cause?: unknown\n *   ) {\n *     super({\n *       code,\n *       category: code === \"CONNECTION_FAILED\" ? \"CONNECTION\" :\n *                code === \"QUERY_TIMEOUT\" ? \"EXECUTION\" : \"CONCURRENCY\",\n *       retryable: code !== \"DEADLOCK\",\n *       message,\n *       details,\n *       cause,\n *     });\n *   }\n * }\n * ```\n */\nexport class StructuredError<\n  TCode extends string,\n  TCategory extends string,\n  // Using Record<string, {}> as default for better compatibility with strict frameworks\n  // eslint-disable-next-line @typescript-eslint/no-empty-object-type\n  TDetails extends Record<string, unknown> = Record<string, {}>,\n> extends BaseError<`${TCode}`> {\n  /**\n   * Stable discriminant for the StructuredError family. Fixed as a literal so it\n   * survives class-name minification. Narrow on {@link code} to distinguish\n   * individual structured errors; subclasses that need their own tag override\n   * this with their own literal.\n   */\n  public override readonly _tag: string = \"StructuredError\";\n\n  /** Error code for programmatic error handling */\n  public readonly code: TCode;\n\n  /** Error category for grouping related errors */\n  public readonly category: TCategory;\n\n  /** Whether this error is retryable */\n  public readonly retryable: boolean;\n\n  /** Optional structured details providing additional context */\n  public readonly details?: TDetails;\n\n  /**\n   * Creates a new StructuredError with typed metadata.\n   *\n   * @param options - Configuration object containing all error metadata\n   */\n  public /*#__PURE__*/ constructor(\n    options: ErrorOptions<TCode, TCategory, TDetails>,\n  ) {\n    super(options.message, options.cause, {\n      name: options.code,\n    });\n\n    this.code = options.code;\n    this.category = options.category;\n    this.retryable = options.retryable;\n    this.details = options.details;\n  }\n\n  /**\n   * Reconstruct a StructuredError from its serialized (`toJSON`/`toLogObject`)\n   * shape. This is the inverse of {@link toJSON}.\n   *\n   * Intended for reconstruction **within a single trust/bounded-context\n   * boundary**: Web Worker / `postMessage` (where `instanceof` is lost across\n   * `structuredClone`), job queues / durable storage, and log replay. Across\n   * services, reconstruct then translate through an Anti-Corruption Layer; do\n   * not treat an upstream's `code` as your own.\n   *\n   * Lenient and safe: missing fields fall back to safe defaults\n   * (`UNKNOWN_ERROR`/`INTERNAL`/non-retryable); malformed input yields that\n   * envelope instead of throwing; only whitelisted fields are read (no\n   * prototype pollution). `details` is copied shallowly (the top level is\n   * decoupled from the payload; nested values stay shared). The original\n   * `stack`/`timestamp` and the cause chain are restored. Reconstructed\n   * fields are **not** an authority on trust: whoever produced the payload\n   * can forge them.\n   *\n   * Always returns a base `StructuredError`: subclass identity and behavior are\n   * **not** restored (a `ValidationError` round-trips to a `StructuredError`,\n   * losing `publicIssues()`/`addIssue()`; its raw `details.issues` survive as\n   * data). Narrow on `code`, not on `_tag`/instanceof.\n   */\n  public static fromJSON(json: unknown): StructuredError<string, string> {\n    return StructuredError.#fromJSON(json, 0);\n  }\n\n  static readonly #MAX_DEPTH = 100;\n\n  static #fromJSON(\n    json: unknown,\n    depth: number,\n  ): StructuredError<string, string> {\n    const obj: Record<string, unknown> =\n      typeof json === \"object\" && json !== null\n        ? (json as Record<string, unknown>)\n        : {};\n\n    const code =\n      typeof obj.code === \"string\" ? obj.code : UNKNOWN_ERROR_DEFAULTS.code;\n    const category =\n      typeof obj.category === \"string\"\n        ? obj.category\n        : UNKNOWN_ERROR_DEFAULTS.category;\n    const retryable =\n      typeof obj.retryable === \"boolean\"\n        ? obj.retryable\n        : UNKNOWN_ERROR_DEFAULTS.retryable;\n    const message =\n      typeof obj.message === \"string\"\n        ? obj.message\n        : UNKNOWN_ERROR_DEFAULTS.message;\n    // Shallow copy: decouples the error's top-level details from the input\n    // payload, so mutating the payload afterwards cannot change the error.\n    // Values nested deeper stay shared; a freshly JSON.parsed payload is not\n    // normally reused, so that is an accepted depth of guarantee.\n    const details =\n      typeof obj.details === \"object\" && obj.details !== null\n        ? { ...(obj.details as Record<string, unknown>) }\n        : undefined;\n    const cause = StructuredError.#reconstructCause(obj.cause, depth);\n\n    const error = new StructuredError({\n      code,\n      category,\n      retryable,\n      message,\n      ...(details !== undefined && { details }),\n      ...(cause !== undefined && { cause }),\n    });\n\n    // Rehydrate the original identity rather than the freshly generated values.\n    StructuredError.#rehydrate(error, \"stack\", obj.stack, \"string\");\n    StructuredError.#rehydrate(error, \"timestamp\", obj.timestamp, \"number\");\n    StructuredError.#rehydrate(\n      error,\n      \"timestampIso\",\n      obj.timestampIso,\n      \"string\",\n    );\n\n    return error as StructuredError<string, string>;\n  }\n\n  static #rehydrate(\n    target: object,\n    key: string,\n    value: unknown,\n    type: \"string\" | \"number\",\n  ): void {\n    if (typeof value === type) {\n      Object.defineProperty(target, key, {\n        value,\n        configurable: true,\n        writable: true,\n        enumerable: key !== \"stack\",\n      });\n    }\n  }\n\n  static #reconstructCause(value: unknown, depth: number): unknown {\n    if (depth >= StructuredError.#MAX_DEPTH) {\n      return undefined;\n    }\n    if (typeof value !== \"object\" || value === null) {\n      // Primitives (and null) are kept verbatim.\n      return value;\n    }\n\n    const obj = value as Record<string, unknown>;\n\n    // Structured shape -> nested StructuredError.\n    if (\n      typeof obj.code === \"string\" &&\n      typeof obj.category === \"string\" &&\n      typeof obj.retryable === \"boolean\"\n    ) {\n      return StructuredError.#fromJSON(obj, depth + 1);\n    }\n\n    // Plain error shape -> a basic Error, chained.\n    if (typeof obj.message === \"string\") {\n      const err = new Error(obj.message);\n      if (typeof obj.name === \"string\") {\n        err.name = obj.name;\n      }\n      if (typeof obj.stack === \"string\") {\n        err.stack = obj.stack;\n      }\n      const nested = StructuredError.#reconstructCause(obj.cause, depth + 1);\n      if (nested !== undefined) {\n        (err as unknown as { cause: unknown }).cause = nested;\n      }\n      return err;\n    }\n\n    // Any other object: opaque data, kept as-is.\n    return value;\n  }\n\n  /**\n   * Extends BaseError's raw log object with code, category, retryable, and\n   * details. Redaction (if configured) is applied by the inherited\n   * {@link toLogObject} to the complete assembled object.\n   */\n  protected override buildLogObject(): Record<string, unknown> {\n    const baseJson = super.buildLogObject();\n\n    return {\n      ...baseJson,\n      code: this.code,\n      category: this.category,\n      retryable: this.retryable,\n      ...(this.details !== undefined && { details: this.details }),\n    };\n  }\n}\n","import type { StructuredError } from \"./StructuredError.js\";\n\n/**\n * Narrows a member of an error union to a single `code`.\n *\n * When `E` is a real union of structured error types (e.g. produced by a\n * catalog), this resolves to the precise member, so `details` is the per-code\n * type. When `E` is a single `StructuredError<\"A\" | \"B\">` there is nothing to\n * narrow, so it falls back to `E` instead of `never`.\n */\ntype CaseArg<E extends StructuredError<string, string>, K extends string> = [\n  Extract<E, { code: K }>,\n] extends [never]\n  ? E\n  : Extract<E, { code: K }>;\n\n/**\n * All handlers, each optional, plus an optional `_` catch-all. Return types are\n * left open so the concrete handler object can drive the result type.\n */\ntype Cases<E extends StructuredError<string, string>> = {\n  [K in E[\"code\"]]?: (error: CaseArg<E, K>) => unknown;\n} & { _?: (error: E) => unknown };\n\n/** The union of every handler's return type. This is the result of `matchError`. */\ntype Result<C> = {\n  [K in keyof C]: C[K] extends (...args: never[]) => infer R ? R : never;\n}[keyof C];\n\n/**\n * Exhaustiveness constraint: if no `_` catch-all is given, every `code` must\n * have a handler. Missing codes are added as required, so an incomplete object\n * fails to type-check.\n */\ntype Exhaustive<\n  E extends StructuredError<string, string>,\n  C,\n> = \"_\" extends keyof C\n  ? C\n  : [Exclude<E[\"code\"], keyof C>] extends [never]\n    ? C\n    : C & {\n        [K in Exclude<E[\"code\"], keyof C>]: (error: CaseArg<E, K>) => unknown;\n      };\n\n/**\n * Exhaustively dispatch on a structured error's `code`, with type narrowing.\n *\n * Pass a handler per `code`. If `error`'s type is a closed union of structured\n * error types and you omit a handler, it is a **compile error** (unless you\n * provide a `_` catch-all). Each handler receives the error narrowed to its\n * case, so `details` is the precise per-code type, and the return type is the\n * union of the handler return types.\n *\n * Errors caught as `unknown` must be narrowed first (e.g. with\n * `isStructuredError`) and annotated as the expected union; exhaustiveness\n * cannot be derived from `unknown`.\n *\n * @param error - The structured error to match on\n * @param cases - A handler per `code`, optionally with a `_` catch-all\n * @returns The value returned by the matching handler\n * @throws Error - When no case matches and no `_` catch-all is provided\n *   (only reachable if the static exhaustiveness check is bypassed)\n *\n * @example\n * ```ts\n * const status = matchError(err, {\n *   USER_NOT_FOUND: () => 404,\n *   EMAIL_TAKEN: () => 409,\n *   RATE_LIMITED: (e) => (e.retryable ? 429 : 503),\n * });\n * ```\n *\n * @example\n * ```ts\n * // Partial handling with a catch-all\n * matchError(err, {\n *   USER_NOT_FOUND: () => render404(),\n *   _: (e) => renderGeneric(e.code),\n * });\n * ```\n */\nexport function matchError<\n  E extends StructuredError<string, string>,\n  const C extends Cases<E>,\n>(error: E, cases: Exhaustive<E, C>): Result<C> {\n  const table = cases as Record<string, ((error: E) => unknown) | undefined>;\n  // Own-property lookup only: a `code` that collides with an `Object.prototype`\n  // member (e.g. \"toString\", \"valueOf\", \"hasOwnProperty\") must route to its\n  // explicit case or the `_` catch-all, never to an inherited method.\n  const ownHandler = Object.prototype.hasOwnProperty.call(table, error.code)\n    ? table[error.code]\n    : undefined;\n  const handler = ownHandler ?? table._;\n\n  if (!handler) {\n    throw new Error(\n      `matchError: unhandled error code \"${error.code}\" (no matching case and no \"_\" catch-all)`,\n    );\n  }\n\n  return handler(error) as Result<C>;\n}\n","import type { ErrorClass, TypeGuard } from \"./guards.js\";\n\ntype MatcherCase = {\n  test: (value: unknown) => boolean;\n  run: (value: unknown) => unknown;\n};\n\n/** Non-exhaustive matcher for arbitrary thrown values. */\nexport interface ThrownMatcher<TResult> {\n  /** Register a local Error-constructor case. */\n  with<T extends Error, const R>(\n    constructor: ErrorClass<T>,\n    handler: (error: T) => R,\n  ): ThrownMatcher<TResult | R>;\n\n  /** Register a case for a non-empty group of local Error constructors. */\n  withAny<const C extends readonly [ErrorClass, ...ErrorClass[]], const R>(\n    constructors: C,\n    handler: (error: InstanceType<C[number]>) => R,\n  ): ThrownMatcher<TResult | R>;\n\n  /** Register a narrowing type guard. */\n  when<T, const R>(\n    guard: TypeGuard<T>,\n    handler: (value: T) => R,\n  ): ThrownMatcher<TResult | R>;\n\n  /** Register a boolean predicate without static narrowing. */\n  when<const R>(\n    predicate: (value: unknown) => boolean,\n    handler: (value: unknown) => R,\n  ): ThrownMatcher<TResult | R>;\n\n  /** Evaluate the registered cases and handle an unmatched value. */\n  otherwise<const R>(handler: (value: unknown) => R): TResult | R;\n}\n\nfunction createMatcher<TResult>(\n  value: unknown,\n  cases: readonly MatcherCase[],\n): ThrownMatcher<TResult> {\n  return {\n    with<T extends Error, const R>(\n      constructor: ErrorClass<T>,\n      handler: (error: T) => R,\n    ): ThrownMatcher<TResult | R> {\n      const nextCase: MatcherCase = {\n        test: (candidate) => candidate instanceof constructor,\n        run: (candidate) => handler(candidate as T),\n      };\n\n      return createMatcher<TResult | R>(value, [...cases, nextCase]);\n    },\n\n    withAny<const C extends readonly [ErrorClass, ...ErrorClass[]], const R>(\n      constructors: C,\n      handler: (error: InstanceType<C[number]>) => R,\n    ): ThrownMatcher<TResult | R> {\n      const snapshot = [...constructors];\n      const nextCase: MatcherCase = {\n        test: (candidate) =>\n          snapshot.some((constructor) => candidate instanceof constructor),\n        run: (candidate) => handler(candidate as InstanceType<C[number]>),\n      };\n\n      return createMatcher<TResult | R>(value, [...cases, nextCase]);\n    },\n\n    when<T, const R>(\n      predicate: TypeGuard<T> | ((value: unknown) => boolean),\n      handler: (value: T) => R,\n    ): ThrownMatcher<TResult | R> {\n      const nextCase: MatcherCase = {\n        test: predicate,\n        run: (candidate) => handler(candidate as T),\n      };\n\n      return createMatcher<TResult | R>(value, [...cases, nextCase]);\n    },\n\n    otherwise<const R>(handler: (value: unknown) => R): TResult | R {\n      for (const matchCase of cases) {\n        if (matchCase.test(value)) {\n          return matchCase.run(value) as TResult;\n        }\n      }\n      return handler(value);\n    },\n  };\n}\n\n/** Start an immutable, first-match-wins matcher for an arbitrary thrown value. */\nexport function matchThrown(value: unknown): ThrownMatcher<never> {\n  return createMatcher<never>(value, []);\n}\n","import type { ErrorClass } from \"./guards.js\";\n\n/** A keyed set of local Error constructors. */\nexport type ErrorClassMap = Readonly<Record<string, ErrorClass>>;\n\ntype ErrorClassHandlers<TClasses extends ErrorClassMap> = {\n  readonly [K in keyof TClasses]: (error: InstanceType<TClasses[K]>) => unknown;\n};\n\ntype MatchResult<THandlers> = THandlers[keyof THandlers] extends (\n  ...args: never[]\n) => infer R\n  ? R\n  : never;\n\ntype ValidClassDefinition<TClasses extends ErrorClassMap> = [\n  keyof TClasses,\n] extends [never]\n  ? never\n  : string extends keyof TClasses\n    ? never\n    : Exclude<keyof TClasses, string> extends never\n      ? Extract<keyof TClasses, `${number}`> extends never\n        ? TClasses\n        : never\n      : never;\n\n/** A reusable, exhaustive matcher for a closed set of Error classes. */\nexport interface ErrorClassSet<TClasses extends ErrorClassMap> {\n  /** Match a value using exactly one handler for every declared class key. */\n  match<const THandlers extends ErrorClassHandlers<TClasses>>(\n    value: unknown,\n    handlers: THandlers &\n      Record<Exclude<keyof THandlers, keyof TClasses>, never>,\n  ): MatchResult<THandlers>;\n}\n\n/** Define a reusable, exhaustive set of local Error classes. */\nexport function defineErrorClassSet<const TClasses extends ErrorClassMap>(\n  classes: ValidClassDefinition<TClasses>,\n): ErrorClassSet<TClasses> {\n  const ownKeys = Reflect.ownKeys(classes);\n  if (ownKeys.some((key) => typeof key !== \"string\")) {\n    throw new Error(\"defineErrorClassSet: keys must be strings\");\n  }\n\n  const keys = Object.keys(classes) as Array<Extract<keyof TClasses, string>>;\n  if (keys.length === 0) {\n    throw new Error(\"defineErrorClassSet: class definition must not be empty\");\n  }\n  if (keys.some((key) => key.trim() === \"\")) {\n    throw new Error(\n      \"defineErrorClassSet: keys must not be empty or whitespace-only\",\n    );\n  }\n  if (keys.some((key) => Number.isFinite(Number(key)))) {\n    throw new Error(\"defineErrorClassSet: keys must not be numeric\");\n  }\n\n  const snapshot = Object.freeze({ ...classes }) as TClasses;\n  const constructors = keys.map((key) => snapshot[key]);\n  if (new Set(constructors).size !== constructors.length) {\n    throw new Error(\"defineErrorClassSet: constructors must be unique\");\n  }\n\n  // match() is first-match-wins in key order, so a base class listed before\n  // one of its subclasses would silently make the subclass handler\n  // unreachable; surface that as a definition error with the fix in the text.\n  for (let earlier = 0; earlier < constructors.length; earlier++) {\n    for (let later = earlier + 1; later < constructors.length; later++) {\n      const earlierClass = constructors[earlier] as ErrorClass;\n      const laterClass = constructors[later] as ErrorClass;\n      if (laterClass.prototype instanceof earlierClass) {\n        throw new Error(\n          `defineErrorClassSet: \"${keys[later] as string}\" extends \"${keys[earlier] as string}\" ` +\n            \"and is listed after it; list subclasses before their base class, \" +\n            \"or the subclass handler is unreachable\",\n        );\n      }\n    }\n  }\n\n  return Object.freeze({\n    match<const THandlers extends ErrorClassHandlers<TClasses>>(\n      value: unknown,\n      handlers: THandlers &\n        Record<Exclude<keyof THandlers, keyof TClasses>, never>,\n    ): MatchResult<THandlers> {\n      for (const key of keys) {\n        const constructor = snapshot[key] as ErrorClass;\n        if (value instanceof constructor) {\n          const handler = handlers[key] as (\n            error: InstanceType<TClasses[typeof key]>,\n          ) => MatchResult<THandlers>;\n          return handler(value as InstanceType<TClasses[typeof key]>);\n        }\n      }\n\n      throw new Error(\"value is outside the declared error class set\");\n    },\n  });\n}\n","import { StructuredError } from \"./StructuredError.js\";\nimport type { RedactMask } from \"./BaseError.js\";\n\n/** JSON-safe static metadata supported by catalog definitions. */\nexport type CatalogJsonValue =\n  | null\n  | boolean\n  | number\n  | string\n  | readonly CatalogJsonValue[]\n  | { readonly [key: string]: CatalogJsonValue };\n\n/** Static boundary metadata attached to one catalog definition. */\nexport type CatalogMetadata = Readonly<Record<string, CatalogJsonValue>>;\n\ndeclare const DETAILS_TYPE: unique symbol;\n\n/** Compile-time-only marker for one error code's details shape. */\nexport type DetailsType<T extends Record<string, unknown>> = {\n  readonly [DETAILS_TYPE]: T;\n};\n\n/** Declare an error code's details type without a consumer-side cast. */\nexport function detailsType<\n  T extends Record<string, unknown>,\n>(): DetailsType<T> {\n  return Object.freeze({}) as unknown as DetailsType<T>;\n}\n\n/** Declarative log-redaction policy applied by every generated factory. */\nexport type CatalogRedactionPolicy =\n  | {\n      readonly mode: \"deny\";\n      readonly keys: readonly string[];\n      readonly mask?: RedactMask;\n    }\n  | {\n      readonly mode: \"allow\";\n      readonly keys: readonly string[];\n      readonly mask?: RedactMask;\n    };\n\n/**\n * Declarative spec for a single error code in a catalog.\n *\n * `details` is a compile-time marker created by {@link detailsType}.\n */\nexport type ErrorSpec = {\n  /** Internal category for this code. */\n  category: string;\n  /** Whether the failed operation can be retried. */\n  retryable: boolean;\n  /** JSON-safe static metadata for transport and boundary adapters. */\n  metadata?: CatalogMetadata;\n  /** Type marker for this code's structured details. */\n  details?: DetailsType<Record<string, unknown>>;\n  /** Sticky log-redaction policy applied to generated instances. */\n  redaction?: CatalogRedactionPolicy;\n};\n\n/** A reusable finite catalog definition. Prefer `satisfies` over annotation. */\nexport type ErrorCatalogDefinition = Readonly<Record<string, ErrorSpec>>;\n\ntype InvalidCatalogSpec<T extends ErrorCatalogDefinition> = {\n  [K in keyof T]: Exclude<keyof T[K], keyof ErrorSpec> extends never\n    ? T[K] extends { redaction: infer R }\n      ? Exclude<keyof R, keyof CatalogRedactionPolicy> extends never\n        ? never\n        : K\n      : never\n    : K;\n}[keyof T];\n\ntype ValidCatalogDefinition<T extends ErrorCatalogDefinition> = [\n  keyof T,\n] extends [never]\n  ? never\n  : string extends keyof T\n    ? never\n    : Exclude<keyof T, string> extends never\n      ? InvalidCatalogSpec<T> extends never\n        ? unknown\n        : never\n      : never;\n\ntype CatalogValidationArgs<T extends ErrorCatalogDefinition> = [\n  ValidCatalogDefinition<T>,\n] extends [never]\n  ? [invalidCatalog: never]\n  : \"\" extends keyof T\n    ? [invalidCatalog: never]\n    : [];\n\ntype CategoryOf<S> = S extends { category: infer C extends string }\n  ? C\n  : string;\n\ntype RetryableOf<S> = S extends { retryable: infer R extends boolean }\n  ? R\n  : boolean;\n\n/** Immutable static metadata returned by `Catalog.meta()`. */\nexport type CatalogMeta<S extends ErrorSpec> = {\n  readonly category: CategoryOf<S>;\n  readonly retryable: RetryableOf<S>;\n} & (S extends { metadata: infer M extends CatalogMetadata }\n  ? { readonly metadata: M }\n  : Record<never, never>);\n\n/** Options accepted by a generated factory (shared, non-details part). */\ntype FactoryBaseOptions = {\n  /** Underlying cause to preserve in the chain. */\n  cause?: unknown;\n};\n\n/**\n * The factory signature for one code. `details` is required when the spec\n * declares a details shape, and the whole options argument is optional when it\n * does not.\n */\ntype FactoryFor<K extends string, S> = S extends {\n  details: DetailsType<infer D extends Record<string, unknown>>;\n}\n  ? (\n      message: string,\n      options: FactoryBaseOptions & { details: D },\n    ) => StructuredError<K, CategoryOf<S>, D>\n  : (\n      message: string,\n      options?: FactoryBaseOptions,\n    ) => StructuredError<K, CategoryOf<S>, Record<string, never>>;\n\n/** Typed factory namespace produced by {@link defineErrors}. */\ntype CatalogFactories<T extends Record<string, ErrorSpec>> = {\n  [K in keyof T]: FactoryFor<K & string, T[K]>;\n};\n\n/** The object returned by {@link defineErrors}. */\nexport type Catalog<T extends ErrorCatalogDefinition> = {\n  /** Factory namespace with one precisely typed constructor per error code. */\n  readonly create: CatalogFactories<T>;\n  /** Finite runtime list of the catalog's error codes. */\n  readonly codes: readonly (keyof T & string)[];\n  /** Returns immutable core fields and static boundary metadata for a code. */\n  meta<K extends keyof T>(code: K): CatalogMeta<T[K]>;\n  /** Recognize any error created by this exact catalog. */\n  is(value: unknown): value is CatalogError<Catalog<T>>;\n  /** Recognize one code created by this exact catalog. */\n  is<K extends keyof T & string>(\n    value: unknown,\n    code: K,\n  ): value is CatalogErrorOf<Catalog<T>, K>;\n};\n\n/**\n * The union of every error type a catalog can produce. Pass this closed set to\n * {@link matchError}. `meta` is excluded automatically.\n *\n * @example\n * ```ts\n * const AppErrors = defineErrors({ ... });\n * type AppError = CatalogError<typeof AppErrors>;\n * ```\n */\nexport type CatalogError<C extends { create: Record<string, unknown> }> = {\n  [K in keyof C[\"create\"]]: C[\"create\"][K] extends (...args: never[]) => infer R\n    ? R extends StructuredError<string, string>\n      ? R\n      : never\n    : never;\n}[keyof C[\"create\"]];\n\n/** Extract one generated error type from a catalog by its code. */\nexport type CatalogErrorOf<\n  C extends { create: Record<string, unknown> },\n  K extends keyof C[\"create\"],\n> = C[\"create\"][K] extends (...args: never[]) => infer R\n  ? R extends StructuredError<string, string>\n    ? R\n    : never\n  : never;\n\ntype RuntimeSpec = {\n  readonly category: string;\n  readonly retryable: boolean;\n  readonly metadata?: CatalogMetadata;\n  readonly redaction?: CatalogRedactionPolicy;\n};\n\n/**\n * Total-node budget for one metadata snapshot. Shared (DAG) references are\n * cloned once per reference, so a small definition could legally expand\n * exponentially; past the budget it is rejected like any other non-JSON-safe\n * metadata. Definition-time and developer-facing, so failing fast is correct.\n */\nconst MAX_METADATA_NODES = 100_000;\n\nfunction cloneJsonValue(\n  value: unknown,\n  seen: Set<object>,\n  state: { nodes: number },\n): CatalogJsonValue {\n  if (++state.nodes > MAX_METADATA_NODES) {\n    throw new Error(\"defineErrors: metadata must be JSON-safe\");\n  }\n  if (\n    value === null ||\n    typeof value === \"string\" ||\n    typeof value === \"boolean\"\n  ) {\n    return value;\n  }\n  if (typeof value === \"number\") {\n    if (Number.isFinite(value)) return value;\n    throw new Error(\"defineErrors: metadata must be JSON-safe\");\n  }\n  if (typeof value !== \"object\") {\n    throw new Error(\"defineErrors: metadata must be JSON-safe\");\n  }\n  if (seen.has(value)) {\n    throw new Error(\"defineErrors: metadata must be JSON-safe\");\n  }\n\n  seen.add(value);\n  try {\n    if (Array.isArray(value)) {\n      for (let index = 0; index < value.length; index++) {\n        if (!Object.prototype.hasOwnProperty.call(value, index)) {\n          throw new Error(\"defineErrors: metadata must be JSON-safe\");\n        }\n      }\n      return Object.freeze(\n        value.map((item) => cloneJsonValue(item, seen, state)),\n      ) as readonly CatalogJsonValue[];\n    }\n\n    const prototype = Object.getPrototypeOf(value) as unknown;\n    if (prototype !== Object.prototype && prototype !== null) {\n      throw new Error(\"defineErrors: metadata must be JSON-safe\");\n    }\n    if (Object.getOwnPropertySymbols(value).length > 0) {\n      throw new Error(\"defineErrors: metadata must be JSON-safe\");\n    }\n\n    const clone = Object.create(null) as Record<string, CatalogJsonValue>;\n    for (const [key, item] of Object.entries(value)) {\n      clone[key] = cloneJsonValue(item, seen, state);\n    }\n    return Object.freeze(clone);\n  } finally {\n    seen.delete(value);\n  }\n}\n\nfunction snapshotRedaction(value: unknown): CatalogRedactionPolicy | undefined {\n  if (value === undefined) return undefined;\n  if (typeof value !== \"object\" || value === null) {\n    throw new Error(\"defineErrors: invalid redaction policy\");\n  }\n\n  const allowedKeys = new Set([\"mode\", \"keys\", \"mask\"]);\n  for (const key of Reflect.ownKeys(value)) {\n    if (typeof key !== \"string\" || !allowedKeys.has(key)) {\n      throw new Error(`defineErrors: unknown redaction field \"${String(key)}\"`);\n    }\n  }\n\n  const policy = value as Partial<CatalogRedactionPolicy>;\n  if (\n    (policy.mode !== \"deny\" && policy.mode !== \"allow\") ||\n    !Array.isArray(policy.keys) ||\n    !policy.keys.every((key) => typeof key === \"string\") ||\n    (policy.mask !== undefined &&\n      typeof policy.mask !== \"string\" &&\n      typeof policy.mask !== \"function\")\n  ) {\n    throw new Error(\"defineErrors: invalid redaction policy\");\n  }\n\n  return Object.freeze({\n    mode: policy.mode,\n    keys: Object.freeze([...policy.keys]),\n    ...(policy.mask !== undefined && { mask: policy.mask }),\n  });\n}\n\n/**\n * Define a catalog of structured errors from a declarative spec.\n *\n * Returns an immutable catalog with namespaced factories, static metadata,\n * local provenance guards, and optional catalog-level redaction. Errors are\n * tagged instances of `StructuredError` discriminated by `code`.\n *\n * @example\n * ```ts\n * const AppErrors = defineErrors({\n *   USER_NOT_FOUND: {\n *     category: \"NOT_FOUND\",\n *     retryable: false,\n *     metadata: { httpStatus: 404 },\n *     details: detailsType<{ userId: string }>(),\n *   },\n *   RATE_LIMITED: {\n *     category: \"RATE_LIMIT\",\n *     retryable: true,\n *     metadata: { httpStatus: 429 },\n *   },\n * });\n *\n * throw AppErrors.create.USER_NOT_FOUND(\"user 123 missing\", {\n *   details: { userId: \"123\" },\n * });\n *\n * const status = AppErrors.meta(err.code).metadata.httpStatus;\n * ```\n */\nexport function defineErrors<const T extends ErrorCatalogDefinition>(\n  catalog: T,\n  ..._validation: CatalogValidationArgs<T>\n): Catalog<T>;\nexport function defineErrors(\n  catalog: ErrorCatalogDefinition,\n): Catalog<ErrorCatalogDefinition> {\n  if (\n    typeof catalog !== \"object\" ||\n    catalog === null ||\n    Array.isArray(catalog) ||\n    (Object.getPrototypeOf(catalog) !== Object.prototype &&\n      Object.getPrototypeOf(catalog) !== null)\n  ) {\n    throw new Error(\"defineErrors: catalog must be a plain object\");\n  }\n\n  const ownKeys = Reflect.ownKeys(catalog);\n  if (ownKeys.some((code) => typeof code !== \"string\")) {\n    throw new Error(\"defineErrors: error codes must be strings\");\n  }\n  if (ownKeys.includes(\"\")) {\n    throw new Error(\"defineErrors: error codes must not be empty\");\n  }\n\n  const create = Object.create(null) as Record<string, unknown>;\n  const provenance = new WeakMap<object, string>();\n  const codes = Object.keys(catalog);\n  if (codes.length === 0) {\n    throw new Error(\"defineErrors: catalog must not be empty\");\n  }\n\n  const snapshot = Object.create(null) as Record<string, RuntimeSpec>;\n  const metaSnapshot = Object.create(null) as Record<\n    string,\n    CatalogMeta<ErrorSpec>\n  >;\n  const allowedSpecKeys = new Set([\n    \"category\",\n    \"retryable\",\n    \"metadata\",\n    \"details\",\n    \"redaction\",\n  ]);\n\n  for (const code of codes) {\n    const spec = catalog[code] as ErrorSpec;\n    if (\n      typeof spec !== \"object\" ||\n      spec === null ||\n      typeof spec.category !== \"string\" ||\n      spec.category.length === 0 ||\n      typeof spec.retryable !== \"boolean\"\n    ) {\n      throw new Error(`defineErrors: invalid definition for code \"${code}\"`);\n    }\n    for (const key of Reflect.ownKeys(spec)) {\n      if (typeof key !== \"string\" || !allowedSpecKeys.has(key)) {\n        throw new Error(\n          `defineErrors: unknown definition field \"${String(key)}\" for code \"${code}\"`,\n        );\n      }\n    }\n\n    if (\n      spec.metadata !== undefined &&\n      (typeof spec.metadata !== \"object\" ||\n        spec.metadata === null ||\n        Array.isArray(spec.metadata))\n    ) {\n      throw new Error(\"defineErrors: metadata must be an object\");\n    }\n    const metadata =\n      spec.metadata === undefined\n        ? undefined\n        : (cloneJsonValue(spec.metadata, new Set(), {\n            nodes: 0,\n          }) as CatalogMetadata);\n    const redaction = snapshotRedaction(spec.redaction);\n\n    snapshot[code] = Object.freeze({\n      category: spec.category,\n      retryable: spec.retryable,\n      ...(metadata !== undefined && { metadata }),\n      ...(redaction !== undefined && { redaction }),\n    });\n    metaSnapshot[code] = Object.freeze({\n      category: spec.category,\n      retryable: spec.retryable,\n      ...(metadata !== undefined && { metadata }),\n    });\n  }\n\n  for (const code of codes) {\n    const spec = snapshot[code] as RuntimeSpec;\n    create[code] = (\n      message: string,\n      options?: FactoryBaseOptions & { details?: Record<string, unknown> },\n    ) => {\n      const error = new StructuredError({\n        code,\n        category: spec.category,\n        retryable: spec.retryable,\n        message,\n        ...(options?.details !== undefined && { details: options.details }),\n        ...(options?.cause !== undefined && { cause: options.cause }),\n      });\n      if (spec.redaction?.mode === \"deny\") {\n        error.redact([...spec.redaction.keys], { mask: spec.redaction.mask });\n      } else if (spec.redaction?.mode === \"allow\") {\n        error.redactAllow([...spec.redaction.keys], {\n          mask: spec.redaction.mask,\n        });\n      }\n      provenance.set(error, code);\n      return error;\n    };\n  }\n\n  return Object.freeze({\n    create: Object.freeze(create),\n    codes: Object.freeze(codes),\n    meta(code: string) {\n      if (!Object.prototype.hasOwnProperty.call(snapshot, code)) {\n        throw new Error(`meta: unknown error code \"${code}\"`);\n      }\n      return metaSnapshot[code] as CatalogMeta<ErrorSpec>;\n    },\n    is(value: unknown, expectedCode?: string): boolean {\n      if (!(value instanceof StructuredError)) return false;\n\n      const actualCode = provenance.get(value);\n      if (actualCode === undefined) return false;\n      if (expectedCode !== undefined && actualCode !== expectedCode) {\n        return false;\n      }\n\n      const spec = snapshot[actualCode];\n      return (\n        spec !== undefined &&\n        value.code === actualCode &&\n        value.category === spec.category &&\n        value.retryable === spec.retryable\n      );\n    },\n  }) as unknown as Catalog<ErrorCatalogDefinition>;\n}\n","import { StructuredError } from \"./StructuredError.js\";\nimport { UNKNOWN_ERROR_DEFAULTS } from \"./defaults.js\";\n\n/** Fallback configuration for {@link toStructuredError}. */\nexport type CoerceOptions = {\n  /** Internal code for the fallback. Default: `\"UNKNOWN_ERROR\"`. */\n  code?: string;\n  /** Internal category for the fallback. Default: `\"INTERNAL\"`. */\n  category?: string;\n  /** Retryable flag for the fallback. Default: `false`. */\n  retryable?: boolean;\n  /** Override the technical message (otherwise derived from the value). */\n  message?: string;\n};\n\nexport function toStructuredError(\n  value: unknown,\n  options: CoerceOptions = {},\n): StructuredError<string, string> {\n  // Pass-through: an existing structured error keeps its own identity. The\n  // return type is intentionally `StructuredError<string, string>` (not the\n  // option literals) because pass-through can return any code/category.\n  if (value instanceof StructuredError) {\n    return value;\n  }\n\n  const code = options.code ?? UNKNOWN_ERROR_DEFAULTS.code;\n  const category = options.category ?? UNKNOWN_ERROR_DEFAULTS.category;\n  const retryable = options.retryable ?? UNKNOWN_ERROR_DEFAULTS.retryable;\n\n  let message: string;\n  let cause: unknown;\n  if (value instanceof Error) {\n    message = options.message ?? value.message;\n    cause = value;\n  } else if (typeof value === \"string\") {\n    message = options.message ?? value;\n    cause = undefined;\n  } else {\n    message = options.message ?? UNKNOWN_ERROR_DEFAULTS.message;\n    // Preserve the raw value (object/number/null) for observability.\n    cause = value;\n  }\n\n  return new StructuredError<string, string>({\n    code,\n    category,\n    retryable,\n    message,\n    ...(cause !== undefined && { cause }),\n  });\n}\n","import { StructuredError } from \"./StructuredError.js\";\n\n/**\n * A single validation issue. Structurally identical to Standard Schema's\n * `Issue` (standardschema.dev), so Zod / Valibot / ArkType / TanStack Form\n * output pipes in unchanged, with no dependency. Extra fields a validator\n * attaches are kept for logs but never cross to a client.\n */\nexport type ValidationIssue = {\n  /** Human-readable message. Keep it client-safe if you choose to expose it. */\n  readonly message: string;\n  /** Path to the offending value (Standard Schema form). */\n  readonly path?: ReadonlyArray<PropertyKey | { readonly key: PropertyKey }>;\n};\n\n/** The fixed, client-safe shape an issue takes on the wire. */\nexport type PublicIssue = {\n  message: string;\n  path?: ReadonlyArray<PropertyKey | { readonly key: PropertyKey }>;\n  /** Included only when the source issue carried one. */\n  code?: string;\n  /** Derived string path (e.g. \"address.zip\") for HTTP clients. */\n  pointer?: string;\n};\n\n/** Options for {@link ValidationError}. */\nexport type ValidationErrorOptions<\n  TCode extends string,\n  TCategory extends string,\n> = {\n  issues?: ValidationIssue[];\n  cause?: unknown;\n  /** Override the code (default `\"VALIDATION_FAILED\"`). */\n  code?: TCode;\n  /** Override the category (default `\"VALIDATION\"`). */\n  category?: TCategory;\n};\n\n/** Options for {@link ValidationError.publicIssues}. */\nexport type PublicIssuesOptions = {\n  /**\n   * Fully customize the wire shape (e.g. RFC-7807 `{ name, reason }`).\n   * Replaces the default whitelist entirely: a custom mapper receives the raw\n   * issue (validator extras included) and must apply its own whitelist,\n   * including copying `path` and narrowing object segments to `{ key }` if it\n   * forwards them.\n   */\n  mapIssue?: (issue: ValidationIssue) => PublicIssue;\n};\n\n/**\n * Aggregate error for validation: collects N field-level issues into one\n * `StructuredError`. Issues are stored in full for logs, but only ever cross to\n * a client through the safe `publicIssues()` whitelist, on explicit opt-in.\n *\n * @example\n * ```ts\n * const v = new ValidationError(\"Registration is invalid\");\n * if (!isEmail(email)) v.addIssue({ message: \"Enter a valid email.\", path: [\"email\"] });\n * if (v.hasIssues()) throw v;\n *\n * // or ingest a Standard Schema validator's output directly:\n * const result = schema[\"~standard\"].validate(input);\n * if (result.issues) throw new ValidationError(\"Invalid input\", { issues: result.issues });\n * ```\n */\nexport class ValidationError<\n  TCode extends string = \"VALIDATION_FAILED\",\n  TCategory extends string = \"VALIDATION\",\n> extends StructuredError<TCode, TCategory, { issues: ValidationIssue[] }> {\n  public override readonly _tag: string = \"ValidationError\";\n\n  /** Live array shared by reference with `details.issues` (full, with extras). */\n  readonly #issues: ValidationIssue[];\n\n  public constructor(\n    message: string,\n    options?: ValidationErrorOptions<TCode, TCategory>,\n  ) {\n    const issues = options?.issues ? [...options.issues] : [];\n    super({\n      code: (options?.code ?? \"VALIDATION_FAILED\") as TCode,\n      category: (options?.category ?? \"VALIDATION\") as TCategory,\n      retryable: false,\n      message,\n      details: { issues },\n      ...(options?.cause !== undefined && { cause: options.cause }),\n    });\n    this.#issues = issues;\n  }\n\n  public addIssue(issue: ValidationIssue): this {\n    this.#issues.push(issue);\n    return this;\n  }\n\n  public addIssues(issues: ValidationIssue[]): this {\n    this.#issues.push(...issues);\n    return this;\n  }\n\n  public hasIssues(): boolean {\n    return this.#issues.length > 0;\n  }\n\n  public get issues(): readonly ValidationIssue[] {\n    return this.#issues;\n  }\n\n  /**\n   * Client-safe projection of the issues. Returns only the fixed whitelist\n   * (`message`, `path`, `code?`, `pointer?`); raw validator extras are never included.\n   * Provide `mapIssue` to emit a fully custom wire shape (e.g. RFC-7807\n   * `{ name, reason }`).\n   */\n  public publicIssues(options?: PublicIssuesOptions): PublicIssue[] {\n    const mapIssue = options?.mapIssue ?? ValidationError.#defaultProjection;\n    return this.#issues.map(mapIssue);\n  }\n\n  static #defaultProjection(issue: ValidationIssue): PublicIssue {\n    const out: PublicIssue = { message: issue.message };\n    if (issue.path !== undefined) {\n      // Fresh copy with object segments narrowed to { key }: a validator may\n      // attach internals to segment objects, and the whitelist must not carry\n      // them (or a shared array reference) to the wire.\n      out.path = issue.path.map((segment) =>\n        typeof segment === \"object\" && segment !== null\n          ? { key: segment.key }\n          : segment,\n      );\n      out.pointer = ValidationError.#toPointer(issue.path);\n    }\n    const code = (issue as { code?: unknown }).code;\n    if (typeof code === \"string\") {\n      out.code = code;\n    }\n    return out;\n  }\n\n  static #toPointer(\n    path: ReadonlyArray<PropertyKey | { readonly key: PropertyKey }>,\n  ): string {\n    return path\n      .map((segment) => (typeof segment === \"object\" ? segment.key : segment))\n      .map((key) => String(key))\n      .join(\".\");\n  }\n}\n","import type { BaseError } from \"../errors/BaseError.js\";\n\n/**\n * Asserts that a condition is truthy, throwing the provided error if it's falsy.\n * This function provides TypeScript type narrowing through assertion signatures.\n *\n * @template T - The error name type extending string\n * @param condition - The value to check for truthiness\n * @param error - The BaseError instance to throw if condition is falsy\n * @throws {BaseError<T>} The provided error when condition is falsy\n *\n * @example\n * ```ts\n * const user = getUser();\n * guard(user, new UserNotFoundError(\"User not found\"));\n * // TypeScript now knows user is not null/undefined\n * console.log(user.name);\n * ```\n *\n * @example\n * ```ts\n * guard(isValidEmail(email), new ValidationError(\"Invalid email format\"));\n * // Continues execution only if email is valid\n * ```\n *\n * @example\n * ```ts\n * // Pass a factory to avoid constructing the error on the happy path.\n * guard(user, () => new UserNotFoundError(id));\n * ```\n */\nexport function guard<T extends string>(\n  condition: unknown,\n  error: BaseError<T> | (() => BaseError<T>),\n): asserts condition {\n  if (!condition) {\n    throw typeof error === \"function\" ? error() : error;\n  }\n}\n","import type { RedactMask } from \"../errors/BaseError.js\";\n\n/**\n * Builds a {@link RedactMask} that reveals a prefix and/or suffix of a string\n * value and masks the middle (e.g. to show *which* API key it was without\n * exposing it, as in `sk_live…AbCd`).\n *\n * Safe by construction:\n * - a value too short to safely reveal (`length <= keepStart + keepEnd`) is\n *   masked **entirely**, never partially exposed;\n * - non-string values are masked entirely.\n *\n * @param options - `keepStart` (default 0), `keepEnd` (default 4), `fill`\n *   (default `\"…\"`, also used as the full mask for short/non-string values).\n *\n * @example\n * ```ts\n * err.redact([\"apiKey\"], { mask: partialMask({ keepStart: 7, keepEnd: 4 }) });\n * // \"sk_live_51HxYz...AbCd\" -> \"sk_live…AbCd\"\n * ```\n */\nexport function partialMask(options?: {\n  keepStart?: number;\n  keepEnd?: number;\n  fill?: string;\n}): RedactMask {\n  const keepStart = options?.keepStart ?? 0;\n  const keepEnd = options?.keepEnd ?? 4;\n  const fill = options?.fill ?? \"…\";\n\n  return (value) => {\n    // Non-strings, and strings too short to safely reveal, are masked entirely.\n    if (typeof value !== \"string\" || value.length <= keepStart + keepEnd) {\n      return fill;\n    }\n    const start = value.slice(0, keepStart);\n    // Use length - keepEnd (not slice(-keepEnd)) to avoid the keepEnd === 0\n    // `-0` trap, which would otherwise reveal the whole string.\n    const end = value.slice(value.length - keepEnd);\n    return start + fill + end;\n  };\n}\n","/**\n * Type guard functions for error type narrowing.\n */\n\nimport { BaseError } from \"./BaseError.js\";\nimport { StructuredError } from \"./StructuredError.js\";\n\n/** Portable fields shared by native and structurally recognized errors. */\nexport type ErrorLike = {\n  readonly name: string;\n  readonly message: string;\n  readonly stack?: string;\n};\n\n/** A reusable predicate that narrows an unknown value to `T`. */\nexport type TypeGuard<T> = (value: unknown) => value is T;\n\n/** Constructor for an Error subclass with any concrete argument list. */\nexport type ErrorClass<T extends Error = Error> = abstract new (\n  ...args: never[]\n) => T;\n\ntype GuardTarget<G> = G extends TypeGuard<infer T> ? T : never;\n\ntype UnionToIntersection<U> = (\n  U extends unknown ? (value: U) => void : never\n) extends (value: infer I) => void\n  ? I\n  : never;\n\ntype GuardIntersection<G extends readonly TypeGuard<unknown>[]> =\n  UnionToIntersection<GuardTarget<G[number]>>;\n\n/**\n * Checks for a native Error or a structurally equivalent cross-realm value.\n * Structural matches establish shape only, not trusted domain identity.\n */\nexport function isError(value: unknown): value is ErrorLike {\n  try {\n    if (typeof value !== \"object\" || value === null || Array.isArray(value)) {\n      return false;\n    }\n\n    const { name, message, stack } = value as Record<string, unknown>;\n    return (\n      typeof name === \"string\" &&\n      typeof message === \"string\" &&\n      (stack === undefined || typeof stack === \"string\")\n    );\n  } catch {\n    return false;\n  }\n}\n\n/** Creates a guard for an error-like value with an exact string or numeric code. */\nexport function hasErrorCode<const C extends string | number>(\n  code: C,\n): TypeGuard<ErrorLike & { readonly code: C }> {\n  return (value: unknown): value is ErrorLike & { readonly code: C } => {\n    if (!isError(value)) return false;\n\n    try {\n      return (value as ErrorLike & { readonly code?: unknown }).code === code;\n    } catch {\n      return false;\n    }\n  };\n}\n\n/** Creates an instanceof guard with an optional additional runtime predicate. */\nexport function isErrorOf<T extends Error>(\n  constructor: ErrorClass<T>,\n  predicate?: (error: T) => boolean,\n): TypeGuard<T> {\n  return (value: unknown): value is T =>\n    value instanceof constructor &&\n    (predicate === undefined || predicate(value));\n}\n\n/** Checks whether a value is an instance of any listed Error constructor. */\nexport function isAnyErrorOf<const C extends readonly ErrorClass[]>(\n  value: unknown,\n  constructors: C,\n): value is InstanceType<C[number]> {\n  return constructors.some((constructor) => value instanceof constructor);\n}\n\n/** Checks that a value satisfies every guard and narrows to their intersection. */\nexport function isAllOf<\n  const G extends readonly [TypeGuard<unknown>, ...TypeGuard<unknown>[]],\n>(value: unknown, guards: G): value is GuardIntersection<G> {\n  return guards.every((guard) => guard(value));\n}\n\n/**\n * Type guard to check if a value is a BaseError instance.\n *\n * @param value - The value to check\n * @returns True if the value is a BaseError instance\n *\n * @example\n * ```ts\n * try {\n *   await someOperation();\n * } catch (error) {\n *   if (isBaseError(error)) {\n *     console.log(error.timestamp);    // TypeScript knows this exists\n *     console.log(error.timestampIso);\n *   }\n * }\n * ```\n */\nexport function isBaseError(value: unknown): value is BaseError<string> {\n  return value instanceof BaseError;\n}\n\n/**\n * Type guard to check if a value is a StructuredError.\n *\n * Uses a two-phase check:\n * 1. Fast path: `instanceof` check for real StructuredError instances\n * 2. Fallback: Duck-typing for cross-realm objects, serialized errors, or plain objects\n *\n * @param value - The value to check\n * @returns True if the value is a StructuredError or has the StructuredError shape\n *\n * @example\n * ```ts\n * try {\n *   await someOperation();\n * } catch (error) {\n *   if (isStructuredError(error)) {\n *     console.log(error.code);      // TypeScript knows this exists\n *     console.log(error.category);\n *     console.log(error.retryable);\n *\n *     if (error.retryable) {\n *       // Retry logic\n *     }\n *   }\n * }\n * ```\n */\nexport function isStructuredError(\n  value: unknown,\n): value is StructuredError<string, string> {\n  // Fast path: instanceof check\n  if (value instanceof StructuredError) return true;\n\n  // Fallback: duck-typing for cross-realm or serialized errors\n  if (typeof value !== \"object\" || value === null) return false;\n\n  const err = value as Record<string, unknown>;\n  return (\n    typeof err.code === \"string\" &&\n    typeof err.category === \"string\" &&\n    typeof err.retryable === \"boolean\"\n  );\n}\n\n/**\n * Type guard to check if an error is retryable.\n * Works with any error that has a `retryable` property (duck-typing).\n *\n * @param value - The value to check\n * @returns True if the value has retryable === true\n *\n * @example\n * ```ts\n * try {\n *   await someOperation();\n * } catch (error) {\n *   if (isRetryable(error)) {\n *     // Safe to retry\n *     await retry(someOperation);\n *   } else {\n *     // Don't retry, handle error\n *     throw error;\n *   }\n * }\n * ```\n */\nexport function isRetryable(\n  value: unknown,\n): value is { retryable: true } & Record<string, unknown> {\n  return (\n    typeof value === \"object\" &&\n    value !== null &&\n    \"retryable\" in value &&\n    (value as Record<string, unknown>).retryable === true\n  );\n}\n","import { isStructuredError } from \"../errors/guards.js\";\n\n/**\n * Checks if a value has a non-empty `cause` (duck-typing).\n *\n * An explicit `cause: undefined` (as produced by `new Error(msg, { cause:\n * undefined })`) counts as no cause, so chain traversal stops there instead of\n * stepping onto a spurious `undefined`.\n *\n * @param value - The value to check\n * @returns True if the value has a `cause` property whose value is not `undefined`\n */\nexport function isErrorWithCause(value: unknown): value is { cause: unknown } {\n  return (\n    typeof value === \"object\" &&\n    value !== null &&\n    \"cause\" in value &&\n    (value as { cause: unknown }).cause !== undefined\n  );\n}\n\n/**\n * Checks if a value is a retryable StructuredError.\n *\n * @param value - The value to check\n * @returns True if the value is a StructuredError with retryable === true\n */\nexport function isRetryableStructuredError(\n  value: unknown,\n): value is { retryable: true } & Record<string, unknown> {\n  return isStructuredError(value) && value.retryable === true;\n}\n","import { isErrorWithCause } from \"./guards.js\";\n\n/**\n * Internal generator that traverses the cause chain.\n *\n * Total by design: these helpers run inside catch paths, where a circular\n * chain (a bug in someone's error wiring) must not turn a retry decision into\n * a new crash. On a cycle the traversal simply ends once the repeated node is\n * reached: at that point every node has been yielded exactly once, so nothing\n * is lost. `maxDepth` is the number of cause **hops** followed, so up to\n * `maxDepth + 1` nodes are yielded.\n *\n * @param error - The error to start traversing from\n * @param maxDepth - Maximum number of cause hops to follow\n * @yields Each error in the cause chain, from outermost to innermost, each\n *   node exactly once\n */\nfunction* traverseCauseChain(\n  error: unknown,\n  maxDepth: number,\n): Generator<unknown> {\n  let current: unknown = error;\n  const seen = new Set<unknown>();\n\n  for (let depth = 0; depth <= maxDepth; depth++) {\n    if (seen.has(current)) return;\n    seen.add(current);\n    yield current;\n\n    if (!isErrorWithCause(current)) return;\n    current = current.cause;\n  }\n}\n\n/**\n * Traverses the cause chain to find the root cause (the last error in the chain).\n *\n * @param error - The error to traverse\n * @param maxDepth - Maximum number of cause hops to follow (default: 100)\n * @returns The root cause, or the last valid error if maxDepth is exceeded.\n *   On a circular chain, the deepest error before the repeat (never throws).\n *\n * @example\n * ```typescript\n * const root = getRootCause(nestedError);\n * if (isRetryableStructuredError(root)) {\n *   // Handle retryable root cause\n * }\n * ```\n */\nexport function getRootCause(error: unknown, maxDepth: number = 100): unknown {\n  let last: unknown = error;\n  for (const current of traverseCauseChain(error, maxDepth)) {\n    last = current;\n  }\n  return last;\n}\n\n/**\n * Finds the first error in the cause chain that matches the predicate.\n *\n * @param error - The error to start traversing from\n * @param predicate - Function that returns true for matching errors\n * @param maxDepth - Maximum number of cause hops to follow (default: 100)\n * @returns The first matching error, or undefined if no match found\n *\n * @example\n * ```typescript\n * const dbError = findInCauseChain(\n *   error,\n *   (e): e is StructuredError => e.code?.startsWith(\"DB_\")\n * );\n * ```\n */\nexport function findInCauseChain<T>(\n  error: unknown,\n  predicate: (e: unknown) => e is T,\n  maxDepth?: number,\n): T | undefined;\nexport function findInCauseChain(\n  error: unknown,\n  predicate: (e: unknown) => boolean,\n  maxDepth?: number,\n): unknown;\nexport function findInCauseChain(\n  error: unknown,\n  predicate: (e: unknown) => boolean,\n  maxDepth: number = 100,\n): unknown {\n  for (const current of traverseCauseChain(error, maxDepth)) {\n    if (predicate(current)) return current;\n  }\n  return undefined;\n}\n\n/**\n * Collects all errors in the cause chain that match the predicate.\n *\n * @param error - The error to start traversing from\n * @param predicate - Function that returns true for errors to collect\n * @param maxDepth - Maximum number of cause hops to follow (default: 100)\n * @returns Array of matching errors, ordered from outermost to innermost\n *\n * @example\n * ```typescript\n * const allRetryable = filterCauseChain(\n *   error,\n *   (e): e is StructuredError & { retryable: true } =>\n *     isRetryableStructuredError(e)\n * );\n * ```\n */\nexport function filterCauseChain<T>(\n  error: unknown,\n  predicate: (e: unknown) => e is T,\n  maxDepth?: number,\n): T[];\nexport function filterCauseChain(\n  error: unknown,\n  predicate: (e: unknown) => boolean,\n  maxDepth?: number,\n): unknown[];\nexport function filterCauseChain(\n  error: unknown,\n  predicate: (e: unknown) => boolean,\n  maxDepth: number = 100,\n): unknown[] {\n  const results: unknown[] = [];\n  for (const current of traverseCauseChain(error, maxDepth)) {\n    if (predicate(current)) results.push(current);\n  }\n  return results;\n}\n\n/**\n * Checks if any error in the cause chain matches the predicate.\n *\n * @param error - The error to start traversing from\n * @param predicate - Function that returns true for matching errors\n * @param maxDepth - Maximum number of cause hops to follow (default: 100)\n * @returns True if at least one error matches the predicate. A circular\n *   chain is evaluated over each distinct node (never throws).\n *\n * @example\n * ```typescript\n * const hasRetryable = someCauseChain(\n *   error,\n *   (e) => isRetryableStructuredError(e)\n * );\n * ```\n */\nexport function someCauseChain(\n  error: unknown,\n  predicate: (e: unknown) => boolean,\n  maxDepth: number = 100,\n): boolean {\n  return findInCauseChain(error, predicate, maxDepth) !== undefined;\n}\n\n/**\n * Checks if all errors in the cause chain match the predicate.\n *\n * @param error - The error to start traversing from\n * @param predicate - Function that returns true for matching errors\n * @param maxDepth - Maximum number of cause hops to follow (default: 100)\n * @returns True if all errors match the predicate, or if the chain is empty.\n *   A circular chain is evaluated over each distinct node (never throws).\n *\n * @example\n * ```typescript\n * const allAreRetryable = everyCauseChain(\n *   error,\n *   (e) => isRetryableStructuredError(e)\n * );\n * ```\n */\nexport function everyCauseChain(\n  error: unknown,\n  predicate: (e: unknown) => boolean,\n  maxDepth: number = 100,\n): boolean {\n  for (const current of traverseCauseChain(error, maxDepth)) {\n    if (!predicate(current)) return false;\n  }\n  return true;\n}\n","import { isRetryable } from \"../errors/guards.js\";\nimport { isRetryableStructuredError } from \"./guards.js\";\nimport {\n  findInCauseChain,\n  getRootCause,\n  someCauseChain,\n} from \"./cause-chain.js\";\n\ntype RetryableError = { retryable: true } & Record<string, unknown>;\n\n/**\n * Checks if any error in the cause chain is a retryable StructuredError.\n *\n * Uses the strict {@link isRetryableStructuredError} predicate: each error\n * must have the full StructuredError shape (`code`, `category`, `retryable`)\n * in addition to `retryable === true`. Errors that extend `BaseError`\n * directly and only set `retryable: true` will NOT match. For those, use\n * {@link someChainRetryable} instead.\n *\n * @param error - The error to check\n * @returns True if any error in the chain is a retryable StructuredError\n *\n * @example\n * ```typescript\n * if (isChainRetryable(error)) {\n *   // Retry the operation\n * }\n * ```\n */\nexport function isChainRetryable(error: unknown): boolean {\n  return someCauseChain(error, isRetryableStructuredError);\n}\n\n/**\n * Checks if any error in the cause chain is retryable, using the loose\n * `retryable === true` predicate.\n *\n * Unlike {@link isChainRetryable}, this does NOT require the full\n * StructuredError shape (`code`/`category`/`retryable`). Use this when your\n * error hierarchy extends `BaseError` directly and signals retryability via\n * a plain `retryable: true` field, common in DDD-style error hierarchies\n * that discriminate by class rather than `code`/`category` strings.\n *\n * @param error - The error to check\n * @param maxDepth - Maximum chain depth to traverse (default: 100)\n * @returns True if any error in the chain has `retryable === true`\n *\n * @example\n * ```typescript\n * class ConcurrencyConflictError extends BaseError<\"ConcurrencyConflictError\"> {\n *   readonly retryable = true as const;\n * }\n *\n * if (someChainRetryable(error)) {\n *   // Retry (works even though ConcurrencyConflictError has no code/category)\n * }\n * ```\n */\nexport function someChainRetryable(\n  error: unknown,\n  maxDepth: number = 100,\n): boolean {\n  return someCauseChain(error, isRetryable, maxDepth);\n}\n\n/**\n * Checks if the root cause of an error is retryable.\n * This provides the most specific retry decision by examining only the deepest error.\n *\n * @param error - The error to check\n * @returns True if the root cause is a retryable StructuredError\n *\n * @example\n * ```typescript\n * // Only retry for root cause issues (e.g., network timeout)\n * if (getRootCauseRetryable(error)) {\n *   await retryOperation();\n * }\n * ```\n */\nexport function getRootCauseRetryable(error: unknown): boolean {\n  const root = getRootCause(error);\n  return isRetryableStructuredError(root);\n}\n\n/**\n * Finds the first retryable error in the cause chain.\n *\n * @param error - The error to start traversing from\n * @returns The first retryable StructuredError, or undefined if none found\n *\n * @example\n * ```typescript\n * const retryable = getFirstRetryableCause(error);\n * if (retryable) {\n *   console.log(`Retryable error: ${retryable.code}`);\n * }\n * ```\n */\nexport function getFirstRetryableCause(\n  error: unknown,\n): RetryableError | undefined {\n  return findInCauseChain(error, (e): e is RetryableError =>\n    isRetryableStructuredError(e),\n  );\n}\n"]}