@utk09/ui-observability 0.1.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.
- package/LICENSE +202 -0
- package/README.md +217 -0
- package/dist/bus/bus.d.ts +134 -0
- package/dist/bus/links.d.ts +106 -0
- package/dist/capture/errors.d.ts +34 -0
- package/dist/capture/interactions.d.ts +29 -0
- package/dist/capture/network.d.ts +40 -0
- package/dist/capture/types.d.ts +78 -0
- package/dist/capture/web-vitals.d.ts +21 -0
- package/dist/constants-D8-4Ged5.cjs +2 -0
- package/dist/constants-D8-4Ged5.cjs.map +1 -0
- package/dist/constants-DbvMIryP.js +110 -0
- package/dist/constants-DbvMIryP.js.map +1 -0
- package/dist/constants.d.ts +339 -0
- package/dist/core/breadcrumbs.d.ts +48 -0
- package/dist/core/config.d.ts +16 -0
- package/dist/core/context.d.ts +35 -0
- package/dist/core/diagnostics.d.ts +76 -0
- package/dist/core/journey.d.ts +112 -0
- package/dist/core/logger.d.ts +117 -0
- package/dist/core/pipeline.d.ts +75 -0
- package/dist/core/record.d.ts +72 -0
- package/dist/core/runtime.d.ts +146 -0
- package/dist/core/sampling.d.ts +9 -0
- package/dist/index.cjs +4 -0
- package/dist/index.cjs.map +1 -0
- package/dist/index.d.ts +167 -0
- package/dist/index.js +2577 -0
- package/dist/index.js.map +1 -0
- package/dist/indexeddb-storage-DvsvCUlO.cjs +2 -0
- package/dist/indexeddb-storage-DvsvCUlO.cjs.map +1 -0
- package/dist/indexeddb-storage-DwpCDRnX.js +88 -0
- package/dist/indexeddb-storage-DwpCDRnX.js.map +1 -0
- package/dist/models/batch.d.ts +22 -0
- package/dist/models/bus.d.ts +97 -0
- package/dist/models/config.d.ts +528 -0
- package/dist/models/log-record.d.ts +54 -0
- package/dist/models/serializer.d.ts +23 -0
- package/dist/models/storage.d.ts +62 -0
- package/dist/storage/emergency-queue.d.ts +16 -0
- package/dist/storage/factory.d.ts +13 -0
- package/dist/storage/indexeddb-storage.d.ts +69 -0
- package/dist/storage/keys.d.ts +8 -0
- package/dist/storage/local-storage.d.ts +80 -0
- package/dist/storage/memory-storage.d.ts +52 -0
- package/dist/transport/compression.d.ts +7 -0
- package/dist/transport/errors.d.ts +29 -0
- package/dist/transport/exit-flush.d.ts +63 -0
- package/dist/transport/http-transport.d.ts +63 -0
- package/dist/transport/retry-engine.d.ts +69 -0
- package/dist/transport/serializers/ecs.d.ts +3 -0
- package/dist/transport/serializers/otlp.d.ts +3 -0
- package/dist/utils/console.d.ts +24 -0
- package/dist/utils/identity.d.ts +36 -0
- package/dist/utils/lock.d.ts +15 -0
- package/dist/utils/platform.d.ts +36 -0
- package/dist/utils/sanitize.d.ts +47 -0
- package/dist/utils/sequence.d.ts +15 -0
- package/dist/utils/timer.d.ts +19 -0
- package/dist/utils/tracing.d.ts +55 -0
- package/dist/utils/unref.d.ts +9 -0
- package/package.json +106 -0
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"index.cjs","names":[],"sources":["../src/utils/timer.ts","../src/core/logger.ts","../src/utils/unref.ts","../src/models/bus.ts","../src/bus/links.ts","../src/bus/bus.ts","../src/capture/errors.ts","../src/capture/interactions.ts","../src/capture/types.ts","../src/capture/network.ts","../src/capture/web-vitals.ts","../src/models/log-record.ts","../src/utils/lock.ts","../src/storage/keys.ts","../src/storage/emergency-queue.ts","../src/storage/local-storage.ts","../src/storage/memory-storage.ts","../src/storage/factory.ts","../src/utils/sanitize.ts","../src/transport/exit-flush.ts","../src/transport/compression.ts","../src/transport/errors.ts","../src/transport/http-transport.ts","../src/utils/identity.ts","../src/models/batch.ts","../src/transport/retry-engine.ts","../src/utils/console.ts","../src/utils/platform.ts","../src/utils/sequence.ts","../src/utils/tracing.ts","../src/core/breadcrumbs.ts","../src/transport/serializers/ecs.ts","../src/transport/serializers/otlp.ts","../src/core/config.ts","../src/core/context.ts","../src/core/diagnostics.ts","../src/core/journey.ts","../src/core/sampling.ts","../src/core/pipeline.ts","../src/core/record.ts","../src/core/runtime.ts","../src/index.ts"],"sourcesContent":["// src/utils/timer.ts\n//\n// Utility functions for timing synchronous and asynchronous operations as metrics.\n\nimport type { CaptureLogger } from \"../capture/types\";\nimport { DURATION_PRECISION } from \"../constants\";\n\n/**\n * Calculates elapsed milliseconds rounded to configured precision.\n * @param startedAt Performance timestamp recorded at operation start.\n * @returns Elapsed duration in milliseconds.\n */\nfunction elapsed(startedAt: number): number {\n return Math.round((performance.now() - startedAt) * DURATION_PRECISION) / DURATION_PRECISION;\n}\n\n/**\n * Logs a successful operation duration histogram metric.\n * @param logger Target telemetry logger.\n * @param label Metric name prefix.\n * @param startedAt Performance timestamp recorded at operation start.\n * @param status Outcome status string.\n * @param attributes Optional contextual attributes.\n */\nfunction finish(\n logger: CaptureLogger,\n label: string,\n startedAt: number,\n status: string,\n attributes?: Record<string, unknown>,\n): void {\n logger.logMetric(`${label}.duration`, elapsed(startedAt), \"ms\", \"histogram\", {\n status,\n ...attributes,\n });\n}\n\n/**\n * Logs an operation failure with elapsed duration attributes.\n * @param logger Target telemetry logger.\n * @param label Operation label.\n * @param startedAt Performance timestamp recorded at operation start.\n * @param error Caught error instance or thrown value.\n * @param attributes Optional contextual attributes.\n */\nfunction fail(\n logger: CaptureLogger,\n label: string,\n startedAt: number,\n error: unknown,\n attributes?: Record<string, unknown>,\n): void {\n logger.error(`${label} failed`, error, {\n \"action.duration_ms\": elapsed(startedAt),\n status: \"FAILURE\",\n ...attributes,\n });\n}\n\n/**\n * Executes and measures the duration of a synchronous function.\n * @param logger Target telemetry logger.\n * @param label Metric name prefix.\n * @param fn Synchronous function to execute.\n * @param attributes Optional contextual attributes.\n * @returns Result returned by the wrapped function.\n */\nexport function timeSync<T>(\n logger: CaptureLogger,\n label: string,\n fn: () => T,\n attributes?: Record<string, unknown>,\n): T {\n const startedAt = performance.now();\n try {\n const result = fn();\n finish(logger, label, startedAt, \"SUCCESS\", attributes);\n return result;\n } catch (error) {\n // Re-throws error to preserve caller control flow.\n fail(logger, label, startedAt, error, attributes);\n throw error;\n }\n}\n\n/**\n * Executes and measures the duration of an asynchronous promise-returning function.\n * @param logger Target telemetry logger.\n * @param label Metric name prefix.\n * @param fn Asynchronous function to execute.\n * @param attributes Optional contextual attributes.\n * @returns Promise resolving to the result of the wrapped function.\n */\nexport async function timeAsync<T>(\n logger: CaptureLogger,\n label: string,\n fn: () => Promise<T>,\n attributes?: Record<string, unknown>,\n): Promise<T> {\n const startedAt = performance.now();\n try {\n const result = await fn();\n finish(logger, label, startedAt, \"SUCCESS\", attributes);\n return result;\n } catch (error) {\n // Re-throws error to preserve caller control flow.\n fail(logger, label, startedAt, error, attributes);\n throw error;\n }\n}\n","// src/core/logger.ts\n//\n// Namespaced logger facade providing scoped logging methods and metrics timing.\n\nimport { DEFAULT_METRIC_UNIT } from \"../constants\";\nimport type { LogLevel, LogType, MetricType } from \"../models/log-record\";\nimport { timeAsync, timeSync } from \"../utils/timer\";\nimport type { ObservabilityRuntime } from \"./runtime\";\n\n/** Configuration options for a scoped OneLogger instance. */\nexport interface OneLoggerOptions {\n /** Contextual attributes merged into all records emitted by this logger. */\n scopedContext?: Record<string, unknown>;\n}\n\n/**\n * Normalizes an unknown thrown value into an Error instance.\n * @param value Caught error instance or primitive value.\n * @returns Normalized Error instance.\n */\nfunction toError(value: unknown): Error {\n return value instanceof Error ? value : new Error(String(value));\n}\n\n/** Namespaced logger instance for recording structured events, metrics, and errors. */\nexport class OneLogger {\n /**\n * @param runtime Underlying observability runtime instance.\n * @param namespace Application subsystem or module namespace.\n * @param options Scoped context options.\n */\n constructor(\n private readonly runtime: ObservabilityRuntime,\n readonly namespace: string,\n private readonly options: OneLoggerOptions = {},\n ) {}\n\n /**\n * Creates a child logger with a nested namespace and merged scoped context.\n * @param namespace Sub-namespace appended with dot notation.\n * @param options Additional scoped context attributes.\n * @returns Nested child OneLogger instance.\n */\n child(namespace: string, options: OneLoggerOptions = {}): OneLogger {\n return new OneLogger(this.runtime, `${this.namespace}.${namespace}`, {\n scopedContext: {\n ...this.options.scopedContext,\n ...options.scopedContext,\n },\n });\n }\n\n /**\n * Logs a trace-level debug record.\n * @param message Log message.\n * @param payload Optional contextual attributes.\n */\n trace = (message: string, payload?: Record<string, unknown>): void => {\n this.write(\"TRACE\", \"system\", message, payload);\n };\n\n /**\n * Logs a debug-level record.\n * @param message Log message.\n * @param payload Optional contextual attributes.\n */\n debug = (message: string, payload?: Record<string, unknown>): void => {\n this.write(\"DEBUG\", \"system\", message, payload);\n };\n\n /**\n * Logs an informational record.\n * @param message Log message.\n * @param payload Optional contextual attributes.\n */\n info = (message: string, payload?: Record<string, unknown>): void => {\n this.write(\"INFO\", \"system\", message, payload);\n };\n\n /**\n * Logs a warning record.\n * @param message Log message.\n * @param payload Optional contextual attributes.\n */\n warn = (message: string, payload?: Record<string, unknown>): void => {\n this.write(\"WARN\", \"system\", message, payload);\n };\n\n /**\n * Logs an error record with attached breadcrumb history.\n * @param message Error description.\n * @param error Caught error instance or reason.\n * @param payload Optional contextual attributes.\n */\n error = (message: string, error?: unknown, payload?: Record<string, unknown>): void => {\n this.writeError(\"ERROR\", message, error, payload);\n };\n\n /**\n * Logs a fatal unrecoverable error record.\n * @param message Error description.\n * @param error Caught error instance or reason.\n * @param payload Optional contextual attributes.\n */\n fatal = (message: string, error?: unknown, payload?: Record<string, unknown>): void => {\n this.writeError(\"FATAL\", message, error, payload);\n };\n\n /**\n * Logs a discrete user interaction action.\n * @param name Action identifier.\n * @param payload Optional action attributes.\n */\n logAction = (name: string, payload?: Record<string, unknown>): void => {\n this.write(\"INFO\", \"action\", name, payload);\n };\n\n /**\n * Logs an application lifecycle or domain event.\n * @param name Event identifier.\n * @param payload Optional event attributes.\n */\n logEvent = (name: string, payload?: Record<string, unknown>): void => {\n this.write(\"INFO\", \"event\", name, payload);\n };\n\n /**\n * Logs a numerical metric measurement.\n * @param name Metric identifier.\n * @param value Numerical measurement.\n * @param unit Unit of measurement.\n * @param type Metric type classification.\n * @param attributes Optional metric attributes.\n */\n logMetric = (\n name: string,\n value: number,\n unit = DEFAULT_METRIC_UNIT,\n type: MetricType = \"gauge\",\n attributes?: Record<string, unknown>,\n ): void => {\n this.write(\"INFO\", \"metric\", name, {\n \"metric.name\": name,\n \"metric.value\": value,\n \"metric.unit\": unit,\n \"metric.type\": type,\n ...attributes,\n });\n };\n\n /**\n * Times a synchronous function execution and records a duration metric.\n * @param label Metric name prefix.\n * @param fn Synchronous function to time.\n * @param attributes Optional contextual attributes.\n * @returns Result returned by the timed function.\n */\n timeSync = <T>(label: string, fn: () => T, attributes?: Record<string, unknown>): T =>\n timeSync(this, label, fn, attributes);\n\n /**\n * Times an asynchronous function execution and records a duration metric.\n * @param label Metric name prefix.\n * @param fn Asynchronous function to time.\n * @param attributes Optional contextual attributes.\n * @returns Promise resolving to the result of the timed function.\n */\n timeAsync = <T>(\n label: string,\n fn: () => Promise<T>,\n attributes?: Record<string, unknown>,\n ): Promise<T> => timeAsync(this, label, fn, attributes);\n\n /**\n * Builds, logs to console, and emits a standard log record.\n * @param level Severity level.\n * @param type Record classification.\n * @param body Primary message.\n * @param payload Optional contextual attributes.\n */\n private write(\n level: LogLevel,\n type: LogType,\n body: string,\n payload?: Record<string, unknown>,\n ): void {\n if (!this.runtime.builder.isEnabled(level)) {\n return;\n }\n\n const record = this.runtime.builder.build({\n level,\n type,\n body,\n namespace: this.namespace,\n scoped: this.options.scopedContext,\n payload,\n });\n\n if (record && type !== \"metric\") {\n this.runtime.breadcrumbs.push({\n t: Date.now(),\n category: type === \"action\" ? \"action\" : type === \"event\" ? \"event\" : \"log\",\n message: body,\n });\n }\n\n // Passes sanitized attributes to console to prevent object retention leaks.\n this.runtime.console.write(level, body, record?.attributes);\n this.runtime.emit(record);\n }\n\n /**\n * Builds, logs to console, and emits an error record with attached breadcrumbs.\n * @param level Severity level (\"ERROR\" or \"FATAL\").\n * @param message Error description.\n * @param error Caught error instance or reason.\n * @param payload Optional contextual attributes.\n */\n private writeError(\n level: \"ERROR\" | \"FATAL\",\n message: string,\n error: unknown,\n payload?: Record<string, unknown>,\n ): void {\n if (!this.runtime.builder.isEnabled(level)) {\n return;\n }\n\n const asError = error === undefined ? undefined : toError(error);\n\n const record = this.runtime.builder.build({\n level,\n type: \"system\",\n body: message,\n namespace: this.namespace,\n scoped: this.options.scopedContext,\n payload: {\n ...payload,\n ...(asError\n ? {\n \"error.type\": asError.name,\n \"error.message\": asError.message,\n \"error.stack_trace\": asError.stack,\n }\n : {}),\n breadcrumbs: this.runtime.breadcrumbs.snapshot(),\n },\n });\n\n this.runtime.console.write(level, message, asError ?? record?.attributes);\n this.runtime.emit(record);\n }\n}\n","// src/utils/unref.ts\n//\n// Utility for safely unreferencing timer handles across Node and browser\n// environments. A pending timer keeps a Node process alive under SSR and in\n// tests.\n\n/** Cross-platform timer handle representing browser numeric IDs or Node Timeout objects. */\nexport type TimerHandle = number | { unref?: () => void };\n\n/**\n * Unreferences a timer handle to prevent it from keeping a Node.js process alive.\n * @param timer Timer handle returned by setTimeout.\n */\nexport function unrefTimer(timer: TimerHandle): void {\n if (typeof timer !== \"number\") {\n timer.unref?.();\n }\n}\n","// src/models/bus.ts\n//\n// Wire protocol types, message definitions, and envelope encoding for cross-realm bus communication.\n\nimport { BUS_PROTOCOL } from \"../constants\";\nimport type { Journey } from \"../core/journey\";\nimport type { LogRecord } from \"./log-record\";\n\n/** Delivery role indicating whether this context sends records directly or forwards upstream. */\nexport type BusRole = \"sender\" | \"forwarder\";\n\n/**\n * Transport channel classification used to route incoming and outgoing bus\n * messages. If `receive` switches on the message alone and cannot tell the\n * channels apart, a same-origin iframe looks like a duplicated tab.\n */\nexport type LinkKind =\n /** Synchronous call into a same-origin parent runtime. */\n | \"direct\"\n /** postMessage to a parent window. */\n | \"parent\"\n /** postMessage to child frames. */\n | \"children\"\n /** BroadcastChannel across same-origin tabs and windows. */\n | \"broadcast\"\n /** OpenFin InterApplicationBus across desktop views and applications. */\n | \"openfin\"\n /** Dedicated worker communication to its owning document. */\n | \"owner\"\n /** Document-side communication to a dedicated worker. */\n | \"worker\";\n\n/** Origin and transport metadata for an incoming bus message. */\nexport interface MessageSource {\n /** Inbound transport channel kind. */\n link: LinkKind;\n /** `event.origin` for `parent` and `children`; otherwise `\"same-origin\"` or `\"openfin\"`. */\n origin: string;\n}\n\n/** Discriminated union of control and telemetry payload messages. */\nexport type BusMessage =\n /** Handshake discovery announcement from a booting forwarder. */\n | { t: \"hello\"; from: string; tabId: string }\n /**\n * Handshake response acknowledging an upstream owner relationship. Addressed\n * through `to`: a welcome published over InterApplicationBus reaches every\n * subscriber, so an unaddressed one lets three waiting views each conclude\n * it has found an owner of its own.\n */\n | { t: \"welcome\"; from: string; to: string; tabId: string }\n /** Telemetry log records forwarded to an upstream sender. */\n | { t: \"records\"; from: string; records: LogRecord[] }\n /** Broadcast update announcing a new or ended journey state. */\n | { t: \"journey\"; from: string; journey: Journey | null }\n /** Query requesting active journey state from connected peers. */\n | { t: \"journey?\"; from: string }\n /** Tab identifier claim broadcast to detect collisions across windows. */\n | { t: \"tab\"; from: string; tabId: string };\n\n/** Transport envelope wrapping bus messages with a protocol version tag. */\nexport interface BusEnvelope {\n /** Protocol version identifier. */\n p: typeof BUS_PROTOCOL;\n /** Encapsulated bus payload. */\n m: BusMessage;\n}\n\n/**\n * Wraps a bus message in a versioned protocol envelope.\n * @param message Message to encapsulate.\n * @returns Envelope ready for transport.\n */\nexport function envelope(message: BusMessage): BusEnvelope {\n return { p: BUS_PROTOCOL, m: message };\n}\n\n/**\n * Validates protocol tags and unpacks raw payloads into bus messages. A\n * document receives `message` events from every embedded thing on the page,\n * including analytics tags, video players and extensions. Without the tag\n * check a video player's message is parsed as a log record.\n * @param data Raw payload received over a transport link.\n * @returns Validated message, or null if payload is invalid or unrecognized.\n */\nexport function unwrap(data: unknown): BusMessage | null {\n if (typeof data !== \"object\" || data === null) {\n return null;\n }\n\n // Validates payload structure at runtime without assuming envelope fields exist.\n const wrapper = data as Record<string, unknown>;\n if (wrapper.p !== BUS_PROTOCOL || typeof wrapper.m !== \"object\" || wrapper.m === null) {\n return null;\n }\n\n const message = wrapper.m as Record<string, unknown>;\n if (typeof message.t !== \"string\") {\n return null;\n }\n\n return message as unknown as BusMessage;\n}\n","// src/bus/links.ts\n//\n// Communication link implementations for direct, frame, broadcast, OpenFin, and worker channels.\n\nimport { RUNTIME_GLOBAL_KEY } from \"../constants\";\nimport type { Diagnostics } from \"../core/diagnostics\";\nimport {\n type BusMessage,\n envelope,\n type LinkKind,\n type MessageSource,\n unwrap,\n} from \"../models/bus\";\n\n/** Bidirectional communication channel for bus message transport. */\nexport interface Link {\n /** Channel transport kind. */\n readonly kind: LinkKind;\n\n /**\n * Sends a message over the channel without throwing.\n * @param message Bus message to transmit.\n */\n post(message: BusMessage): void;\n\n /** Releases listeners, subscriptions, or channels held open by the link. */\n close(): void;\n}\n\n/**\n * Callback invoked when a bus message arrives on a link.\n * @param message Received bus message.\n * @param source Origin and link metadata.\n */\nexport type Receive = (message: BusMessage, source: MessageSource) => void;\n\n/** Interface exposed on global symbol by same-origin parent runtimes. */\nexport interface DirectHost {\n /**\n * Accepts a message directly from a child frame and replies synchronously.\n * @param message Child bus message.\n * @param reply Callback for synchronous response.\n */\n busAccept(message: BusMessage, reply: Receive): void;\n}\n\n/** Message port or dedicated/shared worker interface. */\nexport interface WorkerLike {\n /**\n * Sends a message to the worker or port.\n * @param message Payload to send.\n */\n postMessage(message: unknown): void;\n\n /**\n * Subscribes to incoming message events.\n * @param type Event name (\"message\").\n * @param listener Event handler callback.\n */\n addEventListener(type: \"message\", listener: (event: MessageEvent) => void): void;\n\n /**\n * Unsubscribes from message events.\n * @param type Event name (\"message\").\n * @param listener Event handler to remove.\n */\n removeEventListener(type: \"message\", listener: (event: MessageEvent) => void): void;\n\n /** Starts message delivery on MessagePort instances. */\n start?: () => void;\n}\n\n/** Global symbol used to look up same-origin parent runtime instances. */\nconst RUNTIME_KEY = Symbol.for(RUNTIME_GLOBAL_KEY);\n\n/**\n * Establishes direct synchronous communication with a same-origin parent runtime.\n * @param receive Callback for parent replies.\n * @param diagnostics Diagnostics reporter.\n * @returns Direct link, or null if parent is inaccessible or lacks a runtime.\n */\nexport function createDirectLink(receive: Receive, diagnostics: Diagnostics): Link | null {\n if (typeof window === \"undefined\" || window.parent === window) {\n return null;\n }\n\n let host: DirectHost | undefined;\n try {\n const parentGlobal = window.parent as unknown as Record<symbol, DirectHost | undefined>;\n host = parentGlobal[RUNTIME_KEY];\n } catch {\n // Cross-origin access throws on read.\n return null;\n }\n if (typeof host?.busAccept !== \"function\") {\n return null;\n }\n\n const target = host;\n let open = true;\n\n return {\n kind: \"direct\",\n post(message) {\n if (!open) {\n return;\n }\n\n // Catches errors thrown by parent runtime to protect child logging calls.\n diagnostics.guard(\"bus.send_failed\", \"direct call into the parent runtime\", () => {\n target.busAccept(message, receive);\n });\n },\n close() {\n open = false;\n },\n };\n}\n\n/**\n * Creates a postMessage link to the parent window.\n * @param receive Callback for incoming parent messages.\n * @param diagnostics Diagnostics reporter.\n * @returns Link to parent window, or null if running in top-level window.\n */\nexport function createParentLink(receive: Receive, diagnostics: Diagnostics): Link | null {\n if (typeof window === \"undefined\" || window.parent === window) {\n return null;\n }\n\n const onMessage = (event: MessageEvent): void => {\n const message = unwrap(event.data);\n // The parent is trusted by construction: this context chose to talk to it.\n if (message && event.source === window.parent) {\n receive(message, { link: \"parent\", origin: event.origin });\n }\n };\n addEventListener(\"message\", onMessage);\n\n return {\n kind: \"parent\",\n post(message) {\n diagnostics.guard(\"bus.send_failed\", \"postMessage to parent\", () => {\n // \"*\" is fine outbound: the payload is this context's own records,\n // and the parent already receives them another way. Inbound trust\n // works differently; see createChildrenLink.\n window.parent.postMessage(envelope(message), \"*\");\n });\n },\n close() {\n removeEventListener(\"message\", onMessage);\n },\n };\n}\n\n/**\n * Creates a link listening to child frames with origin allowlist filtering.\n * @param receive Callback for messages from authorized child frames.\n * @param trustedOrigins Additional origins allowed to communicate.\n * @param diagnostics Diagnostics reporter.\n * @returns Children link, or null in non-window environments.\n */\nexport function createChildrenLink(\n receive: Receive,\n trustedOrigins: string[],\n diagnostics: Diagnostics,\n): Link | null {\n if (typeof window === \"undefined\") {\n return null;\n }\n\n const trusted = new Set([window.location.origin, ...trustedOrigins]);\n const sources = new Set<MessageEventSource>();\n\n const onMessage = (event: MessageEvent): void => {\n const message = unwrap(event.data);\n if (!message) {\n return;\n }\n if (!trusted.has(event.origin)) {\n diagnostics.report(\n \"bus.untrusted_origin\",\n `ignored a bus message from ${event.origin}. Add it to bus.trustedOrigins if it is yours.`,\n { origin: event.origin, type: message.t },\n );\n return;\n }\n\n if (event.source) {\n sources.add(event.source);\n }\n receive(message, { link: \"children\", origin: event.origin });\n };\n addEventListener(\"message\", onMessage);\n\n return {\n kind: \"children\",\n post(message) {\n for (const source of sources) {\n const target = source as Window;\n // Evicts closed child windows to prevent memory leaks.\n if (target.closed) {\n sources.delete(source);\n continue;\n }\n diagnostics.guard(\"bus.send_failed\", \"postMessage to child\", () => {\n target.postMessage(envelope(message), \"*\");\n });\n }\n },\n close() {\n removeEventListener(\"message\", onMessage);\n sources.clear();\n },\n };\n}\n\n/**\n * Creates a same-origin BroadcastChannel link for cross-tab control messages.\n * @param channelName BroadcastChannel identifier.\n * @param receive Callback for incoming cross-tab messages.\n * @param diagnostics Diagnostics reporter.\n * @returns Broadcast link, or null if unsupported.\n */\nexport function createBroadcastLink(\n channelName: string,\n receive: Receive,\n diagnostics: Diagnostics,\n): Link | null {\n const BC = (globalThis as { BroadcastChannel?: typeof BroadcastChannel }).BroadcastChannel;\n if (typeof BC === \"undefined\") {\n return null;\n }\n\n const channel = diagnostics.guard(\n \"bus.send_failed\",\n \"opening BroadcastChannel\",\n () => new BC(channelName),\n );\n if (!channel) {\n return null;\n }\n\n channel.onmessage = (event: MessageEvent): void => {\n const message = unwrap(event.data);\n if (message) {\n receive(message, { link: \"broadcast\", origin: \"same-origin\" });\n }\n };\n\n return {\n kind: \"broadcast\",\n post(message) {\n diagnostics.guard(\"bus.send_failed\", \"BroadcastChannel.postMessage\", () => {\n channel.postMessage(envelope(message));\n });\n },\n close() {\n diagnostics.guard(\"bus.send_failed\", \"closing BroadcastChannel\", () => {\n channel.close();\n });\n },\n };\n}\n\n/** Structural interface for OpenFin InterApplicationBus operations. */\ninterface FinIab {\n /**\n * Publishes a message to all topic subscribers.\n * @param topic Topic name.\n * @param message Message payload.\n */\n publish(topic: string, message: unknown): Promise<void>;\n\n /**\n * Subscribes a listener to a topic for matching application identities.\n * @param identity Target application identity.\n * @param topic Topic name.\n * @param listener Message callback.\n */\n subscribe(\n identity: { uuid: string },\n topic: string,\n listener: (message: unknown) => void,\n ): Promise<void>;\n}\n\n/**\n * Creates an OpenFin InterApplicationBus link across desktop views and applications.\n * @param topic InterApplicationBus topic identifier.\n * @param receive Callback for received topic messages.\n * @param diagnostics Diagnostics reporter.\n * @returns OpenFin link, or null if InterApplicationBus is unavailable.\n */\nexport function createOpenFinLink(\n topic: string,\n receive: Receive,\n diagnostics: Diagnostics,\n): Link | null {\n const fin = (globalThis as { fin?: { InterApplicationBus?: FinIab } }).fin;\n const iab = fin?.InterApplicationBus;\n if (!iab) {\n return null;\n }\n\n void diagnostics.guardAsync(\"bus.send_failed\", \"InterApplicationBus.subscribe\", () =>\n iab.subscribe({ uuid: \"*\" }, topic, (raw) => {\n const message = unwrap(raw);\n if (message) {\n receive(message, { link: \"openfin\", origin: \"openfin\" });\n }\n }),\n );\n\n return {\n kind: \"openfin\",\n post(message) {\n void diagnostics.guardAsync(\"bus.send_failed\", \"InterApplicationBus.publish\", () =>\n iab.publish(topic, envelope(message)),\n );\n },\n close() {\n // OpenFin automatically cleans up subscriptions on context teardown.\n },\n };\n}\n\n/**\n * Creates the worker-side link pointing at the document that created this\n * worker. Emits `kind: \"owner\"`.\n * @param receive Callback for incoming messages from the owning document.\n * @param diagnostics Diagnostics reporter.\n * @returns Owner link, or null outside a DedicatedWorkerGlobalScope.\n */\nexport function createOwnerLink(receive: Receive, diagnostics: Diagnostics): Link | null {\n const scope = globalThis as unknown as {\n postMessage?: (message: unknown) => void;\n addEventListener?: (type: string, listener: (event: MessageEvent) => void) => void;\n WorkerGlobalScope?: unknown;\n };\n const send = scope.postMessage;\n if (typeof scope.WorkerGlobalScope === \"undefined\" || !send) {\n return null;\n }\n\n const onMessage = (event: MessageEvent): void => {\n const message = unwrap(event.data);\n if (message) {\n receive(message, { link: \"owner\", origin: \"same-origin\" });\n }\n };\n scope.addEventListener?.(\"message\", onMessage);\n\n return {\n kind: \"owner\",\n post(message) {\n diagnostics.guard(\"bus.send_failed\", \"worker postMessage\", () => {\n send(envelope(message));\n });\n },\n close() {\n // Worker scope listeners terminate with the worker lifecycle.\n },\n };\n}\n\n/**\n * Creates the document-side link pointing at one attached worker or port.\n * Emits `kind: \"worker\"`.\n * @param worker Target worker instance or MessagePort.\n * @param receive Callback for messages from the worker.\n * @param diagnostics Diagnostics reporter.\n * @returns Document-to-worker link.\n */\nexport function createWorkerLink(\n worker: WorkerLike,\n receive: Receive,\n diagnostics: Diagnostics,\n): Link {\n const onMessage = (event: MessageEvent): void => {\n const message = unwrap(event.data);\n if (message) {\n receive(message, { link: \"worker\", origin: \"same-origin\" });\n }\n };\n worker.addEventListener(\"message\", onMessage);\n\n // Activates MessagePort message delivery if supported.\n worker.start?.();\n\n return {\n kind: \"worker\",\n post(message) {\n diagnostics.guard(\"bus.send_failed\", \"postMessage to a worker\", () => {\n worker.postMessage(envelope(message));\n });\n },\n close() {\n worker.removeEventListener(\"message\", onMessage);\n },\n };\n}\n","// src/bus/bus.ts\n//\n// Manages cross-realm bus role resolution, message routing, and boot buffering.\n\nimport type { Diagnostics } from \"../core/diagnostics\";\nimport type { Journey } from \"../core/journey\";\nimport type { BusMessage, BusRole, LinkKind, MessageSource } from \"../models/bus\";\nimport type { ResolvedConfig } from \"../models/config\";\nimport type { LogRecord } from \"../models/log-record\";\nimport type { PlatformMetadata } from \"../utils/platform\";\nimport { unrefTimer } from \"../utils/unref\";\nimport {\n createBroadcastLink,\n createChildrenLink,\n createDirectLink,\n createOpenFinLink,\n createOwnerLink,\n createParentLink,\n createWorkerLink,\n type Link,\n type Receive,\n type WorkerLike,\n} from \"./links\";\n\n/** Callbacks for handling records and journey events from connected realms. */\nexport interface BusHandlers {\n /** Processes records forwarded from child contexts. */\n onRecords: (records: LogRecord[]) => void;\n /** Applies journey updates received from the control bus. */\n onJourney: (journey: Journey | null) => void;\n /** Returns the active journey for inquiring child contexts. */\n onJourneyRequest: () => Journey | null;\n /** Invoked when a tab identifier collision is detected across windows. */\n onTabConflict: () => void;\n}\n\n/** Link types that a sender context may claim ownership over during handshakes. */\nconst OWNED: readonly LinkKind[] = [\"children\", \"direct\", \"worker\"];\n\n/** Structural shape of fin.me identity metadata. */\ninterface OpenFinMe {\n isView?: boolean;\n identity?: { uuid?: string; name?: string };\n}\n\n/** Coordinates cross-realm communication, role resolution, and message dispatch. */\nexport class Bus {\n /** Current bus role. Defaults to \"sender\". */\n private role: BusRole = \"sender\";\n /** Upstream forwarding link, or null when acting as sender. */\n private upstream: Link | null = null;\n /** Open control plane links. */\n private readonly links: Link[] = [];\n /** Shared OpenFin InterApplicationBus link instance. */\n private openFinLink: Link | null = null;\n /** Indicates whether this context is the OpenFin platform provider. */\n private isOpenFinProvider = false;\n /** Indicates whether role resolution has completed. */\n private resolved = false;\n /** Active handshake state awaiting welcome response. */\n private awaitingWelcome: {\n link: LinkKind;\n settle: (ok: boolean) => void;\n } | null = null;\n\n /**\n * @param config Active configuration instance.\n * @param diagnostics Diagnostics reporter.\n * @param platform Platform runtime metadata.\n * @param contextId Unique context identifier for loop prevention.\n * @param tabId Tab identifier announced on broadcast channels.\n * @param handlers Callbacks for routed bus events.\n */\n constructor(\n private readonly config: ResolvedConfig,\n private readonly diagnostics: Diagnostics,\n private readonly platform: PlatformMetadata,\n private readonly contextId: string,\n private readonly tabId: string,\n private readonly handlers: BusHandlers,\n ) {}\n\n /** Returns the resolved bus role. */\n getRole(): BusRole {\n return this.role;\n }\n\n /** Returns whether role resolution has completed. */\n isResolved(): boolean {\n return this.resolved;\n }\n\n /**\n * Resolves bus role and establishes control links.\n * @returns Resolved role.\n */\n async start(): Promise<BusRole> {\n const { bus } = this.config;\n\n if (bus.mode === \"off\") {\n this.role = \"sender\";\n this.resolved = true;\n return this.role;\n }\n\n this.isOpenFinProvider = this.resolveOpenFinProvider();\n\n if (bus.mode === \"sender\" || bus.mode === \"forwarder\") {\n this.role = bus.mode;\n this.openControlLinks();\n if (this.role === \"forwarder\") {\n this.upstream = this.candidateUpstream();\n if (!this.upstream) {\n this.diagnostics.report(\n \"bus.no_owner\",\n 'bus.mode is \"forwarder\" but there is no owner to forward to. Records will be dropped.',\n );\n }\n }\n this.resolved = true;\n this.announce();\n return this.role;\n }\n\n this.openControlLinks();\n\n // Direct synchronous attachment for same-origin parents.\n const direct = createDirectLink(this.receive, this.diagnostics);\n if (direct) {\n this.role = \"forwarder\";\n this.upstream = direct;\n this.resolved = true;\n this.diagnostics.report(\n \"bus.role_resolved\",\n \"attached directly to the same-origin parent runtime\",\n {\n role: \"forwarder\",\n via: \"direct\",\n },\n );\n this.announce();\n return this.role;\n }\n\n const candidate = this.candidateUpstream();\n\n if (!candidate) {\n this.role = \"sender\";\n this.resolved = true;\n this.diagnostics.report(\"bus.role_resolved\", \"no owner to forward to, sending directly\", {\n role: \"sender\",\n });\n this.announce();\n return this.role;\n }\n\n const attempts = this.orphanPolicy() === \"retry\" ? this.config.bus.maxHandshakeAttempts : 1;\n\n let welcomed = false;\n for (let attempt = 0; attempt < attempts && !welcomed; attempt++) {\n welcomed = await this.handshake(candidate);\n }\n\n this.role = welcomed ? \"forwarder\" : \"sender\";\n this.upstream = welcomed ? candidate : null;\n if (!welcomed) {\n // OpenFin link remains open for control messages.\n if (candidate !== this.openFinLink) {\n candidate.close();\n }\n this.diagnostics.report(\n \"bus.handshake_timeout\",\n `no owner answered after ${String(attempts)} attempt(s) of ${String(this.config.bus.handshakeTimeoutMs)}ms, promoting to sender`,\n { via: candidate.kind, crossOrigin: this.isCrossOriginFrame() },\n );\n }\n this.diagnostics.report(\"bus.role_resolved\", `role is ${this.role}`, {\n role: this.role,\n via: welcomed ? candidate.kind : \"none\",\n });\n\n this.resolved = true;\n this.announce();\n return this.role;\n }\n\n /**\n * Forwards records to the upstream owner if configured.\n * @param records Batch of log records to send.\n */\n sendRecords(records: LogRecord[]): void {\n this.upstream?.post({ t: \"records\", from: this.contextId, records });\n }\n\n /**\n * Synchronously processes direct messages from same-origin child contexts.\n * @param message Received bus message.\n * @param reply Direct response callback.\n */\n acceptDirect(message: BusMessage, reply: Receive): void {\n if (message.from === this.contextId) {\n return;\n }\n const source: MessageSource = { link: \"direct\", origin: \"same-origin\" };\n\n if (message.t === \"hello\") {\n if (this.canOwn(\"direct\")) {\n reply(\n {\n t: \"welcome\",\n from: this.contextId,\n to: message.from,\n tabId: this.tabId,\n },\n source,\n );\n }\n return;\n }\n if (message.t === \"journey?\") {\n const current = this.handlers.onJourneyRequest();\n if (current) {\n reply({ t: \"journey\", from: this.contextId, journey: current }, source);\n }\n return;\n }\n this.receive(message, source);\n }\n\n /**\n * Connects a worker instance to the bus control plane.\n * @param worker Worker instance.\n */\n attachWorker(worker: WorkerLike): void {\n this.links.push(createWorkerLink(worker, this.receive, this.diagnostics));\n }\n\n /**\n * Broadcasts journey state changes to all connected links.\n * @param journey Active journey or null if ended.\n */\n broadcastJourney(journey: Journey | null): void {\n this.post({ t: \"journey\", from: this.contextId, journey });\n }\n\n /** Closes all open links and clears internal state. */\n destroy(): void {\n for (const link of this.allLinks()) {\n link.close();\n }\n this.links.length = 0;\n this.upstream = null;\n this.openFinLink = null;\n }\n\n /** Returns all unique active links including upstream. */\n private allLinks(): Link[] {\n if (!this.upstream || this.links.includes(this.upstream)) {\n return this.links;\n }\n return [...this.links, this.upstream];\n }\n\n /** Broadcasts a message across all open links. */\n private post(message: BusMessage): void {\n for (const link of this.allLinks()) {\n link.post(message);\n }\n }\n\n /** Sends a message exclusively over links matching the specified kind. */\n private postOver(link: LinkKind, message: BusMessage): void {\n for (const candidate of this.allLinks()) {\n if (candidate.kind === link) {\n candidate.post(message);\n }\n }\n }\n\n /** Routes incoming messages to registered handlers or upstream targets. */\n private readonly receive = (message: BusMessage, source: MessageSource): void => {\n if (message.from === this.contextId) {\n return;\n }\n\n switch (message.t) {\n case \"hello\":\n if (this.canOwn(source.link)) {\n this.postOver(source.link, {\n t: \"welcome\",\n from: this.contextId,\n to: message.from,\n tabId: this.tabId,\n });\n }\n break;\n\n case \"welcome\":\n if (message.to !== this.contextId) {\n break;\n }\n if (this.awaitingWelcome?.link === source.link) {\n this.awaitingWelcome.settle(true);\n }\n break;\n\n case \"records\":\n if (this.role === \"sender\") {\n this.handlers.onRecords(message.records);\n } else if (this.upstream && source.link !== this.upstream.kind) {\n // Relays records upstream in nested frame chains. Posting back onto\n // the link they arrived on would echo them to their sender.\n this.upstream.post(message);\n }\n break;\n\n case \"journey\":\n this.handlers.onJourney(message.journey);\n break;\n\n case \"journey?\": {\n const current = this.handlers.onJourneyRequest();\n if (current) {\n this.postOver(source.link, {\n t: \"journey\",\n from: this.contextId,\n journey: current,\n });\n }\n break;\n }\n\n case \"tab\":\n // Collisions only apply to distinct contexts sharing the broadcast\n // channel. The id comparison picks one side of the pair: without it\n // both colliding contexts report the conflict and both rename.\n if (\n source.link === \"broadcast\" &&\n message.tabId === this.tabId &&\n this.contextId > message.from\n ) {\n this.handlers.onTabConflict();\n }\n break;\n }\n };\n\n /** Returns whether this context can accept ownership over the given link type. */\n private canOwn(link: LinkKind): boolean {\n if (this.role !== \"sender\") {\n return false;\n }\n if (link === \"openfin\") {\n return this.isOpenFinProvider;\n }\n return OWNED.includes(link);\n }\n\n /** Resolves whether this context represents the OpenFin platform provider. */\n private resolveOpenFinProvider(): boolean {\n const configured = this.config.bus.openFinRole;\n if (configured !== \"auto\") {\n return configured === \"provider\";\n }\n if (this.platform.platform !== \"openfin\" && this.platform.platform !== \"openfin_web\") {\n return false;\n }\n\n const me = (globalThis as { fin?: { me?: OpenFinMe } }).fin?.me;\n if (!me?.identity || me.isView) {\n return false;\n }\n return Boolean(me.identity.name && me.identity.name === me.identity.uuid);\n }\n\n /** Resolves the handshake orphan policy for the current platform context. */\n private orphanPolicy(): \"promote\" | \"retry\" {\n const configured = this.config.bus.orphanPolicy;\n if (configured !== \"auto\") {\n return configured;\n }\n return this.isCrossOriginFrame() ? \"retry\" : \"promote\";\n }\n\n /** Tests whether the parent window is inaccessible due to cross-origin boundaries. */\n private isCrossOriginFrame(): boolean {\n if (typeof window === \"undefined\" || window.parent === window) {\n return false;\n }\n try {\n void (window.parent as unknown as Record<string, unknown>).location;\n return false;\n } catch {\n return true;\n }\n }\n\n /** Identifies the candidate upstream link based on platform hierarchy. */\n private candidateUpstream(): Link | null {\n if (this.platform.isWorker) {\n return createOwnerLink(this.receive, this.diagnostics);\n }\n if (!this.platform.isTopLevelDocument) {\n return createParentLink(this.receive, this.diagnostics);\n }\n if (\n this.platform.platform === \"openfin\" &&\n this.config.bus.openFinHost === \"provider\" &&\n !this.isOpenFinProvider\n ) {\n return this.ensureOpenFinLink();\n }\n return null;\n }\n\n /** Opens control links supported by the current runtime environment. */\n private openControlLinks(): void {\n const push = (link: Link | null): void => {\n if (link) {\n this.links.push(link);\n }\n };\n\n if (this.platform.isTopLevelDocument) {\n push(createChildrenLink(this.receive, this.config.bus.trustedOrigins, this.diagnostics));\n push(createBroadcastLink(this.config.bus.channelName, this.receive, this.diagnostics));\n }\n if (this.platform.platform === \"openfin\" || this.platform.platform === \"openfin_web\") {\n push(this.ensureOpenFinLink());\n }\n }\n\n /** Returns the singleton OpenFin InterApplicationBus link. */\n private ensureOpenFinLink(): Link | null {\n this.openFinLink ??= createOpenFinLink(\n this.config.bus.channelName,\n this.receive,\n this.diagnostics,\n );\n return this.openFinLink;\n }\n\n /**\n * Executes a hello/welcome handshake over candidate link.\n * @param candidate Upstream link candidate.\n * @returns True if welcome response arrived before timeout.\n */\n private handshake(candidate: Link): Promise<boolean> {\n return new Promise((resolve) => {\n let settled = false;\n\n const finish = (result: boolean): void => {\n if (settled) {\n return;\n }\n settled = true;\n this.awaitingWelcome = null;\n clearTimeout(timer);\n resolve(result);\n };\n\n this.awaitingWelcome = { link: candidate.kind, settle: finish };\n // Declared below finish, which reads it: nothing can call finish until\n // the timer exists, because the welcome arrives through the post below.\n const timer = setTimeout(() => {\n finish(false);\n }, this.config.bus.handshakeTimeoutMs);\n unrefTimer(timer);\n candidate.post({ t: \"hello\", from: this.contextId, tabId: this.tabId });\n });\n }\n\n /** Broadcasts tab claim and queries existing journey state. */\n private announce(): void {\n this.postOver(\"broadcast\", {\n t: \"tab\",\n from: this.contextId,\n tabId: this.tabId,\n });\n this.post({ t: \"journey?\", from: this.contextId });\n }\n}\n\n/** Buffers log records during bus role resolution with FIFO overflow eviction. */\nexport class BootBuffer {\n /** Held records in FIFO order. */\n private records: LogRecord[] = [];\n\n /**\n * @param config Active configuration instance.\n * @param diagnostics Diagnostics reporter.\n */\n constructor(\n private readonly config: ResolvedConfig,\n private readonly diagnostics: Diagnostics,\n ) {}\n\n /**\n * Buffers a record, dropping the oldest when capacity is exceeded.\n * @param record Record to buffer.\n */\n push(record: LogRecord): void {\n if (this.records.length >= this.config.bus.maxBootBufferRecords) {\n this.records.shift();\n this.diagnostics.count(\"record.dropped_boot_buffer_full\");\n }\n this.records.push(record);\n }\n\n /**\n * Drains and returns all buffered records in FIFO order.\n * @returns Buffered log records.\n */\n release(): LogRecord[] {\n const released = this.records;\n this.records = [];\n return released;\n }\n}\n","// src/capture/errors.ts\n//\n// Captures uncaught errors, unhandled rejections and failed resource loads.\n\nimport {\n ERROR_STORM_MAX_PER_WINDOW,\n ERROR_STORM_WINDOW_MS,\n MAX_TRACKED_ERROR_SIGNATURES,\n} from \"../constants\";\nimport type { Capture, CaptureContext } from \"./types\";\n\n/** Tracking metadata for a deduplicated error signature. */\ninterface SeenError {\n /** Timestamp when the signature was last reported in epoch milliseconds. */\n at: number;\n /** Occurrences recorded since the last report. */\n count: number;\n}\n\n/** Captures uncaught exceptions, unhandled promise rejections, and failed resource loads. */\nexport class ErrorCapture implements Capture {\n /** Capture module identifier. */\n readonly name = \"errors\";\n\n /** Prevents duplicate listener registration. */\n private installed = false;\n\n /** Recently reported error signatures in LRU order. */\n private readonly seen = new Map<string, SeenError>();\n\n /** Start timestamp of the active throttling window in epoch milliseconds. */\n private windowStart = 0;\n\n /** Errors reported during the active throttling window. */\n private windowCount = 0;\n\n /**\n * @param ctx Capture context containing configuration, diagnostics, logger, and breadcrumbs.\n */\n constructor(private readonly ctx: CaptureContext) {}\n\n /** Subscribes to global error and unhandledrejection events. */\n install(): void {\n if (this.installed || typeof addEventListener === \"undefined\") {\n return;\n }\n this.installed = true;\n\n // Uses capture phase to observe non-bubbling resource load errors.\n addEventListener(\"error\", this.onError, true);\n addEventListener(\"unhandledrejection\", this.onRejection);\n }\n\n /** Removes event listeners and clears tracked error signatures. */\n uninstall(): void {\n if (!this.installed) {\n return;\n }\n this.installed = false;\n\n removeEventListener(\"error\", this.onError, true);\n removeEventListener(\"unhandledrejection\", this.onRejection);\n this.seen.clear();\n }\n\n /** Routes resource load failures and uncaught script errors. */\n private readonly onError = (event: ErrorEvent | Event): void => {\n const target = event.target as (HTMLElement & { src?: string; href?: string }) | null;\n const resourceUrl = target?.src ?? target?.href ?? \"\";\n\n // Filters element-level resource load failures from script errors.\n if (\n target !== null &&\n target !== (globalThis as unknown as EventTarget) &&\n resourceUrl !== \"\"\n ) {\n if (!this.ctx.config.capture.resourceErrors) {\n return;\n }\n\n this.ctx.breadcrumbs.push({\n t: Date.now(),\n category: \"http\",\n message: `resource failed: ${resourceUrl}`,\n });\n this.ctx.logger.warn(\"resource failed to load\", {\n \"error.type\": \"resource\",\n \"resource.url\": resourceUrl,\n \"resource.tag\": target.tagName.toLowerCase(),\n });\n return;\n }\n\n if (!this.ctx.config.capture.errors) {\n return;\n }\n\n const errorEvent = event as ErrorEvent;\n const fallback = errorEvent.message === \"\" ? \"unknown error\" : errorEvent.message;\n const thrown: unknown = errorEvent.error;\n const error = thrown ?? new Error(fallback);\n\n this.report(\"window.onerror\", error, {\n \"error.source\": errorEvent.filename,\n \"error.line\": errorEvent.lineno,\n \"error.column\": errorEvent.colno,\n });\n };\n\n /** Captures unhandled promise rejections. */\n private readonly onRejection = (event: PromiseRejectionEvent): void => {\n if (!this.ctx.config.capture.rejections) {\n return;\n }\n\n this.report(\"unhandledrejection\", event.reason, {\n \"error.type\": \"unhandledrejection\",\n });\n };\n\n /**\n * Rate limits, deduplicates, and logs captured errors.\n * @param source Originating capture event name.\n * @param error Caught error instance or thrown value.\n * @param extra Contextual error attributes.\n */\n private report(source: string, error: unknown, extra: Record<string, unknown>): void {\n const now = Date.now();\n\n if (now - this.windowStart > ERROR_STORM_WINDOW_MS) {\n this.windowStart = now;\n this.windowCount = 0;\n }\n\n this.windowCount++;\n if (this.windowCount > ERROR_STORM_MAX_PER_WINDOW) {\n // A render loop throwing inside requestAnimationFrame produces thousands\n // per second. Shipping all of them is a denial of service on our ingest.\n this.ctx.diagnostics.report(\n \"capture.rate_limited\",\n `more than ${String(ERROR_STORM_MAX_PER_WINDOW)} errors in ${String(ERROR_STORM_WINDOW_MS)}ms, suppressing the rest of this window`,\n );\n return;\n }\n\n const asError = error instanceof Error ? error : new Error(String(error));\n const frame = (asError.stack ?? \"\").split(\"\\n\")[1] ?? \"\";\n const key = `${asError.name}|${asError.message}|${frame}`;\n const previous = this.seen.get(key);\n\n if (previous && now - previous.at < this.ctx.config.capture.errorDedupeMs) {\n previous.count++;\n previous.at = now;\n return;\n }\n\n // Occurrences swallowed since this signature was last reported. Counting\n // them and never emitting the number makes a storm look like a trickle.\n const suppressed = previous ? previous.count - 1 : 0;\n\n // Deleted before it is re-set so the map stays in least-recently-reported\n // order, which is what makes the eviction below evict the right entry.\n this.seen.delete(key);\n this.seen.set(key, { at: now, count: 1 });\n\n // A page throwing with a fresh message every render, which is what a bad\n // template literal inside a loop looks like, would grow this map for as\n // long as the document stays open.\n if (this.seen.size > MAX_TRACKED_ERROR_SIGNATURES) {\n const [oldest] = this.seen.keys();\n this.seen.delete(oldest);\n }\n\n this.ctx.logger.error(asError.message === \"\" ? source : asError.message, asError, {\n ...extra,\n \"error.captured_by\": source,\n \"error.suppressed_count\": suppressed,\n });\n }\n}\n","// src/capture/interactions.ts\n//\n// Captures clicks and in-page navigations as breadcrumbs and trace boundaries.\n\nimport { ARIA_LABEL_MAX_CHARS, CLICK_TEXT_MAX_CHARS, SELECTOR_MAX_CLASSES } from \"../constants\";\nimport type { Capture, CaptureContext } from \"./types\";\n\n/**\n * Generates a concise CSS selector for an element, prioritizing test IDs, IDs, aria-labels, and classes.\n * @param element Target DOM element.\n * @returns Generated CSS selector string.\n */\nfunction describeElement(element: Element | null): string {\n if (element === null) {\n return \"unknown\";\n }\n\n const tag = element.tagName.toLowerCase();\n\n const testId = element.getAttribute(\"data-testid\") ?? element.getAttribute(\"data-test-id\");\n if (testId !== null) {\n return `[data-testid=\"${testId}\"]`;\n }\n if (element.id !== \"\") {\n return `#${element.id}`;\n }\n\n const label = element.getAttribute(\"aria-label\");\n if (label !== null) {\n return `${tag}[aria-label=\"${label.slice(0, ARIA_LABEL_MAX_CHARS)}\"]`;\n }\n\n // Read through getAttribute: an SVG element's `className` is an\n // SVGAnimatedString at runtime, and slicing it would throw.\n const classAttribute = element.getAttribute(\"class\")?.trim() ?? \"\";\n if (classAttribute === \"\") {\n return tag;\n }\n\n const classes = classAttribute.split(/\\s+/).slice(0, SELECTOR_MAX_CLASSES).join(\".\");\n return `${tag}.${classes}`;\n}\n\n/**\n * The two History members this module replaces, typed as properties rather than\n * methods so the originals can be held unbound. Holding a bound copy instead\n * makes uninstall restore a different function than it replaced, and repeated\n * install cycles wrap a bind over the previous bind.\n */\ninterface HistoryMethods {\n pushState: (this: History, ...args: never[]) => void;\n replaceState: (this: History, ...args: never[]) => void;\n}\n\n/**\n * The History object, typed for holding its methods unbound.\n * @returns The global history.\n */\nfunction historyMethods(): HistoryMethods {\n return history;\n}\n\n/** Captures user click interactions and single-page navigation transitions. */\nexport class InteractionCapture implements Capture {\n /** Capture module identifier. */\n readonly name = \"interactions\";\n\n /** Prevents duplicate listener registration. */\n private installed = false;\n\n /** Unpatched History.pushState implementation. */\n private originalPushState: HistoryMethods[\"pushState\"] | null = null;\n\n /** Unpatched History.replaceState implementation. */\n private originalReplaceState: HistoryMethods[\"replaceState\"] | null = null;\n\n /** Tracked URL prior to the latest navigation event. */\n private lastUrl = \"\";\n\n /**\n * @param ctx Capture context containing configuration, diagnostics, logger, breadcrumbs, and tracing.\n */\n constructor(private readonly ctx: CaptureContext) {}\n\n /** Registers click listeners and patches history navigation APIs. */\n install(): void {\n if (this.installed || typeof document === \"undefined\") {\n return;\n }\n this.installed = true;\n this.lastUrl = location.href;\n\n if (this.ctx.config.capture.interactions) {\n // Uses capture phase to observe clicks before event propagation is stopped.\n addEventListener(\"click\", this.onClick, true);\n }\n if (this.ctx.config.capture.navigation) {\n this.installHistory();\n addEventListener(\"popstate\", this.onNavigate);\n addEventListener(\"hashchange\", this.onNavigate);\n }\n }\n\n /** Removes interaction listeners and restores native history methods. */\n uninstall(): void {\n if (!this.installed) {\n return;\n }\n this.installed = false;\n\n removeEventListener(\"click\", this.onClick, true);\n removeEventListener(\"popstate\", this.onNavigate);\n removeEventListener(\"hashchange\", this.onNavigate);\n\n if (this.originalPushState) {\n historyMethods().pushState = this.originalPushState;\n }\n if (this.originalReplaceState) {\n historyMethods().replaceState = this.originalReplaceState;\n }\n this.originalPushState = null;\n this.originalReplaceState = null;\n }\n\n /** Rotates trace context and records a click breadcrumb. */\n private readonly onClick = (event: Event): void => {\n const target = event.target;\n const selector = describeElement(target instanceof Element ? target : null);\n const text =\n target instanceof HTMLElement ? target.innerText.trim().slice(0, CLICK_TEXT_MAX_CHARS) : \"\";\n\n // A click starts a new logical operation, so everything it causes shares one\n // trace id. Without the rotation a click and its five API calls cannot be\n // pulled back as one query.\n this.ctx.tracing.rotate(\"interaction\");\n this.ctx.breadcrumbs.push({\n t: Date.now(),\n category: \"click\",\n message: selector,\n data: text === \"\" ? undefined : { text },\n });\n };\n\n /** Rotates trace context and records a navigation breadcrumb and event on URL changes. */\n private readonly onNavigate = (): void => {\n const from = this.lastUrl;\n const to = location.href;\n if (from === to) {\n return;\n }\n this.lastUrl = to;\n\n this.ctx.tracing.rotate(\"navigation\");\n this.ctx.breadcrumbs.push({\n t: Date.now(),\n category: \"navigation\",\n message: `${from} -> ${to}`,\n });\n\n // Only the previous URL is carried: the record builder stamps the current\n // one as `page.url`. Sending the new URL as `url.full` would make a\n // navigation look like an HTTP request to that address.\n this.ctx.logger.logEvent(\"NAVIGATION\", { \"page.url.previous\": from });\n };\n\n /** Patches History.pushState and replaceState to observe programmatic navigations. */\n private installHistory(): void {\n if (typeof history === \"undefined\" || this.originalPushState) {\n return;\n }\n\n // Held unbound and called through apply. Reading History.prototype instead\n // skips whatever a router already installed on the instance, and leaves\n // uninstall writing a permanent own property where there was none.\n const target = historyMethods();\n const originalPushState = target.pushState;\n const originalReplaceState = target.replaceState;\n this.originalPushState = originalPushState;\n this.originalReplaceState = originalReplaceState;\n const onNavigate = this.onNavigate;\n\n target.pushState = function (this: History, ...args: never[]): void {\n originalPushState.apply(this, args);\n // Queued: location.href is only updated once the call returns, so reading\n // it synchronously reports the previous URL as the new one.\n queueMicrotask(onNavigate);\n };\n\n target.replaceState = function (this: History, ...args: never[]): void {\n originalReplaceState.apply(this, args);\n queueMicrotask(onNavigate);\n };\n }\n}\n","// src/capture/types.ts\n//\n// Shared interfaces, logger abstractions, and utility helpers for auto-capture modules.\n\nimport type { BreadcrumbBuffer } from \"../core/breadcrumbs\";\nimport type { Diagnostics } from \"../core/diagnostics\";\nimport type { ResolvedConfig } from \"../models/config\";\nimport type { MetricType } from \"../models/log-record\";\nimport type { TraceEngine } from \"../utils/tracing\";\n\n/**\n * Logging interface consumed by auto-capture modules. Naming the runtime class\n * here instead would cycle: the runtime installs the capture modules.\n */\nexport interface CaptureLogger {\n /**\n * Logs an error event with an associated error instance or reason.\n * @param message Error description.\n * @param error Caught error instance or reason.\n * @param payload Optional attributes.\n */\n error(message: string, error?: unknown, payload?: Record<string, unknown>): void;\n\n /**\n * Logs a warning event.\n * @param message Warning description.\n * @param payload Optional attributes.\n */\n warn(message: string, payload?: Record<string, unknown>): void;\n\n /**\n * Logs a discrete lifecycle or user event.\n * @param name Event identifier.\n * @param payload Optional attributes.\n */\n logEvent(name: string, payload?: Record<string, unknown>): void;\n\n /**\n * Logs a numerical metric measurement.\n * @param name Metric name.\n * @param value Numerical measurement.\n * @param unit Unit of measurement.\n * @param type Metric type classification.\n * @param attrs Optional metric attributes.\n */\n logMetric(\n name: string,\n value: number,\n unit?: string,\n type?: MetricType,\n attrs?: Record<string, unknown>,\n ): void;\n\n /**\n * Logs a diagnostic debug message.\n * @param message Debug message.\n * @param payload Optional attributes.\n */\n debug(message: string, payload?: Record<string, unknown>): void;\n}\n\n/** Shared runtime dependencies provided to auto-capture instances. */\nexport interface CaptureContext {\n /** Active runtime configuration. */\n config: ResolvedConfig;\n /** Diagnostics reporter for capture faults. */\n diagnostics: Diagnostics;\n /** Logger instance for recorded telemetry. */\n logger: CaptureLogger;\n /** Buffer for recording contextual breadcrumbs. */\n breadcrumbs: BreadcrumbBuffer;\n /** Active trace context provider. */\n tracing: TraceEngine;\n}\n\n/** Lifecycle interface for browser instrumentation modules. */\nexport interface Capture {\n /** Module identifier used in diagnostics. */\n readonly name: string;\n /**\n * Attaches instrumentation listeners and patches target APIs. Patching an\n * already patched function chains the wrapper and doubles every record, so a\n * second call must do nothing.\n */\n install(): void;\n /** Restores native APIs and removes registered listeners. */\n uninstall(): void;\n}\n\n/**\n * Evaluates whether a URL matches any string substring or regular expression pattern.\n * @param url Target URL to test.\n * @param patterns Substrings and regular expressions to test against.\n * @returns True if any pattern matches the URL.\n */\nexport function matchesAny(url: string, patterns: (string | RegExp)[]): boolean {\n return patterns.some((pattern) =>\n typeof pattern === \"string\" ? url.includes(pattern) : pattern.test(url),\n );\n}\n","// src/capture/network.ts\n//\n// Instruments fetch and XMLHttpRequest to record network request outcomes and timing.\n\nimport { type Capture, type CaptureContext, matchesAny } from \"./types\";\n\n/** Signature of the global fetch function. */\ntype FetchFn = typeof fetch;\n\n/** XMLHttpRequest extended with internal telemetry tracking metadata. */\ntype Tracked = XMLHttpRequest & {\n __uiobs?: { method: string; url: string; startedAt: number };\n};\n\n/** Unbound prototype methods intercepted on XMLHttpRequest. */\ninterface XhrMethods {\n open: (this: XMLHttpRequest, ...args: never[]) => void;\n send: (this: XMLHttpRequest, ...args: never[]) => void;\n}\n\n/** Returns the XMLHttpRequest prototype. */\nfunction xhrMethods(): XhrMethods {\n return XMLHttpRequest.prototype;\n}\n\n/** Instruments global fetch and XMLHttpRequest to capture request durations and outcomes. */\nexport class NetworkCapture implements Capture {\n /** Capture module identifier. */\n readonly name = \"network\";\n\n /** Original uninstrumented fetch implementation. */\n private originalFetch: FetchFn | null = null;\n\n /** Original uninstrumented XMLHttpRequest.open implementation. */\n private originalOpen: XhrMethods[\"open\"] | null = null;\n\n /** Original uninstrumented XMLHttpRequest.send implementation. */\n private originalSend: XhrMethods[\"send\"] | null = null;\n\n /**\n * @param ctx Capture context containing configuration, diagnostics, logger, breadcrumbs, and tracing.\n */\n constructor(private readonly ctx: CaptureContext) {}\n\n /** Instruments configured network transport APIs. */\n install(): void {\n if (this.ctx.config.capture.fetch) {\n this.installFetch();\n }\n if (this.ctx.config.capture.xhr) {\n this.installXhr();\n }\n }\n\n /** Restores native network transport implementations and clears references. */\n uninstall(): void {\n if (this.originalFetch) {\n globalThis.fetch = this.originalFetch;\n this.originalFetch = null;\n }\n if (this.originalOpen) {\n xhrMethods().open = this.originalOpen;\n this.originalOpen = null;\n }\n if (this.originalSend) {\n xhrMethods().send = this.originalSend;\n this.originalSend = null;\n }\n }\n\n /**\n * Evaluates whether a URL matches ignore patterns.\n * @param url Request target URL.\n * @returns True if URL should be excluded from telemetry.\n */\n private ignored(url: string): boolean {\n // The endpoint is always in ignoreUrls, added by resolveConfig. Without it\n // one failed POST logs, which POSTs, which logs, forever.\n return matchesAny(url, this.ctx.config.capture.ignoreUrls);\n }\n\n /** Instruments globalThis.fetch with tracing injection and outcome logging. */\n private installFetch(): void {\n if (typeof globalThis.fetch !== \"function\" || this.originalFetch) {\n return;\n }\n\n const original = globalThis.fetch.bind(globalThis);\n this.originalFetch = globalThis.fetch;\n\n const ctx = this.ctx;\n const ignored = (url: string): boolean => this.ignored(url);\n const record = (\n method: string,\n url: string,\n status: number,\n durationMs: number,\n error: unknown,\n ): void => {\n this.record(method, url, status, durationMs, error);\n };\n\n globalThis.fetch = async function instrumentedFetch(input, init) {\n const url = typeof input === \"string\" ? input : input instanceof URL ? input.href : input.url;\n const requested = init?.method ?? (input instanceof Request ? input.method : \"GET\");\n const method = requested.toUpperCase();\n\n if (ignored(url)) {\n return original(input, init);\n }\n\n let fetchInput = input;\n let fetchInit = init;\n\n // Allowlist only. An unexpected traceparent on a third-party request\n // forces a CORS preflight they will not answer, and their API stops\n // working inside the consumer's application.\n if (matchesAny(url, ctx.config.capture.propagateTraceHeaderTo)) {\n try {\n const injected = Object.entries(ctx.tracing.headers());\n\n if (input instanceof Request) {\n // Never spread a non-empty init alongside a Request input: that\n // re-runs the Request constructor over `input` and consumes its\n // body, which throws TypeError on an already-read body.\n const headers = new Headers(input.headers);\n for (const [key, value] of injected) {\n headers.set(key, value);\n }\n fetchInput = new Request(input, { headers });\n } else {\n const headers = new Headers(init?.headers);\n for (const [key, value] of injected) {\n headers.set(key, value);\n }\n fetchInit = { ...init, headers };\n }\n } catch (error) {\n // Send exactly what the caller passed. Losing our header is always\n // better than breaking their request.\n fetchInput = input;\n fetchInit = init;\n ctx.diagnostics.report(\n \"capture.header_failed\",\n \"could not attach traceparent, sending the request unchanged\",\n { url },\n error,\n );\n }\n }\n\n const startedAt = performance.now();\n try {\n const response = await original(fetchInput, fetchInit);\n record(method, url, response.status, performance.now() - startedAt, undefined);\n return response;\n } catch (error) {\n record(method, url, 0, performance.now() - startedAt, error);\n throw error;\n }\n };\n }\n\n /** Instruments XMLHttpRequest open and send prototype methods. */\n private installXhr(): void {\n if (typeof XMLHttpRequest === \"undefined\" || this.originalOpen) {\n return;\n }\n\n const ignored = (url: string): boolean => this.ignored(url);\n const record = (method: string, url: string, status: number, durationMs: number): void => {\n this.record(method, url, status, durationMs, undefined);\n };\n\n const proto = xhrMethods();\n const originalOpen = proto.open;\n const originalSend = proto.send;\n this.originalOpen = originalOpen;\n this.originalSend = originalSend;\n\n proto.open = function (this: Tracked, method: string, url: string | URL, ...rest: never[]) {\n this.__uiobs = {\n method: method.toUpperCase(),\n url: String(url),\n startedAt: 0,\n };\n originalOpen.apply(this, [method, url, ...rest] as never[]);\n };\n\n proto.send = function (this: Tracked, ...args: never[]) {\n const meta = this.__uiobs;\n if (meta && !ignored(meta.url)) {\n meta.startedAt = performance.now();\n this.addEventListener(\"loadend\", () => {\n record(meta.method, meta.url, this.status, performance.now() - meta.startedAt);\n });\n }\n originalSend.apply(this, args);\n };\n }\n\n /**\n * Records request outcome attributes and breadcrumb entry.\n * @param method Uppercase HTTP method.\n * @param url Request target URL.\n * @param status HTTP response status code, or 0 on failure.\n * @param durationMs Request duration in milliseconds.\n * @param error Caught error instance on failed requests.\n */\n private record(\n method: string,\n url: string,\n status: number,\n durationMs: number,\n error: unknown,\n ): void {\n // A throw here runs inside the caller's own fetch. Breaking their request\n // to record that their request broke is the one unacceptable outcome.\n this.ctx.diagnostics.guard(\"capture.record_failed\", `recording ${method} ${url}`, () => {\n const rounded = Math.round(durationMs);\n\n this.ctx.breadcrumbs.push({\n t: Date.now(),\n category: \"http\",\n message: `${method} ${url} ${status === 0 ? \"failed\" : String(status)}`,\n data: { durationMs: rounded },\n });\n\n const attributes = {\n \"http.request.method\": method,\n \"url.full\": url,\n \"http.response.status_code\": status,\n \"http.duration_ms\": rounded,\n };\n\n if (status === 0) {\n this.ctx.logger.error(`${method} ${url} failed`, error, attributes);\n return;\n }\n if (status >= 400) {\n this.ctx.logger.warn(`${method} ${url} returned ${String(status)}`, attributes);\n return;\n }\n\n // DEBUG, so a successful request is dropped by the default minLevel of\n // INFO and only failures cost bandwidth.\n this.ctx.logger.debug(`${method} ${url}`, attributes);\n });\n }\n}\n","// src/capture/web-vitals.ts\n//\n// Captures browser navigation timing and Core Web Vitals metrics via optional peer.\n\nimport type { WebVitalsMetric, WebVitalsModule, WebVitalsReporter } from \"../models/config\";\nimport type { Capture, CaptureContext } from \"./types\";\n\n/**\n * Dynamically loads the optional web-vitals peer dependency.\n * Dynamic specifier prevents bundlers from failing statically when peer is uninstalled.\n * @returns Promise resolving to the web-vitals module.\n */\nfunction defaultLoader(): Promise<WebVitalsModule> {\n const specifier = \"web-vitals\";\n return import(/* @vite-ignore */ specifier) as Promise<WebVitalsModule>;\n}\n\n/** Captures browser navigation timing benchmarks and Core Web Vitals. */\nexport class WebVitalsCapture implements Capture {\n /** Capture module identifier. */\n readonly name = \"web-vitals\";\n\n /** Prevents duplicate listener registration. */\n private installed = false;\n\n /**\n * @param ctx Capture context containing configuration, diagnostics, and logger.\n */\n constructor(private readonly ctx: CaptureContext) {}\n\n /** Reports navigation benchmarks and initiates web-vitals loading. */\n install(): void {\n if (this.installed) {\n return;\n }\n this.installed = true;\n\n this.reportNavigationTiming();\n void this.loadWebVitals();\n }\n\n /** Marks module uninstalled. */\n uninstall(): void {\n this.installed = false;\n }\n\n /** Loads the web-vitals module and registers metric reporters. */\n private async loadWebVitals(): Promise<void> {\n const loader = this.ctx.config.capture.webVitalsLoader ?? defaultLoader;\n const module = await this.ctx.diagnostics.guardAsync(\n \"capture.install_failed\",\n \"loading web-vitals\",\n loader,\n );\n\n if (!module) {\n this.ctx.diagnostics.report(\n \"capture.install_failed\",\n \"web-vitals is not available, so LCP, CLS and INP are unavailable. Navigation timing still works.\",\n );\n return;\n }\n\n const send =\n (name: string, unit: string): WebVitalsReporter =>\n (metric: WebVitalsMetric): void => {\n this.ctx.logger.logMetric(\n `web_vitals.${name}`,\n // Three decimals: CLS is a small fraction, and rounding it to an\n // integer reports every layout shift as zero.\n Math.round(metric.value * 1000) / 1000,\n unit,\n \"gauge\",\n { \"metric.rating\": metric.rating, \"metric.id\": metric.id },\n );\n };\n\n module.onLCP(send(\"lcp\", \"ms\"));\n module.onCLS(send(\"cls\", \"1\"));\n module.onINP(send(\"inp\", \"ms\"));\n module.onFCP(send(\"fcp\", \"ms\"));\n module.onTTFB(send(\"ttfb\", \"ms\"));\n }\n\n /** Extracts and logs PerformanceNavigationTiming benchmarks. */\n private reportNavigationTiming(): void {\n this.ctx.diagnostics.guard(\"capture.install_failed\", \"reading navigation timing\", () => {\n const nav = performance.getEntriesByType(\"navigation\")[0] as\n PerformanceNavigationTiming | undefined;\n if (!nav) {\n return;\n }\n\n const metrics: Record<string, number> = {\n \"navigation.dns_ms\": nav.domainLookupEnd - nav.domainLookupStart,\n \"navigation.tcp_ms\": nav.connectEnd - nav.connectStart,\n \"navigation.ttfb_ms\": nav.responseStart - nav.requestStart,\n \"navigation.response_ms\": nav.responseEnd - nav.responseStart,\n \"navigation.dom_interactive_ms\": nav.domInteractive,\n \"navigation.dom_complete_ms\": nav.domComplete,\n \"navigation.load_ms\": nav.loadEventEnd,\n };\n\n for (const [name, value] of Object.entries(metrics)) {\n // Filters unrecorded or negative timings to avoid false zero readings.\n if (Number.isFinite(value) && value >= 0) {\n this.ctx.logger.logMetric(name, Math.round(value), \"ms\", \"gauge\", {\n \"navigation.type\": nav.type,\n });\n }\n }\n });\n }\n}\n","// src/models/log-record.ts\n//\n// Shape of one log record, plus helpers for building and validating it.\n//\n// Severity tables live in `src/constants.ts`.\n\n/** OpenTelemetry severity levels, in ascending order. */\nexport type LogLevel = \"TRACE\" | \"DEBUG\" | \"INFO\" | \"WARN\" | \"ERROR\" | \"FATAL\";\n\n/**\n * Kind of thing a record describes: `action` (something a person did),\n * `event` (something the application did), `metric` (a measurement), or\n * `system` (this library's own diagnostic output).\n */\nexport type LogType = \"action\" | \"event\" | \"metric\" | \"system\";\n\n/** Metric value type: level, running total, or distribution. */\nexport type MetricType = \"gauge\" | \"counter\" | \"histogram\";\n\n/** Internal record shape, converted to wire format by a serializer. */\nexport interface LogRecord {\n /**\n * Event time, nanoseconds since epoch, as a decimal string.\n * @see {@link nowUnixNano}\n */\n timeUnixNano: string;\n /** Time this library received the event, if different from `timeUnixNano` (e.g. on a forwarded record). */\n observedTimeUnixNano?: string;\n /** Distributed trace id. */\n traceId: string;\n /** Span id within the trace. */\n spanId: string;\n /** OpenTelemetry trace flags. Only the sampled bit is used. */\n traceFlags: number;\n /** OpenTelemetry severity number for `severityText`. */\n severityNumber: number;\n /** Log level. */\n severityText: LogLevel;\n /** Log message. */\n body: string;\n /** Structured attributes, sanitized and size-capped. */\n attributes: Record<string, unknown>;\n /** Resource attributes, shared by every record from one context. */\n resource: Record<string, unknown>;\n}\n\n/**\n * Returns the current time as a Unix nanosecond timestamp.\n * Concatenates rather than multiplies: `Date.now() * 1e6` overflows\n * `Number.MAX_SAFE_INTEGER` and silently corrupts digits. Trailing zeros are\n * unknown precision, not real.\n * @returns Epoch timestamp in nanoseconds, as a decimal string.\n */\nexport function nowUnixNano(): string {\n return `${String(Date.now())}000000`;\n}\n\n/**\n * Checks whether a value has the shape `LogRecord` requires.\n * Used to validate records arriving from another realm, since a malformed\n * one throws during serialization. `severityText` is checked as a string,\n * not a known level, so an unrecognised level from a newer version still\n * passes.\n * @param value The value to check.\n * @returns Whether `value` has the shape `LogRecord` requires.\n */\nexport function isLogRecord(value: unknown): value is LogRecord {\n if (typeof value !== \"object\" || value === null) {\n return false;\n }\n // Widened to `unknown` rather than asserted as `Partial<LogRecord>`, which\n // would tell the compiler these fields are never null and make the checks\n // below look unnecessary.\n const record = value as Record<string, unknown>;\n return (\n typeof record.body === \"string\" &&\n typeof record.severityText === \"string\" &&\n typeof record.timeUnixNano === \"string\" &&\n typeof record.attributes === \"object\" &&\n record.attributes !== null &&\n typeof record.resource === \"object\" &&\n record.resource !== null\n );\n}\n","// src/utils/lock.ts\n//\n// Coordinates origin-wide batch draining operations using the Web Locks API.\n// Without it every window on the origin drains and sends the same batches\n\nimport type { Diagnostics } from \"../core/diagnostics\";\n\n/** Lock grant object or null if lock acquisition was unavailable. */\ntype LockGrant = { name: string } | null;\n\n/** Structural interface for navigator.locks operations. */\ninterface LockManagerLike {\n /**\n * Requests a lock and executes a callback under the acquired lock grant.\n * @param name Lock name.\n * @param options Lock request options.\n * @param callback Callback executed with lock grant.\n */\n request<T>(\n name: string,\n options: { ifAvailable?: boolean },\n callback: (lock: LockGrant) => Promise<T>,\n ): Promise<T>;\n}\n\n/**\n * Executes an asynchronous function under a Web Locks API origin-wide lock.\n * Falls back to direct execution in environments without Web Locks support.\n * @param name Origin-scoped lock identifier.\n * @param diagnostics Diagnostics reporter.\n * @param fn Asynchronous task to execute while holding the lock.\n * @param options Lock acquisition options.\n * @param options.skipIfBusy Skips execution if lock is currently held by another context.\n * @returns Promise resolving to the task result, or undefined if the lock was held\n * and nothing ran. A caller that conflates the two stops rescheduling.\n */\nexport function withDrainLock<T>(\n name: string,\n diagnostics: Diagnostics,\n fn: () => Promise<T>,\n { skipIfBusy = true }: { skipIfBusy?: boolean } = {},\n): Promise<T | undefined> {\n const locks = (globalThis as { navigator?: { locks?: LockManagerLike } }).navigator?.locks;\n\n // Falls back to unguarded execution if Web Locks API is unavailable.\n if (!locks?.request) {\n return fn();\n }\n\n return diagnostics.guardAsync(\"storage.degraded\", `acquiring lock ${name}`, () =>\n locks.request(name, { ifAvailable: skipIfBusy }, (lock) =>\n lock ? fn() : Promise.resolve(undefined),\n ),\n );\n}\n","// src/storage/keys.ts\n//\n// Enumerates and filters sorted localStorage keys matching a prefix. A sandboxed\n// frame and private mode throw on first access rather than returning null.\n\nimport type { Diagnostics } from \"../core/diagnostics\";\n\n/**\n * Returns all sorted localStorage keys matching the specified prefix.\n * @param prefix Storage key prefix to filter by.\n * @param diagnostics Diagnostics reporter.\n * @returns Sorted array of matching storage keys.\n */\nexport function keysWithPrefix(prefix: string, diagnostics: Diagnostics): string[] {\n const out: string[] = [];\n\n diagnostics.guard(\"storage.unavailable\", \"enumerating localStorage\", () => {\n for (let i = 0; i < localStorage.length; i++) {\n // String conversion handles valid indexed key reads without unneeded null branches.\n const key = String(localStorage.key(i));\n if (key.startsWith(prefix)) {\n out.push(key);\n }\n }\n });\n\n return out.sort();\n}\n","// src/storage/emergency-queue.ts\n//\n// Synchronous localStorage queue parking oversized batches during unload for startup recovery.\n// Synchronous and never throws. Runs while the document is being destroyed, where\n// no promise settles.\n\nimport {\n BATCH_KEY_TIME_WIDTH,\n EMERGENCY_LOCK_NAME,\n EMERGENCY_MAX_ENTRIES,\n EMERGENCY_STORAGE_KEY_PREFIX,\n} from \"../constants\";\nimport type { Diagnostics } from \"../core/diagnostics\";\nimport type { LogBatch } from \"../models/batch\";\nimport type { StorageAdapter } from \"../models/storage\";\nimport { withDrainLock } from \"../utils/lock\";\nimport { keysWithPrefix } from \"./keys\";\n\n/**\n * Formats a storage key with zero-padded creation time for FIFO sorting.\n * @param batch Target log batch.\n * @returns Prefixed, timestamp-ordered storage key.\n */\nfunction keyFor(batch: LogBatch): string {\n const at = String(batch.createdAt).padStart(BATCH_KEY_TIME_WIDTH, \"0\");\n return `${EMERGENCY_STORAGE_KEY_PREFIX}${at}.${batch.id}`;\n}\n\n/**\n * Parses and validates a raw storage string into a LogBatch object.\n * @param raw Raw serialized storage string.\n * @param diagnostics Diagnostics reporter.\n * @returns Validated LogBatch or null if unparseable or malformed.\n */\nfunction readBatch(raw: string, diagnostics: Diagnostics): LogBatch | null {\n const parsed = diagnostics.guard(\n \"storage.degraded\",\n \"an emergency entry was not JSON and was dropped\",\n () => JSON.parse(raw) as unknown,\n );\n\n if (typeof parsed !== \"object\" || parsed === null) {\n return null;\n }\n\n const createdAt: unknown = Reflect.get(parsed, \"createdAt\");\n const records: unknown = Reflect.get(parsed, \"records\");\n\n if (typeof createdAt !== \"number\" || !Array.isArray(records)) {\n diagnostics.report(\"storage.degraded\", \"an emergency entry was not a batch and was dropped\");\n return null;\n }\n\n return parsed as LogBatch;\n}\n\n/**\n * Imports all emergency queue entries into the target storage adapter in FIFO order.\n * @param storage Destination storage adapter.\n * @param diagnostics Diagnostics reporter.\n * @returns Total number of recovered batches.\n */\nasync function importAll(storage: StorageAdapter, diagnostics: Diagnostics): Promise<number> {\n let moved = 0;\n\n for (const key of keysWithPrefix(EMERGENCY_STORAGE_KEY_PREFIX, diagnostics)) {\n // Atomically removes key before async persistence to prevent duplicate recovery.\n // A second window importing at the same time cannot take the same batch.\n const raw = diagnostics.guard(\"storage.unavailable\", \"reading the emergency queue\", () => {\n const value = localStorage.getItem(key);\n localStorage.removeItem(key);\n return value;\n });\n\n if (!raw) {\n continue;\n }\n\n const batch = readBatch(raw, diagnostics);\n if (batch === null) {\n continue;\n }\n\n try {\n await storage.save(batch);\n moved++;\n } catch (error) {\n diagnostics.report(\n \"storage.degraded\",\n \"an emergency batch could not be recovered\",\n { key },\n error,\n );\n }\n }\n\n return moved;\n}\n\n/**\n * Synchronously writes an unsent batch to the emergency queue during document unload.\n * @param batch Oversized log batch.\n * @param diagnostics Diagnostics reporter.\n */\nexport function saveToEmergencyQueue(batch: LogBatch, diagnostics: Diagnostics): void {\n diagnostics.guard(\"storage.quota_exceeded\", \"writing the emergency queue\", () => {\n const keys = keysWithPrefix(EMERGENCY_STORAGE_KEY_PREFIX, diagnostics);\n\n // Evicts oldest entries to enforce capacity ceiling.\n for (const old of keys.slice(0, Math.max(0, keys.length - EMERGENCY_MAX_ENTRIES + 1))) {\n localStorage.removeItem(old);\n }\n\n localStorage.setItem(keyFor(batch), JSON.stringify(batch));\n });\n}\n\n/**\n * Recovers batches parked in emergency storage during prior shutdowns.\n * @param storage Destination storage adapter.\n * @param diagnostics Diagnostics reporter.\n * @returns Promise resolving to the number of recovered batches.\n */\nexport async function drainEmergencyQueue(\n storage: StorageAdapter,\n diagnostics: Diagnostics,\n): Promise<number> {\n const moved = await withDrainLock(\n EMERGENCY_LOCK_NAME,\n diagnostics,\n () => importAll(storage, diagnostics),\n { skipIfBusy: false },\n );\n\n return moved ?? 0;\n}\n","// src/storage/local-storage.ts\n//\n// Persistent synchronous storage adapter backed by localStorage using time-ordered\n// keys. The padding makes keys().sort() a sort by creation time. Unpadded it sorts\n// by hex and take() stops returning the oldest batch first.\n\nimport {\n BATCH_KEY_TIME_WIDTH,\n BATCH_STORAGE_KEY_PREFIX,\n QUOTA_EVICTION_DIVISOR,\n STORAGE_NAME_LOCAL,\n} from \"../constants\";\nimport type { Diagnostics } from \"../core/diagnostics\";\nimport type { LogBatch } from \"../models/batch\";\nimport type { GapReporter, PruneResult, StorageAdapter, StorageLimits } from \"../models/storage\";\nimport { keysWithPrefix } from \"./keys\";\n\n/**\n * Formats a storage key with zero-padded creation time for FIFO key sorting. Always\n * from batch.createdAt, never Date.now(). A rebuilt key does not match the one\n * written.\n * @param batch Target log batch.\n * @returns Prefixed, timestamp-ordered storage key.\n */\nfunction keyFor(batch: LogBatch): string {\n const at = String(batch.createdAt).padStart(BATCH_KEY_TIME_WIDTH, \"0\");\n return `${BATCH_STORAGE_KEY_PREFIX}${at}.${batch.id}`;\n}\n\n/** Persistent StorageAdapter implementation backed by localStorage. */\nexport class LocalStorageStorage implements StorageAdapter {\n /** Storage adapter strategy name. */\n readonly name = STORAGE_NAME_LOCAL;\n\n /**\n * @param limits Storage capacity and retention thresholds.\n * @param diagnostics Diagnostics reporter.\n * @param onGap Optional callback for dropped record reporting.\n */\n constructor(\n private readonly limits: StorageLimits,\n private readonly diagnostics: Diagnostics,\n private readonly onGap?: GapReporter,\n ) {}\n\n /**\n * Persists a batch to localStorage, evicting oldest entries on quota errors.\n * @param batch Batch to store.\n */\n async save(batch: LogBatch): Promise<void> {\n const written = this.diagnostics.guard(\n \"storage.quota_exceeded\",\n \"localStorage refused a batch, evicting the oldest\",\n () => {\n localStorage.setItem(keyFor(batch), JSON.stringify(batch));\n return true;\n },\n );\n\n if (written !== true) {\n const keys = this.keys();\n this.evict(keys.slice(0, Math.ceil(keys.length / QUOTA_EVICTION_DIVISOR)));\n return;\n }\n\n await this.prune();\n }\n\n /**\n * Retrieves up to limit batches in chronological order without deletion.\n * @param limit Maximum number of batches to retrieve.\n * @returns Promise resolving to an array of valid batches.\n */\n take(limit: number): Promise<LogBatch[]> {\n const out: LogBatch[] = [];\n\n for (const key of this.keys().slice(0, limit)) {\n const batch = this.read(key);\n // Corrupt and unrecoverable. Dropped without counting a gap: no record count\n // can be read from it.\n if (batch === null) {\n this.removeKey(key);\n continue;\n }\n out.push(batch);\n }\n\n return Promise.resolve(out);\n }\n\n /**\n * Deletes a batch from localStorage by batch ID.\n * @param id Batch identifier.\n */\n remove(id: string): Promise<void> {\n const key = this.keyOf(id);\n if (key !== null) {\n this.removeKey(key);\n }\n return Promise.resolve();\n }\n\n /**\n * Updates delivery attempt count for a stored batch without changing its key.\n * @param id Batch identifier.\n * @param attempts New absolute attempt count.\n */\n bumpAttempts(id: string, attempts: number): Promise<void> {\n const key = this.keyOf(id);\n if (key === null) {\n return Promise.resolve();\n }\n\n const batch = this.read(key);\n if (batch === null) {\n return Promise.resolve();\n }\n\n batch.attempts = attempts;\n this.diagnostics.guard(\"storage.degraded\", \"updating attempts\", () => {\n localStorage.setItem(key, JSON.stringify(batch));\n });\n\n return Promise.resolve();\n }\n\n /**\n * Deletes expired batches and evicts oldest entries exceeding capacity limits.\n * @returns Promise resolving to prune summary metrics.\n */\n prune(): Promise<PruneResult> {\n const cutoff = Date.now() - this.limits.maxAgeMs;\n const result: PruneResult = { batches: 0, records: 0, reason: \"expired\" };\n\n const drop = (key: string, records: number): void => {\n this.removeKey(key);\n result.batches++;\n result.records += records;\n };\n\n const alive: { key: string; records: number }[] = [];\n\n for (const key of this.keys()) {\n const batch = this.read(key);\n if (batch === null) {\n drop(key, 0);\n continue;\n }\n if (batch.createdAt < cutoff) {\n drop(key, batch.records.length);\n continue;\n }\n alive.push({ key, records: batch.records.length });\n }\n\n const excess = alive.length - this.limits.maxBatches;\n if (excess > 0) {\n result.reason = \"over_capacity\";\n for (const entry of alive.slice(0, excess)) {\n drop(entry.key, entry.records);\n }\n }\n\n if (result.batches > 0) {\n this.diagnostics.report(\n \"storage.evicted\",\n `dropped ${String(result.batches)} stored batches (${String(result.records)} records)`,\n { ...result },\n );\n this.onGap?.(result);\n }\n\n return Promise.resolve(result);\n }\n\n /**\n * Returns total count of stored batch keys without deserialization.\n * @returns Promise resolving to batch count.\n */\n count(): Promise<number> {\n return Promise.resolve(this.keys().length);\n }\n\n /** Deletes all matching batch keys from localStorage. */\n clear(): Promise<void> {\n this.evict(this.keys());\n return Promise.resolve();\n }\n\n /** No-op storage teardown method. */\n close(): Promise<void> {\n return Promise.resolve();\n }\n\n /**\n * Deserializes and validates a stored batch from a key.\n * @param key Storage key to read.\n * @returns Validated LogBatch or null if missing or malformed.\n */\n private read(key: string): LogBatch | null {\n const raw = this.diagnostics.guard(\"storage.unavailable\", \"reading a stored batch\", () =>\n localStorage.getItem(key),\n );\n if (!raw) {\n return null;\n }\n\n const parsed = this.diagnostics.guard(\n \"storage.degraded\",\n \"a stored batch was corrupt and was removed\",\n () => JSON.parse(raw) as unknown,\n );\n if (typeof parsed !== \"object\" || parsed === null) {\n return null;\n }\n\n const createdAt: unknown = Reflect.get(parsed, \"createdAt\");\n const records: unknown = Reflect.get(parsed, \"records\");\n if (typeof createdAt !== \"number\" || !Array.isArray(records)) {\n return null;\n }\n\n return parsed as LogBatch;\n }\n\n /**\n * Resolves storage key containing the specified batch ID suffix.\n * @param id Batch identifier.\n * @returns Matching storage key string or null.\n */\n private keyOf(id: string): string | null {\n return this.keys().find((key) => key.endsWith(`.${id}`)) ?? null;\n }\n\n /**\n * Deletes an array of storage keys.\n * @param keys Keys to delete.\n */\n private evict(keys: string[]): void {\n for (const key of keys) {\n this.removeKey(key);\n }\n }\n\n /**\n * Deletes a single storage key with error guarding.\n * @param key Storage key to remove.\n */\n private removeKey(key: string): void {\n this.diagnostics.guard(\"storage.degraded\", \"removing a stored batch\", () => {\n localStorage.removeItem(key);\n });\n }\n\n /**\n * Returns all sorted batch storage keys matching prefix.\n * @returns Sorted array of storage keys.\n */\n private keys(): string[] {\n return keysWithPrefix(BATCH_STORAGE_KEY_PREFIX, this.diagnostics);\n }\n}\n","// src/storage/memory-storage.ts\n//\n// In-memory fallback storage adapter for volatile batch retention during offline\n// periods. A reload loses everything here. Last resort adapter.\n\nimport { STORAGE_NAME_MEMORY } from \"../constants\";\nimport type { LogBatch } from \"../models/batch\";\nimport type { GapReporter, PruneResult, StorageAdapter, StorageLimits } from \"../models/storage\";\n\n/**\n * Sums the total count of records contained across an array of batches.\n * @param batches Batches to measure.\n * @returns Total record count.\n */\nfunction countRecords(batches: LogBatch[]): number {\n return batches.reduce((total, batch) => total + batch.records.length, 0);\n}\n\n/** In-memory StorageAdapter implementation retaining batches in volatile memory. */\nexport class MemoryStorage implements StorageAdapter {\n /** Storage adapter strategy name. */\n readonly name = STORAGE_NAME_MEMORY;\n\n /** Internal array holding batches in chronological FIFO order. */\n private batches: LogBatch[] = [];\n\n /**\n * @param limits Storage capacity and retention thresholds.\n * @param onGap Optional callback for dropped record reporting.\n */\n constructor(\n private readonly limits: StorageLimits,\n private readonly onGap?: GapReporter,\n ) {}\n\n /**\n * Appends a batch to memory storage and applies retention pruning.\n * @param batch Batch to store.\n */\n async save(batch: LogBatch): Promise<void> {\n this.batches.push(batch);\n await this.prune();\n }\n\n /**\n * Retrieves up to limit batches in chronological order without deletion.\n * @param limit Maximum number of batches to retrieve.\n * @returns Promise resolving to an array of batches.\n */\n take(limit: number): Promise<LogBatch[]> {\n return Promise.resolve(this.batches.slice(0, limit));\n }\n\n /**\n * Deletes a batch from memory storage by batch ID.\n * @param id Batch identifier.\n */\n remove(id: string): Promise<void> {\n this.batches = this.batches.filter((batch) => batch.id !== id);\n return Promise.resolve();\n }\n\n /**\n * Updates delivery attempt count for a stored batch.\n * @param id Batch identifier.\n * @param attempts New absolute attempt count.\n */\n bumpAttempts(id: string, attempts: number): Promise<void> {\n const found = this.batches.find((batch) => batch.id === id);\n if (found) {\n found.attempts = attempts;\n }\n return Promise.resolve();\n }\n\n /**\n * Removes expired batches and evicts oldest entries exceeding capacity limits.\n * @returns Promise resolving to prune summary metrics.\n */\n prune(): Promise<PruneResult> {\n const cutoff = Date.now() - this.limits.maxAgeMs;\n const result: PruneResult = { batches: 0, records: 0, reason: \"expired\" };\n\n const expired = this.batches.filter((batch) => batch.createdAt < cutoff);\n this.batches = this.batches.filter((batch) => batch.createdAt >= cutoff);\n result.batches += expired.length;\n result.records += countRecords(expired);\n\n const excess = this.batches.length - this.limits.maxBatches;\n if (excess > 0) {\n result.reason = \"over_capacity\";\n const evicted = this.batches.slice(0, excess);\n this.batches = this.batches.slice(excess);\n result.batches += evicted.length;\n result.records += countRecords(evicted);\n }\n\n if (result.batches > 0) {\n this.onGap?.(result);\n }\n\n return Promise.resolve(result);\n }\n\n /**\n * Returns total count of stored batches.\n * @returns Promise resolving to batch count.\n */\n count(): Promise<number> {\n return Promise.resolve(this.batches.length);\n }\n\n /** Clears all stored batches from memory. */\n clear(): Promise<void> {\n this.batches = [];\n return Promise.resolve();\n }\n\n /** Clears stored batches on storage teardown. */\n close(): Promise<void> {\n this.batches = [];\n return Promise.resolve();\n }\n}\n","// src/storage/factory.ts\n//\n// Factory resolving storage adapters with graceful degradation from IndexedDB to localStorage to memory.\n// Degrades rather than throwing. IndexedDB is unavailable in private mode and\n// sandboxed frames.\n\nimport {\n STORAGE_NAME_INDEXEDDB,\n STORAGE_NAME_MEMORY,\n STORAGE_NAME_NONE,\n STORAGE_PROBE_KEY,\n} from \"../constants\";\nimport type { Diagnostics } from \"../core/diagnostics\";\nimport type { StorageStrategy } from \"../models/config\";\nimport type { GapReporter, StorageAdapter, StorageLimits } from \"../models/storage\";\nimport { LocalStorageStorage } from \"./local-storage\";\nimport { MemoryStorage } from \"./memory-storage\";\n\n/**\n * No-op storage adapter returned when persistence strategy is \"none\". Every method\n * resolves. A sender calling close() on shutdown must not crash.\n */\nconst noop: StorageAdapter = {\n name: STORAGE_NAME_NONE,\n save: () => Promise.resolve(),\n take: () => Promise.resolve([]),\n remove: () => Promise.resolve(),\n bumpAttempts: () => Promise.resolve(),\n prune: () => Promise.resolve({ batches: 0, records: 0, reason: \"expired\" as const }),\n count: () => Promise.resolve(0),\n clear: () => Promise.resolve(),\n close: () => Promise.resolve(),\n};\n\n/**\n * Evaluates whether IndexedDB is accessible in the current execution context.\n * @param diagnostics Diagnostics reporter.\n * @returns True if IDBFactory is available.\n */\nfunction hasIndexedDb(diagnostics: Diagnostics): boolean {\n const available = diagnostics.guard(\"storage.unavailable\", \"reading indexedDB\", () => {\n const factory = (globalThis as { indexedDB?: IDBFactory | null }).indexedDB;\n return factory !== undefined && factory !== null;\n });\n\n return available === true;\n}\n\n/**\n * Tests whether localStorage is accessible and accepts write operations.\n * @param diagnostics Diagnostics reporter.\n * @returns True if localStorage probe write succeeds.\n */\nfunction hasLocalStorage(diagnostics: Diagnostics): boolean {\n const usable = diagnostics.guard(\"storage.unavailable\", \"probing localStorage\", () => {\n localStorage.setItem(STORAGE_PROBE_KEY, \"1\");\n localStorage.removeItem(STORAGE_PROBE_KEY);\n return true;\n });\n\n return usable === true;\n}\n\n/**\n * Instantiates the requested storage adapter, degrading gracefully if dependencies are unavailable.\n * @param strategy Configured persistence strategy.\n * @param dbName IndexedDB database name.\n * @param limits Storage retention and capacity thresholds.\n * @param diagnostics Diagnostics reporter.\n * @param onGap Optional callback for telemetry gap reporting.\n * @returns Promise resolving to the selected StorageAdapter instance.\n */\nexport async function createStorage(\n strategy: StorageStrategy,\n dbName: string,\n limits: StorageLimits,\n diagnostics: Diagnostics,\n onGap?: GapReporter,\n): Promise<StorageAdapter> {\n if (strategy === STORAGE_NAME_NONE) {\n return noop;\n }\n if (strategy === STORAGE_NAME_MEMORY) {\n return new MemoryStorage(limits, onGap);\n }\n\n if (strategy === STORAGE_NAME_INDEXEDDB || strategy === \"auto\") {\n if (hasIndexedDb(diagnostics)) {\n // Dynamically imports IndexedDbStorage to omit storage drivers from main\n // bundle. A chunk that fails to load degrades to the next adapter.\n const adapter = await diagnostics.guardAsync(\n \"storage.unavailable\",\n \"opening IndexedDB\",\n async () => {\n const { IndexedDbStorage } = await import(\"./indexeddb-storage\");\n return new IndexedDbStorage(dbName, limits, diagnostics, onGap);\n },\n );\n if (adapter) {\n return adapter;\n }\n }\n\n if (strategy === STORAGE_NAME_INDEXEDDB) {\n diagnostics.report(\n \"storage.degraded\",\n \"IndexedDB was asked for by name and is unavailable, using memory\",\n );\n return new MemoryStorage(limits, onGap);\n }\n }\n\n if (hasLocalStorage(diagnostics)) {\n return new LocalStorageStorage(limits, diagnostics, onGap);\n }\n\n diagnostics.report(\n \"storage.degraded\",\n \"no persistent storage available, offline logs are memory only\",\n );\n return new MemoryStorage(limits, onGap);\n}\n","// src/utils/sanitize.ts\n//\n// Sanitizes arbitrary data into JSON-safe structures with cycle detection and byte-size estimation.\n// Never throws. Never returns a circular structure.\n\nimport {\n BYTES_PER_BOOLEAN,\n BYTES_PER_CONTAINER,\n BYTES_PER_KEY_OVERHEAD,\n BYTES_PER_NULL,\n BYTES_PER_NUMBER,\n BYTES_PER_QUOTED_STRING,\n HIGH_SURROGATE_MAX,\n HIGH_SURROGATE_MIN,\n MAX_NODE_CLASS_NAMES,\n UTF8_ONE_BYTE_CEILING,\n UTF8_TWO_BYTE_CEILING,\n} from \"../constants\";\n\n/** Structural depth and size limits enforced during object sanitization. */\nexport interface SanitizeLimits {\n /** Maximum recursion depth before truncating nested objects. */\n maxDepth: number;\n /** Maximum items retained in arrays, sets, and maps before truncating. */\n maxArrayLength: number;\n /** Maximum string attribute length in characters. */\n maxAttributeChars: number;\n /** Maximum key-value properties retained in a single object. */\n maxAttributeCount: number;\n /** Maximum error stack trace length in characters. */\n maxStackChars: number;\n}\n\n/**\n * Truncates a string to maximum character length while preserving UTF-16 surrogate pairs.\n * @param value Target string.\n * @param max Maximum allowed character length.\n * @returns Truncated string with appended drop count suffix.\n */\nexport function truncate(value: string, max: number): string {\n if (value.length <= max) {\n return value;\n }\n\n // Avoids splitting UTF-16 surrogate pairs at truncation boundaries. slice works in\n // code units. Half a pair serializes as U+FFFD.\n const end = isHighSurrogate(value.charCodeAt(max - 1)) ? max - 1 : max;\n return `${value.slice(0, end)}… [truncated ${String(value.length - end)} chars]`;\n}\n\n/**\n * Evaluates whether a UTF-16 code unit is a leading surrogate.\n * @param code UTF-16 character code.\n * @returns True if character is a high surrogate.\n */\nfunction isHighSurrogate(code: number): boolean {\n return code >= HIGH_SURROGATE_MIN && code <= HIGH_SURROGATE_MAX;\n}\n\n/** Structural interface for DOM Node inspection across realms. */\ninterface NodeLike {\n nodeName?: string;\n id?: string;\n className?: unknown;\n}\n\n/**\n * Formats a DOM node as a descriptive CSS selector string.\n * @param node Node-like object to format.\n * @returns Formatted selector string.\n */\nfunction describeNode(node: NodeLike): string {\n const tag = (node.nodeName ?? \"NODE\").toLowerCase();\n const id = node.id ? `#${node.id}` : \"\";\n const cls =\n typeof node.className === \"string\" && node.className\n ? `.${node.className.trim().split(/\\s+/).slice(0, MAX_NODE_CLASS_NAMES).join(\".\")}`\n : \"\";\n return `[Element ${tag}${id}${cls}]`;\n}\n\n/** Sanitized JSON-safe output with estimated serialized byte size. */\nexport interface SanitizeResult {\n /** JSON-safe sanitized structure. */\n value: unknown;\n /** Approximate serialized byte count. */\n bytes: number;\n}\n\n/** Mutable byte accumulator passed through recursive sanitization passes. */\ninterface SizeState {\n bytes: number;\n}\n\n/**\n * Sanitizes arbitrary values into JSON-safe structures without throwing.\n * @param value Raw value to sanitize.\n * @param limits Configuration limits for depth, count, and character lengths.\n * @returns JSON-safe sanitized value.\n */\nexport function sanitize(value: unknown, limits: SanitizeLimits): unknown {\n return sanitizeWithSize(value, limits).value;\n}\n\n/**\n * Sanitizes arbitrary values and calculates approximate serialized byte sizes.\n * @param value Raw value to sanitize.\n * @param limits Configuration limits.\n * @returns SanitizeResult containing sanitized value and byte count.\n */\nexport function sanitizeWithSize(value: unknown, limits: SanitizeLimits): SanitizeResult {\n const state: SizeState = { bytes: 0 };\n const result = walk(value, limits, new WeakSet(), 0, state);\n return { value: result, bytes: state.bytes };\n}\n\n/**\n * Adds string length and quotes overhead to size accumulator.\n * @param text Serialized string token.\n * @param state Byte size accumulator.\n * @returns Input text unchanged.\n */\nfunction counted(text: string, state: SizeState): string {\n state.bytes += estimateBytes(text) + BYTES_PER_QUOTED_STRING;\n return text;\n}\n\n/**\n * Recursively walks object trees, replacing cyclic references, hostile getters, and invalid primitives.\n * @param value Target value to sanitize.\n * @param limits Truncation and depth limits.\n * @param seen Set of active ancestor objects for cycle detection.\n * @param depth Current recursion depth.\n * @param state Running byte size accumulator.\n * @returns JSON-safe sanitized representation.\n */\nfunction walk(\n value: unknown,\n limits: SanitizeLimits,\n seen: WeakSet<object>,\n depth: number,\n state: SizeState,\n): unknown {\n if (value === null || value === undefined) {\n state.bytes += BYTES_PER_NULL;\n return value;\n }\n\n if (typeof value === \"string\") {\n return counted(truncate(value, limits.maxAttributeChars), state);\n }\n if (typeof value === \"number\") {\n state.bytes += BYTES_PER_NUMBER;\n return Number.isFinite(value) ? value : String(value);\n }\n if (typeof value === \"boolean\") {\n state.bytes += BYTES_PER_BOOLEAN;\n return value;\n }\n if (typeof value === \"bigint\") {\n return counted(`${value.toString()}n`, state);\n }\n if (typeof value === \"symbol\") {\n return counted(value.toString(), state);\n }\n if (typeof value === \"function\") {\n return counted(`[Function ${value.name === \"\" ? \"anonymous\" : value.name}]`, state);\n }\n\n if (depth >= limits.maxDepth) {\n return counted(\"[MaxDepth]\", state);\n }\n\n if (seen.has(value)) {\n return counted(\"[Circular]\", state);\n }\n seen.add(value);\n state.bytes += BYTES_PER_CONTAINER;\n\n try {\n if (value instanceof Error) {\n return {\n name: counted(value.name, state),\n message: counted(truncate(value.message, limits.maxAttributeChars), state),\n stack: value.stack\n ? counted(truncate(value.stack, limits.maxStackChars), state)\n : undefined,\n cause: value.cause ? walk(value.cause, limits, seen, depth + 1, state) : undefined,\n };\n }\n if (value instanceof Date) {\n return counted(value.toISOString(), state);\n }\n if (value instanceof RegExp) {\n return counted(value.toString(), state);\n }\n if (value instanceof Map) {\n const map: ReadonlyMap<unknown, unknown> = value;\n const out: Record<string, unknown> = {};\n let shown = 0;\n for (const [key, entry] of map) {\n if (shown >= limits.maxArrayLength) {\n out[\"…\"] = counted(`[${String(map.size - limits.maxArrayLength)} more entries]`, state);\n break;\n }\n shown++;\n const name = String(key);\n state.bytes += estimateBytes(name) + BYTES_PER_KEY_OVERHEAD;\n out[name] = walk(entry, limits, seen, depth + 1, state);\n }\n return out;\n }\n if (value instanceof Set) {\n const set: ReadonlySet<unknown> = value;\n return walk([...set].slice(0, limits.maxArrayLength), limits, seen, depth, state);\n }\n if (ArrayBuffer.isView(value)) {\n const length = (value as { length?: number }).length ?? 0;\n return counted(`[${value.constructor.name}(${String(length)})]`, state);\n }\n if (value instanceof Promise) {\n return counted(\"[Promise]\", state);\n }\n if (typeof Node !== \"undefined\" && value instanceof Node) {\n return counted(describeNode(value), state);\n }\n\n if (Array.isArray(value)) {\n const items: readonly unknown[] = value;\n const out: unknown[] = items\n .slice(0, limits.maxArrayLength)\n .map((item) => walk(item, limits, seen, depth + 1, state));\n if (items.length > limits.maxArrayLength) {\n out.push(counted(`[${String(items.length - limits.maxArrayLength)} more items]`, state));\n }\n return out;\n }\n\n const maybeToJson: unknown = (value as { toJSON?: unknown }).toJSON;\n if (typeof maybeToJson === \"function\") {\n const toJson = maybeToJson as () => unknown;\n return walk(toJson.call(value), limits, seen, depth + 1, state);\n }\n\n const record = value as Record<string, unknown>;\n const keys = Object.keys(record);\n const out: Record<string, unknown> = {};\n let count = 0;\n for (const key of keys) {\n if (count >= limits.maxAttributeCount) {\n out[\"…\"] = counted(`[${String(keys.length - count)} more keys]`, state);\n break;\n }\n count++;\n state.bytes += estimateBytes(key) + BYTES_PER_KEY_OVERHEAD;\n out[key] = walk(record[key], limits, seen, depth + 1, state);\n }\n return out;\n } catch (error) {\n // Catches hostile getters and throwing proxies. One costs an attribute, not the\n // record.\n const name = error instanceof Error ? error.name : \"error\";\n return counted(`[Unserializable: ${name}]`, state);\n } finally {\n // Removes object from ancestor set on unwind. Left in, a repeated sibling reads\n // as a cycle.\n seen.delete(value);\n }\n}\n\n/**\n * Estimates UTF-8 encoded byte length for a string.\n * @param value Target string.\n * @returns Estimated UTF-8 byte length.\n */\nexport function estimateBytes(value: string): number {\n let bytes = 0;\n for (let i = 0; i < value.length; i++) {\n const code = value.charCodeAt(i);\n if (code < UTF8_ONE_BYTE_CEILING) {\n bytes += 1;\n } else if (code < UTF8_TWO_BYTE_CEILING) {\n bytes += 2;\n } else if (code >= HIGH_SURROGATE_MIN && code <= HIGH_SURROGATE_MAX) {\n bytes += 4;\n i++;\n } else {\n bytes += 3;\n }\n }\n return bytes;\n}\n","// src/transport/exit-flush.ts\n//\n// Synchronous exit-flush handler delivering buffered batches via sendBeacon, keepalive fetch, or emergency storage.\n// Runs during unload. Nothing awaits.\n\nimport {\n BEACON_LIMIT_BYTES,\n CONTENT_TYPE_TEXT_PLAIN,\n HEADER_CONTENT_TYPE,\n QUERY_PARAM_BATCH_ID,\n QUERY_PARAM_EXIT_REASON,\n} from \"../constants\";\nimport type { Diagnostics } from \"../core/diagnostics\";\nimport type { LogBatch } from \"../models/batch\";\nimport type { ResolvedConfig } from \"../models/config\";\nimport { saveToEmergencyQueue } from \"../storage/emergency-queue\";\nimport { estimateBytes } from \"../utils/sanitize\";\n\n/** Document lifecycle event or manual action that triggered an exit flush. */\nexport type ExitReason = \"hidden\" | \"pagehide\" | \"freeze\" | \"openfin-close\" | \"shutdown\";\n\n/** Structural interface for OpenFin window event subscription. */\ninterface FinMeLike {\n on?: (event: string, listener: () => void) => void;\n removeListener?: (event: string, listener: () => void) => void;\n}\n\n/** Global environment extended with optional OpenFin runtime APIs. */\ntype OpenFinGlobal = typeof globalThis & { fin?: { me?: FinMeLike } };\n\n/** Structural type for inspecting navigator.sendBeacon without restoring global DOM assertions. */\ninterface BeaconGlobal {\n navigator?: { sendBeacon?: (url: string, data: Blob) => boolean };\n}\n\n/** Injected dependencies required by ExitFlush. */\nexport interface ExitFlushDeps {\n /** Active configuration instance. */\n config: ResolvedConfig;\n /** Diagnostics reporter instance. */\n diagnostics: Diagnostics;\n /** Callback draining all pending buffered and unconfirmed batches into a single LogBatch. */\n drainPending: () => LogBatch | null;\n}\n\n/** Flushes pending telemetry on document unload using sendBeacon, keepalive fetch, or emergency storage. */\nexport class ExitFlush {\n /** Indicates whether unload listeners are currently active. */\n private installed = false;\n\n /** Handles visibilitychange events when the document becomes hidden. */\n private readonly onVisibility = (): void => {\n if (document.visibilityState === \"hidden\") {\n this.flush(\"hidden\");\n }\n };\n\n /** Handles window pagehide events. */\n private readonly onPageHide = (): void => {\n this.flush(\"pagehide\");\n };\n\n /** Handles document freeze events. */\n private readonly onFreeze = (): void => {\n this.flush(\"freeze\");\n };\n\n /** Handles OpenFin close-requested events. */\n private readonly onOpenFinClose = (): void => {\n this.flush(\"openfin-close\");\n };\n\n /**\n * @param deps Injected configuration, diagnostics, and drain callback.\n */\n constructor(private readonly deps: ExitFlushDeps) {}\n\n /** Attaches unload listeners across document, window, and OpenFin environments. */\n install(): void {\n if (this.installed || typeof addEventListener === \"undefined\") {\n return;\n }\n this.installed = true;\n\n if (typeof document !== \"undefined\") {\n // visibilitychange and freeze target the document; pagehide targets window.\n document.addEventListener(\"visibilitychange\", this.onVisibility);\n document.addEventListener(\"freeze\", this.onFreeze);\n }\n\n addEventListener(\"pagehide\", this.onPageHide);\n\n const me = (globalThis as OpenFinGlobal).fin?.me;\n this.deps.diagnostics.guard(\"openfin.unavailable\", \"subscribing to close-requested\", () => {\n me?.on?.(\"close-requested\", this.onOpenFinClose);\n });\n }\n\n /** Removes all registered unload listeners and subscriptions. */\n uninstall(): void {\n if (!this.installed) {\n return;\n }\n this.installed = false;\n\n if (typeof document !== \"undefined\") {\n document.removeEventListener(\"visibilitychange\", this.onVisibility);\n document.removeEventListener(\"freeze\", this.onFreeze);\n }\n\n removeEventListener(\"pagehide\", this.onPageHide);\n\n const me = (globalThis as OpenFinGlobal).fin?.me;\n this.deps.diagnostics.guard(\"openfin.unavailable\", \"releasing close-requested\", () => {\n me?.removeListener?.(\"close-requested\", this.onOpenFinClose);\n });\n }\n\n /**\n * Synchronously drains pending records and transmits via beacon, keepalive, or\n * emergency storage. Never awaits and never throws. The caller is an unload\n * listener.\n * @param reason Trigger reason code.\n */\n flush(reason: ExitReason): void {\n const { diagnostics } = this.deps;\n\n const url = this.endpointUrl();\n if (url === null) {\n return;\n }\n\n const batch = this.deps.drainPending();\n if (!batch || batch.records.length === 0) {\n return;\n }\n\n const serialized = diagnostics.guard(\n \"transport.serialize_failed\",\n `the ${reason} exit flush could not serialize its batch`,\n () => this.deps.config.serializer.serialize(batch.records),\n );\n if (!serialized) {\n return;\n }\n\n // Parks oversized payloads in synchronous localStorage queue. localStorage is\n // the only storage writable without awaiting.\n if (estimateBytes(serialized.body) > BEACON_LIMIT_BYTES) {\n saveToEmergencyQueue(batch, diagnostics);\n return;\n }\n\n // Passes batch ID and reason via query parameters. sendBeacon cannot set\n // headers.\n url.searchParams.set(QUERY_PARAM_BATCH_ID, batch.id);\n url.searchParams.set(QUERY_PARAM_EXIT_REASON, reason);\n\n const target = url.toString();\n if (this.beacon(target, serialized.body)) {\n return;\n }\n\n this.keepaliveFetch(target, serialized.body, reason);\n }\n\n /**\n * Resolves and parses the destination endpoint URL.\n * @returns URL instance or null if missing or invalid.\n */\n private endpointUrl(): URL | null {\n const { endpoint } = this.deps.config;\n if (!endpoint) {\n return null;\n }\n\n const url = this.deps.diagnostics.guard(\n \"config.invalid\",\n `the exit flush cannot use endpoint ${endpoint}`,\n () => new URL(endpoint),\n );\n\n return url ?? null;\n }\n\n /**\n * Attempts transmission via navigator.sendBeacon with text/plain payload.\n * @param url Target endpoint URL with query parameters.\n * @param body Serialized payload string.\n * @returns True if the beacon was accepted by the browser.\n */\n private beacon(url: string, body: string): boolean {\n const sent = this.deps.diagnostics.guard(\"transport.http_error\", \"sendBeacon\", () => {\n // Invokes sendBeacon directly on navigator to preserve receiver context. A\n // detached sendBeacon throws on invocation.\n const nav = (globalThis as BeaconGlobal).navigator;\n if (!nav?.sendBeacon) {\n return false;\n }\n\n // Uses text/plain to avoid CORS preflights during document unload. A preflight\n // started during unload rarely completes, dropping the beacon silently.\n return nav.sendBeacon(url, new Blob([body], { type: CONTENT_TYPE_TEXT_PLAIN }));\n });\n\n return sent === true;\n }\n\n /**\n * Fallback POST delivery using fetch with keepalive: true. keepalive outlives the\n * document. A plain fetch is cancelled as the page goes.\n * @param url Target endpoint URL.\n * @param body Serialized payload string.\n * @param reason Trigger reason code.\n */\n private keepaliveFetch(url: string, body: string, reason: ExitReason): void {\n const { config, diagnostics } = this.deps;\n\n diagnostics.guard(\"transport.http_error\", \"the keepalive fetch fallback\", () => {\n void fetch(url, {\n method: \"POST\",\n body,\n headers: { [HEADER_CONTENT_TYPE]: CONTENT_TYPE_TEXT_PLAIN },\n credentials: config.credentials,\n keepalive: true,\n }).catch((error: unknown) => {\n diagnostics.report(\"transport.http_error\", \"the exit flush failed\", { reason }, error);\n });\n });\n }\n}\n","// src/transport/compression.ts\n//\n// Compresses payloads using the native CompressionStream API when available.\n// Returns null rather than raw text. A non-gzip body under Content-Encoding: gzip\n// is a 400 the server cannot explain.\n\nimport { ENCODING_GZIP } from \"../constants\";\n\n/**\n * Compresses a string into a gzip-encoded byte array using CompressionStream.\n * Returns non-shared ArrayBuffer backed Uint8Array compatible with fetch BodyInit.\n * @param text Raw serialized payload to compress.\n * @returns Promise resolving to compressed Uint8Array, or null if CompressionStream is unsupported.\n */\nexport async function gzip(text: string): Promise<Uint8Array<ArrayBuffer> | null> {\n const CS = (globalThis as { CompressionStream?: typeof CompressionStream }).CompressionStream;\n if (CS === undefined) {\n return null;\n }\n\n const stream = new Blob([text]).stream().pipeThrough(new CS(ENCODING_GZIP));\n const buffer = await new Response(stream).arrayBuffer();\n\n return new Uint8Array(buffer);\n}\n","// src/transport/errors.ts\n//\n// Classifies HTTP transport failures and parses server Retry-After backoff headers.\n\nimport { MILLIS_PER_SECOND } from \"../constants\";\n\n/**\n * Failure classification determining retry, backoff, or drop behavior. transient,\n * offline and timeout retry with backoff. throttled waits the server's delay.\n * too_large splits the batch. permanent drops it: it will never be accepted.\n */\nexport type TransportFailureKind =\n \"transient\" | \"throttled\" | \"too_large\" | \"permanent\" | \"timeout\" | \"offline\";\n\n/** Error representing a failed transport attempt with failure classification and metadata. */\nexport class TransportError extends Error {\n /**\n * @param kind Failure classification.\n * @param message Error description.\n * @param status Optional HTTP response status code.\n * @param retryAfterMs Delay requested by the server in milliseconds.\n * @param maxBytes Maximum payload bytes suggested by a 413 response.\n */\n constructor(\n public readonly kind: TransportFailureKind,\n message: string,\n public readonly status?: number,\n public readonly retryAfterMs?: number,\n public readonly maxBytes?: number,\n ) {\n super(message);\n this.name = \"TransportError\";\n }\n}\n\n/**\n * Parses HTTP Retry-After header value (seconds or HTTP date) into millisecond\n * delay. Both forms are legal. A date already past clamps to zero.\n * Clamps negative delays to zero.\n * @param header Raw Retry-After header string or null.\n * @returns Non-negative delay in milliseconds, or undefined if invalid or missing.\n */\nexport function parseRetryAfter(header: string | null): number | undefined {\n if (!header) {\n return undefined;\n }\n\n const seconds = Number(header);\n if (Number.isFinite(seconds)) {\n return Math.max(0, seconds * MILLIS_PER_SECOND);\n }\n\n const date = Date.parse(header);\n return Number.isNaN(date) ? undefined : Math.max(0, date - Date.now());\n}\n","// src/transport/http-transport.ts\n//\n// Serializes, compresses, and delivers log batches over HTTP with error\n// classification. Classifies, reports and throws. What happens to a rejected batch\n// belongs to the caller that owns storage.\n\nimport {\n ENCODING_GZIP,\n HEADER_ATTEMPT,\n HEADER_BATCH_ID,\n HEADER_CONTENT_ENCODING,\n HEADER_CONTENT_TYPE,\n HEADER_RETRY_AFTER,\n HTTP_FORBIDDEN,\n HTTP_PAYLOAD_TOO_LARGE,\n HTTP_REQUEST_TIMEOUT,\n HTTP_SERVER_ERROR_MIN,\n HTTP_SERVICE_UNAVAILABLE,\n HTTP_TOO_MANY_REQUESTS,\n HTTP_UNAUTHORIZED,\n} from \"../constants\";\nimport type { Diagnostics } from \"../core/diagnostics\";\nimport type { LogBatch } from \"../models/batch\";\nimport type { ResolvedConfig } from \"../models/config\";\nimport type { SerializedBatch } from \"../models/serializer\";\nimport { estimateBytes } from \"../utils/sanitize\";\nimport { gzip } from \"./compression\";\nimport { parseRetryAfter, TransportError } from \"./errors\";\n\n/** HTTP transport delivering serialized log batches with header resolution, gzip compression, and error classification. */\nexport class HttpTransport {\n /** Timestamp in epoch milliseconds until which requests are throttled. */\n private throttledUntil = 0;\n\n /**\n * @param config Active configuration instance.\n * @param diagnostics Diagnostics reporter.\n */\n constructor(\n private readonly config: ResolvedConfig,\n private readonly diagnostics: Diagnostics,\n ) {}\n\n /**\n * Delivers a single log batch over HTTP.\n * @param batch Batch to send.\n * @throws TransportError on transient, throttled, 413, or permanent network failures.\n */\n async send(batch: LogBatch): Promise<void> {\n if (!this.config.endpoint || batch.records.length === 0) {\n return;\n }\n\n await this.post(batch);\n }\n\n /**\n * Returns the remaining throttle backoff duration in milliseconds.\n * @returns Milliseconds remaining in throttle window, or 0 if unthrottled.\n */\n throttledForMs(): number {\n return Math.max(0, this.throttledUntil - Date.now());\n }\n\n /**\n * Serializes, encodes, and dispatches a batch, throwing a classified TransportError on failure.\n * @param batch Batch to deliver.\n */\n private async post(batch: LogBatch): Promise<void> {\n const { config } = this;\n\n let serialized: SerializedBatch;\n try {\n serialized = config.serializer.serialize(batch.records);\n } catch (error) {\n this.diagnostics.report(\n \"transport.serialize_failed\",\n \"serializer threw, dropping the batch\",\n { batchId: batch.id },\n error,\n );\n return;\n }\n\n // Headers normalizes header names case-insensitively.\n const headers = new Headers(await this.resolveHeaders());\n headers.set(HEADER_CONTENT_TYPE, serialized.contentType);\n headers.set(HEADER_BATCH_ID, batch.id);\n headers.set(HEADER_ATTEMPT, String(batch.attempts));\n\n const body = await this.encodeBody(serialized.body);\n if (typeof body !== \"string\") {\n headers.set(HEADER_CONTENT_ENCODING, ENCODING_GZIP);\n }\n\n const response = await this.dispatch(headers, body);\n if (response.ok) {\n this.throttledUntil = 0;\n return;\n }\n\n throw await this.classify(response, batch.id);\n }\n\n /**\n * Compresses the serialized payload if gzip compression is enabled and size exceeds threshold.\n * @param text Serialized payload string.\n * @returns Promise resolving to original string or compressed byte array.\n */\n private async encodeBody(text: string): Promise<string | Uint8Array<ArrayBuffer>> {\n const { config } = this;\n if (\n config.compression !== ENCODING_GZIP ||\n estimateBytes(text) < config.compressionThresholdBytes\n ) {\n return text;\n }\n\n const compressed = await this.diagnostics.guardAsync(\n \"transport.http_error\",\n \"gzipping the payload\",\n () => gzip(text),\n );\n\n return compressed ?? text;\n }\n\n /**\n * Executes the HTTP POST request with timeout and network error mapping.\n * @param headers HTTP request headers.\n * @param body Request body string or byte array.\n * @returns Promise resolving to the HTTP Response.\n * @throws TransportError on network failure, timeout, or offline status.\n */\n private async dispatch(\n headers: Headers,\n body: string | Uint8Array<ArrayBuffer>,\n ): Promise<Response> {\n const { config } = this;\n const controller = new AbortController();\n const timer = setTimeout(() => {\n controller.abort();\n }, config.requestTimeoutMs);\n\n try {\n return await fetch(config.endpoint, {\n method: \"POST\",\n headers,\n body,\n credentials: config.credentials,\n signal: controller.signal,\n cache: \"no-store\",\n });\n } catch {\n if (controller.signal.aborted) {\n const waited = String(config.requestTimeoutMs);\n throw new TransportError(\"timeout\", `request exceeded ${waited}ms`);\n }\n const online = (globalThis as { navigator?: { onLine?: boolean } }).navigator?.onLine;\n throw new TransportError(online === false ? \"offline\" : \"transient\", \"network error\");\n } finally {\n clearTimeout(timer);\n }\n }\n\n /**\n * Classifies an HTTP error response into a structured TransportError.\n * @param response Unsuccessful HTTP response.\n * @param batchId Identifier of the rejected batch.\n * @returns Classified TransportError instance.\n */\n private async classify(response: Response, batchId: string): Promise<TransportError> {\n const status = response.status;\n const retryAfterMs = parseRetryAfter(response.headers.get(HEADER_RETRY_AFTER));\n\n if (status === HTTP_UNAUTHORIZED || status === HTTP_FORBIDDEN) {\n const advice =\n \"In a cross-origin iframe the session cookie is a third-party cookie and is very \" +\n \"likely blocked. Forward to the platform document instead of promoting to sender, \" +\n \"or issue the cookie with the Partitioned attribute.\";\n\n this.diagnostics.report(\n \"transport.rejected_credentials\",\n `server returned ${String(status)}. ${advice}`,\n { status, endpoint: this.config.endpoint },\n );\n // Permanent. Retrying a rejected credential forever blocks every batch behind\n // it.\n return new TransportError(\"permanent\", `rejected with ${String(status)}`, status);\n }\n\n if (status === HTTP_PAYLOAD_TOO_LARGE) {\n const maxBytes = await this.readMaxBytes(response);\n return new TransportError(\"too_large\", \"payload too large\", status, undefined, maxBytes);\n }\n\n if (status === HTTP_TOO_MANY_REQUESTS || status === HTTP_SERVICE_UNAVAILABLE) {\n const throttled = status === HTTP_TOO_MANY_REQUESTS;\n this.throttledUntil = Date.now() + (retryAfterMs ?? this.config.retry.baseDelayMs);\n\n if (throttled) {\n this.diagnostics.report(\"transport.throttled\", \"server throttled us\", {\n retryAfterMs,\n });\n }\n\n return new TransportError(\n \"throttled\",\n throttled ? \"throttled\" : \"service unavailable\",\n status,\n retryAfterMs,\n );\n }\n\n if (status === HTTP_REQUEST_TIMEOUT || status >= HTTP_SERVER_ERROR_MIN) {\n return new TransportError(\"transient\", `server error ${String(status)}`, status);\n }\n\n this.diagnostics.report(\n \"transport.dropped_permanent\",\n `server rejected the batch with ${String(status)}, dropping it`,\n { batchId, status },\n );\n return new TransportError(\"permanent\", `rejected with ${String(status)}`, status);\n }\n\n /**\n * Extracts optional maxBytes payload limit from a 413 response body.\n * @param response HTTP 413 Response instance.\n * @returns Promise resolving to maximum byte limit or undefined.\n */\n private async readMaxBytes(response: Response): Promise<number | undefined> {\n return this.diagnostics.guardAsync(\"transport.http_error\", \"reading the 413 body\", async () => {\n const parsed = JSON.parse(await response.text()) as {\n maxBytes?: unknown;\n };\n return typeof parsed.maxBytes === \"number\" ? parsed.maxBytes : undefined;\n });\n }\n\n /**\n * Evaluates configured static or dynamic request headers.\n * @returns Promise resolving to resolved header map.\n */\n private async resolveHeaders(): Promise<Record<string, string>> {\n const { headers } = this.config;\n if (!headers) {\n return {};\n }\n if (typeof headers !== \"function\") {\n return headers;\n }\n\n const resolved = await this.diagnostics.guardAsync(\n \"transport.http_error\",\n \"headers() threw\",\n () => Promise.resolve(headers()),\n );\n return resolved ?? {};\n }\n}\n","// src/utils/identity.ts\n//\n// Generates and manages session, tab, and context correlation identifiers. Storage\n// throws rather than returning null in a sandboxed iframe and in private mode. An\n// unguarded read takes the library down at import.\n\nimport {\n BYTE_VALUE_COUNT,\n ID_BYTE_LENGTH,\n SESSION_ID_KEY,\n SESSION_IDLE_MS,\n SESSION_TOUCH_MS,\n TAB_ID_KEY,\n} from \"../constants\";\nimport type { Diagnostics } from \"../core/diagnostics\";\n\n/** Correlation identifiers attached to log records across session, tab, and realm scopes. */\nexport interface Identity {\n /** Origin-wide user session identifier surviving across tabs until idle expiration. */\n sessionId: string;\n /** Browser tab or desktop window identifier surviving document reloads. */\n tabId: string;\n /** Unique execution realm identifier regenerated on every document load. */\n contextId: string;\n}\n\n/**\n * Generates a random lowercase hexadecimal string of the specified byte length.\n * Uses crypto.getRandomValues when available, falling back to Math.random.\n * @param byteLength Number of random bytes to generate.\n * @returns Hexadecimal string of length byteLength * 2.\n */\nexport function randomHex(byteLength: number): string {\n const bytes = new Uint8Array(byteLength);\n if (typeof crypto !== \"undefined\" && typeof crypto.getRandomValues === \"function\") {\n crypto.getRandomValues(bytes);\n } else {\n for (let i = 0; i < byteLength; i++) {\n bytes[i] = Math.floor(Math.random() * BYTE_VALUE_COUNT);\n }\n }\n return Array.from(bytes, (b) => b.toString(16).padStart(2, \"0\")).join(\"\");\n}\n\n/**\n * Generates a unique identifier string using crypto.randomUUID or randomHex fallback.\n * @returns UUID or random hex identifier.\n */\nexport function newId(): string {\n try {\n if (typeof crypto !== \"undefined\" && typeof crypto.randomUUID === \"function\") {\n return crypto.randomUUID();\n }\n } catch {\n // Catches sandbox SecurityError throws when crypto.randomUUID is blocked. The\n // method is present; only the call fails.\n }\n return randomHex(ID_BYTE_LENGTH);\n}\n\n/**\n * Reads a value from localStorage or sessionStorage with storage error guarding.\n * @param store Storage target (\"local\" or \"session\").\n * @param key Storage key.\n * @param diagnostics Diagnostics reporter.\n * @returns Stored string value or null if unreadable or absent.\n */\nfunction safeRead(\n store: \"local\" | \"session\",\n key: string,\n diagnostics: Diagnostics,\n): string | null {\n return (\n diagnostics.guard(\"storage.unavailable\", `reading ${store}Storage`, () => {\n const s = store === \"local\" ? localStorage : sessionStorage;\n return s.getItem(key);\n }) ?? null\n );\n}\n\n/**\n * Writes a key-value pair to localStorage or sessionStorage with storage error guarding.\n * @param store Storage target (\"local\" or \"session\").\n * @param key Storage key.\n * @param value String value to store.\n * @param diagnostics Diagnostics reporter.\n */\nfunction safeWrite(\n store: \"local\" | \"session\",\n key: string,\n value: string,\n diagnostics: Diagnostics,\n): void {\n diagnostics.guard(\"storage.unavailable\", `writing ${store}Storage`, () => {\n const s = store === \"local\" ? localStorage : sessionStorage;\n s.setItem(key, value);\n });\n}\n\n/**\n * Resolves or initializes session, tab, and context identifiers for the active realm.\n * @param diagnostics Diagnostics reporter.\n * @returns Populated Identity object.\n */\nexport function resolveIdentity(diagnostics: Diagnostics): Identity {\n const contextId = newId();\n const now = Date.now();\n\n let sessionId = newId();\n const rawSession = safeRead(\"local\", SESSION_ID_KEY, diagnostics);\n if (rawSession) {\n try {\n const parsed = JSON.parse(rawSession) as {\n id?: string;\n lastSeenAt?: number;\n };\n if (parsed.id && now - (parsed.lastSeenAt ?? 0) < SESSION_IDLE_MS) {\n sessionId = parsed.id;\n }\n } catch {\n diagnostics.report(\"storage.degraded\", \"session record was not JSON, starting a new session\");\n }\n }\n const session = JSON.stringify({ id: sessionId, lastSeenAt: now });\n safeWrite(\"local\", SESSION_ID_KEY, session, diagnostics);\n\n let tabId = safeRead(\"session\", TAB_ID_KEY, diagnostics) ?? \"\";\n if (!tabId) {\n tabId = newId();\n safeWrite(\"session\", TAB_ID_KEY, tabId, diagnostics);\n }\n\n return { sessionId, tabId, contextId };\n}\n\n/** Timestamp of last recorded session touch in epoch milliseconds. */\nlet lastTouchAt = 0;\n\n/**\n * Updates session activity timestamp in localStorage, throttled by SESSION_TOUCH_MS.\n * @param sessionId Active session identifier.\n * @param diagnostics Diagnostics reporter.\n */\nexport function touchSession(sessionId: string, diagnostics: Diagnostics): void {\n const now = Date.now();\n if (now - lastTouchAt < SESSION_TOUCH_MS) {\n return;\n }\n lastTouchAt = now;\n const session = JSON.stringify({ id: sessionId, lastSeenAt: now });\n safeWrite(\"local\", SESSION_ID_KEY, session, diagnostics);\n}\n\n/** Resets the session touch throttle timer state for testing. */\nexport function resetSessionTouch(): void {\n lastTouchAt = 0;\n}\n","// src/models/batch.ts\n//\n// A batch of log records for delivery to the ingest endpoint.\n\nimport { newId } from \"../utils/identity\";\nimport type { LogRecord } from \"./log-record\";\n\n/**\n * A batch of records with a stable id used for server-side deduplication across retries.\n * @see {@link splitBatch}\n */\nexport interface LogBatch {\n /** Deduplication key. Stable across retries and reloads. */\n id: string;\n /** Records to deliver, in log order. */\n records: LogRecord[];\n /** Batch creation time, in epoch milliseconds. */\n createdAt: number;\n /** Delivery attempts so far. */\n attempts: number;\n}\n\n/**\n * Splits a batch the server rejected as too large into two halves.\n * Each half gets a fresh id; age and attempts carry over unchanged.\n * @param batch The rejected batch.\n * @returns Two batches, or `null` if a single record is already over the limit.\n */\nexport function splitBatch(batch: LogBatch): [LogBatch, LogBatch] | null {\n if (batch.records.length < 2) {\n return null;\n }\n\n const middle = Math.floor(batch.records.length / 2);\n const halve = (records: LogRecord[]): LogBatch => ({\n id: newId(),\n records,\n createdAt: batch.createdAt,\n attempts: batch.attempts,\n });\n\n return [halve(batch.records.slice(0, middle)), halve(batch.records.slice(middle))];\n}\n","// src/transport/retry-engine.ts\n//\n// Scheduled background redelivery of stored log batches using jittered exponential\n// backoff. One timer, never a chain. Every scheduling path clears the pending\n// timer first.\n\nimport { BATCHES_PER_DRAIN, DRAIN_LOCK_NAME } from \"../constants\";\nimport type { Diagnostics } from \"../core/diagnostics\";\nimport { type LogBatch, splitBatch } from \"../models/batch\";\nimport type { ResolvedConfig } from \"../models/config\";\nimport type { StorageAdapter } from \"../models/storage\";\nimport { withDrainLock } from \"../utils/lock\";\nimport { unrefTimer } from \"../utils/unref\";\nimport { TransportError } from \"./errors\";\nimport type { HttpTransport } from \"./http-transport\";\n\n/** Manages timed redelivery of persisted offline batches with backoff, lock coordination, and batch splitting. */\nexport class RetryEngine {\n /** Active retry timer handle or null if unreserved. */\n private timer: ReturnType<typeof setTimeout> | null = null;\n\n /** Consecutive failed delivery attempts for exponential backoff calculation. */\n private attempt = 0;\n\n /** Indicates whether a storage drain operation is actively executing. */\n private draining = false;\n\n /** Indicates whether the engine is stopped. */\n private stopped = false;\n\n /** Online event listener resetting attempts and scheduling immediate drain. */\n private readonly onOnline = (): void => {\n this.attempt = 0;\n this.schedule(0);\n };\n\n /**\n * @param storage Storage adapter holding undelivered batches.\n * @param transport HTTP transport for batch delivery.\n * @param diagnostics Diagnostics reporter.\n * @param config Active configuration instance.\n * @param batchesPerDrain Maximum batches processed per drain tick.\n */\n constructor(\n private readonly storage: StorageAdapter,\n private readonly transport: HttpTransport,\n private readonly diagnostics: Diagnostics,\n private readonly config: ResolvedConfig,\n private readonly batchesPerDrain = BATCHES_PER_DRAIN,\n ) {}\n\n /** Starts the retry engine, listens for online events, and arms the initial timer. */\n start(): void {\n this.stopped = false;\n\n if (typeof addEventListener !== \"undefined\") {\n addEventListener(\"online\", this.onOnline);\n }\n\n this.schedule(this.config.retry.idleDelayMs);\n }\n\n /** Triggers an accelerated retry schedule when a new batch is stored offline. */\n nudge(): void {\n if (!this.draining) {\n this.schedule(this.config.retry.baseDelayMs);\n }\n }\n\n /** Halts retry execution, removes listeners, and clears pending timers. */\n stop(): void {\n this.stopped = true;\n\n if (typeof removeEventListener !== \"undefined\") {\n removeEventListener(\"online\", this.onOnline);\n }\n\n this.clearTimer();\n }\n\n /**\n * Clears existing timers and schedules a new drain execution after a delay.\n * @param delayMs Delay duration in milliseconds.\n */\n private schedule(delayMs: number): void {\n if (this.stopped) {\n return;\n }\n\n this.clearTimer();\n\n const timer = setTimeout(() => {\n void this.drain();\n }, delayMs);\n\n this.timer = timer;\n unrefTimer(timer);\n }\n\n /** Clears the pending timer handle if active. */\n private clearTimer(): void {\n if (this.timer !== null) {\n clearTimeout(this.timer);\n this.timer = null;\n }\n }\n\n /**\n * Computes jittered exponential backoff delay based on consecutive failures. Full\n * jitter, not a fixed offset. Tabs reconnecting together stampede otherwise.\n * @returns Backoff duration in milliseconds.\n */\n private backoffMs(): number {\n const exponential = Math.min(\n this.config.retry.baseDelayMs * 2 ** this.attempt,\n this.config.retry.maxDelayMs,\n );\n\n return Math.random() * exponential;\n }\n\n /** Executes a drain operation protected by the origin-wide Web Lock. */\n private async drain(): Promise<void> {\n if (this.draining) {\n return;\n }\n this.draining = true;\n\n try {\n const ran = await withDrainLock(DRAIN_LOCK_NAME, this.diagnostics, () => this.drainLocked());\n\n // undefined means the lock was held elsewhere. Without the reschedule, one\n // lost race retires this window.\n if (ran !== true) {\n this.schedule(this.config.retry.idleDelayMs);\n }\n } finally {\n this.draining = false;\n }\n }\n\n /**\n * Processes batches while holding the Web Lock and schedules subsequent ticks.\n * Always resolves. A throw leaves the engine idle with no timer armed.\n * @returns Promise resolving to true on completion.\n */\n private async drainLocked(): Promise<true> {\n try {\n const online = (globalThis as { navigator?: { onLine?: boolean } }).navigator?.onLine;\n if (online === false) {\n this.schedule(this.config.retry.idleDelayMs);\n return true;\n }\n\n const batches = await this.storage.take(this.batchesPerDrain);\n\n if (batches.length === 0) {\n this.schedule(this.config.retry.idleDelayMs);\n return true;\n }\n\n for (const batch of batches) {\n if (this.stopped) {\n return true;\n }\n\n const done = await this.deliver(batch);\n if (!done) {\n return true;\n }\n }\n\n this.schedule(batches.length === this.batchesPerDrain ? 0 : this.config.retry.idleDelayMs);\n return true;\n } catch (error) {\n this.diagnostics.report(\"storage.degraded\", \"the drain loop threw\", undefined, error);\n this.attempt++;\n this.schedule(this.backoffMs());\n return true;\n }\n }\n\n /**\n * Attempts delivery of a single batch, removing it on success or handling errors.\n * @param batch Log batch to deliver.\n * @returns True to continue processing next batch; false to halt current drain.\n */\n private async deliver(batch: LogBatch): Promise<boolean> {\n if (batch.attempts >= this.config.storage.maxAttempts) {\n this.diagnostics.report(\n \"storage.dead_lettered\",\n `giving up on a batch after ${batch.attempts.toString()} attempts`,\n { batchId: batch.id, records: batch.records.length },\n );\n await this.storage.remove(batch.id);\n return true;\n }\n\n try {\n await this.transport.send(batch);\n await this.storage.remove(batch.id);\n this.attempt = 0;\n return true;\n } catch (error) {\n const failure = error instanceof TransportError ? error : undefined;\n\n if (failure?.kind === \"permanent\") {\n await this.storage.remove(batch.id);\n return true;\n }\n\n if (failure?.kind === \"too_large\") {\n await this.splitStored(batch, failure.maxBytes);\n return true;\n }\n\n if (failure?.kind === \"offline\") {\n this.schedule(this.config.retry.idleDelayMs);\n return false;\n }\n\n await this.storage.bumpAttempts(batch.id, batch.attempts + 1);\n this.attempt++;\n this.schedule(failure?.retryAfterMs ?? this.backoffMs());\n return false;\n }\n }\n\n /**\n * Splits an oversized batch into two smaller stored batches after a 413 rejection.\n * @param batch Rejected log batch.\n * @param serverMaxBytes Optional byte limit reported by the server.\n */\n private async splitStored(batch: LogBatch, serverMaxBytes: number | undefined): Promise<void> {\n const halves = splitBatch(batch);\n await this.storage.remove(batch.id);\n\n if (!halves) {\n this.diagnostics.report(\n \"transport.dropped_permanent\",\n \"a single record exceeds the server limit and was dropped\",\n {\n batchId: batch.id,\n bodies: batch.records.map((record) => record.body),\n },\n );\n return;\n }\n\n this.diagnostics.report(\"transport.batch_split\", \"the server refused the batch as too large\", {\n from: batch.records.length,\n to: halves[0].records.length,\n serverMaxBytes,\n });\n\n for (const half of halves) {\n await this.storage.save(half);\n }\n }\n}\n","// src/utils/console.ts\n//\n// Formats and mirrors log records to the developer console during local execution\n\nimport { CONSOLE_PREFIX_STYLE, LEVEL_ORDER, LIBRARY_LOG_PREFIX } from \"../constants\";\nimport type { LogLevel } from \"../models/log-record\";\n\n/** Maps log levels to corresponding console method names. */\nconst METHOD: Record<LogLevel, \"debug\" | \"info\" | \"warn\" | \"error\"> = {\n TRACE: \"debug\",\n DEBUG: \"debug\",\n INFO: \"info\",\n WARN: \"warn\",\n ERROR: \"error\",\n FATAL: \"error\",\n};\n\n/** Mirrors log records directly to browser or Node console methods based on severity. */\nexport class ConsoleSink {\n /**\n * @param enabled Indicates whether console mirroring is active.\n * @param minLevel Minimum log level required to emit to the console.\n */\n constructor(\n private enabled: boolean,\n private minLevel: LogLevel,\n ) {}\n\n /**\n * Updates console sink configuration settings.\n * @param enabled Indicates whether console mirroring is active.\n * @param minLevel Minimum log level required to emit to the console.\n */\n update(enabled: boolean, minLevel: LogLevel): void {\n this.enabled = enabled;\n this.minLevel = minLevel;\n }\n\n /**\n * Emits a styled log record to the console if severity clears the configured threshold.\n * @param level Severity level of the record.\n * @param message Primary log message.\n * @param payload Optional contextual payload or object reference.\n */\n write(level: LogLevel, message: string, payload?: unknown): void {\n if (!this.enabled) {\n return;\n }\n if (LEVEL_ORDER[level] < LEVEL_ORDER[this.minLevel]) {\n return;\n }\n // Prevents throws in environments where console is undefined. Absent in a worker\n // realm stripped of it.\n if (typeof console === \"undefined\") {\n return;\n }\n\n const prefix = `%c${LIBRARY_LOG_PREFIX}%c ${level}`;\n if (payload === undefined) {\n console[METHOD[level]](prefix, CONSOLE_PREFIX_STYLE, \"\", message);\n return;\n }\n\n console[METHOD[level]](prefix, CONSOLE_PREFIX_STYLE, \"\", message, payload);\n }\n}\n","// src/utils/platform.ts\n//\n// Detects host platform capabilities, OpenFin container metadata, and worker\n// execution realms. Cached: nothing here changes for the lifetime of a realm.\n// Order matters, a webview is also a browser and is tested first.\n\nimport {\n ANDROID_WEBVIEW_UA_PATTERN,\n IOS_DEVICE_UA_PATTERN,\n MACINTOSH_UA_PATTERN,\n MOBILE_UA_PATTERN,\n OPENFIN_UA_PATTERN,\n SAFARI_UA_TOKEN,\n WEBKIT_UA_TOKEN,\n} from \"../constants\";\nimport type { Diagnostics } from \"../core/diagnostics\";\n\n/** Host runtime environment classification attached to resource attributes. */\nexport type PlatformType =\n | \"openfin\"\n | \"openfin_web\"\n | \"browser\"\n | \"mobile_webview\"\n | \"ionic\"\n | \"web_worker\"\n | \"shared_worker\"\n | \"service_worker\"\n | \"node\";\n\n/** Host environment and runtime container metadata resolved at startup. */\nexport interface PlatformMetadata {\n /** Detected platform runtime classification. */\n platform: PlatformType;\n /** OpenFin application UUID if running inside an OpenFin container. */\n openfinUuid?: string;\n /** OpenFin window or view identifier. */\n openfinName?: string;\n /** Raw navigator user agent string or empty string if unavailable. */\n userAgent: string;\n /** Indicates whether execution occurs inside any worker realm. */\n isWorker: boolean;\n /** Indicates whether this context is the top-level document rather than an iframe. */\n isTopLevelDocument: boolean;\n}\n\n/** Indexed globalThis type for probing runtime globals. */\ntype Global = typeof globalThis & Record<string, unknown>;\n\n/** Cached platform metadata instance. */\nlet cached: PlatformMetadata | null = null;\n\n/** Abstract constructor type for global scope prototype checks. */\ntype ScopeConstructor = abstract new (...args: never[]) => object;\n\n/**\n * Evaluates whether globalThis is an instance of a specified global scope constructor.\n * @param g Global scope object.\n * @param name Scope constructor name to check.\n * @returns True if globalThis inherits from the named scope constructor.\n */\nfunction isGlobalScope(g: Global, name: string): boolean {\n const scope = g[name];\n if (scope === undefined) {\n return false;\n }\n return g instanceof (scope as ScopeConstructor);\n}\n\n/** Structural interface for OpenFin identity inspection. */\ninterface FinLike {\n me?: { identity?: { uuid?: string; name?: string } };\n}\n\n/**\n * Detects and caches host platform metadata for the active realm.\n * @param diagnostics Diagnostics reporter.\n * @returns Detected PlatformMetadata.\n */\nexport function detectPlatform(diagnostics: Diagnostics): PlatformMetadata {\n if (cached) {\n return cached;\n }\n const g = globalThis as Global;\n\n const ua = (g.navigator as Navigator | undefined)?.userAgent ?? \"\";\n let platform: PlatformType = \"browser\";\n let openfinUuid: string | undefined;\n let openfinName: string | undefined;\n let isWorker = false;\n\n const finMe = (g.fin as FinLike | undefined)?.me;\n\n if (isGlobalScope(g, \"ServiceWorkerGlobalScope\")) {\n platform = \"service_worker\";\n isWorker = true;\n } else if (isGlobalScope(g, \"SharedWorkerGlobalScope\")) {\n platform = \"shared_worker\";\n isWorker = true;\n } else if (isGlobalScope(g, \"WorkerGlobalScope\")) {\n platform = \"web_worker\";\n isWorker = true;\n } else if (finMe !== undefined) {\n platform = OPENFIN_UA_PATTERN.test(ua) ? \"openfin\" : \"openfin_web\";\n diagnostics.guard(\"openfin.unavailable\", \"reading fin.me.identity\", () => {\n const identity = finMe.identity;\n openfinUuid = identity?.uuid;\n openfinName = identity?.name;\n });\n } else if (g.Capacitor !== undefined || g.Ionic !== undefined) {\n platform = \"ionic\";\n } else if (g.cordova !== undefined || isWebView(ua)) {\n platform = \"mobile_webview\";\n } else if (typeof document === \"undefined\" && typeof process !== \"undefined\") {\n platform = \"node\";\n }\n\n cached = {\n platform,\n openfinUuid,\n openfinName,\n userAgent: ua,\n isWorker,\n isTopLevelDocument: isTopLevel(),\n };\n return cached;\n}\n\n/**\n * Evaluates whether a user agent string represents an embedded mobile webview.\n * @param ua User agent string.\n * @returns True if user agent matches Android or iOS webview signatures.\n */\nfunction isWebView(ua: string): boolean {\n if (ANDROID_WEBVIEW_UA_PATTERN.test(ua)) {\n return true;\n }\n const ios =\n IOS_DEVICE_UA_PATTERN.test(ua) || (MACINTOSH_UA_PATTERN.test(ua) && MOBILE_UA_PATTERN.test(ua));\n return ios && ua.includes(WEBKIT_UA_TOKEN) && !ua.includes(SAFARI_UA_TOKEN);\n}\n\n/**\n * Determines whether the current window is the top-level browsing context.\n * @returns True if top-level, false if framed or inaccessible due to cross-origin boundaries.\n */\nexport function isTopLevel(): boolean {\n if (typeof window === \"undefined\") {\n return false;\n }\n try {\n return window.self === window.top;\n } catch {\n return false;\n }\n}\n\n/**\n * Retrieves the current document URL without caching.\n * @returns Current location.href or empty string.\n */\nexport function currentUrl(): string {\n try {\n return typeof location !== \"undefined\" ? location.href : \"\";\n } catch {\n return \"\";\n }\n}\n\n/** Resets the cached platform metadata for testing. */\nexport function resetPlatformCache(): void {\n cached = null;\n}\n","// src/utils/sequence.ts\n//\n// Generates monotonic sequence numbers for deterministic per-context record\n// ordering. Clocks step and two records share a millisecond, so timestamps cannot\n// order them. One counter per context: a shared counter shows holes, and a hole\n// reads as a lost record.\n\n/** Monotonic sequence counter establishing total record ordering within an execution context. */\nexport class Sequence {\n /** Last emitted sequence counter value. */\n private value = 0;\n\n /**\n * Increments and returns the next monotonic sequence number starting at 1.\n * @returns Next sequence number.\n */\n next(): number {\n return ++this.value;\n }\n\n /**\n * Resets the sequence counter to zero, for a runtime configured afresh.\n * Continuing the count implies continuity with the previous run.\n */\n reset(): void {\n this.value = 0;\n }\n}\n","// src/utils/tracing.ts\n//\n// Manages ambient distributed tracing contexts, OpenTelemetry span integration, and W3C traceparent headers.\n// One trace id spans consecutive records. Minting one per record gives every\n// trace exactly one span.\n\nimport {\n isSpanContextValid,\n context as otelContext,\n trace as otelTrace,\n propagation,\n} from \"@opentelemetry/api\";\nimport {\n SPAN_ID_BYTES,\n TRACE_FLAGS_MASK,\n TRACE_FLAGS_SAMPLED,\n TRACE_ID_BYTES,\n TRACE_MAX_AGE_MS,\n TRACEPARENT_VERSION,\n} from \"../constants\";\nimport type { Diagnostics } from \"../core/diagnostics\";\nimport { randomHex } from \"./identity\";\n\n/** W3C trace context fields attached to log records and network headers. */\nexport interface TraceContext {\n /** Hexadecimal 32-character W3C trace identifier. */\n traceId: string;\n /** Hexadecimal 16-character W3C span identifier. */\n spanId: string;\n /** Bitfield byte containing W3C trace flags. */\n traceFlags: number;\n}\n\n/** Trigger classification for rotating the ambient trace context. */\nexport type RotateReason = \"start\" | \"interaction\" | \"navigation\" | \"explicit\" | \"maxAge\";\n\n/** Internal trace context tracking creation timestamp for expiration. */\ninterface AmbientTrace extends TraceContext {\n /** Creation timestamp in epoch milliseconds. */\n startedAt: number;\n}\n\n/**\n * Generates a random 32-character hex string conforming to W3C trace ID format.\n * Exported for callers starting their own trace. A wrong-width id is dropped by\n * the backend without a word.\n * @returns 32-character hexadecimal trace ID.\n */\nexport function newTraceId(): string {\n return randomHex(TRACE_ID_BYTES);\n}\n\n/**\n * Generates a random 16-character hex string conforming to W3C span ID format.\n * @returns 16-character hexadecimal span ID.\n */\nexport function newSpanId(): string {\n return randomHex(SPAN_ID_BYTES);\n}\n\n/**\n * Creates a new AmbientTrace instance with sampled trace flag enabled. Set\n * unconditionally: sampling runs before the record is built.\n * @returns Initialized AmbientTrace object.\n */\nfunction mintAmbient(): AmbientTrace {\n return {\n traceId: newTraceId(),\n spanId: newSpanId(),\n traceFlags: TRACE_FLAGS_SAMPLED,\n startedAt: Date.now(),\n };\n}\n\n/**\n * Creates a defensive copy of a TraceContext from an AmbientTrace.\n * @param ambient Source ambient trace object.\n * @returns Defensive copy of TraceContext.\n */\nfunction toTraceContext(ambient: AmbientTrace): TraceContext {\n return {\n traceId: ambient.traceId,\n spanId: ambient.spanId,\n traceFlags: ambient.traceFlags,\n };\n}\n\n/** Manages ambient distributed trace contexts and resolves active OpenTelemetry spans. */\nexport class TraceEngine {\n /**\n * Active ambient trace context. Instance state, never module state. Two runtimes\n * in one document must not share a trace id.\n */\n private ambient: AmbientTrace = mintAmbient();\n\n /**\n * @param diagnostics Diagnostics reporter.\n * @param maxAgeMs Maximum lifetime of an un-rotated ambient trace in milliseconds.\n */\n constructor(\n private readonly diagnostics: Diagnostics,\n private readonly maxAgeMs = TRACE_MAX_AGE_MS,\n ) {}\n\n /**\n * Resolves trace context, prioritizing active OpenTelemetry spans over the ambient trace.\n * @returns Active TraceContext.\n */\n resolve(): TraceContext {\n const fromOtel = this.diagnostics.guard(\n \"trace.otel_failed\",\n \"reading the active OpenTelemetry span\",\n (): TraceContext | undefined => {\n const span = otelTrace.getActiveSpan();\n if (span === undefined) {\n return undefined;\n }\n const spanContext = span.spanContext();\n if (!isSpanContextValid(spanContext)) {\n return undefined;\n }\n return {\n traceId: spanContext.traceId,\n spanId: spanContext.spanId,\n traceFlags: spanContext.traceFlags,\n };\n },\n );\n if (fromOtel !== undefined) {\n return fromOtel;\n }\n\n // Rotates ambient trace if age exceeds maxAgeMs. Checked on read, not on a\n // timer. A timer holds this instance alive for the life of the document.\n if (Date.now() - this.ambient.startedAt > this.maxAgeMs) {\n this.rotate(\"maxAge\");\n }\n return toTraceContext(this.ambient);\n }\n\n /**\n * Rotates the ambient trace context to mark the start of a new logical operation.\n * @param _reason Event reason triggering the rotation.\n * @returns Newly created TraceContext.\n */\n rotate(_reason: RotateReason): TraceContext {\n this.ambient = mintAmbient();\n return toTraceContext(this.ambient);\n }\n\n /**\n * Generates W3C traceparent headers using registered OpenTelemetry propagators or ambient fallback.\n * @returns Header map containing traceparent.\n */\n headers(): Record<string, string> {\n const carrier: Record<string, string> = {};\n this.diagnostics.guard(\"trace.otel_failed\", \"injecting OpenTelemetry headers\", () => {\n propagation.inject(otelContext.active(), carrier);\n });\n if (!carrier.traceparent) {\n const ctx = this.resolve();\n // Masks trace flags to 2-digit hex byte per W3C specification. trace-flags is\n // a bitfield, not a boolean. 00 or 01 discards what an upstream tracer set.\n const flags = (ctx.traceFlags & TRACE_FLAGS_MASK).toString(16).padStart(2, \"0\");\n carrier.traceparent = `${TRACEPARENT_VERSION}-${ctx.traceId}-${ctx.spanId}-${flags}`;\n }\n return carrier;\n }\n}\n","// src/core/breadcrumbs.ts\n//\n// Ring buffer holding a bounded chronological trail of recent user and system\n// events. Crumbs are never sent as records. They reach the backend on an error\n// record's payload. Nothing here throws.\n\nimport { BREADCRUMB_MIN_CAPACITY } from \"../constants\";\n\n/** Category classification for breadcrumb events. */\nexport type BreadcrumbCategory =\n \"log\" | \"action\" | \"event\" | \"click\" | \"navigation\" | \"http\" | \"console\";\n\n/** Lightweight event summary recorded prior to errors. */\nexport interface Breadcrumb {\n /** Timestamp in epoch milliseconds. */\n t: number;\n /** Event category classification. */\n category: BreadcrumbCategory;\n /** Human-readable event description. */\n message: string;\n /** Optional contextual metadata. */\n data?: Record<string, unknown>;\n}\n\n/** Bounded circular ring buffer storing recent breadcrumb events in chronological order. */\nexport class BreadcrumbBuffer {\n /** Internal storage array for the ring buffer. */\n private buffer: (Breadcrumb | undefined)[];\n\n /** Next write index in the circular buffer. */\n private pointer = 0;\n\n /**\n * Indicates whether the buffer has wrapped around its capacity. The pointer alone\n * cannot separate an unwritten ring from one wrapped exactly to the start.\n */\n private filled = false;\n\n /** Maximum number of breadcrumbs retained in memory. */\n private capacity: number;\n\n /**\n * @param capacity Maximum breadcrumb capacity, clamped to minimum allowed size.\n */\n constructor(capacity: number) {\n this.capacity = Math.max(capacity, BREADCRUMB_MIN_CAPACITY);\n this.buffer = new Array<Breadcrumb | undefined>(this.capacity);\n }\n\n /**\n * Resizes buffer capacity while preserving the newest breadcrumbs.\n * @param capacity New maximum capacity.\n */\n resize(capacity: number): void {\n const clamped = Math.max(capacity, BREADCRUMB_MIN_CAPACITY);\n if (clamped === this.capacity) {\n return;\n }\n\n // The clamp guarantees a positive count. slice(-0) keeps the whole trail.\n const kept = this.snapshot().slice(-clamped);\n this.capacity = clamped;\n this.clear();\n for (const crumb of kept) {\n this.push(crumb);\n }\n }\n\n /**\n * Appends a breadcrumb, overwriting the oldest entry when capacity is reached.\n * @param crumb Breadcrumb event to append.\n */\n push(crumb: Breadcrumb): void {\n this.buffer[this.pointer] = crumb;\n this.pointer = (this.pointer + 1) % this.capacity;\n if (this.pointer === 0) {\n this.filled = true;\n }\n }\n\n /**\n * Returns all stored breadcrumbs ordered from oldest to newest.\n * @returns Chronological list of breadcrumbs.\n */\n snapshot(): Breadcrumb[] {\n const ordered = this.filled\n ? [...this.buffer.slice(this.pointer), ...this.buffer.slice(0, this.pointer)]\n : this.buffer.slice(0, this.pointer);\n return ordered.filter((crumb): crumb is Breadcrumb => crumb !== undefined);\n }\n\n /** Clears all stored breadcrumbs and resets buffer state. */\n clear(): void {\n this.buffer = new Array<Breadcrumb | undefined>(this.capacity);\n this.pointer = 0;\n this.filled = false;\n }\n}\n","// src/transport/serializers/ecs.ts\n//\n// Serializes log batches into Elastic Common Schema (ECS) formatted newline-delimited JSON.\n\nimport {\n ATTR_PAGE_URL,\n ATTR_URL_FULL,\n CONTENT_TYPE_NDJSON,\n NANOS_PER_MILLI,\n RESOURCE_BROWSER_USER_AGENT,\n RESOURCE_DEPLOYMENT_ENVIRONMENT,\n RESOURCE_SERVICE_NAME,\n RESOURCE_SERVICE_VERSION,\n SERIALIZER_NAME_ECS,\n} from \"../../constants\";\nimport type { LogRecord } from \"../../models/log-record\";\nimport type { LogSerializer, SerializedBatch } from \"../../models/serializer\";\n\n/** Serializer formatting log records into Elastic Common Schema (ECS) NDJSON documents. */\nexport const ecsSerializer: LogSerializer = {\n /** Format identifier name. */\n name: SERIALIZER_NAME_ECS,\n\n /**\n * Serializes an array of log records into newline-delimited ECS JSON documents.\n * @param records Records to serialize.\n * @returns Serialized NDJSON batch payload.\n */\n serialize(records: LogRecord[]): SerializedBatch {\n const lines = records.map((record) => {\n // BigInt division preserves precision before conversion to millisecond Date.\n // No double holds a nanosecond epoch exactly.\n const millis = Number(BigInt(record.timeUnixNano) / NANOS_PER_MILLI);\n\n return JSON.stringify({\n \"@timestamp\": new Date(millis).toISOString(),\n message: record.body,\n log: { level: record.severityText.toLowerCase() },\n trace: { id: record.traceId },\n span: { id: record.spanId },\n service: {\n name: record.resource[RESOURCE_SERVICE_NAME],\n version: record.resource[RESOURCE_SERVICE_VERSION],\n environment: record.resource[RESOURCE_DEPLOYMENT_ENVIRONMENT],\n },\n user_agent: { original: record.resource[RESOURCE_BROWSER_USER_AGENT] },\n // Prefers request URL over ambient page URL for captured network events.\n url: {\n full: record.attributes[ATTR_URL_FULL] ?? record.attributes[ATTR_PAGE_URL],\n },\n labels: { ...record.resource, ...record.attributes },\n });\n });\n\n return { body: `${lines.join(\"\\n\")}\\n`, contentType: CONTENT_TYPE_NDJSON };\n },\n};\n","// src/transport/serializers/otlp.ts\n//\n// Serializes log batches into OpenTelemetry (OTLP/JSON) formatted log records grouped by resource.\n\nimport {\n CONTENT_TYPE_JSON,\n SERIALIZER_NAME_OTLP,\n TELEMETRY_SDK_NAME,\n TELEMETRY_SDK_VERSION,\n} from \"../../constants\";\nimport type { LogRecord } from \"../../models/log-record\";\nimport type { LogSerializer, SerializedBatch } from \"../../models/serializer\";\n\n/** OTLP AnyValue container with typed value wrappers. */\ntype AnyValue = Record<string, unknown>;\n\n/** OTLP KeyValue pair container. */\ninterface KeyValue {\n /** Attribute key. */\n key: string;\n /** Typed AnyValue container. */\n value: AnyValue;\n}\n\n/** Records grouped by shared resource attributes. */\ninterface ResourceGroup {\n /** Resource attribute map. */\n resource: Record<string, unknown>;\n /** Log records associated with the resource. */\n records: LogRecord[];\n}\n\n/**\n * Wraps a JavaScript value in an OTLP AnyValue container.\n * @param value Raw attribute or resource value.\n * @returns Typed AnyValue object or null if unsupported.\n */\nfunction toAnyValue(value: unknown): AnyValue | null {\n if (value === null || value === undefined) {\n return null;\n }\n\n if (typeof value === \"string\") {\n return { stringValue: value };\n }\n\n if (typeof value === \"boolean\") {\n return { boolValue: value };\n }\n\n // Encodes int64 as decimal strings per OTLP protobuf JSON specification. A number\n // is a silent 400 from a conforming collector.\n if (typeof value === \"number\") {\n return Number.isInteger(value) ? { intValue: String(value) } : { doubleValue: value };\n }\n\n // Converts BigInt to decimal string representation for JSON serialization.\n // JSON.stringify throws on a BigInt and loses the batch.\n if (typeof value === \"bigint\") {\n return { intValue: value.toString() };\n }\n\n if (Array.isArray(value)) {\n const items: readonly unknown[] = value;\n const values = items.map(toAnyValue).filter((item): item is AnyValue => item !== null);\n\n return { arrayValue: { values } };\n }\n\n if (typeof value === \"object\") {\n const nested = value as Record<string, unknown>;\n return { kvlistValue: { values: toKeyValues(nested) } };\n }\n\n return null;\n}\n\n/**\n * Converts a plain object into an array of OTLP KeyValue pairs.\n * @param source Key-value attribute object.\n * @returns Array of valid KeyValue pairs.\n */\nfunction toKeyValues(source: Record<string, unknown>): KeyValue[] {\n const out: KeyValue[] = [];\n\n for (const [key, raw] of Object.entries(source)) {\n const value = toAnyValue(raw);\n if (value) {\n out.push({ key, value });\n }\n }\n\n return out;\n}\n\n/** Memoized JSON string keys per resource object to avoid redundant stringification. */\nconst resourceKeys = new WeakMap<object, string>();\n\n/**\n * Computes or retrieves a stable serialization key for a resource object.\n * @param resource Resource attribute object.\n * @returns JSON key string.\n */\nfunction resourceKey(resource: Record<string, unknown>): string {\n const cached = resourceKeys.get(resource);\n if (cached !== undefined) {\n return cached;\n }\n\n const key = JSON.stringify(resource);\n resourceKeys.set(resource, key);\n\n return key;\n}\n\n/** Serializer formatting log records into OTLP/JSON payloads. */\nexport const otlpSerializer: LogSerializer = {\n /** Format identifier name. */\n name: SERIALIZER_NAME_OTLP,\n\n /**\n * Groups records by resource and encodes them into an OTLP ExportLogsServiceRequest JSON payload.\n * @param records Array of log records to serialize.\n * @returns Serialized JSON batch payload.\n */\n serialize(records: LogRecord[]): SerializedBatch {\n const groups = new Map<string, ResourceGroup>();\n\n for (const record of records) {\n const key = resourceKey(record.resource);\n const group = groups.get(key);\n\n if (group) {\n group.records.push(record);\n continue;\n }\n\n groups.set(key, { resource: record.resource, records: [record] });\n }\n\n const resourceLogs = [...groups.values()].map((group) => ({\n resource: { attributes: toKeyValues(group.resource) },\n scopeLogs: [\n {\n scope: { name: TELEMETRY_SDK_NAME, version: TELEMETRY_SDK_VERSION },\n logRecords: group.records.map((record) => ({\n timeUnixNano: record.timeUnixNano,\n // Falls back to timeUnixNano if observedTimeUnixNano is unset.\n observedTimeUnixNano: record.observedTimeUnixNano ?? record.timeUnixNano,\n severityNumber: record.severityNumber,\n severityText: record.severityText,\n body: { stringValue: record.body },\n traceId: record.traceId,\n spanId: record.spanId,\n flags: record.traceFlags,\n attributes: toKeyValues(record.attributes),\n })),\n },\n ],\n }));\n\n return {\n body: JSON.stringify({ resourceLogs }),\n contentType: CONTENT_TYPE_JSON,\n };\n },\n};\n","// src/core/config.ts\n//\n// Resolves partial consumer options into validated configuration objects and updates live instances.\n// Two rules, both failing silently when broken:\n// 1. A reconfigure merges onto the config in force, not onto the defaults.\n// 2. The resolved object is mutated, never replaced. Subsystems hold the\n// reference from construction.\n// Nothing here throws into the caller.\n\nimport {\n CONFIG_SECTIONS,\n DEFAULT_CONFIG,\n SAMPLING_RATE_FALLBACK,\n SAMPLING_RATE_MAX,\n SAMPLING_RATE_MIN,\n SERIALIZER_NAME_ECS,\n SERIALIZER_NAME_OTLP,\n UNDEFAULTED_CONFIG_KEYS,\n UNKNOWN_SERVICE_NAME,\n} from \"../constants\";\nimport type { ObservabilityConfig, ResolvedConfig } from \"../models/config\";\nimport type { LogSerializer } from \"../models/serializer\";\nimport { ecsSerializer } from \"../transport/serializers/ecs\";\nimport { otlpSerializer } from \"../transport/serializers/otlp\";\nimport type { Diagnostics } from \"./diagnostics\";\n\n/**\n * Type guard verifying if an object implements the LogSerializer interface.\n * @param value Value to check.\n * @returns True if value implements serialize.\n */\nfunction isSerializer(value: unknown): value is LogSerializer {\n if (typeof value !== \"object\" || value === null) {\n return false;\n }\n const serialize: unknown = Reflect.get(value, \"serialize\");\n return typeof serialize === \"function\";\n}\n\n/**\n * Resolves serializer selection to a valid LogSerializer instance.\n * @param requested Serializer name or custom serializer implementation.\n * @param previous Previously resolved serializer instance.\n * @param diagnostics Diagnostics reporter.\n * @returns Resolved LogSerializer instance.\n */\nfunction resolveSerializer(\n requested: unknown,\n previous: LogSerializer | undefined,\n diagnostics: Diagnostics,\n): LogSerializer {\n if (requested === undefined) {\n return previous ?? otlpSerializer;\n }\n if (requested === SERIALIZER_NAME_OTLP) {\n return otlpSerializer;\n }\n if (requested === SERIALIZER_NAME_ECS) {\n return ecsSerializer;\n }\n if (isSerializer(requested)) {\n return requested;\n }\n\n diagnostics.report(\n \"config.invalid\",\n `serializer must be \"${SERIALIZER_NAME_OTLP}\", \"${SERIALIZER_NAME_ECS}\" or an implementation`,\n );\n return otlpSerializer;\n}\n\n/**\n * Resolves partial configuration inputs into a validated ResolvedConfig object.\n * @param input Partial consumer configuration options.\n * @param diagnostics Diagnostics reporter.\n * @param previous Active configuration instance for incremental reconfigurations.\n * @returns Fully populated and validated configuration object.\n */\nexport function resolveConfig(\n input: Partial<ObservabilityConfig>,\n diagnostics: Diagnostics,\n previous?: ResolvedConfig,\n): ResolvedConfig {\n const base = previous ?? DEFAULT_CONFIG;\n\n const merged: ResolvedConfig = {\n ...base,\n ...input,\n // Serializer instance overrides string identifier after object merge.\n serializer: resolveSerializer(input.serializer, previous?.serializer, diagnostics),\n streams: {\n logs: { ...base.streams.logs, ...input.streams?.logs },\n metrics: { ...base.streams.metrics, ...input.streams?.metrics },\n },\n storage: { ...base.storage, ...input.storage },\n retry: { ...base.retry, ...input.retry },\n sampling: {\n ...base.sampling,\n ...input.sampling,\n rates: { ...base.sampling.rates, ...input.sampling?.rates },\n },\n journey: { ...base.journey, ...input.journey },\n bus: { ...base.bus, ...input.bus },\n capture: { ...base.capture, ...input.capture },\n limits: { ...base.limits, ...input.limits },\n console: { ...base.console, ...input.console },\n };\n\n if (!merged.endpoint) {\n diagnostics.report(\n \"config.invalid\",\n \"endpoint is missing. Records will be built and dropped, never sent.\",\n );\n } else {\n try {\n new URL(merged.endpoint);\n } catch (error) {\n diagnostics.report(\n \"config.invalid\",\n `endpoint is not a valid absolute URL: ${merged.endpoint}`,\n undefined,\n error,\n );\n }\n }\n\n if (!merged.serviceName) {\n diagnostics.report(\n \"config.invalid\",\n `serviceName is missing. Every record will report service.name as '${UNKNOWN_SERVICE_NAME}'.`,\n );\n merged.serviceName = UNKNOWN_SERVICE_NAME;\n }\n\n const rate: unknown = merged.sampling.defaultRate;\n if (typeof rate !== \"number\" || rate < SAMPLING_RATE_MIN || rate > SAMPLING_RATE_MAX) {\n diagnostics.report(\"config.invalid\", `sampling.defaultRate must be 0..1, got ${String(rate)}`);\n merged.sampling.defaultRate = SAMPLING_RATE_FALLBACK;\n }\n\n const rates: [string, unknown][] = Object.entries(merged.sampling.rates);\n for (const [ns, r] of rates) {\n if (typeof r !== \"number\" || r < SAMPLING_RATE_MIN || r > SAMPLING_RATE_MAX) {\n diagnostics.report(\n \"config.invalid\",\n `sampling.rates[\"${ns}\"] must be 0..1, got ${String(r)}`,\n );\n merged.sampling.rates[ns] = SAMPLING_RATE_FALLBACK;\n }\n }\n\n // Replaces previous endpoint in ignore list to prevent self-logging loops. One\n // failed POST would otherwise log another, forever.\n merged.capture.ignoreUrls = merged.capture.ignoreUrls.filter((url) => url !== previous?.endpoint);\n if (merged.endpoint && !merged.capture.ignoreUrls.includes(merged.endpoint)) {\n merged.capture.ignoreUrls = [...merged.capture.ignoreUrls, merged.endpoint];\n }\n\n // Validates top-level keys against known schema to detect configuration typos.\n // remoteUrl instead of endpoint is otherwise accepted in silence.\n const known = new Set<string>([...Object.keys(DEFAULT_CONFIG), ...UNDEFAULTED_CONFIG_KEYS]);\n for (const key of Object.keys(input)) {\n if (!known.has(key)) {\n diagnostics.report(\"config.invalid\", `unknown config key \"${key}\", ignored. Typo?`);\n }\n }\n\n return merged;\n}\n\n/**\n * Mutates an existing configuration object in place to propagate updates to referenced sections.\n * @param target Active configuration object to mutate.\n * @param next Source configuration object containing updated values.\n */\nexport function applyResolvedConfig(target: ResolvedConfig, next: ResolvedConfig): void {\n for (const key of Object.keys(next) as (keyof ResolvedConfig)[]) {\n // Cast widens tuple so includes accepts arbitrary string keys. satisfies leaves\n // it narrow and every non-section key fails to compile.\n if ((CONFIG_SECTIONS as readonly string[]).includes(key)) {\n continue;\n }\n Object.assign(target, { [key]: next[key] });\n }\n\n // Merges section objects in place to preserve object references. A new object\n // leaves subsystems on the section captured at construction.\n for (const section of CONFIG_SECTIONS) {\n Object.assign(target[section] as object, next[section] as object);\n }\n}\n","// src/core/context.ts\n//\n// Stores ambient contextual attributes merged into all subsequent log records.\n// Per instance, never module level. A module Map is shared by every runtime in the\n// realm.\n\n/** Key-value store for ambient context attributes attached to log records. */\nexport class ContextStore {\n /** Backing store mapping attribute keys to raw values. */\n private readonly map = new Map<string, unknown>();\n\n /**\n * Sets an ambient context attribute key and value.\n * @param key Attribute key.\n * @param value Raw attribute value.\n */\n set(key: string, value: unknown): void {\n this.map.set(key, value);\n }\n\n /**\n * Merges multiple key-value pairs into the ambient context store.\n * @param values Record of attributes to merge.\n */\n setMany(values: Record<string, unknown>): void {\n for (const [key, value] of Object.entries(values)) {\n this.map.set(key, value);\n }\n }\n\n /**\n * Retrieves an attribute value by key.\n * @param key Attribute key.\n * @returns Stored attribute value or undefined if not set.\n */\n get(key: string): unknown {\n return this.map.get(key);\n }\n\n /**\n * Deletes an attribute from the ambient context store.\n * @param key Attribute key to remove.\n */\n remove(key: string): void {\n this.map.delete(key);\n }\n\n /** Clears all attributes from the ambient context store. */\n clear(): void {\n this.map.clear();\n }\n\n /**\n * Returns a snapshot copy of all ambient context attributes. A copy: a merge\n * target or sanitizer must not mutate the store.\n * @returns Plain object containing stored key-value pairs.\n */\n getAll(): Record<string, unknown> {\n return Object.fromEntries(this.map);\n }\n}\n","// src/core/diagnostics.ts\n//\n// Internal telemetry error reporting, rate-limited emission, and cumulative event counters.\n\nimport { DIAGNOSTIC_THROTTLE_MS, LIBRARY_LOG_PREFIX } from \"../constants\";\n\n/** Closed set of diagnostic event codes emitted by library subsystems. */\nexport type DiagnosticCode =\n | \"config.invalid\"\n | \"config.reconfigured\"\n | \"record.sanitize_failed\"\n | \"record.truncated\"\n | \"record.dropped_by_level\"\n | \"record.dropped_by_sampling\"\n | \"record.dropped_by_redact\"\n | \"record.dropped_boot_buffer_full\"\n | \"record.dropped_pending_full\"\n | \"record.dropped_malformed\"\n | \"journey.expired\"\n | \"journey.adopted\"\n | \"journey.token_too_large\"\n | \"trace.otel_failed\"\n | \"bus.role_resolved\"\n | \"bus.no_owner\"\n | \"bus.handshake_timeout\"\n | \"bus.untrusted_origin\"\n | \"bus.send_failed\"\n | \"transport.http_error\"\n | \"transport.timeout\"\n | \"transport.batch_split\"\n | \"transport.throttled\"\n | \"transport.dropped_permanent\"\n | \"transport.rejected_credentials\"\n | \"transport.serialize_failed\"\n | \"storage.unavailable\"\n | \"storage.degraded\"\n | \"storage.quota_exceeded\"\n | \"storage.evicted\"\n | \"storage.dead_lettered\"\n | \"pipeline.crashed\"\n | \"capture.install_failed\"\n | \"capture.rate_limited\"\n | \"capture.header_failed\"\n | \"capture.record_failed\"\n | \"openfin.unavailable\"\n | \"handler.threw\";\n\n/** Diagnostic event payload dispatched to consumer handlers. */\nexport interface DiagnosticEvent {\n /** Diagnostic fault code. */\n code: DiagnosticCode;\n /** Human-readable description. */\n message: string;\n /** Structured context metadata. */\n detail?: Record<string, unknown>;\n /** Caught error instance or reason. */\n cause?: unknown;\n /** Event timestamp in epoch milliseconds. */\n at: number;\n /** Cumulative count of this code since startup, including rate-limited occurrences. */\n count: number;\n}\n\n/** Consumer callback for receiving rate-limited diagnostic events. */\nexport type DiagnosticHandler = (event: DiagnosticEvent) => void;\n\n/** Internal error reporting channel with rate-limited dispatch and unthrottled counters. */\nexport class Diagnostics {\n /** Running occurrence counts per diagnostic code. */\n private readonly counters = new Map<DiagnosticCode, number>();\n\n /** Timestamp of last emitted event per code in epoch milliseconds. */\n private readonly lastEmitted = new Map<DiagnosticCode, number>();\n\n /**\n * @param handler Optional diagnostic event listener callback.\n * @param throttleMs Minimum duration in milliseconds between emitted events for a single code.\n */\n constructor(\n private handler?: DiagnosticHandler,\n private readonly throttleMs = DIAGNOSTIC_THROTTLE_MS,\n ) {}\n\n /**\n * Updates or removes the active diagnostic event handler.\n * @param handler New diagnostic event handler.\n */\n setHandler(handler?: DiagnosticHandler): void {\n this.handler = handler;\n }\n\n /**\n * Increments the occurrence count for a code without triggering handler emission.\n * @param code Diagnostic code to increment.\n * @param by Increment delta.\n * @returns Updated cumulative total for the code.\n */\n count(code: DiagnosticCode, by = 1): number {\n const total = (this.counters.get(code) ?? 0) + by;\n this.counters.set(code, total);\n return total;\n }\n\n /**\n * Increments counter and dispatches event if outside the throttling window. Never throws.\n * @param code Diagnostic code.\n * @param message Event description.\n * @param detail Optional structured metadata.\n * @param cause Caught error instance or reason.\n */\n report(\n code: DiagnosticCode,\n message: string,\n detail?: Record<string, unknown>,\n cause?: unknown,\n ): void {\n const count = this.count(code);\n const now = Date.now();\n const last = this.lastEmitted.get(code) ?? 0;\n if (now - last < this.throttleMs) {\n return;\n }\n this.lastEmitted.set(code, now);\n\n const event: DiagnosticEvent = {\n code,\n message,\n detail,\n cause,\n at: now,\n count,\n };\n\n if (!this.handler) {\n return;\n }\n try {\n this.handler(event);\n } catch (handlerError) {\n // Increments counter without calling report() to avoid recursion on handler faults.\n this.count(\"handler.threw\");\n if (typeof console !== \"undefined\") {\n // eslint-disable-next-line no-console -- Fallback sink when diagnostic handler throws.\n console.warn(`${LIBRARY_LOG_PREFIX} onDiagnostic handler threw`, handlerError);\n }\n }\n }\n\n /**\n * Executes a synchronous function and reports any thrown error to diagnostics.\n * @param code Diagnostic code to report on throw.\n * @param message Error description.\n * @param fn Function to execute.\n * @returns Function return value, or undefined on throw.\n */\n guard<T>(code: DiagnosticCode, message: string, fn: () => T): T | undefined {\n try {\n return fn();\n } catch (error) {\n this.report(code, message, undefined, error);\n return undefined;\n }\n }\n\n /**\n * Executes an asynchronous function and reports any rejected promise to diagnostics.\n * @param code Diagnostic code to report on rejection.\n * @param message Error description.\n * @param fn Async function to execute.\n * @returns Promise resolving to the return value, or undefined on rejection.\n */\n async guardAsync<T>(\n code: DiagnosticCode,\n message: string,\n fn: () => Promise<T>,\n ): Promise<T | undefined> {\n try {\n return await fn();\n } catch (error) {\n this.report(code, message, undefined, error);\n return undefined;\n }\n }\n\n /**\n * Returns a copy of all cumulative diagnostic event counts since initialization.\n * @returns Map of diagnostic codes to occurrence counts.\n */\n snapshot(): Record<string, number> {\n return Object.fromEntries(this.counters);\n }\n\n /** Clears all counters and throttling history. */\n reset(): void {\n this.counters.clear();\n this.lastEmitted.clear();\n }\n}\n","// src/core/journey.ts\n//\n// Manages multi-window user journey lifecycles, token encoding, persistence, and expiration.\n// Nothing from storage or a token is trusted. Any code on the origin can write\n// either.\n\nimport {\n BASE64_GROUP_CHARS,\n BASE64_PADDING_PATTERN,\n BASE64_PLUS_PATTERN,\n BASE64_SLASH_PATTERN,\n BASE64URL_DASH_PATTERN,\n BASE64URL_UNDERSCORE_PATTERN,\n JOURNEY_STORAGE_KEY,\n JOURNEY_TOKEN_MAX_CHARS,\n JOURNEY_TOKEN_NAME_MAX_CHARS,\n OPENFIN_JOURNEY_CUSTOM_DATA_KEY,\n} from \"../constants\";\nimport type { JourneyOptions } from \"../models/config\";\nimport { newId } from \"../utils/identity\";\nimport { unrefTimer } from \"../utils/unref\";\nimport type { Diagnostics } from \"./diagnostics\";\n\n/** User journey workflow context shared across windows and applications. */\nexport interface Journey {\n /** Unique journey correlation identifier. */\n id: string;\n /** Human-readable journey workflow name. */\n name: string;\n /** Journey start timestamp in epoch milliseconds. */\n startedAt: number;\n /** Optional parent journey identifier when branched from an earlier workflow. */\n parentId?: string;\n /** Context identifier of the document that initiated the journey. */\n ownerContextId: string;\n}\n\n/** Structural interface for OpenFin window metadata. */\ninterface FinLike {\n /** Target OpenFin window or view. */\n me?: {\n /** Resolves initial window creation options including customData. */\n getOptions?: () => Promise<{ customData?: Record<string, unknown> }>;\n };\n}\n\n/** Global environment extended with optional OpenFin APIs. */\ntype OpenFinGlobal = typeof globalThis & { fin?: FinLike };\n\n/**\n * Safely extracts a non-empty string property from an unverified object.\n * @param source Object to read from.\n * @param key Property name.\n * @returns Non-empty string value or undefined.\n */\nfunction readString(source: object, key: string): string | undefined {\n const value: unknown = Reflect.get(source, key);\n return typeof value === \"string\" && value !== \"\" ? value : undefined;\n}\n\n/**\n * Safely extracts a finite numeric property from an unverified object.\n * @param source Object to read from.\n * @param key Property name.\n * @returns Finite number value or undefined.\n */\nfunction readNumber(source: object, key: string): number | undefined {\n const value: unknown = Reflect.get(source, key);\n return typeof value === \"number\" && Number.isFinite(value) ? value : undefined;\n}\n\n/**\n * Parses and validates raw sessionStorage data into a Journey object.\n * @param value Unverified parsed JSON value.\n * @returns Validated Journey instance or null.\n */\nfunction journeyFromStorage(value: unknown): Journey | null {\n if (typeof value !== \"object\" || value === null) {\n return null;\n }\n const id = readString(value, \"id\");\n const name = readString(value, \"name\");\n const startedAt = readNumber(value, \"startedAt\");\n if (id === undefined || name === undefined || startedAt === undefined) {\n return null;\n }\n return {\n id,\n name,\n startedAt,\n parentId: readString(value, \"parentId\"),\n ownerContextId: readString(value, \"ownerContextId\") ?? \"\",\n };\n}\n\n/**\n * Parses and validates decoded token payload into a Journey object.\n * @param value Unverified parsed token payload.\n * @returns Validated Journey instance or null.\n */\nfunction journeyFromTokenPayload(value: unknown): Journey | null {\n if (typeof value !== \"object\" || value === null) {\n return null;\n }\n const id = readString(value, \"i\");\n const name = readString(value, \"n\");\n if (id === undefined || name === undefined) {\n return null;\n }\n return {\n id,\n name,\n startedAt: readNumber(value, \"s\") ?? Date.now(),\n parentId: undefined,\n ownerContextId: \"\",\n };\n}\n\n/**\n * Encodes journey metadata into a compact, URL-safe base64 string.\n * @param journey Journey instance to serialize.\n * @returns Unpadded base64url encoded token string.\n */\nfunction encodeToken(journey: Journey): string {\n const json = JSON.stringify({\n i: journey.id,\n n: journey.name.slice(0, JOURNEY_TOKEN_NAME_MAX_CHARS),\n s: journey.startedAt,\n });\n // Binary string conversion handles multi-byte UTF-8 characters before btoa. btoa\n // throws above U+00FF, so a name in a non-Latin script fails without it.\n const bytes = new TextEncoder().encode(json);\n let binary = \"\";\n for (const byte of bytes) {\n binary += String.fromCharCode(byte);\n }\n return btoa(binary)\n .replace(BASE64_PLUS_PATTERN, \"-\")\n .replace(BASE64_SLASH_PATTERN, \"_\")\n .replace(BASE64_PADDING_PATTERN, \"\");\n}\n\n/** Manages journey lifecycle, cross-window adoption, storage synchronization, and expiration. */\nexport class JourneyEngine {\n /** Active journey context, or null if none is in progress. */\n private journey: Journey | null = null;\n\n /** Active expiration timer handle. */\n private expiryTimer: ReturnType<typeof setTimeout> | null = null;\n\n /**\n * @param options Journey configuration thresholds.\n * @param diagnostics Diagnostics reporter.\n * @param contextId Unique context identifier for this document.\n * @param onLocalChange Callback invoked when journey state changes locally.\n */\n constructor(\n private readonly options: JourneyOptions,\n private readonly diagnostics: Diagnostics,\n private readonly contextId: string,\n private readonly onLocalChange: (journey: Journey | null) => void,\n ) {}\n\n /** Returns the active journey instance or null. */\n current(): Journey | null {\n return this.journey;\n }\n\n /**\n * Discovers and adopts initial journey from URL query parameters, sessionStorage, or OpenFin customData.\n * @returns Promise resolving when journey initialization completes.\n */\n async bootstrap(): Promise<void> {\n const fromUrl = this.readUrlToken();\n if (fromUrl && this.adopt(fromUrl, \"url\")) {\n return;\n }\n\n const fromStorage = this.diagnostics.guard(\n \"storage.unavailable\",\n \"reading the persisted journey\",\n () => sessionStorage.getItem(JOURNEY_STORAGE_KEY),\n );\n if (fromStorage && this.restore(fromStorage)) {\n return;\n }\n\n const fromOpenFin = await this.readOpenFinToken();\n if (fromOpenFin !== null) {\n this.adopt(fromOpenFin, \"openfin.customData\");\n }\n }\n\n /**\n * Initiates a new journey, replacing any active journey and notifying connected peers.\n * @param name Human-readable workflow name.\n * @param opts Optional parent linkage and pre-assigned identifier.\n * @returns Started Journey instance.\n */\n start(name: string, opts: { parent?: boolean; id?: string } = {}): Journey {\n const journey: Journey = {\n id: opts.id ?? newId(),\n name,\n startedAt: Date.now(),\n parentId: opts.parent ? this.journey?.id : undefined,\n ownerContextId: this.contextId,\n };\n this.setJourney(journey);\n this.onLocalChange(journey);\n return journey;\n }\n\n /** Terminates the active journey and broadcasts the change. */\n end(): void {\n if (this.journey === null) {\n return;\n }\n this.setJourney(null);\n this.onLocalChange(null);\n }\n\n /**\n * Applies journey updates received from external bus peers without echoing\n * broadcasts. Echoing makes two windows ping the change back and forth. A journey\n * matching the one in force is ignored, so an echo cannot restart the timer.\n * @param journey Updated Journey instance or null.\n */\n applyRemote(journey: Journey | null): void {\n const current = this.journey;\n if (journey !== null && current !== null && journey.id === current.id) {\n return;\n }\n this.setJourney(journey);\n }\n\n /**\n * Serializes the active journey into a compact token for URL or intent transfer.\n * @returns Base64url token string or undefined if no journey is active or size cap is exceeded.\n */\n getToken(): string | undefined {\n const journey = this.journey;\n if (journey === null) {\n return undefined;\n }\n const token = encodeToken(journey);\n if (token.length > JOURNEY_TOKEN_MAX_CHARS) {\n this.diagnostics.report(\n \"journey.token_too_large\",\n \"journey token exceeded the size cap and was not issued\",\n { length: token.length },\n );\n return undefined;\n }\n return token;\n }\n\n /**\n * Validates and adopts a serialized journey token.\n * @param token Base64url journey token.\n * @param source Originating source description for diagnostics.\n * @param broadcast Indicates whether to broadcast adoption to connected bus peers.\n * @returns True if the token was valid, unexpired, and adopted.\n */\n adopt(token: string, source: string, broadcast = false): boolean {\n const decoded = this.decodeToken(token);\n if (decoded === null) {\n return false;\n }\n if (Date.now() - decoded.startedAt > this.options.maxAgeMs) {\n this.diagnostics.report(\"journey.expired\", \"discarded a seeded journey older than maxAgeMs\", {\n source,\n name: decoded.name,\n });\n return false;\n }\n\n this.setJourney(decoded);\n this.diagnostics.report(\"journey.adopted\", `adopted journey \"${decoded.name}\"`, {\n source,\n journeyId: decoded.id,\n });\n if (broadcast) {\n this.onLocalChange(decoded);\n }\n return true;\n }\n\n /**\n * Ends the journey if the terminated context matches the journey owner and endOnOwnerClose is enabled.\n * @param ownerContextId Context identifier of the closed window.\n */\n ownerClosed(ownerContextId: string): void {\n if (!this.options.endOnOwnerClose) {\n return;\n }\n if (this.journey?.ownerContextId === ownerContextId) {\n this.end();\n }\n }\n\n /** Clears pending expiration timers and releases resources on shutdown. */\n destroy(): void {\n this.clearTimer();\n }\n\n /**\n * Resumes a persisted journey from raw sessionStorage data.\n * @param raw Serialized JSON string from storage.\n * @returns True if journey was successfully restored.\n */\n private restore(raw: string): boolean {\n const parsed = this.diagnostics.guard(\n \"storage.degraded\",\n \"parsing the persisted journey\",\n () => JSON.parse(raw) as unknown,\n );\n const journey = journeyFromStorage(parsed);\n if (journey === null) {\n return false;\n }\n\n if (Date.now() - journey.startedAt > this.options.maxAgeMs) {\n this.diagnostics.report(\n \"journey.expired\",\n \"discarded a persisted journey older than maxAgeMs\",\n { name: journey.name },\n );\n this.clearStored();\n return false;\n }\n\n this.setJourney(journey);\n this.diagnostics.report(\"journey.adopted\", `resumed journey \"${journey.name}\"`, {\n source: \"sessionStorage\",\n journeyId: journey.id,\n });\n return true;\n }\n\n /**\n * Decodes a base64url token into a validated Journey object. Tokens come from URLs\n * anyone can edit. Every step throws on non-token input, so the failure is\n * reported, not raised.\n * @param token Encoded token string.\n * @returns Decoded Journey instance or null on decode error.\n */\n private decodeToken(token: string): Journey | null {\n const decoded = this.diagnostics.guard(\n \"config.invalid\",\n \"decoding a seeded journey token\",\n () => {\n const standard = token\n .replace(BASE64URL_DASH_PATTERN, \"+\")\n .replace(BASE64URL_UNDERSCORE_PATTERN, \"/\");\n const missing =\n (BASE64_GROUP_CHARS - (standard.length % BASE64_GROUP_CHARS)) % BASE64_GROUP_CHARS;\n const padding = \"=\".repeat(missing);\n const bytes = Uint8Array.from(atob(standard + padding), (c) => c.charCodeAt(0));\n return journeyFromTokenPayload(JSON.parse(new TextDecoder().decode(bytes)) as unknown);\n },\n );\n return decoded ?? null;\n }\n\n /**\n * Sets the active journey, updates sessionStorage, and schedules expiration.\n * @param journey Target Journey instance or null.\n */\n private setJourney(journey: Journey | null): void {\n this.journey = journey;\n this.clearTimer();\n\n this.diagnostics.guard(\"storage.unavailable\", \"persisting the journey\", () => {\n if (journey !== null) {\n sessionStorage.setItem(JOURNEY_STORAGE_KEY, JSON.stringify(journey));\n } else {\n sessionStorage.removeItem(JOURNEY_STORAGE_KEY);\n }\n });\n\n if (journey === null) {\n return;\n }\n\n const remaining = Math.max(this.options.maxAgeMs - (Date.now() - journey.startedAt), 0);\n const timer = setTimeout(() => {\n this.diagnostics.report(\n \"journey.expired\",\n `journey \"${journey.name}\" hit maxAgeMs and was ended automatically`,\n { journeyId: journey.id },\n );\n this.journey = null;\n this.expiryTimer = null;\n this.clearStored();\n }, remaining);\n this.expiryTimer = timer;\n unrefTimer(timer);\n }\n\n /** Removes journey data from sessionStorage. */\n private clearStored(): void {\n this.diagnostics.guard(\"storage.unavailable\", \"clearing the persisted journey\", () => {\n sessionStorage.removeItem(JOURNEY_STORAGE_KEY);\n });\n }\n\n /** Cancels any active expiration timer. */\n private clearTimer(): void {\n if (this.expiryTimer !== null) {\n clearTimeout(this.expiryTimer);\n this.expiryTimer = null;\n }\n }\n\n /**\n * Extracts the journey token from the current window location search parameters.\n * @returns Token string or null.\n */\n private readUrlToken(): string | null {\n const token = this.diagnostics.guard(\n \"config.invalid\",\n \"reading the journey token from the URL\",\n () => {\n if (typeof location === \"undefined\") {\n return null;\n }\n return new URL(location.href).searchParams.get(this.options.urlParam);\n },\n );\n return token ?? null;\n }\n\n /**\n * Reads the journey token from OpenFin window creation customData.\n * @returns Promise resolving to token string or null.\n */\n private async readOpenFinToken(): Promise<string | null> {\n const me = (globalThis as OpenFinGlobal).fin?.me;\n const getOptions = me?.getOptions;\n if (getOptions === undefined) {\n return null;\n }\n\n // Uses call to preserve target receiver context on native OpenFin methods. A\n // detached copy throws on invocation.\n const options = await this.diagnostics.guardAsync(\n \"openfin.unavailable\",\n \"reading fin.me.getOptions()\",\n () => getOptions.call(me),\n );\n const token = options?.customData?.[OPENFIN_JOURNEY_CUSTOM_DATA_KEY];\n return typeof token === \"string\" ? token : null;\n }\n}\n","// src/core/sampling.ts\n//\n// Deterministic record sampling based on namespace rules, journey IDs, and trace\n// IDs. Keyed on the journey, so one journey is kept or dropped whole. Stable\n// across windows and reloads.\n\nimport {\n ATTR_APP_NAMESPACE,\n ATTR_JOURNEY_ID,\n ATTR_LOG_TYPE,\n FNV_OFFSET_BASIS,\n FNV_PRIME,\n SAMPLING_RATE_MAX,\n SAMPLING_RATE_MIN,\n UINT32_MAX,\n} from \"../constants\";\nimport type { ResolvedConfig } from \"../models/config\";\nimport type { LogRecord } from \"../models/log-record\";\n\n/**\n * Computes 32-bit FNV-1a hash of a string value. Not a security hash.\n * @param value Key string to hash.\n * @returns Unsigned 32-bit integer hash.\n */\nfunction hash(value: string): number {\n let h = FNV_OFFSET_BASIS;\n\n for (let i = 0; i < value.length; i++) {\n h ^= value.charCodeAt(i);\n h = Math.imul(h, FNV_PRIME);\n }\n\n return h >>> 0;\n}\n\n/**\n * Safely extracts a string attribute value from a log record. Absent and non-string\n * both read as empty. A forwarded record has only passed a shape check.\n * @param record Log record being evaluated.\n * @param key Attribute key.\n * @returns String attribute value, or empty string if missing or non-string.\n */\nfunction readAttr(record: LogRecord, key: string): string {\n const value: unknown = record.attributes[key];\n return typeof value === \"string\" ? value : \"\";\n}\n\n/**\n * Resolves sampling rate for a namespace using longest-prefix matching, so\n * trading.ticks overrides trading.\n * @param namespace Target application namespace.\n * @param config Active configuration instance.\n * @returns Matched namespace sampling rate or default rate.\n */\nfunction rateFor(namespace: string, config: ResolvedConfig): number {\n const { rates, defaultRate } = config.sampling;\n let best: number | undefined;\n let bestLength = -1;\n\n for (const [prefix, rate] of Object.entries(rates)) {\n const matches = namespace === prefix || namespace.startsWith(`${prefix}.`);\n\n if (matches && prefix.length > bestLength) {\n best = rate;\n bestLength = prefix.length;\n }\n }\n\n return best ?? defaultRate;\n}\n\n/**\n * Evaluates whether a log record should be sampled for retention.\n * @param record Record to evaluate.\n * @param config Active configuration instance.\n * @returns True if the record should be retained and transmitted.\n */\nexport function shouldSample(record: LogRecord, config: ResolvedConfig): boolean {\n // Errors and fatal records bypass sampling filters.\n if (record.severityText === \"ERROR\" || record.severityText === \"FATAL\") {\n return true;\n }\n\n if (config.sampling.alwaysSampleTypes.includes(readAttr(record, ATTR_LOG_TYPE))) {\n return true;\n }\n\n const rate = rateFor(readAttr(record, ATTR_APP_NAMESPACE), config);\n if (rate >= SAMPLING_RATE_MAX) {\n return true;\n }\n if (rate <= SAMPLING_RATE_MIN) {\n return false;\n }\n\n // Falls back to trace ID when journey ID is absent. The trace still groups one\n // operation.\n const key = readAttr(record, ATTR_JOURNEY_ID) || record.traceId;\n\n return hash(key) / UINT32_MAX < rate;\n}\n","// src/core/pipeline.ts\n//\n// Stream buffering, batch formation, and delivery pipeline for logs and metrics.\n//\n// Each stream owns its buffer. The exit flush cannot drain bufferTime's array.\n\nimport {\n asapScheduler,\n bufferTime,\n catchError,\n EMPTY,\n filter,\n from,\n map,\n merge,\n mergeMap,\n type Observable,\n observeOn,\n partition,\n Subject,\n type Subscription,\n tap,\n} from \"rxjs\";\nimport { ATTR_LOG_TYPE, LOG_TYPE_METRIC, PENDING_BUFFER_BATCHES } from \"../constants\";\nimport type { LogBatch } from \"../models/batch\";\nimport type { ResolvedConfig, StreamOptions } from \"../models/config\";\nimport { type LogRecord, nowUnixNano } from \"../models/log-record\";\nimport type { StorageAdapter } from \"../models/storage\";\nimport type { HttpTransport } from \"../transport/http-transport\";\nimport type { RetryEngine } from \"../transport/retry-engine\";\nimport { newId } from \"../utils/identity\";\nimport type { Diagnostics } from \"./diagnostics\";\nimport { shouldSample } from \"./sampling\";\n\n/** Pipeline stream classification for logs versus metrics. */\nexport type StreamName = \"logs\" | \"metrics\";\n\n/**\n * Evaluates whether a log record is classified as a metric.\n * @param record Record to evaluate.\n * @returns True if the record log type attribute equals metric.\n */\nfunction isMetric(record: LogRecord): boolean {\n return record.attributes[ATTR_LOG_TYPE] === LOG_TYPE_METRIC;\n}\n\n/** Dedicated stream buffer accumulating records until flushed by timer, capacity, or exit flush. */\nclass RecordStream {\n /** Pending records waiting in chronological order. */\n private pending: LogRecord[] = [];\n\n /**\n * @param config Active configuration instance.\n * @param name Target stream name.\n * @param diagnostics Diagnostics reporter.\n */\n constructor(\n private readonly config: ResolvedConfig,\n readonly name: StreamName,\n private readonly diagnostics: Diagnostics,\n ) {}\n\n /** Stream batching configuration options. */\n get options(): StreamOptions {\n return this.config.streams[this.name];\n }\n\n /** Maximum buffered record capacity before FIFO eviction. */\n private get capacity(): number {\n return Math.max(this.options.batchSize, 1) * PENDING_BUFFER_BATCHES;\n }\n\n /**\n * Buffers a record, dropping the oldest if capacity is exceeded.\n * @param record Record to enqueue.\n */\n add(record: LogRecord): void {\n if (this.pending.length >= this.capacity) {\n this.pending.shift();\n this.diagnostics.count(\"record.dropped_pending_full\");\n }\n\n this.pending.push(record);\n }\n\n /**\n * Drains and returns all buffered records in an atomic operation.\n * @returns Array of buffered records.\n */\n take(): LogRecord[] {\n const records = this.pending;\n this.pending = [];\n\n return records;\n }\n}\n\n/** Pipeline orchestrating log and metric stream buffering, batch creation, and HTTP dispatch. */\nexport class LogPipeline {\n /** Ingress Subject receiving records pushed into the pipeline. */\n readonly records$ = new Subject<LogRecord>();\n\n /** Buffer instances for logs and metrics streams. */\n private readonly streams: Record<StreamName, RecordStream>;\n\n /** Active RxJS subscription managing the pipeline stream. */\n private subscription: Subscription | null = null;\n\n /** Unconfirmed in-flight batches tracked for exit flush recovery. */\n private readonly unconfirmed = new Map<string, LogBatch>();\n\n /** Indicates whether the pipeline has been destroyed. */\n private stopped = false;\n\n /**\n * @param config Active configuration instance.\n * @param transport HTTP transport for live batch delivery.\n * @param storage Storage adapter for offline batch persistence.\n * @param retry Retry engine for redelivering persisted batches.\n * @param diagnostics Diagnostics reporter.\n */\n constructor(\n private readonly config: ResolvedConfig,\n private readonly transport: HttpTransport,\n private readonly storage: StorageAdapter,\n private readonly retry: RetryEngine,\n private readonly diagnostics: Diagnostics,\n ) {\n this.streams = {\n logs: new RecordStream(config, \"logs\", diagnostics),\n metrics: new RecordStream(config, \"metrics\", diagnostics),\n };\n\n this.subscribe();\n }\n\n /**\n * Stamps observed timestamp and enqueues a record into the pipeline.\n * @param record Record to push.\n */\n push(record: LogRecord): void {\n if (this.stopped) {\n return;\n }\n\n record.observedTimeUnixNano = nowUnixNano();\n this.records$.next(record);\n }\n\n /**\n * Atomically drains all buffered and unconfirmed in-flight records into a single exit batch.\n * @returns Combined LogBatch or null if no records are pending.\n */\n drainPending(): LogBatch | null {\n const records = [\n ...[...this.unconfirmed.values()].flatMap((batch) => batch.records),\n ...this.streams.metrics.take(),\n ...this.streams.logs.take(),\n ];\n this.unconfirmed.clear();\n\n if (records.length === 0) {\n return null;\n }\n\n return { id: newId(), records, createdAt: Date.now(), attempts: 0 };\n }\n\n /** Re-subscribes RxJS pipeline stream to apply updated interval and batch size settings. */\n refresh(): void {\n this.subscription?.unsubscribe();\n this.subscribe();\n }\n\n /** Terminates pipeline subscriptions and completes the ingress stream. */\n destroy(): void {\n this.stopped = true;\n this.subscription?.unsubscribe();\n this.subscription = null;\n this.records$.complete();\n }\n\n /** Assembles and subscribes the partitioned RxJS stream pipeline. */\n private subscribe(): void {\n if (this.stopped) {\n return;\n }\n\n // Partitions records by type before sampling to evaluate hash once per record.\n const [metric$, log$] = partition(this.records$, isMetric);\n\n this.subscription = merge(\n this.batches(metric$, this.streams.metrics),\n this.batches(log$, this.streams.logs),\n )\n .pipe(\n // Catches pipeline errors and restarts subscription on failure.\n // Stays ahead of observeOn. Behind it the restart runs a microtask late\n // and records pushed in between reach a Subject with no subscriber.\n catchError((error: unknown) => {\n this.diagnostics.report(\n \"pipeline.crashed\",\n \"the pipeline errored and was restarted\",\n undefined,\n error,\n );\n this.subscribe();\n\n return EMPTY;\n }),\n\n // Dispatches batch processing on microtask boundary after buffering.\n // Ahead of it, records sit in a microtask queue an unloading document\n // never drains.\n observeOn(asapScheduler),\n mergeMap(\n (batch) =>\n from(this.dispatch(batch)).pipe(\n // Inner catchError isolates individual batch delivery rejections.\n // On the outer chain it completes the stream and logging stops.\n catchError((error: unknown) => {\n this.diagnostics.report(\n \"pipeline.crashed\",\n \"dispatch rejected, which it is written never to do\",\n { batchId: batch.id },\n error,\n );\n\n return EMPTY;\n }),\n ),\n this.config.maxConcurrentRequests,\n ),\n )\n .subscribe();\n }\n\n /**\n * Applies sampling, buffers stream records, and triggers timed batch emissions.\n * @param source$ Stream observable emitting records.\n * @param stream Stream buffer managing pending records.\n * @returns Observable emitting closed LogBatch objects.\n */\n private batches(source$: Observable<LogRecord>, stream: RecordStream): Observable<LogBatch> {\n return source$.pipe(\n filter((record) => {\n if (shouldSample(record, this.config)) {\n return true;\n }\n\n this.diagnostics.count(\"record.dropped_by_sampling\");\n return false;\n }),\n\n // Buffers records after sampling evaluation. The reverse order buffers\n // dropped records for the life of the tab and beacons them on exit.\n tap((record) => {\n stream.add(record);\n }),\n\n // Uses bufferTime for trigger cadence while RecordStream owns record\n // retention. The array bufferTime emits is discarded.\n bufferTime(stream.options.flushIntervalMs, null, stream.options.batchSize),\n map(() => this.claim(stream)),\n filter((batch): batch is LogBatch => batch !== null),\n );\n }\n\n /**\n * Drains the stream buffer into a new LogBatch and tracks it in unconfirmed storage.\n * @param stream Stream buffer to drain.\n * @returns Created LogBatch or null if stream was empty.\n */\n private claim(stream: RecordStream): LogBatch | null {\n const records = stream.take();\n if (records.length === 0) {\n return null;\n }\n\n const batch: LogBatch = {\n id: newId(),\n records,\n createdAt: Date.now(),\n attempts: 0,\n };\n this.unconfirmed.set(batch.id, batch);\n\n return batch;\n }\n\n /**\n * Sends a batch over HTTP transport or persists it to offline storage if throttled or failed.\n * @param batch Batch to deliver.\n */\n private async dispatch(batch: LogBatch): Promise<void> {\n try {\n // Persists directly to storage while transport is throttled. Sending here\n // posts a batch every flush interval straight through the throttle.\n // Attempt count unchanged: nothing was sent.\n const throttledMs = this.transport.throttledForMs();\n if (throttledMs > 0) {\n await this.store(batch);\n this.diagnostics.report(\"transport.throttled\", \"stored the batch rather than sending it\", {\n batchId: batch.id,\n records: batch.records.length,\n throttledMs,\n });\n return;\n }\n\n try {\n await this.transport.send(batch);\n } catch (error) {\n // Increments attempt count before storing failed live send. Stored at 0,\n // the batch exceeds storage.maxAttempts by one and attempt headers\n // under-report.\n await this.store({ ...batch, attempts: batch.attempts + 1 });\n this.diagnostics.report(\n \"transport.http_error\",\n \"batch was stored for retry instead of being delivered\",\n { batchId: batch.id, records: batch.records.length },\n error,\n );\n }\n } finally {\n this.unconfirmed.delete(batch.id);\n }\n }\n\n /**\n * Persists an undelivered batch to storage and triggers retry engine.\n * @param batch Batch to persist.\n */\n private async store(batch: LogBatch): Promise<void> {\n await this.diagnostics.guardAsync(\n \"storage.degraded\",\n \"persisting an undelivered batch\",\n async () => {\n await this.storage.save(batch);\n this.retry.nudge();\n },\n );\n }\n}\n","// src/core/record.ts\n//\n// Assembles structured log records from ambient context, journey metadata, trace context, and resource attributes.\n// Never throws into the caller. The resource block is cached, so anything that\n// changes it must call invalidateResource.\n\nimport {\n ATTR_APP_NAMESPACE,\n ATTR_ATTRIBUTES_BYTES,\n ATTR_ATTRIBUTES_DROPPED,\n ATTR_JOURNEY_ID,\n ATTR_JOURNEY_NAME,\n ATTR_JOURNEY_PARENT_ID,\n ATTR_LOG_SEQ,\n ATTR_LOG_TYPE,\n ATTR_PAGE_URL,\n ATTR_SANITIZE_FAILED,\n LEVEL_ORDER,\n RESOURCE_BROWSER_USER_AGENT,\n RESOURCE_CONTEXT_ID,\n RESOURCE_DEPLOYMENT_ENVIRONMENT,\n RESOURCE_HOST_PLATFORM,\n RESOURCE_OPENFIN_NAME,\n RESOURCE_OPENFIN_UUID,\n RESOURCE_SERVICE_NAME,\n RESOURCE_SERVICE_VERSION,\n RESOURCE_SESSION_ID,\n RESOURCE_TAB_ID,\n RESOURCE_TELEMETRY_SDK_LANGUAGE,\n RESOURCE_TELEMETRY_SDK_NAME,\n RESOURCE_TELEMETRY_SDK_VERSION,\n SEVERITY_NUMBER,\n TELEMETRY_SDK_LANGUAGE,\n TELEMETRY_SDK_NAME,\n TELEMETRY_SDK_VERSION,\n} from \"../constants\";\nimport type { ResolvedConfig } from \"../models/config\";\nimport {\n isLogRecord,\n type LogLevel,\n type LogRecord,\n type LogType,\n nowUnixNano,\n} from \"../models/log-record\";\nimport type { Identity } from \"../utils/identity\";\nimport { currentUrl, type PlatformMetadata } from \"../utils/platform\";\nimport { sanitizeWithSize, truncate } from \"../utils/sanitize\";\nimport type { Sequence } from \"../utils/sequence\";\nimport type { TraceEngine } from \"../utils/tracing\";\nimport type { ContextStore } from \"./context\";\nimport type { Diagnostics } from \"./diagnostics\";\nimport type { JourneyEngine } from \"./journey\";\n\n/** Injected dependencies required by RecordBuilder. */\nexport interface RecordBuilderDeps {\n /** Active configuration object reference. */\n config: ResolvedConfig;\n /** Diagnostics reporter instance. */\n diagnostics: Diagnostics;\n /** Ambient context store. */\n context: ContextStore;\n /** Active journey engine. */\n journey: JourneyEngine;\n /** Distributed tracing engine. */\n tracing: TraceEngine;\n /** Monotonic sequence counter. */\n sequence: Sequence;\n /** Context, session, and tab identity context. */\n identity: Identity;\n /** Detected host platform metadata. */\n platform: PlatformMetadata;\n}\n\n/** Input parameters for constructing a single log record. */\nexport interface BuildInput {\n /** Severity level of the log entry. */\n level: LogLevel;\n /** Telemetry type classification. */\n type: LogType;\n /** Primary log message body. */\n body: string;\n /** Originating application namespace. */\n namespace: string;\n /** Pre-merged scoped context from logger instance. */\n scoped?: Record<string, unknown>;\n /** Call-site payload attributes. */\n payload?: Record<string, unknown>;\n}\n\n/**\n * Casts a sanitized plain object value to an attribute record.\n * @param value Sanitized object value.\n * @returns Attribute record.\n */\nfunction asAttributes(value: unknown): Record<string, unknown> {\n return value as Record<string, unknown>;\n}\n\n/** Builds validated and sanitized LogRecord instances from logger inputs. */\nexport class RecordBuilder {\n /** Cached resource attributes block. */\n private resourceCache: Record<string, unknown> | null = null;\n\n /**\n * @param deps Injected builder dependencies.\n */\n constructor(private readonly deps: RecordBuilderDeps) {}\n\n /** Invalidates cached resource attributes to force recomputation on next build. */\n invalidateResource(): void {\n this.resourceCache = null;\n }\n\n /**\n * Evaluates whether a log level clears minimum severity thresholds.\n * @param level Target log severity level.\n * @returns True if the level is enabled.\n */\n isEnabled(level: LogLevel): boolean {\n const { config } = this.deps;\n if (!config.enabled) {\n return false;\n }\n return LEVEL_ORDER[level] >= LEVEL_ORDER[config.minLevel];\n }\n\n /**\n * Builds a structured LogRecord from input attributes, applying sanitization and size budgeting.\n * @param input Logger call input parameters.\n * @returns Completed LogRecord or null if dropped by severity or redaction.\n */\n build(input: BuildInput): LogRecord | null {\n const { config, diagnostics, tracing, journey, sequence } = this.deps;\n\n if (!this.isEnabled(input.level)) {\n diagnostics.count(\"record.dropped_by_level\");\n return null;\n }\n\n const limits = config.limits;\n const traceCtx = tracing.resolve();\n const activeJourney = journey.current();\n const seq = sequence.next();\n const pageUrl = currentUrl();\n\n let attributes: Record<string, unknown>;\n let bytes = 0;\n try {\n const fromContext = sanitizeWithSize(this.deps.context.getAll(), limits);\n const fromScope = sanitizeWithSize(input.scoped ?? {}, limits);\n const fromPayload = sanitizeWithSize(input.payload ?? {}, limits);\n bytes = fromContext.bytes + fromScope.bytes + fromPayload.bytes;\n\n // Merges attributes in increasing order of precedence: context, scope, payload.\n attributes = {\n ...asAttributes(fromContext.value),\n ...asAttributes(fromScope.value),\n ...asAttributes(fromPayload.value),\n };\n } catch (error) {\n diagnostics.report(\n \"record.sanitize_failed\",\n \"attributes could not be sanitized\",\n undefined,\n error,\n );\n attributes = { [ATTR_SANITIZE_FAILED]: true };\n }\n\n // Injects reserved telemetry attributes after payload merge to prevent\n // overwrites. Merged earlier, a payload key named journey.id rewrites the id\n // records correlate on.\n attributes[ATTR_LOG_TYPE] = input.type;\n attributes[ATTR_LOG_SEQ] = seq;\n attributes[ATTR_APP_NAMESPACE] = input.namespace;\n attributes[ATTR_PAGE_URL] = pageUrl;\n if (activeJourney) {\n attributes[ATTR_JOURNEY_ID] = activeJourney.id;\n attributes[ATTR_JOURNEY_NAME] = activeJourney.name;\n if (activeJourney.parentId !== undefined) {\n attributes[ATTR_JOURNEY_PARENT_ID] = activeJourney.parentId;\n }\n }\n\n const body = truncate(input.body, limits.maxBodyChars);\n if (body !== input.body) {\n diagnostics.count(\"record.truncated\");\n }\n\n let record: LogRecord = {\n timeUnixNano: nowUnixNano(),\n traceId: traceCtx.traceId,\n spanId: traceCtx.spanId,\n traceFlags: traceCtx.traceFlags,\n severityNumber: SEVERITY_NUMBER[input.level],\n severityText: input.level,\n body,\n attributes,\n resource: this.resource(),\n };\n\n const redact = config.redact;\n if (redact) {\n const redacted = diagnostics.guard(\"record.sanitize_failed\", \"redact hook threw\", () =>\n redact(record),\n );\n if (redacted === null) {\n diagnostics.count(\"record.dropped_by_redact\");\n return null;\n }\n\n if (redacted !== undefined && redacted !== record) {\n if (isLogRecord(redacted)) {\n // Re-sanitizes mutated record from redact hook. Hook output is consumer\n // code: a cycle, a hostile getter or a BigInt throws at serialization\n // and loses the batch.\n const remeasured = sanitizeWithSize(redacted.attributes, limits);\n record = { ...redacted, attributes: asAttributes(remeasured.value) };\n bytes = remeasured.bytes;\n } else {\n diagnostics.report(\n \"record.sanitize_failed\",\n \"redact hook returned something that is not a record, keeping the original\",\n );\n }\n }\n }\n\n // Truncates attributes when size exceeds maxRecordBytes while retaining indexing\n // keys. Without journey.id and trace_id the record cannot be looked up.\n if (bytes > limits.maxRecordBytes) {\n diagnostics.report(\n \"record.truncated\",\n \"attributes exceeded the size budget and were dropped\",\n { bytes, body: record.body },\n );\n\n const kept: Record<string, unknown> = {\n [ATTR_LOG_TYPE]: input.type,\n [ATTR_LOG_SEQ]: seq,\n [ATTR_APP_NAMESPACE]: input.namespace,\n [ATTR_PAGE_URL]: pageUrl,\n [ATTR_ATTRIBUTES_DROPPED]: true,\n [ATTR_ATTRIBUTES_BYTES]: bytes,\n };\n if (activeJourney) {\n kept[ATTR_JOURNEY_ID] = activeJourney.id;\n kept[ATTR_JOURNEY_NAME] = activeJourney.name;\n }\n record.attributes = kept;\n }\n\n return record;\n }\n\n /**\n * Computes or returns cached resource metadata for this runtime context.\n * @returns Resource attributes record.\n */\n private resource(): Record<string, unknown> {\n if (this.resourceCache) {\n return this.resourceCache;\n }\n const { config, identity, platform } = this.deps;\n\n this.resourceCache = {\n [RESOURCE_SERVICE_NAME]: config.serviceName,\n [RESOURCE_SERVICE_VERSION]: config.serviceVersion,\n [RESOURCE_DEPLOYMENT_ENVIRONMENT]: config.environment,\n [RESOURCE_TELEMETRY_SDK_NAME]: TELEMETRY_SDK_NAME,\n [RESOURCE_TELEMETRY_SDK_VERSION]: TELEMETRY_SDK_VERSION,\n [RESOURCE_TELEMETRY_SDK_LANGUAGE]: TELEMETRY_SDK_LANGUAGE,\n [RESOURCE_HOST_PLATFORM]: platform.platform,\n [RESOURCE_SESSION_ID]: identity.sessionId,\n [RESOURCE_TAB_ID]: identity.tabId,\n [RESOURCE_CONTEXT_ID]: identity.contextId,\n [RESOURCE_BROWSER_USER_AGENT]: platform.userAgent,\n // Omits undefined OpenFin properties from resource attributes.\n ...(platform.openfinUuid === undefined\n ? {}\n : { [RESOURCE_OPENFIN_UUID]: platform.openfinUuid }),\n ...(platform.openfinName === undefined\n ? {}\n : { [RESOURCE_OPENFIN_NAME]: platform.openfinName }),\n };\n return this.resourceCache;\n }\n}\n","// src/core/runtime.ts\n//\n// Central coordination runtime managing subsystem lifecycles, configuration, and telemetry routing.\n\nimport { Bus } from \"../bus/bus\";\nimport type { Receive, WorkerLike } from \"../bus/links\";\nimport { ErrorCapture } from \"../capture/errors\";\nimport { InteractionCapture } from \"../capture/interactions\";\nimport { NetworkCapture } from \"../capture/network\";\nimport type { Capture } from \"../capture/types\";\nimport { WebVitalsCapture } from \"../capture/web-vitals\";\nimport {\n CAPTURE_NAMESPACE,\n GAP_REPORT_THROTTLE_MS,\n RUNTIME_GLOBAL_KEY,\n STORAGE_NAMESPACE,\n TAB_ID_KEY,\n} from \"../constants\";\nimport type { BusMessage } from \"../models/bus\";\nimport type { ObservabilityConfig, ResolvedConfig } from \"../models/config\";\nimport { isLogRecord, type LogRecord } from \"../models/log-record\";\nimport type { PruneResult, StorageAdapter } from \"../models/storage\";\nimport { drainEmergencyQueue } from \"../storage/emergency-queue\";\nimport { createStorage } from \"../storage/factory\";\nimport { ExitFlush } from \"../transport/exit-flush\";\nimport { HttpTransport } from \"../transport/http-transport\";\nimport { RetryEngine } from \"../transport/retry-engine\";\nimport { ConsoleSink } from \"../utils/console\";\nimport { type Identity, newId, resolveIdentity, touchSession } from \"../utils/identity\";\nimport { detectPlatform, type PlatformMetadata } from \"../utils/platform\";\nimport { Sequence } from \"../utils/sequence\";\nimport { TraceEngine } from \"../utils/tracing\";\nimport { BreadcrumbBuffer } from \"./breadcrumbs\";\nimport { applyResolvedConfig, resolveConfig } from \"./config\";\nimport { ContextStore } from \"./context\";\nimport { Diagnostics } from \"./diagnostics\";\nimport { JourneyEngine } from \"./journey\";\nimport { OneLogger } from \"./logger\";\nimport { LogPipeline } from \"./pipeline\";\nimport { RecordBuilder } from \"./record\";\n\n/** Global symbol key pinning the singleton runtime instance across federated bundles. */\nconst RUNTIME_KEY = Symbol.for(RUNTIME_GLOBAL_KEY);\n\n/** Central runtime managing subsystem lifecycles, bus coordination, and record delivery. */\nexport class ObservabilityRuntime {\n /** Diagnostics reporter for internal faults. */\n readonly diagnostics: Diagnostics;\n\n /** Active configuration instance mutated in place during reconfigurations. */\n readonly config: ResolvedConfig;\n\n /** Detected host platform metadata. */\n readonly platform: PlatformMetadata;\n\n /** Identity context containing session, tab, and context identifiers. */\n readonly identity: Identity;\n\n /** Store for ambient application context attributes. */\n readonly context = new ContextStore();\n\n /** Ring buffer holding contextual user breadcrumbs. */\n readonly breadcrumbs: BreadcrumbBuffer;\n\n /** Distributed tracing context engine. */\n readonly tracing: TraceEngine;\n\n /** Monotonic sequence counter for records emitted in this context. */\n readonly sequence = new Sequence();\n\n /** Journey tracking engine managing workflow correlation. */\n readonly journey: JourneyEngine;\n\n /** Record builder assembling structured log records. */\n readonly builder: RecordBuilder;\n\n /** Console sink for local developer output. */\n readonly console: ConsoleSink;\n\n /** Cross-realm communication bus. */\n readonly bus: Bus;\n\n /** Persistent storage adapter for offline batches (sender role only). */\n private storage?: StorageAdapter;\n\n /** HTTP transport instance for live log delivery (sender role only). */\n private transport?: HttpTransport;\n\n /** Background retry engine for redelivering failed batches (sender role only). */\n private retry?: RetryEngine;\n\n /** Primary log pipeline managing stream buffering and delivery (sender role only). */\n private pipeline?: LogPipeline;\n\n /** Exit flush handler executing atomic batch delivery on unload (sender role only). */\n private exitFlush?: ExitFlush;\n\n /** Active auto-capture instrumentation modules. */\n private readonly captures: Capture[] = [];\n\n /** Queue buffering records created before bus role resolution. */\n private bootBuffer: LogRecord[] = [];\n\n /** Batch buffer staging records for microtask forwarding. */\n private forwardBuffer: LogRecord[] = [];\n\n /** Indicates whether a microtask drain is scheduled for the forward buffer. */\n private forwardScheduled = false;\n\n /** Indicates whether asynchronous initialization has completed. */\n private ready = false;\n\n /** Indicates whether the runtime has been permanently shut down. */\n private destroyed = false;\n\n /** Timestamp of the last reported storage gap warning in epoch milliseconds. */\n private lastGapAt = 0;\n\n /**\n * @param input Initial consumer configuration options.\n */\n private constructor(input: Partial<ObservabilityConfig>) {\n this.diagnostics = new Diagnostics(input.onDiagnostic);\n\n this.platform = detectPlatform(this.diagnostics);\n this.config = resolveConfig(input, this.diagnostics);\n this.identity = resolveIdentity(this.diagnostics);\n this.breadcrumbs = new BreadcrumbBuffer(this.config.capture.maxBreadcrumbs);\n this.tracing = new TraceEngine(this.diagnostics);\n this.console = new ConsoleSink(this.config.console.enabled, this.config.console.level);\n\n this.journey = new JourneyEngine(\n this.config.journey,\n this.diagnostics,\n this.identity.contextId,\n (journey) => {\n this.bus.broadcastJourney(journey);\n },\n );\n\n this.builder = new RecordBuilder({\n config: this.config,\n diagnostics: this.diagnostics,\n context: this.context,\n journey: this.journey,\n tracing: this.tracing,\n sequence: this.sequence,\n identity: this.identity,\n platform: this.platform,\n });\n\n this.bus = new Bus(\n this.config,\n this.diagnostics,\n this.platform,\n this.identity.contextId,\n this.identity.tabId,\n {\n onRecords: (records) => {\n this.ingestForwarded(records);\n },\n onJourney: (journey) => {\n this.journey.applyRemote(journey);\n },\n onJourneyRequest: () => this.journey.current(),\n onTabConflict: () => {\n this.regenerateTabId();\n },\n },\n );\n }\n\n /**\n * Direct communication receiver invoked by same-origin child frames.\n * @param message Inbound bus message.\n * @param reply Direct response callback.\n */\n readonly busAccept = (message: BusMessage, reply: Receive): void => {\n if (this.destroyed) {\n return;\n }\n\n this.diagnostics.guard(\"bus.send_failed\", \"accepting a direct message from a child\", () => {\n this.bus.acceptDirect(message, reply);\n });\n };\n\n /**\n * Returns the singleton runtime instance pinned to this realm.\n * @returns Active runtime instance or null.\n */\n static current(): ObservabilityRuntime | null {\n return (\n ((globalThis as Record<symbol, unknown>)[RUNTIME_KEY] as ObservabilityRuntime | undefined) ??\n null\n );\n }\n\n /**\n * Initializes a new runtime instance or updates the existing singleton.\n * @param input Consumer configuration options.\n * @returns Active runtime instance.\n */\n static configure(input: Partial<ObservabilityConfig>): ObservabilityRuntime {\n const existing = ObservabilityRuntime.current();\n if (existing && !existing.destroyed) {\n existing.reconfigure(input);\n return existing;\n }\n\n const runtime = new ObservabilityRuntime(input);\n (globalThis as Record<symbol, unknown>)[RUNTIME_KEY] = runtime;\n void runtime.init();\n return runtime;\n }\n\n /**\n * Updates runtime configuration and refreshes affected subsystems.\n * @param input Partial configuration to merge.\n */\n private reconfigure(input: Partial<ObservabilityConfig>): void {\n applyResolvedConfig(this.config, resolveConfig(input, this.diagnostics, this.config));\n this.diagnostics.setHandler(this.config.onDiagnostic);\n\n this.builder.invalidateResource();\n this.console.update(this.config.console.enabled, this.config.console.level);\n this.breadcrumbs.resize(this.config.capture.maxBreadcrumbs);\n this.pipeline?.refresh();\n\n if (this.ready) {\n this.reinstallCaptures();\n }\n\n this.diagnostics.report(\n \"config.reconfigured\",\n \"configure() was called again, the existing runtime was updated\",\n );\n }\n\n /** Initializes asynchronous subsystems and flushes the boot buffer. */\n private async init(): Promise<void> {\n try {\n const journeyReady = this.journey.bootstrap();\n const role = await this.bus.start();\n\n if (role === \"sender\") {\n await this.becomeSender();\n }\n\n await journeyReady;\n this.installCaptures();\n } catch (error) {\n this.diagnostics.report(\n \"pipeline.crashed\",\n \"startup failed, continuing in a degraded state\",\n undefined,\n error,\n );\n } finally {\n // Flushes buffered boot records regardless of startup outcome.\n this.ready = true;\n this.releaseBootBuffer();\n }\n }\n\n /** Initializes storage, transport, pipeline, and unload listeners for sender role. */\n private async becomeSender(): Promise<void> {\n this.storage = await createStorage(\n this.config.storage.strategy,\n this.config.storage.dbName,\n this.config.storage,\n this.diagnostics,\n this.reportGap,\n );\n this.transport = new HttpTransport(this.config, this.diagnostics);\n this.retry = new RetryEngine(this.storage, this.transport, this.diagnostics, this.config);\n this.pipeline = new LogPipeline(\n this.config,\n this.transport,\n this.storage,\n this.retry,\n this.diagnostics,\n );\n\n this.exitFlush = new ExitFlush({\n config: this.config,\n diagnostics: this.diagnostics,\n drainPending: () => this.pipeline?.drainPending() ?? null,\n });\n\n await drainEmergencyQueue(this.storage, this.diagnostics);\n\n this.retry.start();\n this.exitFlush.install();\n }\n\n /** Instantiates and registers enabled auto-capture modules. */\n private installCaptures(): void {\n const ctx = {\n config: this.config,\n diagnostics: this.diagnostics,\n breadcrumbs: this.breadcrumbs,\n tracing: this.tracing,\n logger: new OneLogger(this, CAPTURE_NAMESPACE),\n };\n const settings = this.config.capture;\n\n if (settings.errors || settings.rejections || settings.resourceErrors) {\n this.captures.push(new ErrorCapture(ctx));\n }\n if (settings.fetch || settings.xhr) {\n this.captures.push(new NetworkCapture(ctx));\n }\n if (settings.interactions || settings.navigation) {\n this.captures.push(new InteractionCapture(ctx));\n }\n if (settings.webVitals) {\n this.captures.push(new WebVitalsCapture(ctx));\n }\n\n for (const capture of this.captures) {\n this.diagnostics.guard(\"capture.install_failed\", `installing ${capture.name}`, () => {\n capture.install();\n });\n }\n }\n\n /** Uninstalls active capture modules and re-creates them from updated configuration. */\n private reinstallCaptures(): void {\n for (const capture of this.captures) {\n this.diagnostics.guard(\"capture.install_failed\", `uninstalling ${capture.name}`, () => {\n capture.uninstall();\n });\n }\n this.captures.length = 0;\n this.installCaptures();\n }\n\n /**\n * Attaches a Web Worker or MessagePort to the bus for record forwarding.\n * @param worker Target Worker or MessagePort instance.\n */\n registerWorker(worker: WorkerLike): void {\n if (this.destroyed) {\n return;\n }\n\n this.diagnostics.guard(\"bus.send_failed\", \"registering a worker\", () => {\n this.bus.attachWorker(worker);\n });\n }\n\n /** Flushes pending telemetry, unregisters listeners, and unpins the runtime instance. */\n async destroy(): Promise<void> {\n if (this.destroyed) {\n return;\n }\n this.destroyed = true;\n\n for (const capture of this.captures) {\n capture.uninstall();\n }\n this.captures.length = 0;\n\n this.exitFlush?.flush(\"shutdown\");\n this.exitFlush?.uninstall();\n this.retry?.stop();\n this.pipeline?.destroy();\n this.journey.destroy();\n this.bus.destroy();\n this.forwardBuffer = [];\n await this.storage?.close();\n\n if (ObservabilityRuntime.current() === this) {\n Reflect.deleteProperty(globalThis, RUNTIME_KEY);\n }\n }\n\n /**\n * Routes a completed log record to the pipeline or forward buffer.\n * @param record Log record to emit, or null if dropped during build.\n */\n emit(record: LogRecord | null): void {\n if (!record || this.destroyed) {\n return;\n }\n\n touchSession(this.identity.sessionId, this.diagnostics);\n\n if (!this.ready) {\n if (this.bootBuffer.length >= this.config.bus.maxBootBufferRecords) {\n this.bootBuffer.shift();\n this.diagnostics.count(\"record.dropped_boot_buffer_full\");\n }\n this.bootBuffer.push(record);\n return;\n }\n\n this.route(record);\n }\n\n /**\n * Directs a record to the forward buffer or local pipeline based on active bus role.\n * @param record Log record to route.\n */\n private route(record: LogRecord): void {\n if (this.bus.getRole() === \"forwarder\") {\n this.forward(record);\n return;\n }\n\n this.pipeline?.push(record);\n }\n\n /**\n * Batches records for asynchronous transmission to the upstream sender.\n * @param record Log record to forward.\n */\n private forward(record: LogRecord): void {\n this.forwardBuffer.push(record);\n if (this.forwardScheduled) {\n return;\n }\n this.forwardScheduled = true;\n\n queueMicrotask(() => {\n this.forwardScheduled = false;\n const records = this.forwardBuffer;\n this.forwardBuffer = [];\n if (records.length > 0) {\n this.bus.sendRecords(records);\n }\n });\n }\n\n /**\n * Validates and enqueues records received from child frames or workers.\n * @param records Inbound payload from bus.\n */\n private ingestForwarded(records: unknown): void {\n if (!Array.isArray(records)) {\n this.diagnostics.count(\"record.dropped_malformed\");\n return;\n }\n\n for (const record of records) {\n if (!isLogRecord(record)) {\n this.diagnostics.count(\"record.dropped_malformed\");\n continue;\n }\n this.pipeline?.push(record);\n }\n }\n\n /** Flushes records buffered during startup and backfills active journey metadata. */\n private releaseBootBuffer(): void {\n const buffered = this.bootBuffer;\n this.bootBuffer = [];\n const journey = this.journey.current();\n\n for (const record of buffered) {\n if (journey && !record.attributes[\"journey.id\"]) {\n record.attributes[\"journey.id\"] = journey.id;\n record.attributes[\"journey.name\"] = journey.name;\n }\n this.route(record);\n }\n }\n\n /**\n * Emits a warning log record when batches are evicted from persistent storage.\n * @param result Storage prune summary metrics.\n */\n private readonly reportGap = (result: PruneResult): void => {\n const now = Date.now();\n if (now - this.lastGapAt < GAP_REPORT_THROTTLE_MS) {\n return;\n }\n this.lastGapAt = now;\n\n new OneLogger(this, STORAGE_NAMESPACE).warn(\"stored records were dropped before delivery\", {\n \"gap.batches\": result.batches,\n \"gap.records\": result.records,\n \"gap.reason\": result.reason,\n });\n };\n\n /** Generates and persists a replacement tab ID when a collision is detected. */\n private regenerateTabId(): void {\n const fresh = newId();\n this.diagnostics.report(\n \"bus.role_resolved\",\n \"another context claimed this tab id, most likely a duplicated tab. Regenerating.\",\n { was: this.identity.tabId, now: fresh },\n );\n\n (this.identity as { tabId: string }).tabId = fresh;\n this.diagnostics.guard(\"storage.unavailable\", \"persisting the new tab id\", () => {\n sessionStorage.setItem(TAB_ID_KEY, fresh);\n });\n this.builder.invalidateResource();\n }\n\n /**\n * Counts the batches held in storage after a failed or deferred delivery.\n * @returns Promise resolving to the number of stored batches. A forwarder reports 0, because it persists nothing.\n */\n async queueDepth(): Promise<number> {\n const count = await this.diagnostics.guardAsync(\n \"storage.degraded\",\n \"counting the batches waiting in storage\",\n () => this.storage?.count() ?? Promise.resolve(0),\n );\n\n return count ?? 0;\n }\n\n /**\n * Flushes all pending records in the pipeline or forward buffer.\n * @returns Promise resolving when queued records are transmitted or handed off.\n */\n async flush(): Promise<void> {\n if (this.bus.getRole() === \"forwarder\") {\n const records = this.forwardBuffer;\n this.forwardBuffer = [];\n if (records.length > 0) {\n this.bus.sendRecords(records);\n }\n return;\n }\n\n const batch = this.pipeline?.drainPending();\n if (!batch || !this.transport) {\n return;\n }\n\n try {\n await this.transport.send(batch);\n } catch (error) {\n await this.diagnostics.guardAsync(\n \"storage.degraded\",\n \"persisting the batch drained by flush()\",\n async () => {\n await this.storage?.save({ ...batch, attempts: 1 });\n this.retry?.nudge();\n },\n );\n this.diagnostics.report(\n \"transport.http_error\",\n \"the batch drained by flush() was stored for retry instead of being delivered\",\n { batchId: batch.id, records: batch.records.length },\n error,\n );\n }\n }\n}\n","// src/index.ts\n//\n// Public library entry point exporting facade APIs, logging primitives, and types.\n\nimport type { WorkerLike } from \"./bus/links\";\nimport type { Journey } from \"./core/journey\";\nimport { OneLogger, type OneLoggerOptions } from \"./core/logger\";\nimport { ObservabilityRuntime } from \"./core/runtime\";\nimport type { ObservabilityConfig } from \"./models/config\";\nimport type { MetricType } from \"./models/log-record\";\n\nexport { OneLogger };\nexport type { Journey, ObservabilityConfig, OneLoggerOptions };\nexport type { WorkerLike } from \"./bus/links\";\nexport type { DiagnosticCode, DiagnosticEvent } from \"./core/diagnostics\";\nexport type { LogLevel, LogRecord, LogType, MetricType } from \"./models/log-record\";\nexport type { LogSerializer, SerializedBatch } from \"./models/serializer\";\nexport type { StorageAdapter } from \"./models/storage\";\n\n/** Cached logger instances keyed by namespace and options. */\nconst loggers = new Map<string, OneLogger>();\n\n/**\n * Retrieves the active realm runtime, initializing an implicit default if unconfigured.\n * @returns Active runtime instance.\n */\nfunction requireRuntime(): ObservabilityRuntime {\n const runtime = ObservabilityRuntime.current();\n if (runtime) {\n return runtime;\n }\n\n // Configures implicit runtime to prevent throws on unconfigured log calls.\n return ObservabilityRuntime.configure({});\n}\n\n/**\n * Initializes or reconfigures the observability runtime instance.\n * @param config Consumer configuration options.\n */\nexport function configure(config: Partial<ObservabilityConfig>): void {\n ObservabilityRuntime.configure(config);\n // Clears cached loggers to rebind them to the updated runtime.\n loggers.clear();\n}\n\n/**\n * Retrieves or creates a cached logger instance for a namespace.\n * @param namespace Application subsystem or module namespace.\n * @param options Scoped context merged into records emitted by this logger.\n * @returns Cached OneLogger instance.\n */\nexport function getLogger(namespace: string, options?: OneLoggerOptions): OneLogger {\n const key = options ? `${namespace}::${JSON.stringify(options)}` : namespace;\n let logger = loggers.get(key);\n\n if (!logger) {\n logger = new OneLogger(requireRuntime(), namespace, options);\n loggers.set(key, logger);\n }\n\n return logger;\n}\n\n/**\n * Retrieves the default root logger instance.\n * @returns Root OneLogger instance for the \"app\" namespace.\n */\nfunction root(): OneLogger {\n return getLogger(\"app\");\n}\n\n/**\n * Logs a trace-level debug record.\n * @param message Detail message.\n * @param payload Optional contextual attributes.\n */\nexport function trace(message: string, payload?: Record<string, unknown>): void {\n root().trace(message, payload);\n}\n\n/**\n * Logs a debug-level record.\n * @param message Detail message.\n * @param payload Optional contextual attributes.\n */\nexport function debug(message: string, payload?: Record<string, unknown>): void {\n root().debug(message, payload);\n}\n\n/**\n * Logs an informational record.\n * @param message Informational message.\n * @param payload Optional contextual attributes.\n */\nexport function info(message: string, payload?: Record<string, unknown>): void {\n root().info(message, payload);\n}\n\n/**\n * Logs a warning record.\n * @param message Warning message.\n * @param payload Optional contextual attributes.\n */\nexport function warn(message: string, payload?: Record<string, unknown>): void {\n root().warn(message, payload);\n}\n\n/**\n * Logs an error record with causal error and breadcrumbs.\n * @param message Error summary.\n * @param err Caught error instance or reason.\n * @param payload Optional contextual attributes.\n */\nexport function error(message: string, err?: unknown, payload?: Record<string, unknown>): void {\n root().error(message, err, payload);\n}\n\n/**\n * Logs a discrete user interaction action.\n * @param name Action identifier.\n * @param payload Optional action attributes.\n */\nexport function logAction(name: string, payload?: Record<string, unknown>): void {\n root().logAction(name, payload);\n}\n\n/**\n * Logs an application lifecycle or domain event.\n * @param name Event identifier.\n * @param payload Optional event attributes.\n */\nexport function logEvent(name: string, payload?: Record<string, unknown>): void {\n root().logEvent(name, payload);\n}\n\n/**\n * Logs a numerical metric measurement.\n * @param name Metric identifier.\n * @param value Measured value.\n * @param unit Unit of measurement.\n * @param type Metric type classification.\n * @param attributes Optional metric attributes.\n */\nexport function logMetric(\n name: string,\n value: number,\n unit?: string,\n type?: MetricType,\n attributes?: Record<string, unknown>,\n): void {\n root().logMetric(name, value, unit, type, attributes);\n}\n\n/**\n * Measures the execution time of a synchronous function and logs a duration metric.\n * @param label Metric name prefix.\n * @param fn Synchronous function to time.\n * @param attributes Optional contextual attributes.\n * @returns Result returned by the timed function.\n */\nexport function timeSync<T>(label: string, fn: () => T, attributes?: Record<string, unknown>): T {\n return root().timeSync(label, fn, attributes);\n}\n\n/**\n * Measures the execution time of an asynchronous function and logs a duration metric.\n * @param label Metric name prefix.\n * @param fn Asynchronous function to time.\n * @param attributes Optional contextual attributes.\n * @returns Promise resolving to the result of the timed function.\n */\nexport function timeAsync<T>(\n label: string,\n fn: () => Promise<T>,\n attributes?: Record<string, unknown>,\n): Promise<T> {\n return root().timeAsync(label, fn, attributes);\n}\n\n/**\n * Sets a key-value pair on ambient context included in subsequent records.\n * @param key Attribute key.\n * @param value Attribute value.\n */\nexport function setContext(key: string, value: unknown): void {\n requireRuntime().context.set(key, value);\n}\n\n/**\n * Merges multiple key-value pairs into the ambient context.\n * @param values Key-value map of attributes to add.\n */\nexport function setContextMap(values: Record<string, unknown>): void {\n requireRuntime().context.setMany(values);\n}\n\n/**\n * Removes an attribute from the ambient context.\n * @param key Attribute key to delete.\n */\nexport function removeContext(key: string): void {\n requireRuntime().context.remove(key);\n}\n\n/**\n * Starts a new journey correlation context.\n * @param name Journey workflow identifier.\n * @param options Configuration options including parent linking.\n * @returns Started Journey instance.\n */\nexport function startJourney(name: string, options?: { parent?: boolean }): Journey {\n return requireRuntime().journey.start(name, options);\n}\n\n/** Terminates the active journey correlation context. */\nexport function endJourney(): void {\n requireRuntime().journey.end();\n}\n\n/**\n * Returns the currently active journey, or null if none is in progress.\n * @returns Active Journey instance or null.\n */\nexport function currentJourney(): Journey | null {\n return requireRuntime().journey.current();\n}\n\n/**\n * Serializes active journey metadata into a cross-context URL token.\n * @returns Serialized token string, or undefined if no journey is active.\n */\nexport function getJourneyToken(): string | undefined {\n return requireRuntime().journey.getToken();\n}\n\n/**\n * Adopts a serialized journey token into this application realm.\n * @param token Serialized journey token.\n * @returns True if token was valid and successfully adopted.\n */\nexport function adoptJourney(token: string): boolean {\n return requireRuntime().journey.adopt(token, \"manual\", true);\n}\n\n/**\n * Connects a Web Worker or MessagePort to the document bus for record routing.\n * @param worker Target Worker or MessagePort instance.\n */\nexport function registerWorker(worker: WorkerLike): void {\n requireRuntime().registerWorker(worker);\n}\n\n/** Rotates trace context to begin a new distributed trace. */\nexport function startTrace(): void {\n requireRuntime().tracing.rotate(\"explicit\");\n}\n\n/**\n * Returns W3C traceparent headers for outgoing HTTP request propagation.\n * @returns Map of trace header keys and values.\n */\nexport function getTraceHeaders(): Record<string, string> {\n return requireRuntime().tracing.headers();\n}\n\n/**\n * Flushes all pending log batches across pipeline streams.\n * @returns Promise resolving once queued batches are processed.\n */\nexport function flush(): Promise<void> {\n return requireRuntime().flush();\n}\n\n/**\n * Counts the batches waiting in storage for delivery.\n * @returns Promise resolving to the number of stored batches. A forwarder reports 0, because it persists nothing.\n */\nexport function getQueueDepth(): Promise<number> {\n return requireRuntime().queueDepth();\n}\n\n/**\n * Returns a snapshot of cumulative diagnostic event counts.\n * @returns Map of diagnostic fault codes to occurrence counts.\n */\nexport function getDiagnosticCounters(): Record<string, number> {\n return requireRuntime().diagnostics.snapshot();\n}\n\n/**\n * Flushes pending records and tears down all runtime subsystems.\n * @returns Promise resolving once shutdown completes.\n */\nexport async function shutdown(): Promise<void> {\n const runtime = ObservabilityRuntime.current();\n // Clears cached logger references to release the terminated runtime.\n loggers.clear();\n await runtime?.destroy();\n}\n"],"mappings":"qKAYA,SAAS,EAAQ,EAA2B,CAC1C,OAAO,KAAK,OAAO,YAAY,IAAI,EAAI,GAAa,EAAA,CAAkB,EAAI,EAAA,CAC5E,CAUA,SAAS,EACP,EACA,EACA,EACA,EACA,EACM,CACN,EAAO,UAAU,GAAG,EAAM,WAAY,EAAQ,CAAS,EAAG,KAAM,YAAa,CAC3E,SACA,GAAG,CACL,CAAC,CACH,CAUA,SAAS,EACP,EACA,EACA,EACA,EACA,EACM,CACN,EAAO,MAAM,GAAG,EAAM,SAAU,EAAO,CACrC,qBAAsB,EAAQ,CAAS,EACvC,OAAQ,UACR,GAAG,CACL,CAAC,CACH,CAUA,SAAgB,EACd,EACA,EACA,EACA,EACG,CACH,IAAM,EAAY,YAAY,IAAI,EAClC,GAAI,CACF,IAAM,EAAS,EAAG,EAElB,OADA,EAAO,EAAQ,EAAO,EAAW,UAAW,CAAU,EAC/C,CACT,OAAS,EAAO,CAGd,MADA,EAAK,EAAQ,EAAO,EAAW,EAAO,CAAU,EAC1C,CACR,CACF,CAUA,eAAsB,EACpB,EACA,EACA,EACA,EACY,CACZ,IAA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