@tallyrow/safesignal 1.0.1 → 1.3.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/context/context-merge.ts","../src/internal/errors/internal-errors.ts","../src/pipeline/control-char-guard.ts","../src/pipeline/freeze.ts","../src/pipeline/redactor.ts","../src/pipeline/sanitizer.ts","../src/pipeline/url-scrubber.ts","../src/pipeline/dispatcher.ts","../src/pipeline/event-builder.ts","../src/pipeline/level-filter.ts","../src/config/env-defaults.ts","../src/config/config.ts","../src/transport/noop-transport.ts","../src/transport/safe-transport.ts","../src/runtime/configured-runtime.ts","../src/runtime/runtime-ref.ts","../src/api/logger.ts","../src/transport/console-transport.ts"],"names":["active","walkContext","walkArray","walkAttributes","walkValue"],"mappings":";;;AAkCO,SAAS,iBACX,OAAA,EACS;AACZ,EAAA,MAAM,SAKF,EAAC;AAEL,EAAA,KAAA,MAAW,OAAO,OAAA,EAAS;AACzB,IAAA,IAAI,QAAQ,MAAA,EAAW;AAEvB,IAAA,IAAI,GAAA,CAAI,gBAAgB,MAAA,EAAW;AACjC,MAAA,MAAA,CAAO,cAAc,GAAA,CAAI,WAAA;AAAA,IAC3B;AACA,IAAA,IAAI,GAAA,CAAI,WAAW,MAAA,EAAW;AAC5B,MAAA,MAAA,CAAO,SAAS,GAAA,CAAI,MAAA;AAAA,IACtB;AACA,IAAA,IAAI,GAAA,CAAI,gBAAgB,MAAA,EAAW;AACjC,MAAA,MAAA,CAAO,cAAc,GAAA,CAAI,WAAA;AAAA,IAC3B;AACA,IAAA,IAAI,GAAA,CAAI,eAAe,MAAA,EAAW;AAChC,MAAA,MAAA,CAAO,UAAA,GAAa,mBAAA;AAAA,QAClB,MAAA,CAAO,cAAc,EAAC;AAAA,QACtB,GAAA,CAAI;AAAA,OACN;AAAA,IACF;AAAA,EACF;AAIA,EAAA,MAAM,MAAkB,EAAC;AACzB,EAAA,IAAI,MAAA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A;AAAA,IAC/C,CAAA;AAAA,IACA,MAAM,OAAA,EAAS;AACb,MAAA,OAAO,WAAW,OAAA,EAAS,CAAC,GAAG,eAAA,EAAiB,OAAO,CAAC,CAAA;AAAA,IAC1D,CAAA;AAAA,IACA,YAAY,OAAA,EAAS;AACnB,MAAA,OAAO,WAAW,OAAA,EAAS,CAAC,GAAG,eAAA,EAAiB,OAAO,CAAC,CAAA;AAAA,IAC1D;AAAA,GACF;AACF;;;ACtNA,SAAS,qBAAqB,KAAA,EAAyC;AACrE,EAAA,MAAM,IAAA,GAAQ,QAA+C,KAAK,CAAA;AAClE,EAAA,IAAI,OAAO,SAAS,UAAA,EAAY;AAC9B,IAAA,OAAQ,IAAA,CAAuB,KAAK,OAAO,CAAA;AAAA,EAC7C;AACA,EAAA,OAAO,OAAA,CAAQ,GAAA,CAAI,IAAA,CAAK,OAAO,CAAA;AACjC;AAEO,IAAM,mBAAqC,OAAkB;AAAA,EAClE,IAAA,EAAM,SAAA;AAAA,EACN,KAAK,KAAA,EAAuB;AAC1B,IAAA,MAAM,GAAA,GAAM,oBAAA,CAAqB,KAAA,CAAM,KAAK,CAAA;AAC5C,IAAA,GAAA,CAAI,KAAA,CAAM,SAAS,KAAK,CAAA;AAAA,EAC1B;AACF,CAAA","file":"index.cjs","sourcesContent":["/**\n * Deterministic `LogContext` merge.\n *\n * Algorithm (per `data-model.md` and `contracts/logger-config.md` LC-7):\n *\n * Sources in increasing precedence order (later wins):\n * 1. configureLogging({ context }) — root static context\n * 2. createLogger({ context }) — per-logger static context\n * 3. logger.child(context) chain — derived loggers\n * 4. correlation() return value — per-emit dynamic context\n *\n * For each source:\n * - `application`, `module`, `environment` — shallow replace if defined\n * - `attributes` — **deep-merge** key-by-key (per `data-model.md`):\n * * if both sides have a plain-object value for the same key, recurse\n * * otherwise the later value replaces the earlier\n * * arrays are treated as leaves and replaced wholesale (the later\n * array wins; we never concatenate)\n *\n * Undefined keys in a later source do NOT overwrite earlier definitions.\n *\n * The function is pure: it never mutates its inputs. The output's\n * `attributes` is always a fresh object — callers receive an independent\n * copy that they may not mutate, but mutating it would not corrupt any\n * source's `attributes`.\n */\n\nimport type { AttributeValue, Attributes, LogContext } from '../api/types.js';\n\n/**\n * Merge an ordered list of partial contexts into a single `LogContext`.\n * `undefined` sources are skipped, which lets callers pass an unconditional\n * sequence without having to filter beforehand.\n */\nexport function mergeContexts(\n ...sources: ReadonlyArray<Partial<LogContext> | undefined>\n): LogContext {\n const merged: {\n application?: LogContext['application'];\n module?: LogContext['module'];\n environment?: string;\n attributes?: Attributes;\n } = {};\n\n for (const src of sources) {\n if (src === undefined) continue;\n\n if (src.application !== undefined) {\n merged.application = src.application;\n }\n if (src.module !== undefined) {\n merged.module = src.module;\n }\n if (src.environment !== undefined) {\n merged.environment = src.environment;\n }\n if (src.attributes !== undefined) {\n merged.attributes = deepMergeAttributes(\n merged.attributes ?? {},\n src.attributes,\n );\n }\n }\n\n // Build the final value without writing `undefined` properties (required\n // by `exactOptionalPropertyTypes: true`).\n const out: LogContext = {};\n if (merged.application !== undefined) out.application = merged.application;\n if (merged.module !== undefined) out.module = merged.module;\n if (merged.environment !== undefined) out.environment = merged.environment;\n if (merged.attributes !== undefined) out.attributes = merged.attributes;\n return out;\n}\n\n/**\n * Deep-merge two `Attributes` records. The earlier record provides the\n * base; the later record overlays on top. For keys present in both:\n * - plain-object × plain-object → recurse\n * - any other shape combination → later value wins (replaces wholesale)\n * Arrays are treated as leaves and replaced, not concatenated, so a\n * later layer's array fully replaces the earlier layer's.\n *\n * Pure: never mutates `earlier` or `later`. Always returns a fresh\n * object for the merged result.\n */\nfunction deepMergeAttributes(earlier: Attributes, later: Attributes): Attributes {\n const result: { [key: string]: AttributeValue } = { ...earlier };\n for (const key of Object.keys(later)) {\n const laterValue = later[key];\n if (laterValue === undefined) continue;\n const earlierValue = result[key];\n if (isPlainAttributeObject(earlierValue) && isPlainAttributeObject(laterValue)) {\n result[key] = deepMergeAttributes(earlierValue, laterValue);\n } else {\n result[key] = laterValue;\n }\n }\n return result;\n}\n\nfunction isPlainAttributeObject(\n value: AttributeValue | undefined,\n): value is Attributes {\n return (\n value !== null &&\n value !== undefined &&\n typeof value === 'object' &&\n !Array.isArray(value)\n );\n}\n","/**\n * Internal error type with a non-enumerable symbol marker so the dispatcher\n * can distinguish package-internal errors from consumer-thrown errors\n * without losing stack info. Never exported from the public surface.\n */\n\nconst PACKAGE_ERROR_MARKER = Symbol('frontend-logging-sdk/package-error');\n\n/**\n * Discriminator for which internal failure mode produced a `PackageError`.\n * Categorizes errors routed through `LoggerConfig.onInternalError`.\n */\nexport type PackageErrorCode =\n | 'transport_send_failed'\n | 'transport_init_failed'\n | 'transport_shutdown_failed'\n | 'redactor_failed'\n | 'correlation_failed'\n | 'backend_init_failed'\n | 'backend_handle_failed'\n | 'sanitizer_limit_clamped'\n | 'no_transport_configured';\n\nexport interface PackageErrorOptions {\n /** The underlying error that caused this one, if any. */\n cause?: unknown;\n /** Transport name when the failure is transport-scoped. */\n transportName?: string;\n}\n\n/**\n * Internal error class carrying a structured `code`, optional cause, and\n * optional transport name. Extends the standard `Error` so it satisfies the\n * public `onInternalError: (err: Error) => void` signature without leaking\n * any of these internal fields' types into the public surface.\n */\nexport class PackageError extends Error {\n readonly code: PackageErrorCode;\n readonly transportName?: string;\n // ES2022 standard Error.cause — declared so this typechecks regardless of\n // the current `lib` setting in tsconfig.\n declare cause?: unknown;\n\n constructor(code: PackageErrorCode, message: string, options: PackageErrorOptions = {}) {\n super(message);\n this.name = 'PackageError';\n this.code = code;\n if (options.cause !== undefined) {\n this.cause = options.cause;\n }\n if (options.transportName !== undefined) {\n this.transportName = options.transportName;\n }\n // Non-enumerable marker so `Object.keys(err)` and JSON serialization\n // don't expose the internal sentinel.\n Object.defineProperty(this, PACKAGE_ERROR_MARKER, {\n value: true,\n enumerable: false,\n writable: false,\n configurable: false,\n });\n }\n}\n\n/**\n * Type guard for `PackageError` instances. Detects errors created by this\n * package even across realm boundaries (different bundler outputs sharing\n * the same `Symbol.for(...)` registry — note we use a module-local Symbol\n * deliberately to scope detection to instances created by *this* loaded\n * copy of the package, not other copies in module-federated environments).\n */\nexport function isPackageError(value: unknown): value is PackageError {\n if (typeof value !== 'object' || value === null) return false;\n return (value as Record<symbol, unknown>)[PACKAGE_ERROR_MARKER] === true;\n}\n\n/**\n * Wrap an arbitrary caught value as a `PackageError`. If `cause` is already\n * a `PackageError`, it is returned as-is so we don't lose the original\n * `code` / `transportName` from a deeper layer.\n */\nexport function wrapAsPackageError(\n code: PackageErrorCode,\n message: string,\n cause: unknown,\n transportName?: string,\n): PackageError {\n if (isPackageError(cause)) return cause;\n const options: PackageErrorOptions = { cause };\n if (transportName !== undefined) {\n options.transportName = transportName;\n }\n return new PackageError(code, message, options);\n}\n\n/**\n * Invoke a consumer-supplied `onInternalError` callback inside an isolating\n * try/catch. Required by the constitution and the failure-safety contract:\n * NO path inside the package may propagate a throw to a consumer logging\n * call site — including throws from the diagnostics hook itself.\n *\n * This is the single helper every internal site must use when notifying\n * `onInternalError`; bare invocations are a hazard.\n */\nexport function safeNotify(\n onInternalError: (err: Error) => void,\n err: PackageError,\n): void {\n try {\n onInternalError(err);\n } catch {\n // Consumer-supplied onInternalError threw. Nothing further we can do\n // without violating the no-throw invariant — swallow.\n }\n}\n","/**\n * Control-character guard. Walks every string value in the event and\n * escapes ASCII control characters (`\\x00`–`\\x1F` except `\\t`, `\\n`,\n * `\\r`) plus the line separators U+2028 and U+2029.\n *\n * Contract: `contracts/log-event.md` (\"Pipeline-applied transformations\"\n * row 4) + plan.md \"Security Architecture > Log-injection & output\n * safety\".\n *\n * Scope:\n * - `event.message`\n * - every string in `event.attributes` (recursive into nested\n * plain objects and arrays produced by the sanitizer)\n * - every string in `event.context.attributes` (same recursion)\n * - `event.error.name`, `event.error.message`, and (if present)\n * `event.error.stack`\n *\n * Escape format: each targeted character is replaced with its\n * six-character escape literal — `\\uXXXX` (lowercase 4-digit hex,\n * zero-padded). This is the conventional representation, unambiguous\n * when serialized into JSON and rendered by any downstream log viewer.\n *\n * `\\t` (U+0009), `\\n` (U+000A), and `\\r` (U+000D) are deliberately\n * preserved — log-injection resistance is provided by\n * `ConsoleTransport`'s object-mode output (event passed as the second\n * argument to `console[level]`, never interpolated into a single line),\n * not by mutating those characters. See plan.md \"Log-injection &\n * output safety\" for the full rationale.\n *\n * NEVER throws: every branch returns a value; the regex match cannot\n * throw on any input.\n */\n\nimport type {\n AttributeValue,\n Attributes,\n ErrorInfo,\n LogContext,\n LogEvent,\n} from '../api/types.js';\nimport type { NormalizedConfig } from '../config/config.js';\nimport type { PipelineStage } from './dispatcher.js';\n\n// Targeted code points:\n// U+0000..U+0008 (NUL through BS)\n// U+000B..U+000C (VT, FF)\n// U+000E..U+001F (SO through US)\n// U+2028 (LINE SEPARATOR)\n// U+2029 (PARAGRAPH SEPARATOR)\n// Excluded by design: U+0009 (\\t), U+000A (\\n), U+000D (\\r).\n//\n// Built from explicit `\\u` escapes in a string and compiled at module\n// load time so the source file carries no literal control bytes (which\n// would otherwise be hostile to editors, diff viewers, and security\n// scanners).\nconst CONTROL_CHAR_CLASS =\n '[\\\\u0000-\\\\u0008\\\\u000B\\\\u000C\\\\u000E-\\\\u001F\\\\u2028\\\\u2029]';\nconst HAS_CONTROL_CHAR = new RegExp(CONTROL_CHAR_CLASS);\nconst CONTROL_CHAR_GLOBAL = new RegExp(CONTROL_CHAR_CLASS, 'g');\n\nfunction escapeControlChars(value: string): string {\n if (!HAS_CONTROL_CHAR.test(value)) return value;\n return value.replace(CONTROL_CHAR_GLOBAL, (ch) => {\n const code = ch.charCodeAt(0);\n return '\\\\u' + code.toString(16).padStart(4, '0');\n });\n}\n\nexport const controlCharGuard: PipelineStage = (event, _config) => {\n const message = escapeControlChars(event.message);\n const attributes = walkAttributes(event.attributes);\n const context = walkContext(event.context);\n\n let error: ErrorInfo | undefined;\n if (event.error !== undefined) {\n const escName = escapeControlChars(event.error.name);\n const escMessage = escapeControlChars(event.error.message);\n const stack = event.error.stack;\n const escStack = stack === undefined ? undefined : escapeControlChars(stack);\n if (\n escName === event.error.name &&\n escMessage === event.error.message &&\n escStack === stack\n ) {\n error = event.error;\n } else {\n error = { name: escName, message: escMessage };\n if (escStack !== undefined) error.stack = escStack;\n }\n }\n\n const noChange =\n message === event.message &&\n attributes === event.attributes &&\n context === event.context &&\n error === event.error;\n if (noChange) return event;\n\n const next: LogEvent = {\n timestamp: event.timestamp,\n level: event.level,\n message,\n attributes,\n context,\n };\n if (error !== undefined) next.error = error;\n return next;\n};\n\nfunction walkAttributes(attrs: Attributes): Attributes {\n let changed = false;\n let result: { [key: string]: AttributeValue } | null = null;\n for (const key of Object.keys(attrs)) {\n const value = attrs[key];\n if (value === undefined) continue;\n const escaped = walkValue(value);\n if (escaped !== value) {\n if (result === null) {\n result = {};\n for (const k of Object.keys(attrs)) {\n const existing = attrs[k];\n if (existing !== undefined) result[k] = existing;\n }\n }\n result[key] = escaped;\n changed = true;\n }\n }\n return changed && result !== null ? result : attrs;\n}\n\nfunction walkValue(value: AttributeValue): AttributeValue {\n if (typeof value === 'string') return escapeControlChars(value);\n if (Array.isArray(value)) return walkArray(value);\n if (value !== null && typeof value === 'object') return walkAttributes(value);\n return value;\n}\n\nfunction walkArray(arr: AttributeValue[]): AttributeValue[] {\n let changed = false;\n let result: AttributeValue[] | null = null;\n for (let i = 0; i < arr.length; i++) {\n const item = arr[i];\n if (item === undefined) continue;\n const escaped = walkValue(item);\n if (escaped !== item) {\n if (result === null) result = arr.slice();\n result[i] = escaped;\n changed = true;\n }\n }\n return changed && result !== null ? result : arr;\n}\n\nfunction walkContext(context: LogContext): LogContext {\n if (context.attributes === undefined) return context;\n const escaped = walkAttributes(context.attributes);\n if (escaped === context.attributes) return context;\n return { ...context, attributes: escaped };\n}\n","/**\n * Dev-only deep-freeze stage. Runs last in the pipeline (after the\n * control-char guard) so that the event handed off to the dispatcher\n * is immutable in development builds.\n *\n * Contract: `contracts/log-event.md` (\"Immutability\") + plan.md\n * \"Security Architecture > Pipeline ordering\".\n *\n * Build-time gating:\n * - In development builds (`__DEV__ === true`, the default for\n * `vitest` and any non-production `tsup` build), the event is\n * recursively `Object.freeze`d so consumer transports cannot\n * accidentally mutate it before delivery.\n * - In production builds (`__DEV__ === false`), the entire\n * freeze body is unreachable. `tsup` replaces `__DEV__` with the\n * literal `false` at build time and tree-shakes the `deepFreeze`\n * helper out of the production bundle — preserving the documented\n * \"zero runtime cost in production\" guarantee.\n *\n * The module reads ONLY the build-time global `__DEV__`. It never\n * consults `process.env`, `import.meta.env`, `location`,\n * `document.cookie`, or any other ambient state (enforced by\n * `tests/contract/no-ambient-state.test.ts` — T013).\n */\n\nimport type { LogEvent } from '../api/types.js';\nimport type { NormalizedConfig } from '../config/config.js';\nimport type { PipelineStage } from './dispatcher.js';\n\nexport const freezeInDev: PipelineStage = (event, _config) => {\n if (!__DEV__) return event;\n deepFreeze(event);\n return event;\n};\n\nfunction deepFreeze(value: object): void {\n if (Object.isFrozen(value)) return;\n Object.freeze(value);\n for (const key of Object.keys(value)) {\n const child = (value as Record<string, unknown>)[key];\n if (child !== null && typeof child === 'object') {\n deepFreeze(child);\n }\n }\n}\n","/**\n * Redactor — masks values whose **key** matches the default denylist\n * (case-insensitive, immediate property name only, never a value\n * substring) and values whose **shape** matches a documented sensitive\n * pattern (JWT, Bearer-prefixed token). Runs in the pipeline AFTER the\n * sanitizer and URL scrubber have normalized the event and BEFORE the\n * control-char guard, freeze, and any transport.\n *\n * Contract: `contracts/redaction.md` (R-1..R-10).\n *\n * Two surfaces:\n * - `redact` (pipeline stage): wraps `config.redactor` (or the\n * default `createRedactor()` when not supplied), invokes it\n * synchronously, and enforces the fail-closed contract:\n * * If the redactor throws, the dispatcher's outer try/catch\n * drops the event and routes the throw to `onInternalError`.\n * * If the redactor returns `null`, the event is dropped (the\n * pipeline contract for explicit drop).\n * * If the redactor returns a value that is neither a LogEvent\n * nor `null`, this stage throws a `PackageError('redactor_failed')`\n * so the same fail-closed path applies.\n * - `createRedactor(rules?)` (public, re-exported from\n * `src/index.ts`): returns a `Redactor` configured with the\n * default rules when called with no argument, or with the\n * consumer's rule set (FULL replacement of defaults) when an\n * array is supplied. An empty array is a valid no-op rule set.\n *\n * Match semantics (per contract):\n * - **Key match**: a rule's `key` is tested against the immediate\n * property name being inspected. String keys match via case-\n * insensitive equality; RegExp keys match via `.test()`. A match\n * replaces the entire value (including object/array subtrees)\n * with `rule.replacement ?? '[REDACTED]'`. Recursion does not\n * descend into a value whose key matched — the whole subtree is\n * considered sensitive.\n * - **Shape match**: a rule's `shape` (RegExp) is tested against\n * leaf string values regardless of key context. A match replaces\n * the value with `rule.replacement ?? '[REDACTED]'`. Shape rules\n * do not match objects or arrays as containers — only leaf\n * strings.\n * - **Combination**: a rule with both `key` and `shape` matches\n * when either matches.\n *\n * Scope per field:\n * - `event.attributes` — recursive walk; key + shape rules apply.\n * - `event.context.attributes` — same recursive walk.\n * - `event.message` — string scan; shape rules only (no key context).\n * - `event.error.name`, `event.error.message`, `event.error.stack` —\n * string scan; shape rules only.\n */\n\nimport type {\n AttributeValue,\n Attributes,\n ErrorInfo,\n LogContext,\n LogEvent,\n LogLevel,\n RedactionRule,\n Redactor,\n} from '../api/types.js';\nimport { PackageError } from '../internal/errors/internal-errors.js';\nimport type { NormalizedConfig } from '../config/config.js';\nimport type { PipelineStage } from './dispatcher.js';\n\nconst DEFAULT_REPLACEMENT = '[REDACTED]';\n\n// Default rule set — must mirror contracts/redaction.md.\nconst DEFAULT_RULES: ReadonlyArray<RedactionRule> = [\n // Key rules (immediate-name match, case-insensitive).\n { key: /^password$|^passwd$/i },\n { key: /^token$|access[_-]?token|refresh[_-]?token|bearer[_-]?token/i },\n { key: /^authorization$|^auth$/i },\n { key: /^cookie$|^set-cookie$/i },\n { key: /^secret$/i },\n { key: /api[_-]?key/i },\n { key: /session[_-]?id|^sid$/i },\n { key: /^ssn$/i },\n { key: /credit[_-]?card|^cardNumber$|^cvv$/i },\n // Shape rules (leaf-string match).\n { shape: /^[A-Za-z0-9_-]{8,}\\.[A-Za-z0-9_-]{8,}\\.[A-Za-z0-9_-]{8,}$/ },\n { shape: /^Bearer\\s+[A-Za-z0-9._-]+$/i },\n];\n\ninterface KeyRule {\n readonly match: (key: string) => boolean;\n readonly replacement: string;\n}\n\ninterface ShapeRule {\n readonly pattern: RegExp;\n readonly replacement: string;\n}\n\ninterface CompiledRules {\n readonly keyRules: ReadonlyArray<KeyRule>;\n readonly shapeRules: ReadonlyArray<ShapeRule>;\n}\n\nfunction compileRules(rules: ReadonlyArray<RedactionRule>): CompiledRules {\n const keyRules: KeyRule[] = [];\n const shapeRules: ShapeRule[] = [];\n for (const rule of rules) {\n const replacement = rule.replacement ?? DEFAULT_REPLACEMENT;\n if (rule.key !== undefined) {\n keyRules.push(makeKeyRule(rule.key, replacement));\n }\n if (rule.shape !== undefined) {\n shapeRules.push({ pattern: rule.shape, replacement });\n }\n }\n return { keyRules, shapeRules };\n}\n\nfunction makeKeyRule(key: string | RegExp, replacement: string): KeyRule {\n if (typeof key === 'string') {\n const expected = key.toLowerCase();\n return {\n match: (candidate) => candidate.toLowerCase() === expected,\n replacement,\n };\n }\n return { match: (candidate) => key.test(candidate), replacement };\n}\n\n// ---------------------------------------------------------------------------\n// Public factory\n// ---------------------------------------------------------------------------\n\nexport function createRedactor(rules?: RedactionRule[]): Redactor {\n const active = rules ?? DEFAULT_RULES;\n const compiled = compileRules(active);\n\n return function defaultStyleRedactor(event: LogEvent): LogEvent | null {\n const attributes = walkObject(event.attributes, compiled);\n const context = walkContext(event.context, compiled);\n const message = applyShapeRules(event.message, compiled.shapeRules);\n\n let error: ErrorInfo | undefined = event.error;\n if (event.error !== undefined) {\n const escName = applyShapeRules(event.error.name, compiled.shapeRules);\n const escMessage = applyShapeRules(event.error.message, compiled.shapeRules);\n const stack = event.error.stack;\n const escStack =\n stack === undefined ? undefined : applyShapeRules(stack, compiled.shapeRules);\n const errorChanged =\n escName !== event.error.name ||\n escMessage !== event.error.message ||\n escStack !== stack;\n if (errorChanged) {\n error = { name: escName, message: escMessage };\n if (escStack !== undefined) error.stack = escStack;\n }\n }\n\n const noChange =\n attributes === event.attributes &&\n context === event.context &&\n message === event.message &&\n error === event.error;\n if (noChange) return event;\n\n const next: LogEvent = {\n timestamp: event.timestamp,\n level: event.level,\n message,\n attributes,\n context,\n };\n if (error !== undefined) next.error = error;\n return next;\n };\n}\n\n// ---------------------------------------------------------------------------\n// Pipeline stage\n// ---------------------------------------------------------------------------\n\nlet cachedDefaultRedactor: Redactor | null = null;\nfunction getDefaultRedactor(): Redactor {\n if (cachedDefaultRedactor === null) {\n cachedDefaultRedactor = createRedactor();\n }\n return cachedDefaultRedactor;\n}\n\nexport const redact: PipelineStage = (event, config) => {\n const redactor = config.redactor ?? getDefaultRedactor();\n // Any throw from the redactor escapes here; the dispatcher's outer\n // try/catch will route it through onInternalError as fail-closed.\n const result = redactor(event);\n if (result === null) return null;\n if (!isLogEventShape(result)) {\n throw new PackageError(\n 'redactor_failed',\n 'Redactor returned a value that is neither a LogEvent nor null; the event is dropped (fail-closed).',\n );\n }\n return result;\n};\n\n// ---------------------------------------------------------------------------\n// Internals\n// ---------------------------------------------------------------------------\n\nfunction walkObject(attrs: Attributes, rules: CompiledRules): Attributes {\n let changed = false;\n let result: { [key: string]: AttributeValue } | null = null;\n for (const key of Object.keys(attrs)) {\n const value = attrs[key];\n if (value === undefined) continue;\n\n const newValue = redactValueAtKey(value, key, rules);\n if (newValue !== value) {\n if (result === null) {\n result = {};\n for (const k of Object.keys(attrs)) {\n const existing = attrs[k];\n if (existing !== undefined) result[k] = existing;\n }\n }\n result[key] = newValue;\n changed = true;\n }\n }\n return changed && result !== null ? result : attrs;\n}\n\nfunction walkContext(context: LogContext, rules: CompiledRules): LogContext {\n if (context.attributes === undefined) return context;\n const next = walkObject(context.attributes, rules);\n if (next === context.attributes) return context;\n return { ...context, attributes: next };\n}\n\nfunction redactValueAtKey(\n value: AttributeValue,\n key: string,\n rules: CompiledRules,\n): AttributeValue {\n // Key rules win: a key match replaces the WHOLE subtree under that key\n // (including nested objects/arrays) so we never recurse into a value\n // whose key marks it sensitive.\n for (const rule of rules.keyRules) {\n if (rule.match(key)) return rule.replacement;\n }\n\n if (typeof value === 'string') {\n return applyShapeRules(value, rules.shapeRules);\n }\n if (Array.isArray(value)) {\n return walkArray(value, rules);\n }\n if (value !== null && typeof value === 'object') {\n return walkObject(value, rules);\n }\n return value;\n}\n\nfunction walkArray(arr: AttributeValue[], rules: CompiledRules): AttributeValue[] {\n let changed = false;\n let result: AttributeValue[] | null = null;\n for (let i = 0; i < arr.length; i++) {\n const item = arr[i];\n if (item === undefined) continue;\n let newItem: AttributeValue;\n if (typeof item === 'string') {\n newItem = applyShapeRules(item, rules.shapeRules);\n } else if (Array.isArray(item)) {\n newItem = walkArray(item, rules);\n } else if (item !== null && typeof item === 'object') {\n newItem = walkObject(item, rules);\n } else {\n newItem = item;\n }\n if (newItem !== item) {\n if (result === null) result = arr.slice();\n result[i] = newItem;\n changed = true;\n }\n }\n return changed && result !== null ? result : arr;\n}\n\nfunction applyShapeRules(value: string, rules: ReadonlyArray<ShapeRule>): string {\n for (const rule of rules) {\n if (rule.pattern.test(value)) return rule.replacement;\n }\n return value;\n}\n\nconst VALID_LEVELS: ReadonlySet<LogLevel> = new Set<LogLevel>([\n 'debug',\n 'info',\n 'warn',\n 'error',\n]);\n\nfunction isLogEventShape(value: unknown): value is LogEvent {\n // `null` is intercepted by the upstream `result === null` check in\n // `redact()` (a redactor returning `null` is a valid drop, not a\n // shape failure), so the `value === null` half of the guard below\n // is unreachable via the configured pipeline. Kept as defense in\n // depth for any future call site that bypasses the upstream check.\n if (\n typeof value !== 'object' ||\n /* v8 ignore next */\n value === null\n ) {\n return false;\n }\n const obj = value as Record<string, unknown>;\n if (typeof obj['timestamp'] !== 'string') return false;\n if (typeof obj['level'] !== 'string') return false;\n if (!VALID_LEVELS.has(obj['level'] as LogLevel)) return false;\n if (typeof obj['message'] !== 'string') return false;\n if (obj['attributes'] === null || typeof obj['attributes'] !== 'object') return false;\n if (obj['context'] === null || typeof obj['context'] !== 'object') return false;\n return true;\n}\n","/**\n * Sanitizer — normalizes arbitrary consumer input into a bounded,\n * predictable `AttributeValue` tree before any downstream stage\n * (URL scrubber, redactor, control-char guard, freeze) sees it.\n *\n * Contract: `contracts/sanitization.md` (rows S-1..S-10).\n *\n * Invariants:\n * - NEVER throws. Every branch has a defined fallback; any residual\n * unexpected throw inside `sanitizeValue` collapses to\n * `\"[Unserializable]\"` (defensive belt).\n * - Class instances and DOM/framework objects are **type-tagged, not\n * recursed** — this is the security property that prevents\n * side-effectful getters from being invoked and prevents huge\n * object graphs (React fibers, full DOM trees) from being pulled\n * into events.\n * - Bounds (`maxDepth`, `maxStringLength`, `maxArrayLength`,\n * `maxAttributeCount`) come from `config.sanitizerLimits`, which\n * `normalizeConfig()` already clamped to documented Min..Max.\n * - `maxAttributeCount` is **cumulative across the whole event**;\n * when exceeded, a single `\"[Truncated: <N> keys omitted]\"` marker\n * is attached at the top-level attributes.\n */\n\nimport type { AttributeValue, ErrorInfo, LogContext, LogEvent } from '../api/types.js';\nimport type { NormalizedConfig } from '../config/config.js';\nimport type { PipelineStage } from './dispatcher.js';\n\nconst TRUNCATION_MARKER_KEY = '__truncated__';\nconst STRING_TRUNCATION_SUFFIX = '...[truncated]';\nconst UNSERIALIZABLE_MARKER = '[Unserializable]';\n\ninterface SanitizeContext {\n readonly maxDepth: number;\n readonly maxStringLength: number;\n readonly maxArrayLength: number;\n readonly maxAttributeCount: number;\n keysUsed: number;\n keysOmitted: number;\n readonly seen: WeakSet<object>;\n}\n\nexport const sanitize: PipelineStage = (event, config) => {\n const ctx = newContext(config);\n\n const sanitizedAttributes = sanitizeRootObject(event.attributes, ctx);\n const sanitizedContext = sanitizeContext(event.context, ctx);\n\n const next: LogEvent = {\n timestamp: event.timestamp,\n level: event.level,\n message: truncateString(event.message, ctx.maxStringLength),\n attributes: sanitizedAttributes,\n context: sanitizedContext,\n };\n\n if (event.error !== undefined) {\n next.error = sanitizeErrorInfo(event.error, ctx);\n }\n\n if (ctx.keysOmitted > 0) {\n next.attributes = withTruncationMarker(next.attributes, ctx.keysOmitted);\n }\n\n return next;\n};\n\nfunction newContext(config: NormalizedConfig): SanitizeContext {\n const limits = config.sanitizerLimits;\n return {\n maxDepth: limits.maxDepth,\n maxStringLength: limits.maxStringLength,\n maxArrayLength: limits.maxArrayLength,\n maxAttributeCount: limits.maxAttributeCount,\n keysUsed: 0,\n keysOmitted: 0,\n seen: new WeakSet<object>(),\n };\n}\n\nfunction sanitizeRootObject(\n source: unknown,\n ctx: SanitizeContext,\n): { [key: string]: AttributeValue } {\n if (source === null || typeof source !== 'object' || Array.isArray(source)) {\n return {};\n }\n return sanitizeObject(source as Record<string, unknown>, 0, ctx);\n}\n\nfunction sanitizeContext(source: LogContext, ctx: SanitizeContext): LogContext {\n if (source.attributes === undefined) return source;\n const sanitizedAttrs = sanitizeRootObject(source.attributes, ctx);\n return { ...source, attributes: sanitizedAttrs };\n}\n\nfunction sanitizeErrorInfo(error: ErrorInfo, ctx: SanitizeContext): ErrorInfo {\n const info: ErrorInfo = {\n name: truncateString(error.name, ctx.maxStringLength),\n message: truncateString(error.message, ctx.maxStringLength),\n };\n if (error.stack !== undefined) {\n info.stack = truncateString(error.stack, ctx.maxStringLength);\n }\n return info;\n}\n\nfunction withTruncationMarker(\n attrs: { [key: string]: AttributeValue },\n omitted: number,\n): { [key: string]: AttributeValue } {\n const tagged: { [key: string]: AttributeValue } = { ...attrs };\n tagged[TRUNCATION_MARKER_KEY] = `[Truncated: ${String(omitted)} keys omitted]`;\n return tagged;\n}\n\nfunction truncateString(value: string, maxLength: number): string {\n if (value.length <= maxLength) return value;\n return value.slice(0, maxLength) + STRING_TRUNCATION_SUFFIX;\n}\n\n/**\n * Outer dispatch for an unknown value. Wrapped in try/catch so that\n * any pathological input (throwing getters on a plain object, Proxy\n * traps, `Invalid Date` toISOString, etc.) collapses to a marker\n * rather than escaping the sanitizer. This is the defensive belt that\n * guarantees S-2 (\"the sanitizer never throws on any input\").\n */\nfunction sanitizeValue(\n value: unknown,\n depth: number,\n ctx: SanitizeContext,\n): AttributeValue {\n try {\n return sanitizeValueImpl(value, depth, ctx);\n } catch {\n return UNSERIALIZABLE_MARKER;\n }\n}\n\nfunction sanitizeValueImpl(\n value: unknown,\n depth: number,\n ctx: SanitizeContext,\n): AttributeValue {\n if (depth > ctx.maxDepth) return '[MaxDepth]';\n\n // null and primitives ------------------------------------------------------\n if (value === null) return null;\n const t = typeof value;\n if (t === 'string') return truncateString(value as string, ctx.maxStringLength);\n if (t === 'number') {\n const n = value as number;\n return Number.isFinite(n) ? n : null;\n }\n if (t === 'boolean') return value as boolean;\n if (t === 'bigint') return String(value);\n if (t === 'function') return '[Function]';\n if (t === 'symbol') return '[Symbol]';\n if (t === 'undefined') return null;\n\n // value is a non-null object below\n const obj = value as object;\n\n // Cycle guard -------------------------------------------------------------\n if (ctx.seen.has(obj)) return '[Circular]';\n\n // Arrays ------------------------------------------------------------------\n if (Array.isArray(value)) {\n return sanitizeArray(value, depth, ctx);\n }\n\n // Date --------------------------------------------------------------------\n if (value instanceof Date) {\n return dateToIso(value);\n }\n\n // Error -------------------------------------------------------------------\n if (value instanceof Error) {\n return sanitizeErrorAsAttribute(value, depth, ctx);\n }\n\n // DOM type tags (most specific first; guarded for SSR) --------------------\n if (typeof Element !== 'undefined' && value instanceof Element) {\n return `[Element:${tagNameOf(value)}]`;\n }\n if (typeof Document !== 'undefined' && value instanceof Document) {\n return '[Document]';\n }\n if (typeof Window !== 'undefined' && value instanceof Window) {\n return '[Window]';\n }\n if (typeof Node !== 'undefined' && value instanceof Node) {\n return '[Node]';\n }\n\n // Framework type tags -----------------------------------------------------\n if (typeof Event !== 'undefined' && value instanceof Event) {\n return `[Event:${eventTypeOf(value)}]`;\n }\n if (typeof Promise !== 'undefined' && value instanceof Promise) {\n return '[Promise]';\n }\n if (typeof Map !== 'undefined' && value instanceof Map) {\n return '[Map]';\n }\n if (typeof Set !== 'undefined' && value instanceof Set) {\n return '[Set]';\n }\n if (typeof WeakMap !== 'undefined' && value instanceof WeakMap) {\n return '[WeakMap]';\n }\n if (typeof WeakSet !== 'undefined' && value instanceof WeakSet) {\n return '[WeakSet]';\n }\n if (typeof Request !== 'undefined' && value instanceof Request) {\n return '[Request]';\n }\n if (typeof Response !== 'undefined' && value instanceof Response) {\n return '[Response]';\n }\n if (typeof Blob !== 'undefined' && value instanceof Blob) {\n return '[Blob]';\n }\n if (typeof FormData !== 'undefined' && value instanceof FormData) {\n return '[FormData]';\n }\n if (typeof URL !== 'undefined' && value instanceof URL) {\n return '[URL]';\n }\n\n // Plain object vs class instance ------------------------------------------\n if (isPlainObject(obj)) {\n return sanitizeObject(obj as Record<string, unknown>, depth, ctx);\n }\n return `[${getConstructorName(obj)}]`;\n}\n\nfunction sanitizeArray(\n arr: ReadonlyArray<unknown>,\n depth: number,\n ctx: SanitizeContext,\n): AttributeValue[] {\n ctx.seen.add(arr as unknown as object);\n const out: AttributeValue[] = [];\n const len = arr.length;\n const limit = len > ctx.maxArrayLength ? ctx.maxArrayLength : len;\n for (let i = 0; i < limit; i++) {\n // Per contract: `undefined` inside arrays → `null`. We delegate\n // that coercion to `sanitizeValue`'s `typeof === 'undefined'`\n // branch so the per-item shape rules stay in one place.\n out.push(sanitizeValue(arr[i], depth + 1, ctx));\n }\n if (len > ctx.maxArrayLength) {\n const omitted = len - ctx.maxArrayLength;\n out.push(`[Truncated: ${String(omitted)} elements omitted]`);\n }\n ctx.seen.delete(arr as unknown as object);\n return out;\n}\n\nfunction sanitizeObject(\n obj: Record<string, unknown>,\n depth: number,\n ctx: SanitizeContext,\n): { [key: string]: AttributeValue } {\n ctx.seen.add(obj);\n const result: { [key: string]: AttributeValue } = {};\n const keys = ownEnumerableKeys(obj);\n for (const key of keys) {\n const raw = readProperty(obj, key);\n if (raw === undefined) continue; // top-level undefined keys are dropped\n if (ctx.keysUsed >= ctx.maxAttributeCount) {\n ctx.keysOmitted++;\n continue;\n }\n ctx.keysUsed++;\n result[key] = sanitizeValue(raw, depth + 1, ctx);\n }\n ctx.seen.delete(obj);\n return result;\n}\n\n/**\n * Reduce an `Error` encountered inside attributes to its documented\n * `{name, message, stack?}` shape and recurse through the plain-object\n * path so strings get length-truncated and keys get counted toward\n * `maxAttributeCount`.\n */\nfunction sanitizeErrorAsAttribute(\n err: Error,\n depth: number,\n ctx: SanitizeContext,\n): { [key: string]: AttributeValue } {\n const reduced: Record<string, unknown> = {\n name: safeString(() => err.name, 'Error'),\n message: safeString(() => err.message, ''),\n };\n const stack = safeOptional(() => err.stack);\n if (stack !== undefined) {\n reduced['stack'] = stack;\n }\n return sanitizeObject(reduced, depth, ctx);\n}\n\n// ---------------------------------------------------------------------------\n// Low-level helpers (each isolated so a single throwing access cannot\n// derail the recursion).\n// ---------------------------------------------------------------------------\n\nfunction ownEnumerableKeys(obj: object): string[] {\n try {\n return Object.keys(obj);\n } catch {\n return [];\n }\n}\n\nfunction readProperty(obj: Record<string, unknown>, key: string): unknown {\n try {\n return obj[key];\n } catch {\n return UNSERIALIZABLE_MARKER;\n }\n}\n\nfunction isPlainObject(obj: object): boolean {\n // `Object.getPrototypeOf(obj)` can in principle throw via a Proxy's\n // `getPrototypeOf` trap, but any such input has already thrown — and\n // been collapsed to `'[Unserializable]'` — by an earlier `instanceof`\n // check in `sanitizeValueImpl` (those checks also call\n // `Object.getPrototypeOf` internally). The `sanitizeValue` outer\n // defensive belt is the single source of truth for that recovery, so\n // a redundant local try/catch here would only ever be dead code.\n const proto = Object.getPrototypeOf(obj) as object | null;\n return proto === null || proto === Object.prototype;\n}\n\nfunction getConstructorName(obj: object): string {\n try {\n const proto = Object.getPrototypeOf(obj) as { constructor?: { name?: unknown } } | null;\n const ctor = proto?.constructor;\n const name = ctor?.name;\n if (typeof name === 'string' && name.length > 0) return name;\n } catch {\n /* fall through */\n }\n return 'Object';\n}\n\nfunction tagNameOf(el: Element): string {\n try {\n const t = el.tagName;\n return typeof t === 'string' && t.length > 0 ? t.toLowerCase() : 'element';\n } catch {\n return 'element';\n }\n}\n\nfunction eventTypeOf(ev: Event): string {\n try {\n const t = ev.type;\n return typeof t === 'string' && t.length > 0 ? t : 'event';\n } catch {\n return 'event';\n }\n}\n\nfunction dateToIso(d: Date): AttributeValue {\n try {\n return d.toISOString();\n } catch {\n // Invalid Date throws RangeError.\n return null;\n }\n}\n\nfunction safeString(read: () => unknown, fallback: string): string {\n try {\n const v = read();\n return typeof v === 'string' ? v : fallback;\n } catch {\n return fallback;\n }\n}\n\nfunction safeOptional(read: () => unknown): string | undefined {\n try {\n const v = read();\n return typeof v === 'string' ? v : undefined;\n } catch {\n return undefined;\n }\n}\n","/**\n * URL scrubber — strips sensitive query and fragment parameters from\n * URL-shaped string values before any transport sees the event.\n *\n * Contract: `contracts/redaction.md` (URL-derived secrets) + plan.md\n * \"Security Architecture > URL scrubbing\".\n *\n * Two surfaces:\n * - `urlScrub` (pipeline stage): walks `event.message`,\n * `event.attributes`, `event.context.attributes`, `event.error.*`\n * and rewrites any string that parses as an http(s) URL,\n * replacing sensitive query and (optionally) fragment param values\n * with `'[REDACTED]'`. Runs upstream of the redactor.\n * - `scrubUrl(url, options?)` (public helper, re-exported from\n * `src/index.ts`): the same operation surfaced directly so consumers\n * can pre-scrub URLs they want to log intentionally.\n *\n * Security invariants:\n * - NEVER throws. Malformed URLs, throwing getters on plain objects\n * (already collapsed by the sanitizer upstream), and pathological\n * fragments all fall through to \"return input unchanged\".\n * - Returns input unchanged for any string that is not a parseable\n * http(s) URL. Path segments, host, and authority are NOT modified\n * — only query and fragment parameter VALUES are replaced. Param\n * names are preserved.\n * - Operates on names (case-insensitive), never on value substrings —\n * the package never inspects a URL value's content for sensitive\n * shapes (that is the redactor's job, applied later in the pipeline).\n */\n\nimport type {\n AttributeValue,\n Attributes,\n ErrorInfo,\n LogContext,\n LogEvent,\n ScrubUrlOptions,\n} from '../api/types.js';\nimport type { NormalizedConfig } from '../config/config.js';\nimport type { PipelineStage } from './dispatcher.js';\n\nconst REDACTED = '[REDACTED]';\n\n/**\n * Default denylist of query/fragment parameter names whose values should\n * be replaced. Mirrors `contracts/redaction.md`'s key denylist so the\n * URL scrubber and the redactor stay consistent at the value-shape\n * boundary. Match is case-insensitive (every pattern carries the `i`\n * flag) and full-name only (no substring matches).\n */\nconst DEFAULT_PARAM_DENYLIST: ReadonlyArray<RegExp> = [\n /^password$/i,\n /^passwd$/i,\n /^token$/i,\n /access[_-]?token/i,\n /refresh[_-]?token/i,\n /bearer[_-]?token/i,\n /id[_-]?token/i,\n /^authorization$/i,\n /^auth$/i,\n /^cookie$/i,\n /^set-cookie$/i,\n /^secret$/i,\n /client[_-]?secret/i,\n /api[_-]?key/i,\n /session[_-]?id/i,\n /^sid$/i,\n /^ssn$/i,\n /credit[_-]?card/i,\n /^cardnumber$/i,\n /^cvv$/i,\n];\n\n// ---------------------------------------------------------------------------\n// Public helper\n// ---------------------------------------------------------------------------\n\nexport function scrubUrl(url: string, options?: ScrubUrlOptions): string {\n if (typeof url !== 'string' || url.length === 0) return url;\n\n let parsed: URL;\n try {\n parsed = new URL(url);\n } catch {\n return url;\n }\n\n if (parsed.protocol !== 'http:' && parsed.protocol !== 'https:') {\n return url;\n }\n\n const extras = options?.extraParams ?? [];\n const scrubFragment = options?.fragment !== false;\n\n let changed = false;\n changed = scrubSearchParams(parsed, extras) || changed;\n if (scrubFragment) {\n changed = scrubHashFragment(parsed, extras) || changed;\n }\n\n if (!changed) return url;\n\n // `URL.prototype.toString` does not throw for a URL object that was\n // constructed via `new URL()` and only mutated through `searchParams`\n // and `hash` (both of which accept arbitrary string input without\n // validation). No defensive belt is required here.\n return parsed.toString();\n}\n\n// ---------------------------------------------------------------------------\n// Pipeline stage\n// ---------------------------------------------------------------------------\n\nexport const urlScrub: PipelineStage = (event, _config) => {\n const message = maybeScrubString(event.message);\n const attributes = walkAttributes(event.attributes);\n const context = walkContext(event.context);\n\n let error: ErrorInfo | undefined = undefined;\n if (event.error !== undefined) {\n const scrubbedMessage = maybeScrubString(event.error.message);\n const stack = event.error.stack;\n const scrubbedStack = stack === undefined ? undefined : maybeScrubString(stack);\n error = { name: event.error.name, message: scrubbedMessage };\n if (scrubbedStack !== undefined) error.stack = scrubbedStack;\n }\n\n const noChange =\n message === event.message &&\n attributes === event.attributes &&\n context === event.context &&\n error === event.error;\n if (noChange) return event;\n\n const next: LogEvent = {\n timestamp: event.timestamp,\n level: event.level,\n message,\n attributes,\n context,\n };\n if (error !== undefined) next.error = error;\n return next;\n};\n\n// ---------------------------------------------------------------------------\n// Internals\n// ---------------------------------------------------------------------------\n\nfunction scrubSearchParams(\n parsed: URL,\n extras: ReadonlyArray<string | RegExp>,\n): boolean {\n // Snapshot the original (name, value) sequence so we can rebuild the\n // params in the same order — `params.delete(name)` followed by\n // `params.append(name, REDACTED)` would otherwise move the rewritten\n // param to the end of the search-string output, which is surprising\n // for consumers eyeballing scrubbed URLs.\n const entries: Array<[string, string]> = [];\n for (const [name, value] of parsed.searchParams.entries()) {\n entries.push([name, value]);\n }\n let changed = false;\n for (let i = 0; i < entries.length; i++) {\n // Non-null assertion: `i < entries.length` guarantees the index is\n // populated. Avoids a dead `undefined` branch under\n // `noUncheckedIndexedAccess`.\n const entry = entries[i]!;\n if (isDenied(entry[0], extras)) {\n entries[i] = [entry[0], REDACTED];\n changed = true;\n }\n }\n if (!changed) return false;\n const uniqueKeys = new Set<string>();\n for (const entry of entries) uniqueKeys.add(entry[0]);\n for (const key of uniqueKeys) parsed.searchParams.delete(key);\n for (const [name, value] of entries) parsed.searchParams.append(name, value);\n return true;\n}\n\nfunction scrubHashFragment(\n parsed: URL,\n extras: ReadonlyArray<string | RegExp>,\n): boolean {\n const hash = parsed.hash;\n if (hash.length < 2 || !hash.startsWith('#')) return false;\n const body = hash.slice(1);\n // Fragment must contain a `key=value` pair to be scrubbable.\n if (!body.includes('=')) return false;\n\n const parts = body.split('&');\n let changed = false;\n const out: string[] = [];\n for (const part of parts) {\n const eq = part.indexOf('=');\n if (eq < 0) {\n out.push(part);\n continue;\n }\n const rawKey = part.slice(0, eq);\n const decodedKey = tryDecode(rawKey);\n if (isDenied(decodedKey, extras)) {\n out.push(`${rawKey}=${encodeURIComponent(REDACTED)}`);\n changed = true;\n } else {\n out.push(part);\n }\n }\n if (!changed) return false;\n\n parsed.hash = '#' + out.join('&');\n return true;\n}\n\nfunction isDenied(name: string, extras: ReadonlyArray<string | RegExp>): boolean {\n for (const pattern of DEFAULT_PARAM_DENYLIST) {\n if (pattern.test(name)) return true;\n }\n for (const pattern of extras) {\n if (typeof pattern === 'string') {\n if (pattern.toLowerCase() === name.toLowerCase()) return true;\n } else if (pattern.test(name)) {\n return true;\n }\n }\n return false;\n}\n\nfunction tryDecode(value: string): string {\n try {\n return decodeURIComponent(value);\n } catch {\n return value;\n }\n}\n\n/**\n * Fast-path: only attempt URL parsing for strings that begin with\n * `http://` or `https://`. Keeps the per-emission cost predictable when\n * attributes carry many non-URL strings.\n */\nfunction maybeScrubString(value: string): string {\n if (value.length < 8) return value;\n if (value.startsWith('http://') || value.startsWith('https://')) {\n return scrubUrl(value);\n }\n return value;\n}\n\nfunction walkAttributes(\n attrs: Attributes,\n): Attributes {\n let changed = false;\n let result: { [key: string]: AttributeValue } | null = null;\n for (const key of Object.keys(attrs)) {\n const value = attrs[key];\n if (value === undefined) continue;\n const scrubbed = walkValue(value);\n if (scrubbed !== value) {\n if (result === null) {\n result = {};\n for (const k of Object.keys(attrs)) {\n const existing = attrs[k];\n if (existing !== undefined) result[k] = existing;\n }\n }\n result[key] = scrubbed;\n changed = true;\n }\n }\n return changed && result !== null ? result : attrs;\n}\n\nfunction walkValue(value: AttributeValue): AttributeValue {\n if (typeof value === 'string') return maybeScrubString(value);\n if (Array.isArray(value)) return walkArray(value);\n if (value !== null && typeof value === 'object') return walkAttributes(value);\n return value;\n}\n\nfunction walkArray(arr: AttributeValue[]): AttributeValue[] {\n let changed = false;\n let result: AttributeValue[] | null = null;\n for (let i = 0; i < arr.length; i++) {\n const item = arr[i];\n if (item === undefined) continue;\n const scrubbed = walkValue(item);\n if (scrubbed !== item) {\n if (result === null) result = arr.slice();\n result[i] = scrubbed;\n changed = true;\n }\n }\n return changed && result !== null ? result : arr;\n}\n\nfunction walkContext(context: LogContext): LogContext {\n if (context.attributes === undefined) return context;\n const scrubbed = walkAttributes(context.attributes);\n if (scrubbed === context.attributes) return context;\n return { ...context, attributes: scrubbed };\n}\n","/**\n * Dispatcher — runs an already-built `LogEvent` through the locked\n * security pipeline order and fans the result out directly to the\n * `SafeTransport`-wrapped transports stored on the active runtime.\n *\n * LevelFilter (in logger.ts, upstream of dispatch())\n * ↓\n * EventBuilder (in logger.ts, upstream of dispatch())\n * ↓\n * Sanitize → URLScrub → Redact → ControlCharGuard → Freeze(dev) →\n * SafeTransport[]\n *\n * Each stage is a separate module: `sanitizer.ts`, `url-scrubber.ts`,\n * `redactor.ts`, `control-char-guard.ts`, `freeze.ts`. The wiring\n * below routes events through every stage in the contracted order\n * before any transport sees them (locked as a contract test by T048).\n *\n * Security invariant: **no transport can run before the redactor**.\n * The stage order below is the only emit path. There is no backend\n * indirection in the v1 default path — the dispatcher fans events\n * out directly to the wrapped transports on `runtime.transports`,\n * each already isolated by `SafeTransport` per FS-1/FS-2/FS-11/FS-12.\n *\n * Stage semantics:\n * - Each stage receives the in-flight event + the normalized config.\n * - A stage MAY return a transformed event, the same event, or\n * `null` to **drop the event** (used by the redactor for\n * fail-closed handling per `contracts/redaction.md`).\n *\n * Error semantics:\n * - Any uncaught throw from a stage is caught here and routed\n * through `config.onInternalError`. The event is dropped in that\n * case (fail-closed: we don't emit partially-processed data).\n * - Transport fan-out runs inside per-transport try/catch so a\n * single throwing transport cannot break sibling delivery. Each\n * transport is `SafeTransport`-wrapped at `configureLogging()`\n * time, so the try/catch here is a defensive belt for any\n * residual escape (FS-11 / FS-12).\n *\n * Vendor-neutrality: this module imports no observability-vendor\n * SDK. The seam between core pipeline and consumer transports is a\n * plain function call. Future vendor adapters are implemented as\n * peer transports, not by re-introducing an internal backend indirection.\n */\n\nimport type { LogEvent } from '../api/types.js';\nimport type { NormalizedConfig } from '../config/config.js';\nimport { safeNotify, wrapAsPackageError } from '../internal/errors/internal-errors.js';\nimport { controlCharGuard } from './control-char-guard.js';\nimport { freezeInDev } from './freeze.js';\nimport { redact } from './redactor.js';\nimport { sanitize } from './sanitizer.js';\nimport { urlScrub } from './url-scrubber.js';\n\n/**\n * Pipeline-stage function signature. Returning `null` drops the event.\n *\n * Stages are pure with respect to the `config` argument (read-only).\n * Mutation of the in-flight `event` is allowed within a stage but\n * discouraged — returning a new object keeps stages composable.\n */\nexport type PipelineStage = (\n event: LogEvent,\n config: NormalizedConfig,\n) => LogEvent | null;\n\n/**\n * Run an event through every pipeline stage in order and fan out to\n * the configured transports. Pre-pipeline level filtering happens in\n * `logger.ts` so a filtered-out emission never reaches this function.\n */\nexport function dispatch(event: LogEvent, config: NormalizedConfig): void {\n let current: LogEvent | null;\n try {\n current = sanitize(event, config);\n if (current === null) return;\n\n current = urlScrub(current, config);\n if (current === null) return;\n\n current = redact(current, config);\n if (current === null) return;\n\n current = controlCharGuard(current, config);\n if (current === null) return;\n\n current = freezeInDev(current, config);\n if (current === null) return;\n } catch (err) {\n // Fail-closed: a thrown pipeline stage drops the event entirely\n // and routes the error via `onInternalError`.\n safeNotify(\n config.onInternalError,\n wrapAsPackageError(\n 'redactor_failed',\n 'A pipeline stage threw; the event was dropped (fail-closed).',\n err,\n ),\n );\n return;\n }\n\n // Direct transport fan-out. Each transport in `config.transports` is\n // already `SafeTransport`-wrapped at `configureLogging()` time\n // (`buildConfiguredRuntime` in `runtime/configured-runtime.ts`), so\n // synchronous throws and rejected Promises are isolated inside the\n // wrapper. The per-transport try/catch + Promise rejection swallow\n // below are a defensive belt for any residual escape (e.g., a test\n // that passes a raw transport directly through this function).\n for (const transport of config.transports) {\n try {\n const result = transport.send(current);\n if (result instanceof Promise) {\n result.then(undefined, () => undefined);\n }\n } catch {\n // SafeTransport already catches; this is a defensive belt for\n // unwrapped transports.\n }\n }\n}\n","/**\n * Event builder — packages the inputs that the logger has already merged\n * into the canonical `LogEvent` shape.\n *\n * Responsibilities:\n * - Assign `timestamp` from `new Date().toISOString()`. Consumer-supplied\n * timestamps are NOT accepted (per `contracts/log-event.md` LE-11).\n * - Default `attributes` to `{}`.\n * - Reduce an `unknown` error value to the documented `ErrorInfo` shape\n * (`{ name, message, stack? }`) — never holds onto the raw `Error`.\n *\n * The builder does NOT perform sanitization, redaction, URL scrubbing,\n * or control-char escaping. Those are separate pipeline stages that land\n * in Phase 5 (T031, T032, T034, T035).\n */\n\nimport type {\n Attributes,\n ErrorInfo,\n LogContext,\n LogEvent,\n LogLevel,\n} from '../api/types.js';\n\nexport interface BuildLogEventInput {\n level: LogLevel;\n message: string;\n attributes: Attributes | undefined;\n context: LogContext;\n /** Raw caught value from `logger.error(msg, attrs, err)`; reduced to `ErrorInfo`. */\n errorValue: unknown;\n}\n\n/** Build a canonical `LogEvent` from already-merged inputs. */\nexport function buildLogEvent(input: BuildLogEventInput): LogEvent {\n const event: LogEvent = {\n timestamp: new Date().toISOString(),\n level: input.level,\n message: input.message,\n attributes: input.attributes ?? {},\n context: input.context,\n };\n if (input.errorValue !== undefined) {\n event.error = reduceError(input.errorValue);\n }\n return event;\n}\n\n/**\n * Reduce any `unknown` error value to the documented `ErrorInfo` shape.\n * Non-Error inputs are coerced to `{ name: 'NonError', message: String(value) }`.\n * Exported for unit-testability and for any future pipeline stage that\n * needs to re-reduce an error value (the dispatcher does not today).\n */\nexport function reduceError(value: unknown): ErrorInfo {\n if (value instanceof Error) {\n const info: ErrorInfo = { name: value.name, message: value.message };\n if (value.stack !== undefined) info.stack = value.stack;\n return info;\n }\n return { name: 'NonError', message: String(value) };\n}\n","/**\n * Level filter — the cheapest possible drop-fast step in the pipeline.\n * Runs BEFORE event construction so a filtered-out emission performs no\n * work beyond a constant-time numeric comparison.\n *\n * Resolution chain per `contracts/logger-config.md` LC-1..LC-3 splits\n * across two modules:\n *\n * - `normalizeConfig()` (T006) resolves `LoggerConfig.level`\n * (a `LogLevel`, a `LevelMap` looked up by `environment`, or the\n * env-default table) into a single `LogLevel` stored on\n * `NormalizedConfig.level`. The hard `warn` fallback also happens\n * there.\n *\n * - `passesLevelFilter()` here applies the per-logger\n * `CreateLoggerOptions.level` override on top of that resolved value.\n *\n * `LEVEL_NUMBER` is internal-only (per `data-model.md` \"internal numeric\n * values are not exported\").\n */\n\nimport type { LogLevel } from '../api/types.js';\n\nconst LEVEL_NUMBER: Readonly<Record<LogLevel, number>> = {\n debug: 10,\n info: 20,\n warn: 30,\n error: 40,\n};\n\n/**\n * Resolve the effective minimum level for an emission: a per-logger\n * `CreateLoggerOptions.level` override wins; otherwise the\n * already-resolved `NormalizedConfig.level` applies.\n */\nexport function resolveEffectiveLevel(\n perLoggerLevel: LogLevel | undefined,\n configLevel: LogLevel,\n): LogLevel {\n return perLoggerLevel ?? configLevel;\n}\n\n/**\n * Return `true` if an event at `eventLevel` should reach downstream\n * pipeline stages; `false` if the level filter drops it.\n */\nexport function passesLevelFilter(\n eventLevel: LogLevel,\n perLoggerLevel: LogLevel | undefined,\n configLevel: LogLevel,\n): boolean {\n const effective = resolveEffectiveLevel(perLoggerLevel, configLevel);\n return LEVEL_NUMBER[eventLevel] >= LEVEL_NUMBER[effective];\n}\n","/**\n * Environment-aware default levels and sanitizer-limit bounds. Internal to\n * the package — the values here are the source of truth that\n * `contracts/logger-config.md` and `contracts/sanitization.md` describe.\n *\n * The package MUST NOT read `process.env`, `import.meta.env`, `location`, or\n * `document.cookie`. Consumers MUST pass `environment` explicitly via\n * `configureLogging({ environment })`. The defaults below resolve based on\n * the value the consumer supplied.\n */\n\nimport type { LogLevel, SanitizerLimits } from '../api/types.js';\n\n/** Per-environment baseline minimum level. Unknown environments fall back to `warn`. */\nexport const DEFAULT_LEVEL_BY_ENVIRONMENT: Readonly<Record<string, LogLevel>> = {\n production: 'warn',\n development: 'debug',\n test: 'warn',\n};\n\n/** Hard fallback when no level resolution path yields a value. */\nexport const FALLBACK_LEVEL: LogLevel = 'warn';\n\n/** Default sanitizer bounds per `contracts/sanitization.md`. */\nexport const DEFAULT_SANITIZER_LIMITS: Readonly<SanitizerLimits> = {\n maxDepth: 8,\n maxStringLength: 8192,\n maxArrayLength: 1000,\n maxAttributeCount: 256,\n};\n\n/**\n * Min/Max bounds per sanitizer limit. Consumer-supplied values outside these\n * bounds clamp to the nearest bound and emit one `onInternalError` notice\n * via `normalizeConfig()`.\n */\nexport const SANITIZER_LIMIT_BOUNDS: Readonly<{\n [K in keyof SanitizerLimits]: Readonly<{ min: number; max: number }>;\n}> = {\n maxDepth: { min: 1, max: 16 },\n maxStringLength: { min: 64, max: 65536 },\n maxArrayLength: { min: 1, max: 10000 },\n maxAttributeCount: { min: 1, max: 4096 },\n};\n\n/**\n * Resolve the default level for a given environment string. Returns\n * `FALLBACK_LEVEL` when the environment is undefined or unknown.\n */\nexport function defaultLevelForEnvironment(environment: string | undefined): LogLevel {\n if (environment === undefined) return FALLBACK_LEVEL;\n return DEFAULT_LEVEL_BY_ENVIRONMENT[environment] ?? FALLBACK_LEVEL;\n}\n","/**\n * Configuration normalization. Internal — the resulting `NormalizedConfig`\n * is never exposed to consumers.\n *\n * Normalization is deterministic: given the same `LoggerConfig` input,\n * `normalizeConfig` always produces an equivalent `NormalizedConfig`.\n * `SanitizerLimits` values outside the documented `min`/`max` bounds are\n * clamped, and each clamping event emits one `onInternalError` notice\n * (per `contracts/logger-config.md` LC-10).\n */\n\nimport type {\n AppIdentity,\n LevelMap,\n LogContext,\n LoggerConfig,\n LogLevel,\n ModuleIdentity,\n Redactor,\n SanitizerLimits,\n Transport,\n} from '../api/types.js';\n\nimport { PackageError, safeNotify } from '../internal/errors/internal-errors.js';\n\nimport {\n DEFAULT_SANITIZER_LIMITS,\n SANITIZER_LIMIT_BOUNDS,\n defaultLevelForEnvironment,\n} from './env-defaults.js';\n\n/**\n * Fully-normalized configuration produced by `normalizeConfig`. Internal\n * across the package — never exposed in public types or contracts.\n *\n * Fields are typed as `T | undefined` (rather than `T?`) so consumers of\n * `NormalizedConfig` can rely on the keys always being present, which keeps\n * downstream code stable under `exactOptionalPropertyTypes: true`.\n */\nexport interface NormalizedConfig {\n readonly application: AppIdentity | undefined;\n readonly module: ModuleIdentity | undefined;\n readonly environment: string | undefined;\n /** Single resolved level for the configured environment. */\n readonly level: LogLevel;\n readonly context: Partial<LogContext>;\n readonly correlation: (() => Partial<LogContext>) | undefined;\n readonly transports: ReadonlyArray<Transport>;\n readonly redactor: Redactor | undefined;\n readonly sanitizerLimits: SanitizerLimits;\n readonly onInternalError: (err: Error) => void;\n}\n\n/** Silent default for `onInternalError`. */\nconst NOOP_ON_INTERNAL_ERROR: (err: Error) => void = () => undefined;\n\n/**\n * Produce a `NormalizedConfig` from a consumer `LoggerConfig`. Pure and\n * deterministic apart from invoking the `onInternalError` callback for each\n * out-of-bounds sanitizer limit. Transport factories are invoked once here.\n */\nexport function normalizeConfig(config: LoggerConfig): NormalizedConfig {\n const environment = config.environment;\n const onInternalError = config.onInternalError ?? NOOP_ON_INTERNAL_ERROR;\n\n const sanitizerLimits = resolveSanitizerLimits(\n config.sanitizerLimits,\n onInternalError,\n );\n\n const level = resolveConfigLevel(config.level, environment);\n\n const transports = (config.transports ?? []).map((entry) =>\n typeof entry === 'function' ? entry() : entry,\n );\n\n return {\n application: config.application,\n module: config.module,\n environment,\n level,\n context: config.context ?? {},\n correlation: config.correlation,\n transports,\n redactor: config.redactor,\n sanitizerLimits,\n onInternalError,\n };\n}\n\n/**\n * Resolve `LoggerConfig.level` (which may be a `LogLevel`, a `LevelMap`, or\n * undefined) against the configured environment, falling back to the\n * documented env-default table.\n */\nfunction resolveConfigLevel(\n level: LogLevel | LevelMap | undefined,\n environment: string | undefined,\n): LogLevel {\n if (level === undefined) {\n return defaultLevelForEnvironment(environment);\n }\n if (typeof level === 'string') {\n return level;\n }\n // LevelMap branch — look up by environment, fall back to env default.\n if (environment !== undefined) {\n const map = level as Record<string, LogLevel | undefined>;\n const mapped = map[environment];\n if (mapped !== undefined) return mapped;\n }\n return defaultLevelForEnvironment(environment);\n}\n\n/**\n * Apply consumer-supplied sanitizer-limit overrides on top of the documented\n * defaults, clamping to documented `min`/`max`. Each clamped value emits one\n * `onInternalError` notice per `configureLogging()` call.\n */\nfunction resolveSanitizerLimits(\n overrides: Partial<SanitizerLimits> | undefined,\n onInternalError: (err: Error) => void,\n): SanitizerLimits {\n if (overrides === undefined) {\n return { ...DEFAULT_SANITIZER_LIMITS };\n }\n\n const limits: SanitizerLimits = { ...DEFAULT_SANITIZER_LIMITS };\n const keys = Object.keys(SANITIZER_LIMIT_BOUNDS) as Array<keyof SanitizerLimits>;\n\n for (const key of keys) {\n const requested = overrides[key];\n if (requested === undefined) continue;\n\n const bounds = SANITIZER_LIMIT_BOUNDS[key];\n if (requested > bounds.max) {\n limits[key] = bounds.max;\n safeNotify(\n onInternalError,\n new PackageError(\n 'sanitizer_limit_clamped',\n `sanitizerLimits.${key} value ${String(requested)} exceeds max ${String(bounds.max)}; clamped to ${String(bounds.max)}`,\n ),\n );\n } else if (requested < bounds.min) {\n limits[key] = bounds.min;\n safeNotify(\n onInternalError,\n new PackageError(\n 'sanitizer_limit_clamped',\n `sanitizerLimits.${key} value ${String(requested)} is below min ${String(bounds.min)}; clamped to ${String(bounds.min)}`,\n ),\n );\n } else {\n limits[key] = requested;\n }\n }\n\n return limits;\n}\n","/**\n * Built-in `NoopTransport`. Silently swallows every event.\n *\n * This is the automatic fallback when `LoggerConfig.transports` is\n * undefined or empty (per `contracts/logger-config.md` LC default\n * resolution). Useful in tests, in environments where logging is\n * deliberately disabled, and as a placeholder during incremental\n * configuration.\n */\n\nimport type { Transport, TransportFactory } from '../api/types.js';\n\nexport const NoopTransport: TransportFactory = (): Transport => ({\n name: 'noop',\n send(): void {\n // intentionally empty\n },\n});\n","/**\n * `SafeTransport` wraps any consumer-supplied `Transport` so that synchronous\n * throws and rejected Promises from `send()`, `flush()`, or `shutdown()`\n * never propagate to the caller. The first failure per wrapped transport\n * per session emits one `onInternalError` notice; subsequent failures are\n * silent (no log spam — FS-12).\n *\n * Locks the failure-safety invariants:\n * FS-1 sync throw from send() → caught\n * FS-2 rejected Promise from send() → swallowed (no unhandled rejection)\n * FS-11 one transport throws while others succeed → others still run\n * (the dispatcher iterates over wrapped transports; each is isolated)\n * FS-12 one notice per transport per session\n */\n\nimport type { LogEvent, Transport } from '../api/types.js';\nimport {\n type PackageErrorCode,\n safeNotify,\n wrapAsPackageError,\n} from '../internal/errors/internal-errors.js';\n\nexport class SafeTransport implements Transport {\n readonly name: string;\n private readonly inner: Transport;\n private readonly onInternalError: (err: Error) => void;\n private notified = false;\n\n constructor(inner: Transport, onInternalError: (err: Error) => void) {\n this.inner = inner;\n this.name = inner.name;\n this.onInternalError = onInternalError;\n }\n\n send(event: LogEvent): void {\n try {\n const result = this.inner.send(event);\n if (result instanceof Promise) {\n result.then(undefined, (reason: unknown) => {\n this.notify(reason, 'transport_send_failed');\n });\n }\n } catch (err) {\n this.notify(err, 'transport_send_failed');\n }\n }\n\n async flush(): Promise<void> {\n if (this.inner.flush === undefined) return;\n try {\n await this.inner.flush();\n } catch (err) {\n this.notify(err, 'transport_send_failed');\n }\n }\n\n async shutdown(): Promise<void> {\n if (this.inner.shutdown === undefined) return;\n try {\n await this.inner.shutdown();\n } catch (err) {\n this.notify(err, 'transport_shutdown_failed');\n }\n }\n\n private notify(cause: unknown, code: PackageErrorCode): void {\n if (this.notified) return;\n this.notified = true;\n safeNotify(\n this.onInternalError,\n wrapAsPackageError(\n code,\n `Transport '${this.name}' failed: ${describe(cause)}`,\n cause,\n this.name,\n ),\n );\n }\n}\n\nfunction describe(value: unknown): string {\n if (value instanceof Error) return value.message;\n if (typeof value === 'string') return value;\n return String(value);\n}\n","/**\n * `ConfiguredRuntime` — the shared package-level runtime resource\n * produced by `configureLogging()`.\n *\n * Architectural role (per `plan.md` \"Runtime Scale Architecture\" and\n * constitution v1.2.0 Principle VII): every `Logger` handle reads\n * this runtime at emit time. Logger handles are cheap, side-effect-\n * free context objects; the expensive state (normalized config,\n * already-wrapped `SafeTransport[]`, redactor, sanitizer limits,\n * `onInternalError` sink, correlation hook) lives once here and is\n * shared across every logger derived from a single\n * `configureLogging()` invocation.\n *\n * Per `plan.md`'s \"Vendor-Neutral Core Architecture\", this record\n * has **no `backend` field**. The dispatcher (`pipeline/dispatcher.ts`)\n * fans events out directly to the `SafeTransport`-wrapped transports\n * stored here; there is no telemetry-backend indirection on the v1\n * default path. Future vendor adapters are peer transports, not a\n * resurrected backend slot.\n *\n * The build/shutdown helpers here are pure with respect to the\n * `runtime-ref` slot — they construct + tear down a runtime\n * instance but never touch the active-runtime pointer. The slot\n * swap is performed by `runtime-ref.ts::installRuntime()` so the\n * two responsibilities stay separate.\n */\n\nimport type {\n LogContext,\n LoggerConfig,\n Redactor,\n SanitizerLimits,\n Transport,\n} from '../api/types.js';\nimport { type NormalizedConfig, normalizeConfig } from '../config/config.js';\nimport { NoopTransport } from '../transport/noop-transport.js';\nimport { SafeTransport } from '../transport/safe-transport.js';\n\nexport interface ConfiguredRuntime {\n /**\n * The normalized configuration. `transports` here is the same\n * already-wrapped array exposed on this record's top-level\n * `transports` field; keep both pointers stable for future\n * read-paths that prefer one or the other.\n */\n readonly config: NormalizedConfig;\n\n /**\n * Already-`SafeTransport`-wrapped transports. Each one is isolated\n * for sync throws and rejected Promises (see `SafeTransport`).\n * Empty consumer transport lists are auto-replaced with a single\n * `NoopTransport()` per the documented default in\n * `contracts/failure-safety.md`.\n */\n readonly transports: ReadonlyArray<Transport>;\n\n /** Custom redactor; `undefined` falls back to the default in the redact stage. */\n readonly redactor: Redactor | undefined;\n\n /** Effective sanitizer bounds (clamped to documented Min..Max at normalize time). */\n readonly sanitizerLimits: SanitizerLimits;\n\n /** Diagnostics hook. Always defined (defaults to a no-op silent sink). */\n readonly onInternalError: (err: Error) => void;\n\n /** Per-emit dynamic context hook. Optional. Synchronous. */\n readonly correlation: (() => Partial<LogContext>) | undefined;\n}\n\n/**\n * Build a fresh `ConfiguredRuntime` from a consumer `LoggerConfig`.\n * Normalizes the config (clamps sanitizer limits, resolves level\n * from env defaults, etc.), wraps every consumer transport in\n * `SafeTransport`, and installs the auto-`NoopTransport` fallback\n * for empty transport lists. Pure with respect to the active-\n * runtime slot — call `runtime-ref.ts::installRuntime()` to make\n * the returned record active.\n */\nexport function buildConfiguredRuntime(config: LoggerConfig): ConfiguredRuntime {\n const normalized = normalizeConfig(config);\n\n // Empty consumer transport list → auto-NoopTransport per\n // `contracts/failure-safety.md` \"no transport configured\" row.\n const sourceTransports: ReadonlyArray<Transport> =\n normalized.transports.length === 0\n ? [NoopTransport()]\n : normalized.transports;\n\n const wrapped: ReadonlyArray<Transport> = sourceTransports.map(\n (t) => new SafeTransport(t, normalized.onInternalError),\n );\n\n // Re-build the normalized config with the wrapped transports so\n // downstream code that reads `config.transports` (the dispatcher's\n // direct transport fan-out) sees the wrapped list.\n const installedConfig: NormalizedConfig = {\n ...normalized,\n transports: wrapped,\n };\n\n return {\n config: installedConfig,\n transports: wrapped,\n redactor: normalized.redactor,\n sanitizerLimits: normalized.sanitizerLimits,\n onInternalError: normalized.onInternalError,\n correlation: normalized.correlation,\n };\n}\n\n/**\n * Best-effort teardown of a previously-active `ConfiguredRuntime`.\n * Calls `flush()` then `shutdown()` on every transport, each\n * isolated in its own try/catch so a single transport's failure\n * cannot block sibling teardown. `SafeTransport` already wraps each\n * transport's `flush`/`shutdown` and routes errors through the\n * `onInternalError` sink (with the per-transport notice budget),\n * so the try/catch here is a belt-and-suspenders guard for any\n * residual throw that escapes the wrapper.\n *\n * Pure with respect to the active-runtime slot — the caller is\n * responsible for first swapping the slot via\n * `runtime-ref.ts::installRuntime()` before invoking this\n * function, so retained `Logger` references already see the new\n * runtime when teardown begins.\n */\nexport async function shutdownRuntime(runtime: ConfiguredRuntime): Promise<void> {\n for (const transport of runtime.transports) {\n if (transport.flush !== undefined) {\n try {\n await transport.flush();\n } catch {\n // SafeTransport already notified onInternalError.\n }\n }\n if (transport.shutdown !== undefined) {\n try {\n await transport.shutdown();\n } catch {\n // SafeTransport already notified onInternalError.\n }\n }\n }\n}\n","/**\n * Module-scoped active-runtime slot.\n *\n * The single source of truth for \"which `ConfiguredRuntime` is\n * currently active in this loaded copy of the package.\" Every\n * `Logger` handle reads through `getActiveRuntime()` at emit time,\n * so retained `Logger` references automatically pick up a new\n * runtime after `configureLogging()` performs an atomic swap via\n * `installRuntime()` (locks FR-031 / SC-012).\n *\n * Storage is **module-scoped only** — a top-level `let`. Per\n * constitution v1.2.0 Principle VII and FR-033, the slot:\n * - does NOT use `globalThis` / `window` / `self` / `document`\n * - does NOT register under `Symbol.for(...)`\n * - does NOT install any cross-realm or cross-bundle sharing\n * mechanism\n *\n * That is the load-bearing property that makes duplicate-package-\n * copy behavior **isolated** (FR-033): when a federated bundler\n * causes two physical copies of this package to load on a single\n * page, each copy has its own private `active` variable. Configuring\n * one copy does not affect the other; loggers from one copy cannot\n * cross-route events into the other copy's transports. Consumers\n * who want cross-copy sharing configure their bundler's module-\n * federation `shared` map at build time — there is no runtime\n * back door here.\n *\n * `getActiveRuntime()` returns `undefined` until the first call\n * to `installRuntime()` (or until `configureLogging()` triggers\n * lazy install via the safe-defaults runtime). Callers should\n * handle the undefined case by installing a default; the package's\n * own emit path does this via the lazy-install in\n * `src/api/logger.ts::ensureState()`.\n */\n\nimport type { ConfiguredRuntime } from './configured-runtime.js';\n\n/**\n * The single active-runtime cell. Module-scoped; never exported as a\n * mutable binding. External access goes through `getActiveRuntime()`\n * (read) and `installRuntime()` (atomic write + return-previous).\n */\nlet active: ConfiguredRuntime | undefined;\n\n/**\n * Read the currently-active `ConfiguredRuntime`, or `undefined` if\n * no runtime has been installed yet. Constant-time slot read; no\n * allocation; never throws.\n *\n * Read fresh at every emit so retained logger references see the\n * latest configuration after a swap. Callers MUST NOT cache the\n * result across emits.\n */\nexport function getActiveRuntime(): ConfiguredRuntime | undefined {\n return active;\n}\n\n/**\n * Atomic swap: install `runtime` as the active runtime and return\n * the previously-active one (or `undefined` for the first install).\n *\n * The swap itself is a single assignment, so the slot transitions\n * from \"old\" to \"new\" in one step — no observer can ever see a\n * partially-installed state. Teardown of the previous runtime\n * (flush + shutdown of its transports) is the CALLER's\n * responsibility; this function does not perform any teardown\n * because the caller may want to inspect the previous runtime\n * before tearing it down.\n *\n * `configureLogging()` calls this then schedules\n * `shutdownRuntime(previous)` fire-and-forget so the new runtime\n * is live for the very next emit while the old one's transports\n * are still flushing in the background.\n */\nexport function installRuntime(\n runtime: ConfiguredRuntime,\n): ConfiguredRuntime | undefined {\n const previous = active;\n active = runtime;\n return previous;\n}\n\n/**\n * Reset the active-runtime slot to `undefined`. Test-only helper:\n * the package's own test suite uses this to isolate test cases\n * from each other so a leftover runtime from one test cannot\n * affect the next. Not exposed from the runtime public surface;\n * callers reach for it explicitly only when they have a specific\n * need to drop state (e.g., between `vi.isolateModules` runs in\n * the duplicate-copy isolation test landing in T064).\n */\nexport function clearActiveRuntimeForTests(): void {\n active = undefined;\n}\n","/**\n * Public logger factories and root configuration flow.\n *\n * - `configureLogging(config)` — install (or replace) the package's\n * module-scoped configuration. Atomic: the new runtime is built\n * and installed in a single slot swap, then the previously-active\n * runtime is torn down in the background so existing logger\n * references keep working without modification.\n * - `createLogger(options?)` — return a `Logger` whose context layers\n * on top of the current root configuration.\n * - `getRootLogger()` — singleton root logger created on first access.\n *\n * Behavior before `configureLogging()` is called is identical to a\n * `configureLogging({})` invocation: env-unknown defaults (`warn`+),\n * a single `NoopTransport`, and direct transport fan-out from the\n * dispatcher. All emissions return synchronously and never throw.\n *\n * Vendor-neutrality: this module imports no observability-vendor SDK.\n * The dispatcher fans sanitized + redacted events directly to the\n * `SafeTransport`-wrapped consumer transports stored on the active\n * `ConfiguredRuntime`. There is no telemetry backend in the v1\n * default path; future vendor adapters are peer transports.\n */\n\nimport { mergeContexts } from '../context/context-merge.js';\nimport { safeNotify, wrapAsPackageError } from '../internal/errors/internal-errors.js';\nimport { dispatch } from '../pipeline/dispatcher.js';\nimport { buildLogEvent } from '../pipeline/event-builder.js';\nimport { passesLevelFilter } from '../pipeline/level-filter.js';\nimport {\n type ConfiguredRuntime,\n buildConfiguredRuntime,\n shutdownRuntime,\n} from '../runtime/configured-runtime.js';\nimport {\n getActiveRuntime,\n installRuntime,\n} from '../runtime/runtime-ref.js';\nimport type {\n Attributes,\n CreateLoggerOptions,\n LogContext,\n Logger,\n LoggerConfig,\n LogLevel,\n} from './types.js';\n\nlet rootLogger: Logger | undefined;\n\n/**\n * Build a fresh `ConfiguredRuntime` from `config`, install it as the\n * active runtime, and shut down the previously-active runtime's\n * transports in the background. The runtime-slot swap is atomic:\n * retained `Logger` references that read through `getActiveRuntime()`\n * at emit time see the new runtime immediately.\n */\nfunction installState(config: LoggerConfig): ConfiguredRuntime {\n const runtime = buildConfiguredRuntime(config);\n\n // Atomic active-runtime swap. After this assignment retained\n // Logger references see the new runtime; the old runtime's\n // transports continue to flush + shutdown in the background.\n const previousRuntime = installRuntime(runtime);\n\n // Fire-and-forget teardown of the previous runtime. Each transport's\n // flush/shutdown is already isolated by SafeTransport; the\n // `.then(undefined, …)` is a final unhandled-rejection swallow per\n // the no-throw invariant.\n if (previousRuntime !== undefined) {\n void shutdownRuntime(previousRuntime).then(undefined, () => undefined);\n }\n return runtime;\n}\n\n/** Lazily install safe defaults so pre-configure emissions just work. */\nfunction ensureState(): ConfiguredRuntime {\n let runtime = getActiveRuntime();\n if (runtime === undefined) {\n runtime = installState({});\n }\n return runtime;\n}\n\n/**\n * Install or replace the package's configuration. Safe to call multiple\n * times — the previous runtime's transports are flushed + shut down\n * (fire-and-forget) and the new configuration is installed via an\n * atomic active-runtime-slot swap, so existing logger references\n * continue to work without re-acquisition.\n *\n * Per FR-031 / SC-012, the swap is observable to any subsequent emit\n * from a retained `Logger` reference: emit reads through\n * `getActiveRuntime()` at the time of the call, so the new runtime is\n * live for the very next emission.\n *\n * Per FR-032 the call is the single explicit named API for installing\n * a runtime. There is no implicit module-load side effect that\n * replaces the runtime; only an explicit `configureLogging()`\n * invocation can swap it.\n */\nexport function configureLogging(config: LoggerConfig): void {\n installState(config);\n}\n\n/**\n * Create a logger whose context layers on top of the current root\n * configuration. The returned logger holds no captured state — every\n * emission reads the *current* module-scoped configuration, so calling\n * `configureLogging()` later affects loggers already created.\n */\nexport function createLogger(options: CreateLoggerOptions = {}): Logger {\n return makeLogger(options, []);\n}\n\n/** Singleton root logger created on first access. */\nexport function getRootLogger(): Logger {\n if (rootLogger === undefined) {\n rootLogger = createLogger();\n }\n return rootLogger;\n}\n\nfunction makeLogger(\n options: CreateLoggerOptions,\n chainedContexts: ReadonlyArray<Partial<LogContext>>,\n): Logger {\n // Per-logger context, including the optional `module` shortcut. If both\n // `options.module` and `options.context.module` are set, the explicit\n // `options.module` shortcut wins because it is appended last to the\n // merge precedence chain.\n const loggerContextLayers: ReadonlyArray<Partial<LogContext>> = [\n options.context ?? {},\n options.module !== undefined ? { module: options.module } : {},\n ];\n\n function emit(\n level: LogLevel,\n message: string,\n attributes?: Attributes,\n errorValue?: unknown,\n ): void {\n const runtime = ensureState();\n const cfg = runtime.config;\n\n // Level filter — runs first so a filtered-out emission performs no\n // work beyond a constant-time numeric comparison.\n if (!passesLevelFilter(level, options.level, cfg.level)) {\n return;\n }\n\n // Root identity carried at the LoggerConfig top level becomes the\n // lowest-precedence layer; per-logger / child / correlation override.\n const rootIdentity: Partial<LogContext> = {};\n if (cfg.application !== undefined) {\n rootIdentity.application = cfg.application;\n }\n if (cfg.module !== undefined) {\n rootIdentity.module = cfg.module;\n }\n if (cfg.environment !== undefined) {\n rootIdentity.environment = cfg.environment;\n }\n\n // Invoke correlation() inside a guard so a throwing callback drops\n // its contribution for this event but does not drop the event.\n let correlation: Partial<LogContext> | undefined;\n if (cfg.correlation !== undefined) {\n try {\n correlation = cfg.correlation();\n } catch (err) {\n safeNotify(\n cfg.onInternalError,\n wrapAsPackageError(\n 'correlation_failed',\n 'correlation() callback threw; its output is dropped for this event.',\n err,\n ),\n );\n }\n }\n\n // Documented merge precedence (data-model.md, contracts/logger-config.md\n // LC-7): root → per-logger → child chain → correlation. The prior code\n // had `chainedContexts` BEFORE `loggerContextLayers`, which caused a\n // per-logger `module` identity to win over a `.child({ module: ... })`\n // override (locked as a regression by T053).\n const context = mergeContexts(\n rootIdentity,\n cfg.context,\n ...loggerContextLayers,\n ...chainedContexts,\n correlation,\n );\n\n const event = buildLogEvent({\n level,\n message,\n attributes,\n context,\n errorValue,\n });\n\n // Route through the locked pipeline order in src/pipeline/dispatcher.ts:\n // Sanitize → URLScrub → Redact → ControlCharGuard → Freeze →\n // direct transport fan-out. The dispatcher owns its own try/catch\n // around every stage and around every transport.send() call, so no\n // error can escape into this caller.\n dispatch(event, cfg);\n }\n\n return {\n debug(message, attributes) {\n emit('debug', message, attributes);\n },\n info(message, attributes) {\n emit('info', message, attributes);\n },\n warn(message, attributes) {\n emit('warn', message, attributes);\n },\n error(message, attributes, errorValue) {\n emit('error', message, attributes, errorValue);\n },\n child(context) {\n return makeLogger(options, [...chainedContexts, context]);\n },\n withContext(context) {\n return makeLogger(options, [...chainedContexts, context]);\n },\n };\n}\n","/**\n * Built-in `ConsoleTransport`. Passes events to `console[level]` with the\n * event message as the first argument and the **structured `LogEvent`\n * object as the second argument** — never interpolated into a single\n * string. Falls back to `console.log` only when `console[level]` is not a\n * function (the modern browser console always defines all four levels).\n *\n * This is the only built-in delivery path that produces visible output.\n * Console output preserves the structured-only invariant (FR-016, plan\n * §Log-injection & output safety).\n */\n\nimport type { LogEvent, Transport, TransportFactory } from '../api/types.js';\n\ntype ConsoleMethod = (message?: unknown, ...optional: unknown[]) => void;\n\nfunction resolveConsoleMethod(level: LogEvent['level']): ConsoleMethod {\n const slot = (console as unknown as Record<string, unknown>)[level];\n if (typeof slot === 'function') {\n return (slot as ConsoleMethod).bind(console);\n }\n return console.log.bind(console);\n}\n\nexport const ConsoleTransport: TransportFactory = (): Transport => ({\n name: 'console',\n send(event: LogEvent): void {\n const log = resolveConsoleMethod(event.level);\n log(event.message, event);\n },\n});\n"]}
1
+ {"version":3,"sources":["../src/context/context-merge.ts","../src/internal/errors/internal-errors.ts","../src/pipeline/control-char-guard.ts","../src/pipeline/freeze.ts","../src/pipeline/redactor.ts","../src/pipeline/sanitizer.ts","../src/pipeline/url-scrubber.ts","../src/pipeline/dispatcher.ts","../src/pipeline/event-builder.ts","../src/pipeline/level-filter.ts","../src/config/env-defaults.ts","../src/config/config.ts","../src/transport/noop-transport.ts","../src/transport/safe-transport.ts","../src/runtime/configured-runtime.ts","../src/runtime/runtime-ref.ts","../src/trace/validate.ts","../src/api/logger.ts","../src/trace/traceparent.ts","../src/transport/console-transport.ts"],"names":["active","walkContext","walkArray","walkAttributes","walkValue"],"mappings":";;;AAkCO,SAAS,iBACX,OAAA,EACS;AACZ,EAAA,MAAM,SAMF,EAAC;AAEL,EAAA,KAAA,MAAW,OAAO,OAAA,EAAS;AACzB,IAAA,IAAI,QAAQ,MAAA,EAAW;AAEvB,IAAA,IAAI,GAAA,CAAI,gBAAgB,MAAA,EAAW;AACjC,MAAA,MAAA,CAAO,cAAc,GAAA,CAAI,WAAA;AAAA,IAC3B;AACA,IAAA,IAAI,GAAA,CAAI,WAAW,MAAA,EAAW;AAC5B,MAAA,MAAA,CAAO,SAAS,GAAA,CAAI,MAAA;AAAA,IACtB;AACA,IAAA,IAAI,GAAA,CAAI,gBAAgB,MAAA,EAAW;AACjC,MAAA,MAAA,CAAO,cAAc,GAAA,CAAI,WAAA;AAAA,IAC3B;AACA,IAAA,IAAI,GAAA,CAAI,eAAe,MAAA,EAAW;AAChC,MAAA,MAAA,CAAO,UAAA,GAAa,mBAAA;AAAA,QAClB,MAAA,CAAO,cAAc,EAAC;AAAA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-7):\n *\n * Sources in increasing precedence order (later wins):\n * 1. configureLogging({ context }) — root static context\n * 2. createLogger({ context }) — per-logger static context\n * 3. logger.child(context) chain — derived loggers\n * 4. correlation() return value — per-emit dynamic context\n *\n * For each source:\n * - `application`, `module`, `environment` — shallow replace if defined\n * - `attributes` — **deep-merge** key-by-key (per `data-model.md`):\n * * if both sides have a plain-object value for the same key, recurse\n * * otherwise the later value replaces the earlier\n * * arrays are treated as leaves and replaced wholesale (the later\n * array wins; we never concatenate)\n *\n * Undefined keys in a later source do NOT overwrite earlier definitions.\n *\n * The function is pure: it never mutates its inputs. The output's\n * `attributes` is always a fresh object — callers receive an independent\n * copy that they may not mutate, but mutating it would not corrupt any\n * source's `attributes`.\n */\n\nimport type { Attributes, AttributeValue, LogContext } from '../api/types.js';\n\n/**\n * Merge an ordered list of partial contexts into a single `LogContext`.\n * `undefined` sources are skipped, which lets callers pass an unconditional\n * sequence without having to filter beforehand.\n */\nexport function mergeContexts(\n ...sources: ReadonlyArray<Partial<LogContext> | undefined>\n): LogContext {\n const merged: {\n application?: LogContext['application'];\n module?: LogContext['module'];\n environment?: string;\n attributes?: Attributes;\n trace?: LogContext['trace'];\n } = {};\n\n for (const src of sources) {\n if (src === undefined) continue;\n\n if (src.application !== undefined) {\n merged.application = src.application;\n }\n if (src.module !== undefined) {\n merged.module = src.module;\n }\n if (src.environment !== undefined) {\n merged.environment = src.environment;\n }\n if (src.attributes !== undefined) {\n merged.attributes = deepMergeAttributes(\n merged.attributes ?? {},\n src.attributes,\n );\n }\n // `trace` is an atomic identity unit — shallow-replace if defined (like\n // application/module). Deep-merging could mix a traceId from one layer\n // with a spanId from another, producing an incoherent record. Validation\n // (normalizeTraceContext) happens once after merge, in the emit path.\n if (src.trace !== undefined) {\n merged.trace = src.trace;\n }\n }\n\n // Build the final value without writing `undefined` properties (required\n // by `exactOptionalPropertyTypes: true`).\n const out: LogContext = {};\n if (merged.application !== undefined) out.application = merged.application;\n if (merged.module !== undefined) out.module = merged.module;\n if (merged.environment !== undefined) out.environment = merged.environment;\n if (merged.attributes !== undefined) out.attributes = merged.attributes;\n if (merged.trace !== undefined) out.trace = merged.trace;\n return out;\n}\n\n/**\n * Deep-merge two `Attributes` records. The earlier record provides the\n * base; the later record overlays on top. For keys present in both:\n * - plain-object × plain-object → recurse\n * - any other shape combination → later value wins (replaces wholesale)\n * Arrays are treated as leaves and replaced, not concatenated, so a\n * later layer's array fully replaces the earlier layer's.\n *\n * Pure: never mutates `earlier` or `later`. Always returns a fresh\n * object for the merged result.\n */\nfunction deepMergeAttributes(\n earlier: Attributes,\n later: Attributes,\n): Attributes {\n const result: { [key: string]: AttributeValue } = { ...earlier };\n for (const key of Object.keys(later)) {\n const laterValue = later[key];\n if (laterValue === undefined) continue;\n const earlierValue = result[key];\n if (\n isPlainAttributeObject(earlierValue) &&\n isPlainAttributeObject(laterValue)\n ) {\n result[key] = deepMergeAttributes(earlierValue, laterValue);\n } else {\n result[key] = laterValue;\n }\n }\n return result;\n}\n\nfunction isPlainAttributeObject(\n value: AttributeValue | undefined,\n): value is Attributes {\n return (\n value !== null &&\n value !== undefined &&\n typeof value === 'object' &&\n !Array.isArray(value)\n );\n}\n","/**\n * Internal error type with a non-enumerable symbol marker so the dispatcher\n * can distinguish package-internal errors from consumer-thrown errors\n * without losing stack info. Never exported from the public surface.\n */\n\nconst PACKAGE_ERROR_MARKER = Symbol('frontend-logging-sdk/package-error');\n\n/**\n * Discriminator for which internal failure mode produced a `PackageError`.\n * Categorizes errors routed through `LoggerConfig.onInternalError`.\n */\nexport type PackageErrorCode =\n | 'transport_send_failed'\n | 'transport_init_failed'\n | 'transport_shutdown_failed'\n | 'redactor_failed'\n | 'correlation_failed'\n | 'backend_init_failed'\n | 'backend_handle_failed'\n | 'sanitizer_limit_clamped'\n | 'no_transport_configured';\n\nexport interface PackageErrorOptions {\n /** The underlying error that caused this one, if any. */\n cause?: unknown;\n /** Transport name when the failure is transport-scoped. */\n transportName?: string;\n}\n\n/**\n * Internal error class carrying a structured `code`, optional cause, and\n * optional transport name. Extends the standard `Error` so it satisfies the\n * public `onInternalError: (err: Error) => void` signature without leaking\n * any of these internal fields' types into the public surface.\n */\nexport class PackageError extends Error {\n readonly code: PackageErrorCode;\n readonly transportName?: string;\n // ES2022 standard Error.cause — declared so this typechecks regardless of\n // the current `lib` setting in tsconfig.\n declare cause?: unknown;\n\n constructor(\n code: PackageErrorCode,\n message: string,\n options: PackageErrorOptions = {},\n ) {\n super(message);\n this.name = 'PackageError';\n this.code = code;\n if (options.cause !== undefined) {\n this.cause = options.cause;\n }\n if (options.transportName !== undefined) {\n this.transportName = options.transportName;\n }\n // Non-enumerable marker so `Object.keys(err)` and JSON serialization\n // don't expose the internal sentinel.\n Object.defineProperty(this, PACKAGE_ERROR_MARKER, {\n value: true,\n enumerable: false,\n writable: false,\n configurable: false,\n });\n }\n}\n\n/**\n * Type guard for `PackageError` instances. Detects errors created by this\n * package even across realm boundaries (different bundler outputs sharing\n * the same `Symbol.for(...)` registry — note we use a module-local Symbol\n * deliberately to scope detection to instances created by *this* loaded\n * copy of the package, not other copies in module-federated environments).\n */\nexport function isPackageError(value: unknown): value is PackageError {\n if (typeof value !== 'object' || value === null) return false;\n return (value as Record<symbol, unknown>)[PACKAGE_ERROR_MARKER] === true;\n}\n\n/**\n * Wrap an arbitrary caught value as a `PackageError`. If `cause` is already\n * a `PackageError`, it is returned as-is so we don't lose the original\n * `code` / `transportName` from a deeper layer.\n */\nexport function wrapAsPackageError(\n code: PackageErrorCode,\n message: string,\n cause: unknown,\n transportName?: string,\n): PackageError {\n if (isPackageError(cause)) return cause;\n const options: PackageErrorOptions = { cause };\n if (transportName !== undefined) {\n options.transportName = transportName;\n }\n return new PackageError(code, message, options);\n}\n\n/**\n * Invoke a consumer-supplied `onInternalError` callback inside an isolating\n * try/catch. Required by the constitution and the failure-safety contract:\n * NO path inside the package may propagate a throw to a consumer logging\n * call site — including throws from the diagnostics hook itself.\n *\n * This is the single helper every internal site must use when notifying\n * `onInternalError`; bare invocations are a hazard.\n */\nexport function safeNotify(\n onInternalError: (err: Error) => void,\n err: PackageError,\n): void {\n try {\n onInternalError(err);\n } catch {\n // Consumer-supplied onInternalError threw. Nothing further we can do\n // without violating the no-throw invariant — swallow.\n }\n}\n","/**\n * Control-character guard. Walks every string value in the event and\n * escapes ASCII control characters (`\\x00`–`\\x1F` except `\\t`, `\\n`,\n * `\\r`) plus the line separators U+2028 and U+2029.\n *\n * Contract: `contracts/log-event.md` (\"Pipeline-applied transformations\"\n * row 4) + plan.md \"Security Architecture > Log-injection & output\n * safety\".\n *\n * Scope:\n * - `event.message`\n * - every string in `event.attributes` (recursive into nested\n * plain objects and arrays produced by the sanitizer)\n * - every string in `event.context.attributes` (same recursion)\n * - `event.error.name`, `event.error.message`, and (if present)\n * `event.error.stack`\n *\n * Escape format: each targeted character is replaced with its\n * six-character escape literal — `\\uXXXX` (lowercase 4-digit hex,\n * zero-padded). This is the conventional representation, unambiguous\n * when serialized into JSON and rendered by any downstream log viewer.\n *\n * `\\t` (U+0009), `\\n` (U+000A), and `\\r` (U+000D) are deliberately\n * preserved — log-injection resistance is provided by\n * `ConsoleTransport`'s object-mode output (event passed as the second\n * argument to `console[level]`, never interpolated into a single line),\n * not by mutating those characters. See plan.md \"Log-injection &\n * output safety\" for the full rationale.\n *\n * NEVER throws: every branch returns a value; the regex match cannot\n * throw on any input.\n */\n\nimport type {\n Attributes,\n AttributeValue,\n ErrorInfo,\n LogContext,\n LogEvent,\n} from '../api/types.js';\nimport type { PipelineStage } from './dispatcher.js';\n\n// Targeted code points:\n// U+0000..U+0008 (NUL through BS)\n// U+000B..U+000C (VT, FF)\n// U+000E..U+001F (SO through US)\n// U+2028 (LINE SEPARATOR)\n// U+2029 (PARAGRAPH SEPARATOR)\n// Excluded by design: U+0009 (\\t), U+000A (\\n), U+000D (\\r).\n//\n// Built from explicit `\\u` escapes in a string and compiled at module\n// load time so the source file carries no literal control bytes (which\n// would otherwise be hostile to editors, diff viewers, and security\n// scanners).\nconst CONTROL_CHAR_CLASS =\n '[\\\\u0000-\\\\u0008\\\\u000B\\\\u000C\\\\u000E-\\\\u001F\\\\u2028\\\\u2029]';\nconst HAS_CONTROL_CHAR = new RegExp(CONTROL_CHAR_CLASS);\nconst CONTROL_CHAR_GLOBAL = new RegExp(CONTROL_CHAR_CLASS, 'g');\n\nfunction escapeControlChars(value: string): string {\n if (!HAS_CONTROL_CHAR.test(value)) return value;\n return value.replace(CONTROL_CHAR_GLOBAL, (ch) => {\n const code = ch.charCodeAt(0);\n return `\\\\u${code.toString(16).padStart(4, '0')}`;\n });\n}\n\nexport const controlCharGuard: PipelineStage = (event, _config) => {\n const message = escapeControlChars(event.message);\n const attributes = walkAttributes(event.attributes);\n const context = walkContext(event.context);\n\n let error: ErrorInfo | undefined;\n if (event.error !== undefined) {\n const escName = escapeControlChars(event.error.name);\n const escMessage = escapeControlChars(event.error.message);\n const stack = event.error.stack;\n const escStack =\n stack === undefined ? undefined : escapeControlChars(stack);\n if (\n escName === event.error.name &&\n escMessage === event.error.message &&\n escStack === stack\n ) {\n error = event.error;\n } else {\n error = { name: escName, message: escMessage };\n if (escStack !== undefined) error.stack = escStack;\n }\n }\n\n const noChange =\n message === event.message &&\n attributes === event.attributes &&\n context === event.context &&\n error === event.error;\n if (noChange) return event;\n\n const next: LogEvent = {\n timestamp: event.timestamp,\n level: event.level,\n message,\n attributes,\n context,\n };\n if (error !== undefined) next.error = error;\n return next;\n};\n\nfunction walkAttributes(attrs: Attributes): Attributes {\n let changed = false;\n let result: { [key: string]: AttributeValue } | null = null;\n for (const key of Object.keys(attrs)) {\n const value = attrs[key];\n if (value === undefined) continue;\n const escaped = walkValue(value);\n if (escaped !== value) {\n if (result === null) {\n result = {};\n for (const k of Object.keys(attrs)) {\n const existing = attrs[k];\n if (existing !== undefined) result[k] = existing;\n }\n }\n result[key] = escaped;\n changed = true;\n }\n }\n return changed && result !== null ? result : attrs;\n}\n\nfunction walkValue(value: AttributeValue): AttributeValue {\n if (typeof value === 'string') return escapeControlChars(value);\n if (Array.isArray(value)) return walkArray(value);\n if (value !== null && typeof value === 'object') return walkAttributes(value);\n return value;\n}\n\nfunction walkArray(arr: AttributeValue[]): AttributeValue[] {\n let changed = false;\n let result: AttributeValue[] | null = null;\n for (let i = 0; i < arr.length; i++) {\n const item = arr[i];\n if (item === undefined) continue;\n const escaped = walkValue(item);\n if (escaped !== item) {\n if (result === null) result = arr.slice();\n result[i] = escaped;\n changed = true;\n }\n }\n return changed && result !== null ? result : arr;\n}\n\nfunction walkContext(context: LogContext): LogContext {\n if (context.attributes === undefined) return context;\n const escaped = walkAttributes(context.attributes);\n if (escaped === context.attributes) return context;\n return { ...context, attributes: escaped };\n}\n","import type { PipelineStage } from './dispatcher.js';\n\nexport const freezeInDev: PipelineStage = (event, _config) => {\n if (!__DEV__) return event;\n deepFreeze(event);\n return event;\n};\n\nfunction deepFreeze(value: object): void {\n if (Object.isFrozen(value)) return;\n Object.freeze(value);\n for (const key of Object.keys(value)) {\n const child = (value as Record<string, unknown>)[key];\n if (child !== null && typeof child === 'object') {\n deepFreeze(child);\n }\n }\n}\n","/**\n * Redactor — masks values whose **key** matches the default denylist\n * (case-insensitive, immediate property name only, never a value\n * substring) and values whose **shape** matches a documented sensitive\n * pattern (JWT, Bearer-prefixed token). Runs in the pipeline AFTER the\n * sanitizer and URL scrubber have normalized the event and BEFORE the\n * control-char guard, freeze, and any transport.\n *\n * Contract: `contracts/redaction.md` (R-1..R-10).\n *\n * Two surfaces:\n * - `redact` (pipeline stage): wraps `config.redactor` (or the\n * default `createRedactor()` when not supplied), invokes it\n * synchronously, and enforces the fail-closed contract:\n * * If the redactor throws, the dispatcher's outer try/catch\n * drops the event and routes the throw to `onInternalError`.\n * * If the redactor returns `null`, the event is dropped (the\n * pipeline contract for explicit drop).\n * * If the redactor returns a value that is neither a LogEvent\n * nor `null`, this stage throws a `PackageError('redactor_failed')`\n * so the same fail-closed path applies.\n * - `createRedactor(rules?)` (public, re-exported from\n * `src/index.ts`): returns a `Redactor` configured with the\n * default rules when called with no argument, or with the\n * consumer's rule set (FULL replacement of defaults) when an\n * array is supplied. An empty array is a valid no-op rule set.\n *\n * Match semantics (per contract):\n * - **Key match**: a rule's `key` is tested against the immediate\n * property name being inspected. String keys match via case-\n * insensitive equality; RegExp keys match via `.test()`. A match\n * replaces the entire value (including object/array subtrees)\n * with `rule.replacement ?? '[REDACTED]'`. Recursion does not\n * descend into a value whose key matched — the whole subtree is\n * considered sensitive.\n * - **Shape match**: a rule's `shape` (RegExp) is tested against\n * leaf string values regardless of key context. A match replaces\n * the value with `rule.replacement ?? '[REDACTED]'`. Shape rules\n * do not match objects or arrays as containers — only leaf\n * strings.\n * - **Combination**: a rule with both `key` and `shape` matches\n * when either matches.\n *\n * Scope per field:\n * - `event.attributes` — recursive walk; key + shape rules apply.\n * - `event.context.attributes` — same recursive walk.\n * - `event.message` — string scan; shape rules only (no key context).\n * - `event.error.name`, `event.error.message`, `event.error.stack` —\n * string scan; shape rules only.\n */\n\nimport type {\n Attributes,\n AttributeValue,\n ErrorInfo,\n LogContext,\n LogEvent,\n LogLevel,\n RedactionRule,\n Redactor,\n} from '../api/types.js';\nimport { PackageError } from '../internal/errors/internal-errors.js';\nimport type { PipelineStage } from './dispatcher.js';\n\nconst DEFAULT_REPLACEMENT = '[REDACTED]';\n\n// Default rule set — must mirror contracts/redaction.md.\nconst DEFAULT_RULES: ReadonlyArray<RedactionRule> = [\n // Key rules (immediate-name match, case-insensitive).\n { key: /^password$|^passwd$/i },\n { key: /^token$|access[_-]?token|refresh[_-]?token|bearer[_-]?token/i },\n { key: /^authorization$|^auth$/i },\n { key: /^cookie$|^set-cookie$/i },\n { key: /^secret$/i },\n { key: /api[_-]?key/i },\n { key: /session[_-]?id|^sid$/i },\n { key: /^ssn$/i },\n { key: /credit[_-]?card|^cardNumber$|^cvv$/i },\n // Shape rules (leaf-string match).\n { shape: /^[A-Za-z0-9_-]{8,}\\.[A-Za-z0-9_-]{8,}\\.[A-Za-z0-9_-]{8,}$/ },\n { shape: /^Bearer\\s+[A-Za-z0-9._-]+$/i },\n];\n\ninterface KeyRule {\n readonly match: (key: string) => boolean;\n readonly replacement: string;\n}\n\ninterface ShapeRule {\n readonly pattern: RegExp;\n readonly replacement: string;\n}\n\ninterface CompiledRules {\n readonly keyRules: ReadonlyArray<KeyRule>;\n readonly shapeRules: ReadonlyArray<ShapeRule>;\n}\n\nfunction compileRules(rules: ReadonlyArray<RedactionRule>): CompiledRules {\n const keyRules: KeyRule[] = [];\n const shapeRules: ShapeRule[] = [];\n for (const rule of rules) {\n const replacement = rule.replacement ?? DEFAULT_REPLACEMENT;\n if (rule.key !== undefined) {\n keyRules.push(makeKeyRule(rule.key, replacement));\n }\n if (rule.shape !== undefined) {\n shapeRules.push({ pattern: rule.shape, replacement });\n }\n }\n return { keyRules, shapeRules };\n}\n\nfunction makeKeyRule(key: string | RegExp, replacement: string): KeyRule {\n if (typeof key === 'string') {\n const expected = key.toLowerCase();\n return {\n match: (candidate) => candidate.toLowerCase() === expected,\n replacement,\n };\n }\n return { match: (candidate) => key.test(candidate), replacement };\n}\n\n// ---------------------------------------------------------------------------\n// Public factory\n// ---------------------------------------------------------------------------\n\nexport function createRedactor(rules?: RedactionRule[]): Redactor {\n const active = rules ?? DEFAULT_RULES;\n const compiled = compileRules(active);\n\n return function defaultStyleRedactor(event: LogEvent): LogEvent | null {\n const attributes = walkObject(event.attributes, compiled);\n const context = walkContext(event.context, compiled);\n const message = applyShapeRules(event.message, compiled.shapeRules);\n\n let error: ErrorInfo | undefined = event.error;\n if (event.error !== undefined) {\n const escName = applyShapeRules(event.error.name, compiled.shapeRules);\n const escMessage = applyShapeRules(\n event.error.message,\n compiled.shapeRules,\n );\n const stack = event.error.stack;\n const escStack =\n stack === undefined\n ? undefined\n : applyShapeRules(stack, compiled.shapeRules);\n const errorChanged =\n escName !== event.error.name ||\n escMessage !== event.error.message ||\n escStack !== stack;\n if (errorChanged) {\n error = { name: escName, message: escMessage };\n if (escStack !== undefined) error.stack = escStack;\n }\n }\n\n const noChange =\n attributes === event.attributes &&\n context === event.context &&\n message === event.message &&\n error === event.error;\n if (noChange) return event;\n\n const next: LogEvent = {\n timestamp: event.timestamp,\n level: event.level,\n message,\n attributes,\n context,\n };\n if (error !== undefined) next.error = error;\n return next;\n };\n}\n\n// ---------------------------------------------------------------------------\n// Pipeline stage\n// ---------------------------------------------------------------------------\n\nlet cachedDefaultRedactor: Redactor | null = null;\nfunction getDefaultRedactor(): Redactor {\n if (cachedDefaultRedactor === null) {\n cachedDefaultRedactor = createRedactor();\n }\n return cachedDefaultRedactor;\n}\n\nexport const redact: PipelineStage = (event, config) => {\n const redactor = config.redactor ?? getDefaultRedactor();\n // Any throw from the redactor escapes here; the dispatcher's outer\n // try/catch will route it through onInternalError as fail-closed.\n const result = redactor(event);\n if (result === null) return null;\n if (!isLogEventShape(result)) {\n throw new PackageError(\n 'redactor_failed',\n 'Redactor returned a value that is neither a LogEvent nor null; the event is dropped (fail-closed).',\n );\n }\n return result;\n};\n\n// ---------------------------------------------------------------------------\n// Internals\n// ---------------------------------------------------------------------------\n\nfunction walkObject(attrs: Attributes, rules: CompiledRules): Attributes {\n let changed = false;\n let result: { [key: string]: AttributeValue } | null = null;\n for (const key of Object.keys(attrs)) {\n const value = attrs[key];\n if (value === undefined) continue;\n\n const newValue = redactValueAtKey(value, key, rules);\n if (newValue !== value) {\n if (result === null) {\n result = {};\n for (const k of Object.keys(attrs)) {\n const existing = attrs[k];\n if (existing !== undefined) result[k] = existing;\n }\n }\n result[key] = newValue;\n changed = true;\n }\n }\n return changed && result !== null ? result : attrs;\n}\n\nfunction walkContext(context: LogContext, rules: CompiledRules): LogContext {\n if (context.attributes === undefined) return context;\n const next = walkObject(context.attributes, rules);\n if (next === context.attributes) return context;\n return { ...context, attributes: next };\n}\n\nfunction redactValueAtKey(\n value: AttributeValue,\n key: string,\n rules: CompiledRules,\n): AttributeValue {\n // Key rules win: a key match replaces the WHOLE subtree under that key\n // (including nested objects/arrays) so we never recurse into a value\n // whose key marks it sensitive.\n for (const rule of rules.keyRules) {\n if (rule.match(key)) return rule.replacement;\n }\n\n if (typeof value === 'string') {\n return applyShapeRules(value, rules.shapeRules);\n }\n if (Array.isArray(value)) {\n return walkArray(value, rules);\n }\n if (value !== null && typeof value === 'object') {\n return walkObject(value, rules);\n }\n return value;\n}\n\nfunction walkArray(\n arr: AttributeValue[],\n rules: CompiledRules,\n): AttributeValue[] {\n let changed = false;\n let result: AttributeValue[] | null = null;\n for (let i = 0; i < arr.length; i++) {\n const item = arr[i];\n if (item === undefined) continue;\n let newItem: AttributeValue;\n if (typeof item === 'string') {\n newItem = applyShapeRules(item, rules.shapeRules);\n } else if (Array.isArray(item)) {\n newItem = walkArray(item, rules);\n } else if (item !== null && typeof item === 'object') {\n newItem = walkObject(item, rules);\n } else {\n newItem = item;\n }\n if (newItem !== item) {\n if (result === null) result = arr.slice();\n result[i] = newItem;\n changed = true;\n }\n }\n return changed && result !== null ? result : arr;\n}\n\nfunction applyShapeRules(\n value: string,\n rules: ReadonlyArray<ShapeRule>,\n): string {\n for (const rule of rules) {\n if (rule.pattern.test(value)) return rule.replacement;\n }\n return value;\n}\n\nconst VALID_LEVELS: ReadonlySet<LogLevel> = new Set<LogLevel>([\n 'debug',\n 'info',\n 'warn',\n 'error',\n]);\n\nfunction isLogEventShape(value: unknown): value is LogEvent {\n // `null` is intercepted by the upstream `result === null` check in\n // `redact()` (a redactor returning `null` is a valid drop, not a\n // shape failure), so the `value === null` half of the guard below\n // is unreachable via the configured pipeline. Kept as defense in\n // depth for any future call site that bypasses the upstream check.\n if (\n typeof value !== 'object' ||\n /* v8 ignore next */\n value === null\n ) {\n return false;\n }\n const obj = value as Record<string, unknown>;\n if (typeof obj.timestamp !== 'string') return false;\n if (typeof obj.level !== 'string') return false;\n if (!VALID_LEVELS.has(obj.level as LogLevel)) return false;\n if (typeof obj.message !== 'string') return false;\n if (obj.attributes === null || typeof obj.attributes !== 'object')\n return false;\n if (obj.context === null || typeof obj.context !== 'object') return false;\n return true;\n}\n","/**\n * Sanitizer — normalizes arbitrary consumer input into a bounded,\n * predictable `AttributeValue` tree before any downstream stage\n * (URL scrubber, redactor, control-char guard, freeze) sees it.\n *\n * Contract: `contracts/sanitization.md` (rows S-1..S-10).\n *\n * Invariants:\n * - NEVER throws. Every branch has a defined fallback; any residual\n * unexpected throw inside `sanitizeValue` collapses to\n * `\"[Unserializable]\"` (defensive belt).\n * - Class instances and DOM/framework objects are **type-tagged, not\n * recursed** — this is the security property that prevents\n * side-effectful getters from being invoked and prevents huge\n * object graphs (React fibers, full DOM trees) from being pulled\n * into events.\n * - Bounds (`maxDepth`, `maxStringLength`, `maxArrayLength`,\n * `maxAttributeCount`) come from `config.sanitizerLimits`, which\n * `normalizeConfig()` already clamped to documented Min..Max.\n * - `maxAttributeCount` is **cumulative across the whole event**;\n * when exceeded, a single `\"[Truncated: <N> keys omitted]\"` marker\n * is attached at the top-level attributes.\n */\n\nimport type {\n AttributeValue,\n ErrorInfo,\n LogContext,\n LogEvent,\n} from '../api/types.js';\nimport type { NormalizedConfig } from '../config/config.js';\nimport type { PipelineStage } from './dispatcher.js';\n\nconst TRUNCATION_MARKER_KEY = '__truncated__';\nconst STRING_TRUNCATION_SUFFIX = '...[truncated]';\nconst UNSERIALIZABLE_MARKER = '[Unserializable]';\n\ninterface SanitizeContext {\n readonly maxDepth: number;\n readonly maxStringLength: number;\n readonly maxArrayLength: number;\n readonly maxAttributeCount: number;\n keysUsed: number;\n keysOmitted: number;\n readonly seen: WeakSet<object>;\n}\n\nexport const sanitize: PipelineStage = (event, config) => {\n const ctx = newContext(config);\n\n const sanitizedAttributes = sanitizeRootObject(event.attributes, ctx);\n const sanitizedContext = sanitizeContext(event.context, ctx);\n\n const next: LogEvent = {\n timestamp: event.timestamp,\n level: event.level,\n message: truncateString(event.message, ctx.maxStringLength),\n attributes: sanitizedAttributes,\n context: sanitizedContext,\n };\n\n if (event.error !== undefined) {\n next.error = sanitizeErrorInfo(event.error, ctx);\n }\n\n if (ctx.keysOmitted > 0) {\n next.attributes = withTruncationMarker(next.attributes, ctx.keysOmitted);\n }\n\n return next;\n};\n\nfunction newContext(config: NormalizedConfig): SanitizeContext {\n const limits = config.sanitizerLimits;\n return {\n maxDepth: limits.maxDepth,\n maxStringLength: limits.maxStringLength,\n maxArrayLength: limits.maxArrayLength,\n maxAttributeCount: limits.maxAttributeCount,\n keysUsed: 0,\n keysOmitted: 0,\n seen: new WeakSet<object>(),\n };\n}\n\nfunction sanitizeRootObject(\n source: unknown,\n ctx: SanitizeContext,\n): { [key: string]: AttributeValue } {\n if (source === null || typeof source !== 'object' || Array.isArray(source)) {\n return {};\n }\n return sanitizeObject(source as Record<string, unknown>, 0, ctx);\n}\n\nfunction sanitizeContext(source: LogContext, ctx: SanitizeContext): LogContext {\n if (source.attributes === undefined) return source;\n const sanitizedAttrs = sanitizeRootObject(source.attributes, ctx);\n return { ...source, attributes: sanitizedAttrs };\n}\n\nfunction sanitizeErrorInfo(error: ErrorInfo, ctx: SanitizeContext): ErrorInfo {\n const info: ErrorInfo = {\n name: truncateString(error.name, ctx.maxStringLength),\n message: truncateString(error.message, ctx.maxStringLength),\n };\n if (error.stack !== undefined) {\n info.stack = truncateString(error.stack, ctx.maxStringLength);\n }\n return info;\n}\n\nfunction withTruncationMarker(\n attrs: { [key: string]: AttributeValue },\n omitted: number,\n): { [key: string]: AttributeValue } {\n const tagged: { [key: string]: AttributeValue } = { ...attrs };\n tagged[TRUNCATION_MARKER_KEY] =\n `[Truncated: ${String(omitted)} keys omitted]`;\n return tagged;\n}\n\nfunction truncateString(value: string, maxLength: number): string {\n if (value.length <= maxLength) return value;\n return value.slice(0, maxLength) + STRING_TRUNCATION_SUFFIX;\n}\n\n/**\n * Outer dispatch for an unknown value. Wrapped in try/catch so that\n * any pathological input (throwing getters on a plain object, Proxy\n * traps, `Invalid Date` toISOString, etc.) collapses to a marker\n * rather than escaping the sanitizer. This is the defensive belt that\n * guarantees S-2 (\"the sanitizer never throws on any input\").\n */\nfunction sanitizeValue(\n value: unknown,\n depth: number,\n ctx: SanitizeContext,\n): AttributeValue {\n try {\n return sanitizeValueImpl(value, depth, ctx);\n } catch {\n return UNSERIALIZABLE_MARKER;\n }\n}\n\nfunction sanitizeValueImpl(\n value: unknown,\n depth: number,\n ctx: SanitizeContext,\n): AttributeValue {\n if (depth > ctx.maxDepth) return '[MaxDepth]';\n\n // null and primitives ------------------------------------------------------\n if (value === null) return null;\n const t = typeof value;\n if (t === 'string')\n return truncateString(value as string, ctx.maxStringLength);\n if (t === 'number') {\n const n = value as number;\n return Number.isFinite(n) ? n : null;\n }\n if (t === 'boolean') return value as boolean;\n if (t === 'bigint') return String(value);\n if (t === 'function') return '[Function]';\n if (t === 'symbol') return '[Symbol]';\n if (t === 'undefined') return null;\n\n // value is a non-null object below\n const obj = value as object;\n\n // Cycle guard -------------------------------------------------------------\n if (ctx.seen.has(obj)) return '[Circular]';\n\n // Arrays ------------------------------------------------------------------\n if (Array.isArray(value)) {\n return sanitizeArray(value, depth, ctx);\n }\n\n // Date --------------------------------------------------------------------\n if (value instanceof Date) {\n return dateToIso(value);\n }\n\n // Error -------------------------------------------------------------------\n if (value instanceof Error) {\n return sanitizeErrorAsAttribute(value, depth, ctx);\n }\n\n // DOM type tags (most specific first; guarded for SSR) --------------------\n if (typeof Element !== 'undefined' && value instanceof Element) {\n return `[Element:${tagNameOf(value)}]`;\n }\n if (typeof Document !== 'undefined' && value instanceof Document) {\n return '[Document]';\n }\n if (typeof Window !== 'undefined' && value instanceof Window) {\n return '[Window]';\n }\n if (typeof Node !== 'undefined' && value instanceof Node) {\n return '[Node]';\n }\n\n // Framework type tags -----------------------------------------------------\n if (typeof Event !== 'undefined' && value instanceof Event) {\n return `[Event:${eventTypeOf(value)}]`;\n }\n if (typeof Promise !== 'undefined' && value instanceof Promise) {\n return '[Promise]';\n }\n if (typeof Map !== 'undefined' && value instanceof Map) {\n return '[Map]';\n }\n if (typeof Set !== 'undefined' && value instanceof Set) {\n return '[Set]';\n }\n if (typeof WeakMap !== 'undefined' && value instanceof WeakMap) {\n return '[WeakMap]';\n }\n if (typeof WeakSet !== 'undefined' && value instanceof WeakSet) {\n return '[WeakSet]';\n }\n if (typeof Request !== 'undefined' && value instanceof Request) {\n return '[Request]';\n }\n if (typeof Response !== 'undefined' && value instanceof Response) {\n return '[Response]';\n }\n if (typeof Blob !== 'undefined' && value instanceof Blob) {\n return '[Blob]';\n }\n if (typeof FormData !== 'undefined' && value instanceof FormData) {\n return '[FormData]';\n }\n if (typeof URL !== 'undefined' && value instanceof URL) {\n return '[URL]';\n }\n\n // Plain object vs class instance ------------------------------------------\n if (isPlainObject(obj)) {\n return sanitizeObject(obj as Record<string, unknown>, depth, ctx);\n }\n return `[${getConstructorName(obj)}]`;\n}\n\nfunction sanitizeArray(\n arr: ReadonlyArray<unknown>,\n depth: number,\n ctx: SanitizeContext,\n): AttributeValue[] {\n ctx.seen.add(arr as unknown as object);\n const out: AttributeValue[] = [];\n const len = arr.length;\n const limit = len > ctx.maxArrayLength ? ctx.maxArrayLength : len;\n for (let i = 0; i < limit; i++) {\n // Per contract: `undefined` inside arrays → `null`. We delegate\n // that coercion to `sanitizeValue`'s `typeof === 'undefined'`\n // branch so the per-item shape rules stay in one place.\n out.push(sanitizeValue(arr[i], depth + 1, ctx));\n }\n if (len > ctx.maxArrayLength) {\n const omitted = len - ctx.maxArrayLength;\n out.push(`[Truncated: ${String(omitted)} elements omitted]`);\n }\n ctx.seen.delete(arr as unknown as object);\n return out;\n}\n\nfunction sanitizeObject(\n obj: Record<string, unknown>,\n depth: number,\n ctx: SanitizeContext,\n): { [key: string]: AttributeValue } {\n ctx.seen.add(obj);\n const result: { [key: string]: AttributeValue } = {};\n const keys = ownEnumerableKeys(obj);\n for (const key of keys) {\n const raw = readProperty(obj, key);\n if (raw === undefined) continue; // top-level undefined keys are dropped\n if (ctx.keysUsed >= ctx.maxAttributeCount) {\n ctx.keysOmitted++;\n continue;\n }\n ctx.keysUsed++;\n result[key] = sanitizeValue(raw, depth + 1, ctx);\n }\n ctx.seen.delete(obj);\n return result;\n}\n\n/**\n * Reduce an `Error` encountered inside attributes to its documented\n * `{name, message, stack?}` shape and recurse through the plain-object\n * path so strings get length-truncated and keys get counted toward\n * `maxAttributeCount`.\n */\nfunction sanitizeErrorAsAttribute(\n err: Error,\n depth: number,\n ctx: SanitizeContext,\n): { [key: string]: AttributeValue } {\n const reduced: Record<string, unknown> = {\n name: safeString(() => err.name, 'Error'),\n message: safeString(() => err.message, ''),\n };\n const stack = safeOptional(() => err.stack);\n if (stack !== undefined) {\n reduced.stack = stack;\n }\n return sanitizeObject(reduced, depth, ctx);\n}\n\n// ---------------------------------------------------------------------------\n// Low-level helpers (each isolated so a single throwing access cannot\n// derail the recursion).\n// ---------------------------------------------------------------------------\n\nfunction ownEnumerableKeys(obj: object): string[] {\n try {\n return Object.keys(obj);\n } catch {\n return [];\n }\n}\n\nfunction readProperty(obj: Record<string, unknown>, key: string): unknown {\n try {\n return obj[key];\n } catch {\n return UNSERIALIZABLE_MARKER;\n }\n}\n\nfunction isPlainObject(obj: object): boolean {\n // `Object.getPrototypeOf(obj)` can in principle throw via a Proxy's\n // `getPrototypeOf` trap, but any such input has already thrown — and\n // been collapsed to `'[Unserializable]'` — by an earlier `instanceof`\n // check in `sanitizeValueImpl` (those checks also call\n // `Object.getPrototypeOf` internally). The `sanitizeValue` outer\n // defensive belt is the single source of truth for that recovery, so\n // a redundant local try/catch here would only ever be dead code.\n const proto = Object.getPrototypeOf(obj) as object | null;\n return proto === null || proto === Object.prototype;\n}\n\nfunction getConstructorName(obj: object): string {\n try {\n const proto = Object.getPrototypeOf(obj) as {\n constructor?: { name?: unknown };\n } | null;\n const ctor = proto?.constructor;\n const name = ctor?.name;\n if (typeof name === 'string' && name.length > 0) return name;\n } catch {\n /* fall through */\n }\n return 'Object';\n}\n\nfunction tagNameOf(el: Element): string {\n try {\n const t = el.tagName;\n return typeof t === 'string' && t.length > 0 ? t.toLowerCase() : 'element';\n } catch {\n return 'element';\n }\n}\n\nfunction eventTypeOf(ev: Event): string {\n try {\n const t = ev.type;\n return typeof t === 'string' && t.length > 0 ? t : 'event';\n } catch {\n return 'event';\n }\n}\n\nfunction dateToIso(d: Date): AttributeValue {\n try {\n return d.toISOString();\n } catch {\n // Invalid Date throws RangeError.\n return null;\n }\n}\n\nfunction safeString(read: () => unknown, fallback: string): string {\n try {\n const v = read();\n return typeof v === 'string' ? v : fallback;\n } catch {\n return fallback;\n }\n}\n\nfunction safeOptional(read: () => unknown): string | undefined {\n try {\n const v = read();\n return typeof v === 'string' ? v : undefined;\n } catch {\n return undefined;\n }\n}\n","/**\n * URL scrubber — strips sensitive query and fragment parameters from\n * URL-shaped string values before any transport sees the event.\n *\n * Contract: `contracts/redaction.md` (URL-derived secrets) + plan.md\n * \"Security Architecture > URL scrubbing\".\n *\n * Two surfaces:\n * - `urlScrub` (pipeline stage): walks `event.message`,\n * `event.attributes`, `event.context.attributes`, `event.error.*`\n * and rewrites any string that parses as an http(s) URL,\n * replacing sensitive query and (optionally) fragment param values\n * with `'[REDACTED]'`. Runs upstream of the redactor.\n * - `scrubUrl(url, options?)` (public helper, re-exported from\n * `src/index.ts`): the same operation surfaced directly so consumers\n * can pre-scrub URLs they want to log intentionally.\n *\n * Security invariants:\n * - NEVER throws. Malformed URLs, throwing getters on plain objects\n * (already collapsed by the sanitizer upstream), and pathological\n * fragments all fall through to \"return input unchanged\".\n * - Returns input unchanged for any string that is not a parseable\n * http(s) URL. Path segments, host, and authority are NOT modified\n * — only query and fragment parameter VALUES are replaced. Param\n * names are preserved.\n * - Operates on names (case-insensitive), never on value substrings —\n * the package never inspects a URL value's content for sensitive\n * shapes (that is the redactor's job, applied later in the pipeline).\n */\n\nimport type {\n Attributes,\n AttributeValue,\n ErrorInfo,\n LogContext,\n LogEvent,\n ScrubUrlOptions,\n} from '../api/types.js';\nimport type { PipelineStage } from './dispatcher.js';\n\nconst REDACTED = '[REDACTED]';\n\n/**\n * Default denylist of query/fragment parameter names whose values should\n * be replaced. Mirrors `contracts/redaction.md`'s key denylist so the\n * URL scrubber and the redactor stay consistent at the value-shape\n * boundary. Match is case-insensitive (every pattern carries the `i`\n * flag) and full-name only (no substring matches).\n */\nconst DEFAULT_PARAM_DENYLIST: ReadonlyArray<RegExp> = [\n /^password$/i,\n /^passwd$/i,\n /^token$/i,\n /access[_-]?token/i,\n /refresh[_-]?token/i,\n /bearer[_-]?token/i,\n /id[_-]?token/i,\n /^authorization$/i,\n /^auth$/i,\n /^cookie$/i,\n /^set-cookie$/i,\n /^secret$/i,\n /client[_-]?secret/i,\n /api[_-]?key/i,\n /session[_-]?id/i,\n /^sid$/i,\n /^ssn$/i,\n /credit[_-]?card/i,\n /^cardnumber$/i,\n /^cvv$/i,\n];\n\n// ---------------------------------------------------------------------------\n// Public helper\n// ---------------------------------------------------------------------------\n\nexport function scrubUrl(url: string, options?: ScrubUrlOptions): string {\n if (typeof url !== 'string' || url.length === 0) return url;\n\n let parsed: URL;\n try {\n parsed = new URL(url);\n } catch {\n return url;\n }\n\n if (parsed.protocol !== 'http:' && parsed.protocol !== 'https:') {\n return url;\n }\n\n const extras = options?.extraParams ?? [];\n const scrubFragment = options?.fragment !== false;\n\n let changed = false;\n changed = scrubSearchParams(parsed, extras) || changed;\n if (scrubFragment) {\n changed = scrubHashFragment(parsed, extras) || changed;\n }\n\n if (!changed) return url;\n\n // `URL.prototype.toString` does not throw for a URL object that was\n // constructed via `new URL()` and only mutated through `searchParams`\n // and `hash` (both of which accept arbitrary string input without\n // validation). No defensive belt is required here.\n return parsed.toString();\n}\n\n// ---------------------------------------------------------------------------\n// Pipeline stage\n// ---------------------------------------------------------------------------\n\nexport const urlScrub: PipelineStage = (event, _config) => {\n const message = maybeScrubString(event.message);\n const attributes = walkAttributes(event.attributes);\n const context = walkContext(event.context);\n\n let error: ErrorInfo | undefined;\n if (event.error !== undefined) {\n const scrubbedMessage = maybeScrubString(event.error.message);\n const stack = event.error.stack;\n const scrubbedStack =\n stack === undefined ? undefined : maybeScrubString(stack);\n error = { name: event.error.name, message: scrubbedMessage };\n if (scrubbedStack !== undefined) error.stack = scrubbedStack;\n }\n\n const noChange =\n message === event.message &&\n attributes === event.attributes &&\n context === event.context &&\n error === event.error;\n if (noChange) return event;\n\n const next: LogEvent = {\n timestamp: event.timestamp,\n level: event.level,\n message,\n attributes,\n context,\n };\n if (error !== undefined) next.error = error;\n return next;\n};\n\n// ---------------------------------------------------------------------------\n// Internals\n// ---------------------------------------------------------------------------\n\nfunction scrubSearchParams(\n parsed: URL,\n extras: ReadonlyArray<string | RegExp>,\n): boolean {\n // Snapshot the original (name, value) sequence so we can rebuild the\n // params in the same order — `params.delete(name)` followed by\n // `params.append(name, REDACTED)` would otherwise move the rewritten\n // param to the end of the search-string output, which is surprising\n // for consumers eyeballing scrubbed URLs.\n const entries: Array<[string, string]> = [];\n for (const [name, value] of parsed.searchParams.entries()) {\n entries.push([name, value]);\n }\n let changed = false;\n for (let i = 0; i < entries.length; i++) {\n // Non-null assertion: `i < entries.length` guarantees the index is\n // populated. Avoids a dead `undefined` branch under\n // `noUncheckedIndexedAccess`.\n const entry = entries[i]!;\n if (isDenied(entry[0], extras)) {\n entries[i] = [entry[0], REDACTED];\n changed = true;\n }\n }\n if (!changed) return false;\n const uniqueKeys = new Set<string>();\n for (const entry of entries) uniqueKeys.add(entry[0]);\n for (const key of uniqueKeys) parsed.searchParams.delete(key);\n for (const [name, value] of entries) parsed.searchParams.append(name, value);\n return true;\n}\n\nfunction scrubHashFragment(\n parsed: URL,\n extras: ReadonlyArray<string | RegExp>,\n): boolean {\n const hash = parsed.hash;\n if (hash.length < 2 || !hash.startsWith('#')) return false;\n const body = hash.slice(1);\n // Fragment must contain a `key=value` pair to be scrubbable.\n if (!body.includes('=')) return false;\n\n const parts = body.split('&');\n let changed = false;\n const out: string[] = [];\n for (const part of parts) {\n const eq = part.indexOf('=');\n if (eq < 0) {\n out.push(part);\n continue;\n }\n const rawKey = part.slice(0, eq);\n const decodedKey = tryDecode(rawKey);\n if (isDenied(decodedKey, extras)) {\n out.push(`${rawKey}=${encodeURIComponent(REDACTED)}`);\n changed = true;\n } else {\n out.push(part);\n }\n }\n if (!changed) return false;\n\n parsed.hash = `#${out.join('&')}`;\n return true;\n}\n\nfunction isDenied(\n name: string,\n extras: ReadonlyArray<string | RegExp>,\n): boolean {\n for (const pattern of DEFAULT_PARAM_DENYLIST) {\n if (pattern.test(name)) return true;\n }\n for (const pattern of extras) {\n if (typeof pattern === 'string') {\n if (pattern.toLowerCase() === name.toLowerCase()) return true;\n } else if (pattern.test(name)) {\n return true;\n }\n }\n return false;\n}\n\nfunction tryDecode(value: string): string {\n try {\n return decodeURIComponent(value);\n } catch {\n return value;\n }\n}\n\n/**\n * Fast-path: only attempt URL parsing for strings that begin with\n * `http://` or `https://`. Keeps the per-emission cost predictable when\n * attributes carry many non-URL strings.\n */\nfunction maybeScrubString(value: string): string {\n if (value.length < 8) return value;\n if (value.startsWith('http://') || value.startsWith('https://')) {\n return scrubUrl(value);\n }\n return value;\n}\n\nfunction walkAttributes(attrs: Attributes): Attributes {\n let changed = false;\n let result: { [key: string]: AttributeValue } | null = null;\n for (const key of Object.keys(attrs)) {\n const value = attrs[key];\n if (value === undefined) continue;\n const scrubbed = walkValue(value);\n if (scrubbed !== value) {\n if (result === null) {\n result = {};\n for (const k of Object.keys(attrs)) {\n const existing = attrs[k];\n if (existing !== undefined) result[k] = existing;\n }\n }\n result[key] = scrubbed;\n changed = true;\n }\n }\n return changed && result !== null ? result : attrs;\n}\n\nfunction walkValue(value: AttributeValue): AttributeValue {\n if (typeof value === 'string') return maybeScrubString(value);\n if (Array.isArray(value)) return walkArray(value);\n if (value !== null && typeof value === 'object') return walkAttributes(value);\n return value;\n}\n\nfunction walkArray(arr: AttributeValue[]): AttributeValue[] {\n let changed = false;\n let result: AttributeValue[] | null = null;\n for (let i = 0; i < arr.length; i++) {\n const item = arr[i];\n if (item === undefined) continue;\n const scrubbed = walkValue(item);\n if (scrubbed !== item) {\n if (result === null) result = arr.slice();\n result[i] = scrubbed;\n changed = true;\n }\n }\n return changed && result !== null ? result : arr;\n}\n\nfunction walkContext(context: LogContext): LogContext {\n if (context.attributes === undefined) return context;\n const scrubbed = walkAttributes(context.attributes);\n if (scrubbed === context.attributes) return context;\n return { ...context, attributes: scrubbed };\n}\n","/**\n * Dispatcher — runs an already-built `LogEvent` through the locked\n * security pipeline order and fans the result out directly to the\n * `SafeTransport`-wrapped transports stored on the active runtime.\n *\n * LevelFilter (in logger.ts, upstream of dispatch())\n * ↓\n * EventBuilder (in logger.ts, upstream of dispatch())\n * ↓\n * Sanitize → URLScrub → Redact → ControlCharGuard → Freeze(dev) →\n * SafeTransport[]\n *\n * Each stage is a separate module: `sanitizer.ts`, `url-scrubber.ts`,\n * `redactor.ts`, `control-char-guard.ts`, `freeze.ts`. The wiring\n * below routes events through every stage in the contracted order\n * before any transport sees them (locked as a contract test by T048).\n *\n * Security invariant: **no transport can run before the redactor**.\n * The stage order below is the only emit path. There is no backend\n * indirection in the v1 default path — the dispatcher fans events\n * out directly to the wrapped transports on `runtime.transports`,\n * each already isolated by `SafeTransport` per FS-1/FS-2/FS-11/FS-12.\n *\n * Stage semantics:\n * - Each stage receives the in-flight event + the normalized config.\n * - A stage MAY return a transformed event, the same event, or\n * `null` to **drop the event** (used by the redactor for\n * fail-closed handling per `contracts/redaction.md`).\n *\n * Error semantics:\n * - Any uncaught throw from a stage is caught here and routed\n * through `config.onInternalError`. The event is dropped in that\n * case (fail-closed: we don't emit partially-processed data).\n * - Transport fan-out runs inside per-transport try/catch so a\n * single throwing transport cannot break sibling delivery. Each\n * transport is `SafeTransport`-wrapped at `configureLogging()`\n * time, so the try/catch here is a defensive belt for any\n * residual escape (FS-11 / FS-12).\n *\n * Vendor-neutrality: this module imports no observability-vendor\n * SDK. The seam between core pipeline and consumer transports is a\n * plain function call. Future vendor adapters are implemented as\n * peer transports, not by re-introducing an internal backend indirection.\n */\n\nimport type { LogEvent } from '../api/types.js';\nimport type { NormalizedConfig } from '../config/config.js';\nimport {\n safeNotify,\n wrapAsPackageError,\n} from '../internal/errors/internal-errors.js';\nimport { controlCharGuard } from './control-char-guard.js';\nimport { freezeInDev } from './freeze.js';\nimport { redact } from './redactor.js';\nimport { sanitize } from './sanitizer.js';\nimport { urlScrub } from './url-scrubber.js';\n\n/**\n * Pipeline-stage function signature. Returning `null` drops the event.\n *\n * Stages are pure with respect to the `config` argument (read-only).\n * Mutation of the in-flight `event` is allowed within a stage but\n * discouraged — returning a new object keeps stages composable.\n */\nexport type PipelineStage = (\n event: LogEvent,\n config: NormalizedConfig,\n) => LogEvent | null;\n\n/**\n * Run an event through every pipeline stage in order and fan out to\n * the configured transports. Pre-pipeline level filtering happens in\n * `logger.ts` so a filtered-out emission never reaches this function.\n */\nexport function dispatch(event: LogEvent, config: NormalizedConfig): void {\n let current: LogEvent | null;\n try {\n current = sanitize(event, config);\n if (current === null) return;\n\n current = urlScrub(current, config);\n if (current === null) return;\n\n current = redact(current, config);\n if (current === null) return;\n\n current = controlCharGuard(current, config);\n if (current === null) return;\n\n current = freezeInDev(current, config);\n if (current === null) return;\n } catch (err) {\n // Fail-closed: a thrown pipeline stage drops the event entirely\n // and routes the error via `onInternalError`.\n safeNotify(\n config.onInternalError,\n wrapAsPackageError(\n 'redactor_failed',\n 'A pipeline stage threw; the event was dropped (fail-closed).',\n err,\n ),\n );\n return;\n }\n\n // Direct transport fan-out. Each transport in `config.transports` is\n // already `SafeTransport`-wrapped at `configureLogging()` time\n // (`buildConfiguredRuntime` in `runtime/configured-runtime.ts`), so\n // synchronous throws and rejected Promises are isolated inside the\n // wrapper. The per-transport try/catch + Promise rejection swallow\n // below are a defensive belt for any residual escape (e.g., a test\n // that passes a raw transport directly through this function).\n for (const transport of config.transports) {\n try {\n const result = transport.send(current);\n if (result instanceof Promise) {\n result.then(undefined, () => undefined);\n }\n } catch {\n // SafeTransport already catches; this is a defensive belt for\n // unwrapped transports.\n }\n }\n}\n","/**\n * Event builder — packages the inputs that the logger has already merged\n * into the canonical `LogEvent` shape.\n *\n * Responsibilities:\n * - Assign `timestamp` from `new Date().toISOString()`. Consumer-supplied\n * timestamps are NOT accepted (per `contracts/log-event.md` LE-11).\n * - Default `attributes` to `{}`.\n * - Reduce an `unknown` error value to the documented `ErrorInfo` shape\n * (`{ name, message, stack? }`) — never holds onto the raw `Error`.\n *\n * The builder does NOT perform sanitization, redaction, URL scrubbing,\n * or control-char escaping. Those are separate pipeline stages that land\n * in Phase 5 (T031, T032, T034, T035).\n */\n\nimport type {\n Attributes,\n ErrorInfo,\n LogContext,\n LogEvent,\n LogLevel,\n} from '../api/types.js';\n\nexport interface BuildLogEventInput {\n level: LogLevel;\n message: string;\n attributes: Attributes | undefined;\n context: LogContext;\n /** Raw caught value from `logger.error(msg, attrs, err)`; reduced to `ErrorInfo`. */\n errorValue: unknown;\n}\n\n/** Build a canonical `LogEvent` from already-merged inputs. */\nexport function buildLogEvent(input: BuildLogEventInput): LogEvent {\n const event: LogEvent = {\n timestamp: new Date().toISOString(),\n level: input.level,\n message: input.message,\n attributes: input.attributes ?? {},\n context: input.context,\n };\n if (input.errorValue !== undefined) {\n event.error = reduceError(input.errorValue);\n }\n return event;\n}\n\n/**\n * Reduce any `unknown` error value to the documented `ErrorInfo` shape.\n * Non-Error inputs are coerced to `{ name: 'NonError', message: String(value) }`.\n * Exported for unit-testability and for any future pipeline stage that\n * needs to re-reduce an error value (the dispatcher does not today).\n */\nexport function reduceError(value: unknown): ErrorInfo {\n if (value instanceof Error) {\n const info: ErrorInfo = { name: value.name, message: value.message };\n if (value.stack !== undefined) info.stack = value.stack;\n return info;\n }\n return { name: 'NonError', message: String(value) };\n}\n","/**\n * Level filter — the cheapest possible drop-fast step in the pipeline.\n * Runs BEFORE event construction so a filtered-out emission performs no\n * work beyond a constant-time numeric comparison.\n *\n * Resolution chain per `contracts/logger-config.md` LC-1..LC-3 splits\n * across two modules:\n *\n * - `normalizeConfig()` (T006) resolves `LoggerConfig.level`\n * (a `LogLevel`, a `LevelMap` looked up by `environment`, or the\n * env-default table) into a single `LogLevel` stored on\n * `NormalizedConfig.level`. The hard `warn` fallback also happens\n * there.\n *\n * - `passesLevelFilter()` here applies the per-logger\n * `CreateLoggerOptions.level` override on top of that resolved value.\n *\n * `LEVEL_NUMBER` is internal-only (per `data-model.md` \"internal numeric\n * values are not exported\").\n */\n\nimport type { LogLevel } from '../api/types.js';\n\nconst LEVEL_NUMBER: Readonly<Record<LogLevel, number>> = {\n debug: 10,\n info: 20,\n warn: 30,\n error: 40,\n};\n\n/**\n * Resolve the effective minimum level for an emission: a per-logger\n * `CreateLoggerOptions.level` override wins; otherwise the\n * already-resolved `NormalizedConfig.level` applies.\n */\nexport function resolveEffectiveLevel(\n perLoggerLevel: LogLevel | undefined,\n configLevel: LogLevel,\n): LogLevel {\n return perLoggerLevel ?? configLevel;\n}\n\n/**\n * Return `true` if an event at `eventLevel` should reach downstream\n * pipeline stages; `false` if the level filter drops it.\n */\nexport function passesLevelFilter(\n eventLevel: LogLevel,\n perLoggerLevel: LogLevel | undefined,\n configLevel: LogLevel,\n): boolean {\n const effective = resolveEffectiveLevel(perLoggerLevel, configLevel);\n return LEVEL_NUMBER[eventLevel] >= LEVEL_NUMBER[effective];\n}\n","/**\n * Environment-aware default levels and sanitizer-limit bounds. Internal to\n * the package — the values here are the source of truth that\n * `contracts/logger-config.md` and `contracts/sanitization.md` describe.\n *\n * The package MUST NOT read `process.env`, `import.meta.env`, `location`, or\n * `document.cookie`. Consumers MUST pass `environment` explicitly via\n * `configureLogging({ environment })`. The defaults below resolve based on\n * the value the consumer supplied.\n */\n\nimport type { LogLevel, SanitizerLimits } from '../api/types.js';\n\n/** Per-environment baseline minimum level. Unknown environments fall back to `warn`. */\nexport const DEFAULT_LEVEL_BY_ENVIRONMENT: Readonly<Record<string, LogLevel>> =\n {\n production: 'warn',\n development: 'debug',\n test: 'warn',\n };\n\n/** Hard fallback when no level resolution path yields a value. */\nexport const FALLBACK_LEVEL: LogLevel = 'warn';\n\n/** Default sanitizer bounds per `contracts/sanitization.md`. */\nexport const DEFAULT_SANITIZER_LIMITS: Readonly<SanitizerLimits> = {\n maxDepth: 8,\n maxStringLength: 8192,\n maxArrayLength: 1000,\n maxAttributeCount: 256,\n};\n\n/**\n * Min/Max bounds per sanitizer limit. Consumer-supplied values outside these\n * bounds clamp to the nearest bound and emit one `onInternalError` notice\n * via `normalizeConfig()`.\n */\nexport const SANITIZER_LIMIT_BOUNDS: Readonly<{\n [K in keyof SanitizerLimits]: Readonly<{ min: number; max: number }>;\n}> = {\n maxDepth: { min: 1, max: 16 },\n maxStringLength: { min: 64, max: 65536 },\n maxArrayLength: { min: 1, max: 10000 },\n maxAttributeCount: { min: 1, max: 4096 },\n};\n\n/**\n * Resolve the default level for a given environment string. Returns\n * `FALLBACK_LEVEL` when the environment is undefined or unknown.\n */\nexport function defaultLevelForEnvironment(\n environment: string | undefined,\n): LogLevel {\n if (environment === undefined) return FALLBACK_LEVEL;\n return DEFAULT_LEVEL_BY_ENVIRONMENT[environment] ?? FALLBACK_LEVEL;\n}\n","/**\n * Configuration normalization. Internal — the resulting `NormalizedConfig`\n * is never exposed to consumers.\n *\n * Normalization is deterministic: given the same `LoggerConfig` input,\n * `normalizeConfig` always produces an equivalent `NormalizedConfig`.\n * `SanitizerLimits` values outside the documented `min`/`max` bounds are\n * clamped, and each clamping event emits one `onInternalError` notice\n * (per `contracts/logger-config.md` LC-10).\n */\n\nimport type {\n AppIdentity,\n LevelMap,\n LogContext,\n LoggerConfig,\n LogLevel,\n ModuleIdentity,\n Redactor,\n SanitizerLimits,\n Transport,\n} from '../api/types.js';\n\nimport {\n PackageError,\n safeNotify,\n} from '../internal/errors/internal-errors.js';\n\nimport {\n DEFAULT_SANITIZER_LIMITS,\n defaultLevelForEnvironment,\n SANITIZER_LIMIT_BOUNDS,\n} from './env-defaults.js';\n\n/**\n * Fully-normalized configuration produced by `normalizeConfig`. Internal\n * across the package — never exposed in public types or contracts.\n *\n * Fields are typed as `T | undefined` (rather than `T?`) so consumers of\n * `NormalizedConfig` can rely on the keys always being present, which keeps\n * downstream code stable under `exactOptionalPropertyTypes: true`.\n */\nexport interface NormalizedConfig {\n readonly application: AppIdentity | undefined;\n readonly module: ModuleIdentity | undefined;\n readonly environment: string | undefined;\n /** Single resolved level for the configured environment. */\n readonly level: LogLevel;\n readonly context: Partial<LogContext>;\n readonly correlation: (() => Partial<LogContext>) | undefined;\n readonly transports: ReadonlyArray<Transport>;\n readonly redactor: Redactor | undefined;\n readonly sanitizerLimits: SanitizerLimits;\n readonly onInternalError: (err: Error) => void;\n}\n\n/** Silent default for `onInternalError`. */\nconst NOOP_ON_INTERNAL_ERROR: (err: Error) => void = () => undefined;\n\n/**\n * Produce a `NormalizedConfig` from a consumer `LoggerConfig`. Pure and\n * deterministic apart from invoking the `onInternalError` callback for each\n * out-of-bounds sanitizer limit. Transport factories are invoked once here.\n */\nexport function normalizeConfig(config: LoggerConfig): NormalizedConfig {\n const environment = config.environment;\n const onInternalError = config.onInternalError ?? NOOP_ON_INTERNAL_ERROR;\n\n const sanitizerLimits = resolveSanitizerLimits(\n config.sanitizerLimits,\n onInternalError,\n );\n\n const level = resolveConfigLevel(config.level, environment);\n\n const transports = (config.transports ?? []).map((entry) =>\n typeof entry === 'function' ? entry() : entry,\n );\n\n return {\n application: config.application,\n module: config.module,\n environment,\n level,\n context: config.context ?? {},\n correlation: config.correlation,\n transports,\n redactor: config.redactor,\n sanitizerLimits,\n onInternalError,\n };\n}\n\n/**\n * Resolve `LoggerConfig.level` (which may be a `LogLevel`, a `LevelMap`, or\n * undefined) against the configured environment, falling back to the\n * documented env-default table.\n */\nfunction resolveConfigLevel(\n level: LogLevel | LevelMap | undefined,\n environment: string | undefined,\n): LogLevel {\n if (level === undefined) {\n return defaultLevelForEnvironment(environment);\n }\n if (typeof level === 'string') {\n return level;\n }\n // LevelMap branch — look up by environment, fall back to env default.\n if (environment !== undefined) {\n const map = level as Record<string, LogLevel | undefined>;\n const mapped = map[environment];\n if (mapped !== undefined) return mapped;\n }\n return defaultLevelForEnvironment(environment);\n}\n\n/**\n * Apply consumer-supplied sanitizer-limit overrides on top of the documented\n * defaults, clamping to documented `min`/`max`. Each clamped value emits one\n * `onInternalError` notice per `configureLogging()` call.\n */\nfunction resolveSanitizerLimits(\n overrides: Partial<SanitizerLimits> | undefined,\n onInternalError: (err: Error) => void,\n): SanitizerLimits {\n if (overrides === undefined) {\n return { ...DEFAULT_SANITIZER_LIMITS };\n }\n\n const limits: SanitizerLimits = { ...DEFAULT_SANITIZER_LIMITS };\n const keys = Object.keys(SANITIZER_LIMIT_BOUNDS) as Array<\n keyof SanitizerLimits\n >;\n\n for (const key of keys) {\n const requested = overrides[key];\n if (requested === undefined) continue;\n\n const bounds = SANITIZER_LIMIT_BOUNDS[key];\n if (requested > bounds.max) {\n limits[key] = bounds.max;\n safeNotify(\n onInternalError,\n new PackageError(\n 'sanitizer_limit_clamped',\n `sanitizerLimits.${key} value ${String(requested)} exceeds max ${String(bounds.max)}; clamped to ${String(bounds.max)}`,\n ),\n );\n } else if (requested < bounds.min) {\n limits[key] = bounds.min;\n safeNotify(\n onInternalError,\n new PackageError(\n 'sanitizer_limit_clamped',\n `sanitizerLimits.${key} value ${String(requested)} is below min ${String(bounds.min)}; clamped to ${String(bounds.min)}`,\n ),\n );\n } else {\n limits[key] = requested;\n }\n }\n\n return limits;\n}\n","/**\n * Built-in `NoopTransport`. Silently swallows every event.\n *\n * This is the automatic fallback when `LoggerConfig.transports` is\n * undefined or empty (per `contracts/logger-config.md` LC default\n * resolution). Useful in tests, in environments where logging is\n * deliberately disabled, and as a placeholder during incremental\n * configuration.\n */\n\nimport type { Transport, TransportFactory } from '../api/types.js';\n\nexport const NoopTransport: TransportFactory = (): Transport => ({\n name: 'noop',\n send(): void {\n // intentionally empty\n },\n});\n","/**\n * `SafeTransport` wraps any consumer-supplied `Transport` so that synchronous\n * throws and rejected Promises from `send()`, `flush()`, or `shutdown()`\n * never propagate to the caller. The first failure per wrapped transport\n * per session emits one `onInternalError` notice; subsequent failures are\n * silent (no log spam — FS-12).\n *\n * Locks the failure-safety invariants:\n * FS-1 sync throw from send() → caught\n * FS-2 rejected Promise from send() → swallowed (no unhandled rejection)\n * FS-11 one transport throws while others succeed → others still run\n * (the dispatcher iterates over wrapped transports; each is isolated)\n * FS-12 one notice per transport per session\n */\n\nimport type { LogEvent, Transport } from '../api/types.js';\nimport {\n type PackageErrorCode,\n safeNotify,\n wrapAsPackageError,\n} from '../internal/errors/internal-errors.js';\n\nexport class SafeTransport implements Transport {\n readonly name: string;\n private readonly inner: Transport;\n private readonly onInternalError: (err: Error) => void;\n private notified = false;\n\n constructor(inner: Transport, onInternalError: (err: Error) => void) {\n this.inner = inner;\n this.name = inner.name;\n this.onInternalError = onInternalError;\n }\n\n send(event: LogEvent): void {\n try {\n const result = this.inner.send(event);\n if (result instanceof Promise) {\n result.then(undefined, (reason: unknown) => {\n this.notify(reason, 'transport_send_failed');\n });\n }\n } catch (err) {\n this.notify(err, 'transport_send_failed');\n }\n }\n\n async flush(): Promise<void> {\n if (this.inner.flush === undefined) return;\n try {\n await this.inner.flush();\n } catch (err) {\n this.notify(err, 'transport_send_failed');\n }\n }\n\n async shutdown(): Promise<void> {\n if (this.inner.shutdown === undefined) return;\n try {\n await this.inner.shutdown();\n } catch (err) {\n this.notify(err, 'transport_shutdown_failed');\n }\n }\n\n private notify(cause: unknown, code: PackageErrorCode): void {\n if (this.notified) return;\n this.notified = true;\n safeNotify(\n this.onInternalError,\n wrapAsPackageError(\n code,\n `Transport '${this.name}' failed: ${describe(cause)}`,\n cause,\n this.name,\n ),\n );\n }\n}\n\nfunction describe(value: unknown): string {\n if (value instanceof Error) return value.message;\n if (typeof value === 'string') return value;\n return String(value);\n}\n","/**\n * `ConfiguredRuntime` — the shared package-level runtime resource\n * produced by `configureLogging()`.\n *\n * Architectural role (per `plan.md` \"Runtime Scale Architecture\" and\n * constitution v1.2.0 Principle VII): every `Logger` handle reads\n * this runtime at emit time. Logger handles are cheap, side-effect-\n * free context objects; the expensive state (normalized config,\n * already-wrapped `SafeTransport[]`, redactor, sanitizer limits,\n * `onInternalError` sink, correlation hook) lives once here and is\n * shared across every logger derived from a single\n * `configureLogging()` invocation.\n *\n * Per `plan.md`'s \"Vendor-Neutral Core Architecture\", this record\n * has **no `backend` field**. The dispatcher (`pipeline/dispatcher.ts`)\n * fans events out directly to the `SafeTransport`-wrapped transports\n * stored here; there is no telemetry-backend indirection on the v1\n * default path. Future vendor adapters are peer transports, not a\n * resurrected backend slot.\n *\n * The build/shutdown helpers here are pure with respect to the\n * `runtime-ref` slot — they construct + tear down a runtime\n * instance but never touch the active-runtime pointer. The slot\n * swap is performed by `runtime-ref.ts::installRuntime()` so the\n * two responsibilities stay separate.\n */\n\nimport type {\n LogContext,\n LoggerConfig,\n Redactor,\n SanitizerLimits,\n Transport,\n} from '../api/types.js';\nimport { type NormalizedConfig, normalizeConfig } from '../config/config.js';\nimport { NoopTransport } from '../transport/noop-transport.js';\nimport { SafeTransport } from '../transport/safe-transport.js';\n\nexport interface ConfiguredRuntime {\n /**\n * The normalized configuration. `transports` here is the same\n * already-wrapped array exposed on this record's top-level\n * `transports` field; keep both pointers stable for future\n * read-paths that prefer one or the other.\n */\n readonly config: NormalizedConfig;\n\n /**\n * Already-`SafeTransport`-wrapped transports. Each one is isolated\n * for sync throws and rejected Promises (see `SafeTransport`).\n * Empty consumer transport lists are auto-replaced with a single\n * `NoopTransport()` per the documented default in\n * `contracts/failure-safety.md`.\n */\n readonly transports: ReadonlyArray<Transport>;\n\n /** Custom redactor; `undefined` falls back to the default in the redact stage. */\n readonly redactor: Redactor | undefined;\n\n /** Effective sanitizer bounds (clamped to documented Min..Max at normalize time). */\n readonly sanitizerLimits: SanitizerLimits;\n\n /** Diagnostics hook. Always defined (defaults to a no-op silent sink). */\n readonly onInternalError: (err: Error) => void;\n\n /** Per-emit dynamic context hook. Optional. Synchronous. */\n readonly correlation: (() => Partial<LogContext>) | undefined;\n}\n\n/**\n * Build a fresh `ConfiguredRuntime` from a consumer `LoggerConfig`.\n * Normalizes the config (clamps sanitizer limits, resolves level\n * from env defaults, etc.), wraps every consumer transport in\n * `SafeTransport`, and installs the auto-`NoopTransport` fallback\n * for empty transport lists. Pure with respect to the active-\n * runtime slot — call `runtime-ref.ts::installRuntime()` to make\n * the returned record active.\n */\nexport function buildConfiguredRuntime(\n config: LoggerConfig,\n): ConfiguredRuntime {\n const normalized = normalizeConfig(config);\n\n // Empty consumer transport list → auto-NoopTransport per\n // `contracts/failure-safety.md` \"no transport configured\" row.\n const sourceTransports: ReadonlyArray<Transport> =\n normalized.transports.length === 0\n ? [NoopTransport()]\n : normalized.transports;\n\n const wrapped: ReadonlyArray<Transport> = sourceTransports.map(\n (t) => new SafeTransport(t, normalized.onInternalError),\n );\n\n // Re-build the normalized config with the wrapped transports so\n // downstream code that reads `config.transports` (the dispatcher's\n // direct transport fan-out) sees the wrapped list.\n const installedConfig: NormalizedConfig = {\n ...normalized,\n transports: wrapped,\n };\n\n return {\n config: installedConfig,\n transports: wrapped,\n redactor: normalized.redactor,\n sanitizerLimits: normalized.sanitizerLimits,\n onInternalError: normalized.onInternalError,\n correlation: normalized.correlation,\n };\n}\n\n/**\n * Best-effort teardown of a previously-active `ConfiguredRuntime`.\n * Calls `flush()` then `shutdown()` on every transport, each\n * isolated in its own try/catch so a single transport's failure\n * cannot block sibling teardown. `SafeTransport` already wraps each\n * transport's `flush`/`shutdown` and routes errors through the\n * `onInternalError` sink (with the per-transport notice budget),\n * so the try/catch here is a belt-and-suspenders guard for any\n * residual throw that escapes the wrapper.\n *\n * Pure with respect to the active-runtime slot — the caller is\n * responsible for first swapping the slot via\n * `runtime-ref.ts::installRuntime()` before invoking this\n * function, so retained `Logger` references already see the new\n * runtime when teardown begins.\n */\nexport async function shutdownRuntime(\n runtime: ConfiguredRuntime,\n): Promise<void> {\n for (const transport of runtime.transports) {\n if (transport.flush !== undefined) {\n try {\n await transport.flush();\n } catch {\n // SafeTransport already notified onInternalError.\n }\n }\n if (transport.shutdown !== undefined) {\n try {\n await transport.shutdown();\n } catch {\n // SafeTransport already notified onInternalError.\n }\n }\n }\n}\n","/**\n * Module-scoped active-runtime slot.\n *\n * The single source of truth for \"which `ConfiguredRuntime` is\n * currently active in this loaded copy of the package.\" Every\n * `Logger` handle reads through `getActiveRuntime()` at emit time,\n * so retained `Logger` references automatically pick up a new\n * runtime after `configureLogging()` performs an atomic swap via\n * `installRuntime()` (locks FR-031 / SC-012).\n *\n * Storage is **module-scoped only** — a top-level `let`. Per\n * constitution v1.2.0 Principle VII and FR-033, the slot:\n * - does NOT use `globalThis` / `window` / `self` / `document`\n * - does NOT register under `Symbol.for(...)`\n * - does NOT install any cross-realm or cross-bundle sharing\n * mechanism\n *\n * That is the load-bearing property that makes duplicate-package-\n * copy behavior **isolated** (FR-033): when a federated bundler\n * causes two physical copies of this package to load on a single\n * page, each copy has its own private `active` variable. Configuring\n * one copy does not affect the other; loggers from one copy cannot\n * cross-route events into the other copy's transports. Consumers\n * who want cross-copy sharing configure their bundler's module-\n * federation `shared` map at build time — there is no runtime\n * back door here.\n *\n * `getActiveRuntime()` returns `undefined` until the first call\n * to `installRuntime()` (or until `configureLogging()` triggers\n * lazy install via the safe-defaults runtime). Callers should\n * handle the undefined case by installing a default; the package's\n * own emit path does this via the lazy-install in\n * `src/api/logger.ts::ensureState()`.\n */\n\nimport type { ConfiguredRuntime } from './configured-runtime.js';\n\n/**\n * The single active-runtime cell. Module-scoped; never exported as a\n * mutable binding. External access goes through `getActiveRuntime()`\n * (read) and `installRuntime()` (atomic write + return-previous).\n */\nlet active: ConfiguredRuntime | undefined;\n\n/**\n * Read the currently-active `ConfiguredRuntime`, or `undefined` if\n * no runtime has been installed yet. Constant-time slot read; no\n * allocation; never throws.\n *\n * Read fresh at every emit so retained logger references see the\n * latest configuration after a swap. Callers MUST NOT cache the\n * result across emits.\n */\nexport function getActiveRuntime(): ConfiguredRuntime | undefined {\n return active;\n}\n\n/**\n * Atomic swap: install `runtime` as the active runtime and return\n * the previously-active one (or `undefined` for the first install).\n *\n * The swap itself is a single assignment, so the slot transitions\n * from \"old\" to \"new\" in one step — no observer can ever see a\n * partially-installed state. Teardown of the previous runtime\n * (flush + shutdown of its transports) is the CALLER's\n * responsibility; this function does not perform any teardown\n * because the caller may want to inspect the previous runtime\n * before tearing it down.\n *\n * `configureLogging()` calls this then schedules\n * `shutdownRuntime(previous)` fire-and-forget so the new runtime\n * is live for the very next emit while the old one's transports\n * are still flushing in the background.\n */\nexport function installRuntime(\n runtime: ConfiguredRuntime,\n): ConfiguredRuntime | undefined {\n const previous = active;\n active = runtime;\n return previous;\n}\n\n/**\n * Reset the active-runtime slot to `undefined`. Test-only helper:\n * the package's own test suite uses this to isolate test cases\n * from each other so a leftover runtime from one test cannot\n * affect the next. Not exposed from the runtime public surface;\n * callers reach for it explicitly only when they have a specific\n * need to drop state (e.g., between `vi.isolateModules` runs in\n * the duplicate-copy isolation test landing in T064).\n */\nexport function clearActiveRuntimeForTests(): void {\n active = undefined;\n}\n","/**\n * Fail-closed validation/normalization of W3C Trace Context.\n *\n * `normalizeTraceContext` is the single point where supplied trace context —\n * whether handed in directly as `context.trace` or produced by\n * `parseTraceparent` — is checked against W3C rules. It is called once per\n * emit during context resolution, before sanitize/redact.\n *\n * Policy (require both ids; contract TC-4, research D4):\n * - `traceId` MUST be 32 lowercase-hex, not all-zero.\n * - `spanId` MUST be 16 lowercase-hex, not all-zero.\n * - If either id is invalid, the WHOLE trace is dropped (returns\n * `undefined`) — a real W3C `traceparent` always carries both, so partial\n * validity is a malformed-input artifact, and a half-correlated record is\n * misleading (Principle VI).\n * - `traceFlags` is kept only as an integer in [0, 255], else omitted.\n * - `traceState` is kept only as a string within `MAX_TRACESTATE_LEN`, else\n * omitted.\n *\n * Pure and side-effect-free; NEVER throws.\n *\n * Specs: `specs/008-trace-context/contracts/trace-context.md` TC-4;\n * `data-model.md`.\n */\n\nimport type { TraceContext } from '../api/types.js';\n\n/** Max `tracestate` length (W3C caps the header at 512 chars). */\nexport const MAX_TRACESTATE_LEN = 512;\n\nconst TRACE_ID_RE = /^[0-9a-f]{32}$/;\nconst SPAN_ID_RE = /^[0-9a-f]{16}$/;\nconst ALL_ZERO_TRACE_ID = '0'.repeat(32);\nconst ALL_ZERO_SPAN_ID = '0'.repeat(16);\n\nfunction isValidTraceId(value: unknown): value is string {\n return (\n typeof value === 'string' &&\n TRACE_ID_RE.test(value) &&\n value !== ALL_ZERO_TRACE_ID\n );\n}\n\nfunction isValidSpanId(value: unknown): value is string {\n return (\n typeof value === 'string' &&\n SPAN_ID_RE.test(value) &&\n value !== ALL_ZERO_SPAN_ID\n );\n}\n\n/**\n * Validate + normalize an arbitrary candidate into a `TraceContext`, or return\n * `undefined` when the ids are absent/invalid. Optional parts that are invalid\n * are individually omitted while valid ids are kept.\n */\nexport function normalizeTraceContext(\n candidate: unknown,\n): TraceContext | undefined {\n if (typeof candidate !== 'object' || candidate === null) {\n return undefined;\n }\n const c = candidate as {\n traceId?: unknown;\n spanId?: unknown;\n traceFlags?: unknown;\n traceState?: unknown;\n };\n\n if (!isValidTraceId(c.traceId) || !isValidSpanId(c.spanId)) {\n return undefined; // require both ids — drop the whole trace fail-closed\n }\n\n const trace: TraceContext = { traceId: c.traceId, spanId: c.spanId };\n\n if (\n typeof c.traceFlags === 'number' &&\n Number.isInteger(c.traceFlags) &&\n c.traceFlags >= 0 &&\n c.traceFlags <= 255\n ) {\n trace.traceFlags = c.traceFlags;\n }\n\n if (\n typeof c.traceState === 'string' &&\n c.traceState.length > 0 &&\n c.traceState.length <= MAX_TRACESTATE_LEN\n ) {\n trace.traceState = c.traceState;\n }\n\n return trace;\n}\n","/**\n * Public logger factories and root configuration flow.\n *\n * - `configureLogging(config)` — install (or replace) the package's\n * module-scoped configuration. Atomic: the new runtime is built\n * and installed in a single slot swap, then the previously-active\n * runtime is torn down in the background so existing logger\n * references keep working without modification.\n * - `createLogger(options?)` — return a `Logger` whose context layers\n * on top of the current root configuration.\n * - `getRootLogger()` — singleton root logger created on first access.\n *\n * Behavior before `configureLogging()` is called is identical to a\n * `configureLogging({})` invocation: env-unknown defaults (`warn`+),\n * a single `NoopTransport`, and direct transport fan-out from the\n * dispatcher. All emissions return synchronously and never throw.\n *\n * Vendor-neutrality: this module imports no observability-vendor SDK.\n * The dispatcher fans sanitized + redacted events directly to the\n * `SafeTransport`-wrapped consumer transports stored on the active\n * `ConfiguredRuntime`. There is no telemetry backend in the v1\n * default path; future vendor adapters are peer transports.\n */\n\nimport { mergeContexts } from '../context/context-merge.js';\nimport {\n safeNotify,\n wrapAsPackageError,\n} from '../internal/errors/internal-errors.js';\nimport { dispatch } from '../pipeline/dispatcher.js';\nimport { buildLogEvent } from '../pipeline/event-builder.js';\nimport { passesLevelFilter } from '../pipeline/level-filter.js';\nimport {\n buildConfiguredRuntime,\n type ConfiguredRuntime,\n shutdownRuntime,\n} from '../runtime/configured-runtime.js';\nimport { getActiveRuntime, installRuntime } from '../runtime/runtime-ref.js';\nimport { normalizeTraceContext } from '../trace/validate.js';\nimport type {\n Attributes,\n CreateLoggerOptions,\n LogContext,\n Logger,\n LoggerConfig,\n LogLevel,\n} from './types.js';\n\nlet rootLogger: Logger | undefined;\n\n/**\n * Build a fresh `ConfiguredRuntime` from `config`, install it as the\n * active runtime, and shut down the previously-active runtime's\n * transports in the background. The runtime-slot swap is atomic:\n * retained `Logger` references that read through `getActiveRuntime()`\n * at emit time see the new runtime immediately.\n */\nfunction installState(config: LoggerConfig): ConfiguredRuntime {\n const runtime = buildConfiguredRuntime(config);\n\n // Atomic active-runtime swap. After this assignment retained\n // Logger references see the new runtime; the old runtime's\n // transports continue to flush + shutdown in the background.\n const previousRuntime = installRuntime(runtime);\n\n // Fire-and-forget teardown of the previous runtime. Each transport's\n // flush/shutdown is already isolated by SafeTransport; the\n // `.then(undefined, …)` is a final unhandled-rejection swallow per\n // the no-throw invariant.\n if (previousRuntime !== undefined) {\n void shutdownRuntime(previousRuntime).then(undefined, () => undefined);\n }\n return runtime;\n}\n\n/** Lazily install safe defaults so pre-configure emissions just work. */\nfunction ensureState(): ConfiguredRuntime {\n let runtime = getActiveRuntime();\n if (runtime === undefined) {\n runtime = installState({});\n }\n return runtime;\n}\n\n/**\n * Install or replace the package's configuration. Safe to call multiple\n * times — the previous runtime's transports are flushed + shut down\n * (fire-and-forget) and the new configuration is installed via an\n * atomic active-runtime-slot swap, so existing logger references\n * continue to work without re-acquisition.\n *\n * Per FR-031 / SC-012, the swap is observable to any subsequent emit\n * from a retained `Logger` reference: emit reads through\n * `getActiveRuntime()` at the time of the call, so the new runtime is\n * live for the very next emission.\n *\n * Per FR-032 the call is the single explicit named API for installing\n * a runtime. There is no implicit module-load side effect that\n * replaces the runtime; only an explicit `configureLogging()`\n * invocation can swap it.\n */\nexport function configureLogging(config: LoggerConfig): void {\n installState(config);\n}\n\n/**\n * Create a logger whose context layers on top of the current root\n * configuration. The returned logger holds no captured state — every\n * emission reads the *current* module-scoped configuration, so calling\n * `configureLogging()` later affects loggers already created.\n */\nexport function createLogger(options: CreateLoggerOptions = {}): Logger {\n return makeLogger(options, []);\n}\n\n/** Singleton root logger created on first access. */\nexport function getRootLogger(): Logger {\n if (rootLogger === undefined) {\n rootLogger = createLogger();\n }\n return rootLogger;\n}\n\nfunction makeLogger(\n options: CreateLoggerOptions,\n chainedContexts: ReadonlyArray<Partial<LogContext>>,\n): Logger {\n // Per-logger context, including the optional `module` shortcut. If both\n // `options.module` and `options.context.module` are set, the explicit\n // `options.module` shortcut wins because it is appended last to the\n // merge precedence chain.\n const loggerContextLayers: ReadonlyArray<Partial<LogContext>> = [\n options.context ?? {},\n options.module !== undefined ? { module: options.module } : {},\n ];\n\n function emit(\n level: LogLevel,\n message: string,\n attributes?: Attributes,\n errorValue?: unknown,\n ): void {\n const runtime = ensureState();\n const cfg = runtime.config;\n\n // Level filter — runs first so a filtered-out emission performs no\n // work beyond a constant-time numeric comparison.\n if (!passesLevelFilter(level, options.level, cfg.level)) {\n return;\n }\n\n // Root identity carried at the LoggerConfig top level becomes the\n // lowest-precedence layer; per-logger / child / correlation override.\n const rootIdentity: Partial<LogContext> = {};\n if (cfg.application !== undefined) {\n rootIdentity.application = cfg.application;\n }\n if (cfg.module !== undefined) {\n rootIdentity.module = cfg.module;\n }\n if (cfg.environment !== undefined) {\n rootIdentity.environment = cfg.environment;\n }\n\n // Invoke correlation() inside a guard so a throwing callback drops\n // its contribution for this event but does not drop the event.\n let correlation: Partial<LogContext> | undefined;\n if (cfg.correlation !== undefined) {\n try {\n correlation = cfg.correlation();\n } catch (err) {\n safeNotify(\n cfg.onInternalError,\n wrapAsPackageError(\n 'correlation_failed',\n 'correlation() callback threw; its output is dropped for this event.',\n err,\n ),\n );\n }\n }\n\n // Documented merge precedence (data-model.md, contracts/logger-config.md\n // LC-7): root → per-logger → child chain → correlation. The prior code\n // had `chainedContexts` BEFORE `loggerContextLayers`, which caused a\n // per-logger `module` identity to win over a `.child({ module: ... })`\n // override (locked as a regression by T053).\n const context = mergeContexts(\n rootIdentity,\n cfg.context,\n ...loggerContextLayers,\n ...chainedContexts,\n correlation,\n );\n\n // Fail-closed trace-context validation (once per emit, before sanitize/\n // redact). Invalid/absent trace ⇒ no `trace` field; never throws.\n if (context.trace !== undefined) {\n const normalized = normalizeTraceContext(context.trace);\n if (normalized === undefined) {\n delete context.trace;\n } else {\n context.trace = normalized;\n }\n }\n\n const event = buildLogEvent({\n level,\n message,\n attributes,\n context,\n errorValue,\n });\n\n // Route through the locked pipeline order in src/pipeline/dispatcher.ts:\n // Sanitize → URLScrub → Redact → ControlCharGuard → Freeze →\n // direct transport fan-out. The dispatcher owns its own try/catch\n // around every stage and around every transport.send() call, so no\n // error can escape into this caller.\n dispatch(event, cfg);\n }\n\n return {\n debug(message, attributes) {\n emit('debug', message, attributes);\n },\n info(message, attributes) {\n emit('info', message, attributes);\n },\n warn(message, attributes) {\n emit('warn', message, attributes);\n },\n error(message, attributes, errorValue) {\n emit('error', message, attributes, errorValue);\n },\n child(context) {\n return makeLogger(options, [...chainedContexts, context]);\n },\n withContext(context) {\n return makeLogger(options, [...chainedContexts, context]);\n },\n };\n}\n","/**\n * Pure W3C `traceparent` parser — the one ergonomic affordance for the common\n * case where a host holds the header string (e.g. SSR-injected) rather than a\n * pre-parsed object.\n *\n * Format: `version-traceId-spanId-flags` =\n * `00-<32hex>-<16hex>-<2hex>`. Version `00` is the current spec; for forward\n * compatibility, any 2-hex version is accepted and only the four known fields\n * are read (extra trailing fields are ignored).\n *\n * The parsed candidate is run through `normalizeTraceContext`, so the result is\n * always a valid `TraceContext` or `undefined`. NEVER throws.\n *\n * Specs: `specs/008-trace-context/contracts/trace-context.md` TC-5;\n * `research.md` D2.\n */\n\nimport type { TraceContext } from '../api/types.js';\n\nimport { normalizeTraceContext } from './validate.js';\n\nconst VERSION_RE = /^[0-9a-f]{2}$/;\n\n/**\n * Parse a W3C `traceparent` string (and optional `tracestate`) into a validated\n * `TraceContext`, or `undefined` on any shape violation. Pure; never throws.\n */\nexport function parseTraceparent(\n traceparent: string,\n tracestate?: string,\n): TraceContext | undefined {\n if (typeof traceparent !== 'string') return undefined;\n\n const parts = traceparent.trim().split('-');\n if (parts.length < 4) return undefined;\n\n const [version, traceId, spanId, flagsHex] = parts;\n if (version === undefined || !VERSION_RE.test(version)) return undefined;\n // Version ff is explicitly invalid per the W3C spec.\n if (version === 'ff') return undefined;\n if (flagsHex === undefined || !/^[0-9a-f]{2}$/.test(flagsHex)) {\n return undefined;\n }\n\n const traceFlags = Number.parseInt(flagsHex, 16);\n\n // normalizeTraceContext does the id/hex/non-zero + bound checks and returns\n // undefined if traceId/spanId are not well-formed.\n return normalizeTraceContext({\n traceId,\n spanId,\n traceFlags,\n ...(typeof tracestate === 'string' ? { traceState: tracestate } : {}),\n });\n}\n","/**\n * Built-in `ConsoleTransport`. Passes events to `console[level]` with the\n * event message as the first argument and the **structured `LogEvent`\n * object as the second argument** — never interpolated into a single\n * string. Falls back to `console.log` only when `console[level]` is not a\n * function (the modern browser console always defines all four levels).\n *\n * This is the only built-in delivery path that produces visible output.\n * Console output preserves the structured-only invariant (FR-016, plan\n * §Log-injection & output safety).\n */\n\nimport type { LogEvent, Transport, TransportFactory } from '../api/types.js';\n\ntype ConsoleMethod = (message?: unknown, ...optional: unknown[]) => void;\n\nfunction resolveConsoleMethod(level: LogEvent['level']): ConsoleMethod {\n const slot = (console as unknown as Record<string, unknown>)[level];\n if (typeof slot === 'function') {\n return (slot as ConsoleMethod).bind(console);\n }\n return console.log.bind(console);\n}\n\nexport const ConsoleTransport: TransportFactory = (): Transport => ({\n name: 'console',\n send(event: LogEvent): void {\n const log = resolveConsoleMethod(event.level);\n log(event.message, event);\n },\n});\n"]}