@utk09/ui-observability 0.5.0 → 0.7.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/CHANGELOG.md +31 -0
- package/README.md +119 -60
- package/dist/bus/bus.d.ts +10 -10
- package/dist/bus/links.d.ts +1 -1
- package/dist/bus-DeZzr2bx.cjs +2 -0
- package/dist/bus-DeZzr2bx.cjs.map +1 -0
- package/dist/{bus-D3OO0OcL.js → bus-DfAbg_pg.js} +19 -19
- package/dist/bus-DfAbg_pg.js.map +1 -0
- package/dist/capture/network.d.ts +2 -2
- package/dist/capture/types.d.ts +10 -10
- package/dist/capture/web-vitals.d.ts +3 -3
- package/dist/constants-C8nZQBmQ.js +86 -0
- package/dist/constants-C8nZQBmQ.js.map +1 -0
- package/dist/constants-IBL_jd5R.cjs +2 -0
- package/dist/constants-IBL_jd5R.cjs.map +1 -0
- package/dist/constants.d.ts +56 -43
- package/dist/core/breadcrumbs.d.ts +14 -14
- package/dist/core/config.d.ts +5 -4
- package/dist/core/context.d.ts +2 -2
- package/dist/core/diagnostics.d.ts +10 -9
- package/dist/core/journey.d.ts +23 -20
- package/dist/core/logger.d.ts +7 -7
- package/dist/core/pipeline.d.ts +34 -29
- package/dist/core/record.d.ts +6 -6
- package/dist/core/runtime.d.ts +20 -18
- package/dist/core/sampling.d.ts +15 -16
- package/dist/core/sender.d.ts +1 -1
- package/dist/{errors-Dme9tz-6.js → errors-4MQyjZVj.js} +4 -4
- package/dist/errors-4MQyjZVj.js.map +1 -0
- package/dist/{errors-DPju_xSI.cjs → errors-CUdShXe7.cjs} +2 -2
- package/dist/errors-CUdShXe7.cjs.map +1 -0
- package/dist/index.cjs +1 -1
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.ts +7 -5
- package/dist/index.js +136 -115
- package/dist/index.js.map +1 -1
- package/dist/{indexeddb-storage-nxs_rxGx.js → indexeddb-storage-0LtUALBg.js} +16 -16
- package/dist/indexeddb-storage-0LtUALBg.js.map +1 -0
- package/dist/indexeddb-storage-CcEJlq2l.cjs +2 -0
- package/dist/indexeddb-storage-CcEJlq2l.cjs.map +1 -0
- package/dist/{interactions-DP0-rIPJ.cjs → interactions-BMNPQ3WH.cjs} +2 -2
- package/dist/interactions-BMNPQ3WH.cjs.map +1 -0
- package/dist/{interactions-C1romMpE.js → interactions-BaCmoGLB.js} +2 -2
- package/dist/interactions-BaCmoGLB.js.map +1 -0
- package/dist/models/batch.d.ts +12 -9
- package/dist/models/bus.d.ts +12 -13
- package/dist/models/config.d.ts +85 -44
- package/dist/models/log-record.d.ts +12 -10
- package/dist/models/serializer.d.ts +3 -2
- package/dist/models/storage.d.ts +2 -2
- package/dist/network-DBNvxCE3.cjs +2 -0
- package/dist/network-DBNvxCE3.cjs.map +1 -0
- package/dist/{network-au-Tqt1n.js → network-jQ2t8rU4.js} +4 -4
- package/dist/network-jQ2t8rU4.js.map +1 -0
- package/dist/platform-ByQllE_W.cjs +2 -0
- package/dist/platform-ByQllE_W.cjs.map +1 -0
- package/dist/{platform-DMYo3AX3.js → platform-YuByH8A5.js} +8 -8
- package/dist/platform-YuByH8A5.js.map +1 -0
- package/dist/{sampling-ByI5H44E.js → sampling-CbYySsZ1.js} +21 -18
- package/dist/sampling-CbYySsZ1.js.map +1 -0
- package/dist/sampling-Cs50xsZl.cjs +2 -0
- package/dist/sampling-Cs50xsZl.cjs.map +1 -0
- package/dist/{sender-R7lOpyNc.js → sender-BIob8eZz.js} +60 -60
- package/dist/sender-BIob8eZz.js.map +1 -0
- package/dist/sender-iOjzcueM.cjs +3 -0
- package/dist/sender-iOjzcueM.cjs.map +1 -0
- package/dist/storage/emergency-queue.d.ts +2 -2
- package/dist/storage/factory.d.ts +2 -1
- package/dist/storage/idb-driver.d.ts +19 -19
- package/dist/storage/indexeddb-storage.d.ts +18 -17
- package/dist/storage/keys.d.ts +1 -1
- package/dist/storage/local-storage.d.ts +19 -18
- package/dist/storage/memory-storage.d.ts +12 -11
- package/dist/transport/compression.d.ts +2 -2
- package/dist/transport/errors.d.ts +8 -7
- package/dist/transport/exit-flush.d.ts +27 -24
- package/dist/transport/http-transport.d.ts +18 -11
- package/dist/transport/retry-engine.d.ts +33 -28
- package/dist/transport/serializers/ecs.d.ts +1 -1
- package/dist/transport/serializers/otlp.d.ts +1 -1
- package/dist/unref-16maCyKA.js.map +1 -1
- package/dist/unref-CU9Nyz_9.cjs.map +1 -1
- package/dist/utils/console.d.ts +7 -6
- package/dist/utils/identity.d.ts +6 -5
- package/dist/utils/lock.d.ts +4 -4
- package/dist/utils/platform.d.ts +5 -3
- package/dist/utils/sanitize.d.ts +5 -2
- package/dist/utils/sequence.d.ts +2 -2
- package/dist/utils/tracing.d.ts +8 -7
- package/dist/web-vitals-B2FYsEAU.cjs +2 -0
- package/dist/web-vitals-B2FYsEAU.cjs.map +1 -0
- package/dist/{web-vitals-DwWdLBq6.js → web-vitals-DHZ0yA_H.js} +4 -4
- package/dist/web-vitals-DHZ0yA_H.js.map +1 -0
- package/package.json +4 -2
- package/dist/bus-D3OO0OcL.js.map +0 -1
- package/dist/bus-OdRJVUzr.cjs +0 -2
- package/dist/bus-OdRJVUzr.cjs.map +0 -1
- package/dist/constants-B6kdsCzF.js +0 -75
- package/dist/constants-B6kdsCzF.js.map +0 -1
- package/dist/constants-DZH04585.cjs +0 -2
- package/dist/constants-DZH04585.cjs.map +0 -1
- package/dist/errors-DPju_xSI.cjs.map +0 -1
- package/dist/errors-Dme9tz-6.js.map +0 -1
- package/dist/indexeddb-storage-lGdoHGHy.cjs +0 -2
- package/dist/indexeddb-storage-lGdoHGHy.cjs.map +0 -1
- package/dist/indexeddb-storage-nxs_rxGx.js.map +0 -1
- package/dist/interactions-C1romMpE.js.map +0 -1
- package/dist/interactions-DP0-rIPJ.cjs.map +0 -1
- package/dist/network-DDVIJSHd.cjs +0 -2
- package/dist/network-DDVIJSHd.cjs.map +0 -1
- package/dist/network-au-Tqt1n.js.map +0 -1
- package/dist/platform-DMYo3AX3.js.map +0 -1
- package/dist/platform-g99Kn755.cjs +0 -2
- package/dist/platform-g99Kn755.cjs.map +0 -1
- package/dist/sampling-ByI5H44E.js.map +0 -1
- package/dist/sampling-Dui-Fp3u.cjs +0 -2
- package/dist/sampling-Dui-Fp3u.cjs.map +0 -1
- package/dist/sender-R7lOpyNc.js.map +0 -1
- package/dist/sender-vLcbQhiB.cjs +0 -3
- package/dist/sender-vLcbQhiB.cjs.map +0 -1
- package/dist/web-vitals-DM2nvcMJ.cjs +0 -2
- package/dist/web-vitals-DM2nvcMJ.cjs.map +0 -1
- package/dist/web-vitals-DwWdLBq6.js.map +0 -1
package/dist/index.cjs.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.cjs","names":["DURATION_PRECISION","timeSync","timeAsync","DEFAULT_METRIC_UNIT","timeSync","timeAsync","LEVEL_ORDER","sanitize","RECORD_LIMITS","CONSOLE_PREFIX_STYLE","randomHex","TRACE_MAX_AGE_MS","TRACEPARENT_HEADER","SERIALIZER_NAME_OTLP","CONSOLE_DEFAULT_LEVEL","DEFAULT_CONFIG","UNKNOWN_SERVICE_NAME","UNDEFAULTED_CONFIG_KEYS","CONFIG_SECTIONS","UNDEFAULTED_SECTION_KEYS","DIAGNOSTIC_THROTTLE_MS","LIBRARY_LOG_PREFIX","JOURNEY_MAX_AGE_MS","JOURNEY_URL_PARAM","BASE64_PLUS_PATTERN","BASE64_SLASH_PATTERN","BASE64_PADDING_PATTERN","BROWSER_STORES","JOURNEY_STORAGE_KEY","newId","BASE64URL_DASH_PATTERN","BASE64URL_UNDERSCORE_PATTERN","withDeadline","OPENFIN_OPTIONS_TIMEOUT_MS","OPENFIN_JOURNEY_CUSTOM_DATA_KEY","LEVEL_ORDER","shouldSampleInput","currentUrl","stripUrlQuery","sanitizeWithSize","ATTR_SANITIZE_FAILED","ATTR_LOG_TYPE","ATTR_LOG_SEQ","ATTR_APP_NAMESPACE","ATTR_PAGE_URL","ATTR_JOURNEY_ID","ATTR_JOURNEY_NAME","ATTR_JOURNEY_PARENT_ID","truncate","nowUnixNano","SEVERITY_NUMBER","isLogRecord","ATTR_ATTRIBUTES_DROPPED","ATTR_ATTRIBUTES_BYTES","RESOURCE_SERVICE_NAME","RESOURCE_SERVICE_VERSION","RESOURCE_DEPLOYMENT_ENVIRONMENT","RESOURCE_TELEMETRY_SDK_NAME","TELEMETRY_SDK_NAME","RESOURCE_TELEMETRY_SDK_VERSION","TELEMETRY_SDK_VERSION","RESOURCE_TELEMETRY_SDK_LANGUAGE","TELEMETRY_SDK_LANGUAGE","RESOURCE_HOST_PLATFORM","RESOURCE_SESSION_ID","RESOURCE_TAB_ID","RESOURCE_CONTEXT_ID","RESOURCE_BROWSER_USER_AGENT","RESOURCE_OPENFIN_UUID","RESOURCE_OPENFIN_NAME","RUNTIME_GLOBAL_KEY","RUNTIME_STOPPED_KEY","detectPlatform","memoryStores","BROWSER_STORES","resolveIdentity","SessionTouch","RECORD_LIMITS","CAPTURE_NAMESPACE","isLogRecord","shouldSample","STORAGE_NAMESPACE","newId","require_constants","require_sampling","require_platform","require_unref","elapsed","startedAt","finish","logger","label","attributes","fail","error","timeSync$1","result","fn","timeAsync$1","toError","value","text","diagnostics","isPlainObject","proto","OneLogger","bind","namespace","options","message","payload","name","unit","type","runtime","level","body","dropped","record","ships","asPayload","asError","METHOD","ConsoleSink","minLevel","prefix","method","details","Sequence","TRACE_ID_PATTERN","SPAN_ID_PATTERN","NON_ZERO","isUsableSpanContext","context","newTraceId","newSpanId","mintAmbient","toTraceContext","ambient","TraceEngine","maxAgeMs","load","fromOtel","otel","span","spanContext","carrier","\"traceparent\"","ctx","flags","BreadcrumbBuffer","capacity","crumb","isSerializer","resolveSerializer","requested","previous","resolveConsole","resolveConfig","base","merged","input","rate","rates","ns","r","url","reportUnknownKeys","known","key","section","values","sectionKeys","applyResolvedConfig","next","target","ContextStore","Diagnostics","handler","throttleMs","total","code","by","count","now","event","handlerError","JOURNEY_OPTIONS","readString","source","readNumber","journeyFromStorage","id","journeyFromTokenPayload","encodeToken","json","journey","bytes","binary","byte","JourneyEngine","contextId","onLocalChange","stores","fromUrl","fromStorage","fromOpenFin","opts","current","token","decoded","broadcast","ownerContextId","raw","standard","missing","padding","c","remaining","timer","me","getOptions","asAttributes","RecordBuilder","deps","config","traceCtx","tracing","activeJourney","seq","sequence","pageUrl","fromContext","limits","fromScope","fromPayload","redact","redacted","remeasured","kept","platform","identity","CAPTURE_LOADERS","RUNTIME_KEY","STOPPED_KEY","ObservabilityRuntime","bus","reply","existing","accepted","built","captures","journeyReady","Bus","records","sender","Sender","held","generation","settings","names","classes","CaptureModule","capture","worker","closing","buffer","buffered","fresh","loggers","requireRuntime","configure","getLogger","root","trace","debug","info","warn","err","logAction","logEvent","logMetric","timeSync","timeAsync","setContext","setContextMap","removeContext","startJourney","endJourney","currentJourney","getJourneyToken","adoptJourney","registerWorker","startTrace","getTraceHeaders","flush","getQueueDepth","getDiagnosticCounters","shutdown"],"sources":["../src/utils/timer.ts","../src/core/logger.ts","../src/utils/console.ts","../src/utils/sequence.ts","../src/utils/tracing.ts","../src/core/breadcrumbs.ts","../src/core/config.ts","../src/core/context.ts","../src/core/diagnostics.ts","../src/core/journey.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, LogRecord, LogType, MetricType } from \"../models/log-record\";\nimport { timeAsync, timeSync } from \"../utils/timer\";\nimport type { Diagnostics } from \"./diagnostics\";\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 * @param diagnostics Diagnostics reporter.\n * @returns Normalized Error instance.\n */\nfunction toError(value: unknown, diagnostics: Diagnostics): Error {\n if (value instanceof Error) {\n return value;\n }\n\n // String() throws on a null-prototype object and on a throwing toString.\n // log.error() runs inside a consumer catch block and must not throw out of it.\n const text = diagnostics.guard(\"record.sanitize_failed\", \"describing an error reason\", () =>\n String(value),\n );\n\n return new Error(text ?? typeof value);\n}\n\n/**\n * Tests whether a value is an attribute bag rather than an error reason.\n * Cross-realm safe: an object literal from an iframe has that realm's\n * Object.prototype, whose own prototype is still null.\n * @param value Value found in the error slot.\n * @returns True if the value is a plain object.\n */\nfunction isPlainObject(value: unknown): value is Record<string, unknown> {\n if (typeof value !== \"object\" || value === null || Array.isArray(value)) {\n return false;\n }\n if (value instanceof Error) {\n return false;\n }\n\n const proto = Object.getPrototypeOf(value) as object | null;\n return proto === null || Object.getPrototypeOf(proto) === null;\n}\n\n/** Namespaced logger instance for recording structured events, metrics, and errors. */\nexport class OneLogger {\n /**\n * @param bind Returns the runtime for each write.\n * A logger that exists before configure() writes to the configured runtime.\n * @param namespace Application subsystem or module namespace.\n * @param options Scoped context options.\n */\n constructor(\n private readonly bind: () => 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.bind, `${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. A plain object in the\n * error slot with no payload given is read as the payload.\n * @param message Error description.\n * @param error Caught error instance, reason, or payload.\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. A plain object in the error slot\n * with no payload given is read as the payload.\n * @param message Error description.\n * @param error Caught error instance, reason, or payload.\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 const runtime = this.bind();\n\n // Guard against a write after shutdown. The write must do nothing on the stopped runtime.\n if (runtime.isDestroyed()) {\n return;\n }\n\n // minLevel limits what the library sends. The console level limits what it prints.\n if (!runtime.builder.isEnabled(level)) {\n if (this.mirrors(runtime, level)) {\n this.print(runtime, level, body, payload, undefined, null);\n }\n\n return;\n }\n\n const { record, dropped } = runtime.builder.build({\n level,\n type,\n body,\n namespace: this.namespace,\n scoped: this.options.scopedContext,\n payload,\n });\n\n // Crumbs are memory-only and never billed, so a record sampling dropped still\n // leaves its trail for the next error. A redact hook that dropped the record\n // wanted the body gone, and a crumb would ship it on the next error anyway.\n if (type !== \"metric\" && dropped !== \"redact\") {\n runtime.breadcrumbs.push({\n t: Date.now(),\n category: type === \"action\" ? \"action\" : type === \"event\" ? \"event\" : \"log\",\n message: body,\n });\n }\n\n this.print(runtime, level, body, payload, undefined, record);\n 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, reason, or payload.\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 const runtime = this.bind();\n\n if (runtime.isDestroyed()) {\n return;\n }\n\n const ships = runtime.builder.isEnabled(level);\n\n if (!ships && !this.mirrors(runtime, level)) {\n return;\n }\n\n // Every sibling method is (name, payload?), so log.error(\"failed\", { id })\n // is the natural call. Describing that object as the error reason would put\n // \"[object Object]\" in error.message and drop the caller's fields.\n const asPayload = payload === undefined && isPlainObject(error);\n const attributes = asPayload ? error : payload;\n const asError =\n asPayload || error === undefined ? undefined : toError(error, runtime.diagnostics);\n\n if (!ships) {\n this.print(runtime, level, message, attributes, asError, null);\n return;\n }\n\n const { record } = runtime.builder.build({\n level,\n type: \"system\",\n body: message,\n namespace: this.namespace,\n scoped: this.options.scopedContext,\n payload: {\n ...attributes,\n ...(asError\n ? {\n \"error.type\": asError.name,\n \"error.message\": asError.message,\n \"error.stack_trace\": asError.stack,\n }\n : {}),\n breadcrumbs: runtime.breadcrumbs.snapshot(),\n },\n });\n\n this.print(runtime, level, message, attributes, asError, record);\n runtime.emit(record);\n }\n\n /**\n * Prints one log line. With a redact hook, the line shows only what redact returned.\n * A host can record console arguments. The console must not show what redact removes.\n * @param runtime Runtime of this write.\n * @param level Severity level.\n * @param message Primary message.\n * @param payload Caller payload.\n * @param error Error of an error call.\n * @param record Built record, or null if the library did not build it or redact dropped it.\n */\n private print(\n runtime: ObservabilityRuntime,\n level: LogLevel,\n message: string,\n payload: Record<string, unknown> | undefined,\n error: Error | undefined,\n record: LogRecord | null,\n ): void {\n if (!runtime.config.redact) {\n runtime.console.write(this.namespace, level, message, payload, error);\n return;\n }\n\n // The record attributes hold the error fields after redact.\n if (record) {\n runtime.console.write(this.namespace, level, record.body, record.attributes);\n return;\n }\n\n runtime.console.write(this.namespace, level, message, undefined, error);\n }\n\n /**\n * Tests whether the console prints a level that the library does not send.\n * @param runtime Runtime of this write.\n * @param level Severity level.\n * @returns True if logging is on and the console accepts the level.\n */\n private mirrors(runtime: ObservabilityRuntime, level: LogLevel): boolean {\n return runtime.config.enabled && runtime.console.accepts(level);\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, RECORD_LIMITS } from \"../constants\";\nimport type { Diagnostics } from \"../core/diagnostics\";\nimport type { LogLevel } from \"../models/log-record\";\nimport { sanitize } from \"./sanitize\";\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 minLevel Minimum log level required to emit, or null to mirror nothing.\n * @param diagnostics Diagnostics reporter.\n */\n constructor(\n private minLevel: LogLevel | null,\n private diagnostics: Diagnostics,\n ) {}\n\n /**\n * Updates the console mirroring threshold.\n * @param minLevel Minimum log level required to emit, or null to mirror nothing.\n */\n update(minLevel: LogLevel | null): void {\n this.minLevel = minLevel;\n }\n\n /**\n * Tests whether a level clears the console threshold.\n * @param level Severity level of the record.\n * @returns True if the sink prints this level.\n */\n accepts(level: LogLevel): boolean {\n return this.minLevel !== null && LEVEL_ORDER[level] >= LEVEL_ORDER[this.minLevel];\n }\n\n /**\n * Prints a styled log line if the level clears the console threshold.\n * @param namespace Logger namespace, shown in the prefix.\n * @param level Severity level of the record.\n * @param message Primary log message.\n * @param payload Caller payload. The sink prints a sanitized copy.\n * @param error Error to print before the payload.\n */\n write(\n namespace: string,\n level: LogLevel,\n message: string,\n payload?: Record<string, unknown>,\n error?: Error,\n ): void {\n if (!this.accepts(level)) {\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 // The namespace goes in as a %s argument. A %o or %c in it then prints as text.\n const prefix = `%c[%s]%c ${level}`;\n const method = METHOD[level];\n\n // A host can replace console with instrumented methods that throw. Unguarded,\n // the mirror takes down the caller's log call.\n this.diagnostics.guard(\"handler.threw\", `mirroring to console.${method}`, () => {\n const details: unknown[] = [];\n\n if (error !== undefined) {\n details.push(error);\n }\n\n // Devtools keeps a reference to each logged object. A copy releases the caller's object.\n if (payload !== undefined) {\n details.push(sanitize(payload, RECORD_LIMITS));\n }\n\n console[method](prefix, CONSOLE_PREFIX_STYLE, namespace, \"\", message, ...details);\n });\n }\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 SPAN_ID_BYTES,\n TRACE_FLAGS_MASK,\n TRACE_FLAGS_SAMPLED,\n TRACE_ID_BYTES,\n TRACE_MAX_AGE_MS,\n TRACEPARENT_HEADER,\n TRACEPARENT_VERSION,\n} from \"../constants\";\nimport type { Diagnostics } from \"../core/diagnostics\";\nimport type { OtelApi, OtelLoader, OtelSpanContext } from \"../models/config\";\nimport { randomHex } from \"./identity\";\n\n/** Hex widths the W3C format fixes. A span context of another width is unusable. */\nconst TRACE_ID_PATTERN = /^[0-9a-f]{32}$/;\nconst SPAN_ID_PATTERN = /^[0-9a-f]{16}$/;\n\n/** Any digit other than zero. An all-zero id is what an unstarted span reports. */\nconst NON_ZERO = /[1-9a-f]/;\n\n/**\n * Evaluates whether a span context can carry correlation. Replaces the\n * package's own isSpanContextValid, which is not available when the peer is not\n * installed.\n * @param context Span context reported by the host.\n * @returns True if both ids have the W3C width and neither is all zeros.\n */\nfunction isUsableSpanContext(context: OtelSpanContext): boolean {\n return (\n TRACE_ID_PATTERN.test(context.traceId) &&\n NON_ZERO.test(context.traceId) &&\n SPAN_ID_PATTERN.test(context.spanId) &&\n NON_ZERO.test(context.spanId)\n );\n}\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 /** The optional peer once loaded. Undefined while it loads, and forever if it is absent. */\n private otel: OtelApi | undefined;\n\n /**\n * @param diagnostics Diagnostics reporter.\n * @param maxAgeMs Maximum lifetime of an un-rotated ambient trace in milliseconds.\n * @param load Loader for the OpenTelemetry API. If it is not set, OTel is off.\n * Do not import the peer by name. The Vite dev server fails if the peer is not installed.\n */\n constructor(\n private readonly diagnostics: Diagnostics,\n private readonly maxAgeMs = TRACE_MAX_AGE_MS,\n private readonly load?: OtelLoader,\n ) {}\n\n /**\n * Loads the OpenTelemetry API. Until the load completes, records use the ambient trace.\n * If there is no loader or the load fails, all records use the ambient trace.\n * @returns Promise resolving once the attempt has settled.\n */\n async loadOtel(): Promise<void> {\n if (!this.load) {\n return;\n }\n\n try {\n this.otel = await this.load();\n } catch (error) {\n this.diagnostics.report(\n \"trace.otel_failed\",\n \"@opentelemetry/api is not available, so records carry this library's own trace ids\",\n undefined,\n error,\n );\n }\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.activeSpanContext();\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 * Reads the host's active span, if the peer is loaded and a span is running.\n * @returns Trace context of the active span, or undefined.\n */\n private activeSpanContext(): TraceContext | undefined {\n const otel = this.otel;\n if (!otel) {\n return undefined;\n }\n\n return this.diagnostics.guard(\n \"trace.otel_failed\",\n \"reading the active OpenTelemetry span\",\n (): TraceContext | undefined => {\n const span = otel.trace.getActiveSpan();\n if (span === undefined) {\n return undefined;\n }\n const spanContext = span.spanContext();\n if (!isUsableSpanContext(spanContext)) {\n return undefined;\n }\n return {\n traceId: spanContext.traceId,\n spanId: spanContext.spanId,\n traceFlags: spanContext.traceFlags,\n };\n },\n );\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 const otel = this.otel;\n if (otel) {\n this.diagnostics.guard(\"trace.otel_failed\", \"injecting OpenTelemetry headers\", () => {\n otel.propagation.inject(otel.context.active(), carrier);\n });\n }\n if (!carrier[TRACEPARENT_HEADER]) {\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_HEADER] = `${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 readonly 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 * 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/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 CONSOLE_DEFAULT_LEVEL,\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 UNDEFAULTED_SECTION_KEYS,\n UNKNOWN_SERVICE_NAME,\n} from \"../constants\";\nimport type {\n ConsoleOption,\n ObservabilityConfig,\n ResolvedConfig,\n SerializerChoice,\n} from \"../models/config\";\nimport type { LogLevel } from \"../models/log-record\";\nimport type { LogSerializer } from \"../models/serializer\";\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 * Validates the serializer option. A name stays a name. The transport selects the implementation.\n * @param requested Serializer name or custom serializer implementation.\n * @param previous Serializer option in force.\n * @param diagnostics Diagnostics reporter.\n * @returns Valid serializer option.\n */\nfunction resolveSerializer(\n requested: unknown,\n previous: SerializerChoice | undefined,\n diagnostics: Diagnostics,\n): SerializerChoice {\n if (requested === undefined) {\n return previous ?? SERIALIZER_NAME_OTLP;\n }\n if (requested === SERIALIZER_NAME_OTLP || requested === SERIALIZER_NAME_ECS) {\n return requested;\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 SERIALIZER_NAME_OTLP;\n}\n\n/**\n * Normalizes the console option into a minimum mirror level.\n * @param requested Consumer console option.\n * @param previous Console level in force.\n * @returns Min level to mirror, or null when mirroring is off.\n */\nfunction resolveConsole(\n requested: ConsoleOption | undefined,\n previous: LogLevel | null,\n): LogLevel | null {\n if (requested === undefined) {\n return previous;\n }\n if (requested === false) {\n return null;\n }\n if (requested === true) {\n return CONSOLE_DEFAULT_LEVEL;\n }\n return requested;\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 // An unset environment variable gives undefined. Keep the current endpoint.\n endpoint: input.endpoint === undefined ? base.endpoint : input.endpoint,\n // Serializer instance overrides string identifier after object merge.\n serializer: resolveSerializer(input.serializer, previous?.serializer, diagnostics),\n console: resolveConsole(input.console, base.console),\n sampling: {\n ...base.sampling,\n ...input.sampling,\n rates: { ...base.sampling.rates, ...input.sampling?.rates },\n },\n bus: { ...base.bus, ...input.bus },\n capture: { ...base.capture, ...input.capture },\n };\n\n // null selects console-only mode, which is valid. Report only \"\".\n if (merged.endpoint === \"\") {\n diagnostics.report(\n \"config.invalid\",\n \"endpoint is missing. The library builds records and drops them. Set endpoint: null for console-only mode.\",\n );\n } else if (merged.endpoint !== null) {\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 reportUnknownKeys(input, diagnostics);\n\n return merged;\n}\n\n/**\n * Reports a config key that matches nothing in the schema, at the top level and one\n * level inside each section. A typo type-checks through `Partial` and then does\n * nothing: `remoteUrl` for `endpoint`, `capture.webVital` for `capture.webVitals`.\n * Namespace keys under `sampling.rates` are free-form and sit a level deeper.\n * @param input Partial consumer configuration options.\n * @param diagnostics Diagnostics reporter.\n */\nfunction reportUnknownKeys(input: Partial<ObservabilityConfig>, diagnostics: Diagnostics): void {\n const known = new Set<string>([...Object.keys(DEFAULT_CONFIG), ...UNDEFAULTED_CONFIG_KEYS]);\n\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 for (const section of CONFIG_SECTIONS) {\n const values: unknown = input[section];\n\n if (typeof values !== \"object\" || values === null) {\n continue;\n }\n\n const sectionKeys = new Set<string>([\n ...Object.keys(DEFAULT_CONFIG[section]),\n ...UNDEFAULTED_SECTION_KEYS[section],\n ]);\n\n for (const key of Object.keys(values)) {\n if (!sectionKeys.has(key)) {\n diagnostics.report(\n \"config.invalid\",\n `unknown config key \"${section}.${key}\", ignored. Typo?`,\n );\n }\n }\n }\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_ceiling\"\n | \"record.dropped_by_redact\"\n | \"record.dropped_boot_buffer_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_END_ON_OWNER_CLOSE,\n JOURNEY_MAX_AGE_MS,\n JOURNEY_STORAGE_KEY,\n JOURNEY_TOKEN_MAX_CHARS,\n JOURNEY_TOKEN_NAME_MAX_CHARS,\n OPENFIN_JOURNEY_CUSTOM_DATA_KEY,\n JOURNEY_URL_PARAM,\n OPENFIN_OPTIONS_TIMEOUT_MS,\n} from \"../constants\";\nimport { withDeadline } from \"../utils/deadline\";\nimport { BROWSER_STORES, type IdentityStores, newId } from \"../utils/identity\";\nimport { unrefTimer } from \"../utils/unref\";\nimport type { Diagnostics } from \"./diagnostics\";\n\n/** Lifetime rules for a journey (one user task spanning several contexts). */\nexport interface JourneyOptions {\n /** Max time a journey stays open before it is treated as abandoned, in milliseconds. */\n maxAgeMs: number;\n /** Whether closing the owning context ends the journey for everyone. */\n endOnOwnerClose: boolean;\n /** Query parameter checked at boot for a seeded journey token. */\n urlParam: string;\n}\n\n/** Journey lifetime policy in force. Tests build an engine with shorter values. */\nexport const JOURNEY_OPTIONS: JourneyOptions = {\n maxAgeMs: JOURNEY_MAX_AGE_MS,\n endOnOwnerClose: JOURNEY_END_ON_OWNER_CLOSE,\n urlParam: JOURNEY_URL_PARAM,\n};\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 * @param stores Identity stores that hold the journey.\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 private readonly stores: IdentityStores = BROWSER_STORES,\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 () => this.stores.session().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 this.stores.session().setItem(JOURNEY_STORAGE_KEY, JSON.stringify(journey));\n } else {\n this.stores.session().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 the session store. */\n private clearStored(): void {\n this.diagnostics.guard(\"storage.unavailable\", \"clearing the persisted journey\", () => {\n this.stores.session().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. Bounded by\n * OPENFIN_OPTIONS_TIMEOUT_MS: a deadline reached here reports openfin.unavailable\n * and yields no token, which is the same outcome as a window created without one.\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 () => withDeadline(getOptions.call(me), OPENFIN_OPTIONS_TIMEOUT_MS),\n );\n const token = options?.customData?.[OPENFIN_JOURNEY_CUSTOM_DATA_KEY];\n return typeof token === \"string\" ? token : null;\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, stripUrlQuery } from \"../utils/platform\";\nimport { type SanitizeLimits, 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\";\nimport { shouldSampleInput } from \"./sampling\";\n\n/** Injected dependencies required by RecordBuilder. */\nexport interface RecordBuilderDeps {\n /** Active configuration object reference. */\n config: ResolvedConfig;\n /** Per-record size caps. */\n limits: RecordLimits;\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/** Per-record size caps, applied after sanitize and again after redact. */\nexport interface RecordLimits extends SanitizeLimits {\n /** Max record body length, in characters. */\n maxBodyChars: number;\n /** Max total attribute bytes per record. */\n maxRecordBytes: number;\n}\n\n/** Reason a record was not built. */\nexport type DropReason = \"level\" | \"sampling\" | \"redact\";\n\n/** Outcome of one build call. */\nexport interface BuildResult {\n /** Completed record, or null when it was dropped. */\n record: LogRecord | null;\n /** Why it was dropped. Absent when a record was built. */\n dropped?: DropReason;\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 The record, or null with the reason it was dropped.\n */\n build(input: BuildInput): BuildResult {\n const { config, diagnostics, tracing, journey, sequence, limits } = this.deps;\n\n if (!this.isEnabled(input.level)) {\n diagnostics.count(\"record.dropped_by_level\");\n return { record: null, dropped: \"level\" };\n }\n\n const traceCtx = tracing.resolve();\n const activeJourney = journey.current();\n\n // Sampling before the attribute walk below. A record nothing will send must\n // not pay for sanitize, redact and the resource block.\n const sampled = shouldSampleInput(\n {\n level: input.level,\n type: input.type,\n namespace: input.namespace,\n journeyId: activeJourney?.id ?? \"\",\n traceId: traceCtx.traceId,\n },\n config,\n );\n if (!sampled) {\n diagnostics.count(\"record.dropped_by_sampling\");\n return { record: null, dropped: \"sampling\" };\n }\n\n const seq = sequence.next();\n // Query and fragment carry tokens and user input. The path is the grouping signal.\n const url = currentUrl();\n const pageUrl = config.capture.fullUrls ? url : stripUrlQuery(url);\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 { record: null, dropped: \"redact\" };\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 type { Bus } from \"../bus/bus\";\nimport type { Receive, WorkerLike } from \"../bus/links\";\nimport type { Capture, CaptureContext, CaptureOnce } from \"../capture/types\";\nimport {\n BUS_MAX_BOOT_BUFFER_RECORDS,\n CAPTURE_NAMESPACE,\n GAP_REPORT_THROTTLE_MS,\n MAX_BREADCRUMBS,\n RECORD_LIMITS,\n RUNTIME_GLOBAL_KEY,\n RUNTIME_STOPPED_KEY,\n STORAGE_NAMESPACE,\n} from \"../constants\";\nimport type { BusMessage, BusRole } from \"../models/bus\";\nimport type {\n IdentityStrategy,\n ObservabilityConfig,\n ResolvedConfig,\n StorageStrategy,\n} from \"../models/config\";\nimport { isLogRecord, type LogRecord } from \"../models/log-record\";\nimport type { PruneResult } from \"../models/storage\";\nimport { ConsoleSink } from \"../utils/console\";\nimport {\n BROWSER_STORES,\n type Identity,\n type IdentityStores,\n memoryStores,\n newId,\n persistTabId,\n resolveIdentity,\n SessionTouch,\n} 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, JOURNEY_OPTIONS } from \"./journey\";\nimport { OneLogger } from \"./logger\";\nimport { RecordBuilder } from \"./record\";\nimport { shouldSample } from \"./sampling\";\nimport type { Sender } from \"./sender\";\n\n/** Constructor of one capture module. */\ntype CaptureClass = new (ctx: CaptureContext) => Capture;\n\n/** Import of each capture module. Each import makes a separate chunk. */\nconst CAPTURE_LOADERS = {\n errors: async (): Promise<CaptureClass> => (await import(\"../capture/errors\")).ErrorCapture,\n network: async (): Promise<CaptureClass> => (await import(\"../capture/network\")).NetworkCapture,\n interactions: async (): Promise<CaptureClass> =>\n (await import(\"../capture/interactions\")).InteractionCapture,\n webVitals: async (): Promise<CaptureClass> =>\n (await import(\"../capture/web-vitals\")).WebVitalsCapture,\n};\n\n/** Name of one capture module. */\ntype CaptureName = keyof typeof CAPTURE_LOADERS;\n\n/** Global symbol key pinning the singleton runtime instance across federated bundles. */\nconst RUNTIME_KEY = Symbol.for(RUNTIME_GLOBAL_KEY);\n\n/** Global symbol key of the runtime that shutdown() stopped. */\nconst STOPPED_KEY = Symbol.for(RUNTIME_STOPPED_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 /** Stores for identity and journey keys. The runtime sets them at startup. */\n private readonly stores: IdentityStores;\n\n /** Identity strategy that the runtime used to make the stores. */\n private readonly identityBuiltAs: IdentityStrategy;\n\n /** Throttled writer of the session's last-seen timestamp. */\n private readonly sessionTouch: SessionTouch;\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 /**\n * Cross-realm communication bus. It is null until its chunk loads.\n * In bus.mode \"off\", it loads only when a child frame or a worker needs it.\n */\n private bus: Bus | null = null;\n\n /** Load and construction of the bus. It is undefined until the first need. */\n private busBuilt?: Promise<Bus | null>;\n\n /** Load and start of the bus. It is undefined until the first need. */\n private busLoad?: Promise<Bus | null>;\n\n /** Storage strategy the adapter was built from, set once the build starts. */\n private storageBuiltAs?: StorageStrategy;\n\n /** Delivery stack. The runtime sets it in the sender role with an endpoint, after the chunk loads. */\n private sender?: Sender;\n\n /** Load of the delivery stack. It is undefined when nothing loads. A record then has no destination. */\n private senderLoad?: Promise<void>;\n\n /** Records that arrive while the delivery stack loads. */\n private pendingRecords: LogRecord[] = [];\n\n /** Active auto-capture instrumentation modules. */\n private readonly captures: Capture[] = [];\n\n /** Count of capture installs. An install that a later install replaced stops after its load. */\n private captureGeneration = 0;\n\n /** Capture work that a rebuild of the capture modules must not repeat. */\n private readonly captureOnce: CaptureOnce = { webVitals: false, navigationTiming: false };\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 startup has decided the bus role. A sender load waits for it. */\n private roleResolved = 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.identityBuiltAs = this.config.identity;\n this.stores = this.identityBuiltAs === \"memory\" ? memoryStores() : BROWSER_STORES;\n this.identity = resolveIdentity(this.diagnostics, this.stores);\n this.sessionTouch = new SessionTouch(this.diagnostics, this.stores);\n this.breadcrumbs = new BreadcrumbBuffer(MAX_BREADCRUMBS);\n this.tracing = new TraceEngine(this.diagnostics, undefined, this.config.otelLoader);\n // Do not await. Without OTel, records use the ambient trace. No record is lost.\n void this.tracing.loadOtel();\n this.console = new ConsoleSink(this.config.console, this.diagnostics);\n\n this.journey = new JourneyEngine(\n JOURNEY_OPTIONS,\n this.diagnostics,\n this.identity.contextId,\n (journey) => {\n this.bus?.broadcastJourney(journey);\n },\n this.stores,\n );\n\n this.builder = new RecordBuilder({\n config: this.config,\n limits: RECORD_LIMITS,\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\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 // Messages wait for the bus in arrival order. A promise runs its callbacks in order.\n void this.ensureBus().then((bus) => {\n if (!bus || this.destroyed) {\n return;\n }\n\n this.diagnostics.guard(\"bus.send_failed\", \"accepting a direct message from a child\", () => {\n bus.acceptDirect(message, reply);\n });\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 * Returns the runtime that shutdown() stopped, until the next configure().\n * @returns Stopped runtime instance or null.\n */\n static stopped(): ObservabilityRuntime | null {\n return (\n ((globalThis as Record<symbol, unknown>)[STOPPED_KEY] as ObservabilityRuntime | undefined) ??\n null\n );\n }\n\n /**\n * Tests whether shutdown() stopped this runtime.\n * @returns True after destroy() starts.\n */\n isDestroyed(): boolean {\n return this.destroyed;\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 Reflect.deleteProperty(globalThis, STOPPED_KEY);\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 const accepted = this.keepEndpoint(input);\n applyResolvedConfig(this.config, resolveConfig(accepted, this.diagnostics, this.config));\n this.diagnostics.setHandler(this.config.onDiagnostic);\n\n this.builder.invalidateResource();\n this.console.update(this.config.console);\n this.keepBuiltStorage();\n this.keepBuiltIdentity();\n\n // A stale capture load stops at its generation check. A reinstall is safe at any time.\n void this.installCaptures();\n\n if (this.roleResolved) {\n void this.syncSender();\n }\n\n this.diagnostics.report(\n \"config.reconfigured\",\n \"configure() was called again, the existing runtime was updated\",\n );\n }\n\n /**\n * Restores the storage strategy the adapter was built from. Every other key is read\n * live, but the adapter is built once: swapping it strands the batches already\n * persisted under the old one, which is worse than refusing the change.\n */\n private keepBuiltStorage(): void {\n const built = this.storageBuiltAs;\n\n if (built === undefined || this.config.storage === built) {\n return;\n }\n\n this.diagnostics.report(\n \"config.invalid\",\n `storage cannot change after startup, still ${built}`,\n { requested: this.config.storage },\n );\n this.config.storage = built;\n }\n\n /**\n * Refuses to remove the endpoint once the delivery stack exists. Without an endpoint,\n * the retry engine removes each stored batch as delivered.\n * @param input Partial configuration to merge.\n * @returns Input with the endpoint removal taken out.\n */\n private keepEndpoint(input: Partial<ObservabilityConfig>): Partial<ObservabilityConfig> {\n if (this.senderLoad === undefined || (input.endpoint !== null && input.endpoint !== \"\")) {\n return input;\n }\n\n this.diagnostics.report(\n \"config.invalid\",\n \"endpoint cannot be removed after the delivery stack loads. The endpoint in force stays.\",\n );\n\n // An undefined endpoint keeps the endpoint in force, and keeps it in ignoreUrls.\n return { ...input, endpoint: undefined };\n }\n\n /**\n * Restores the identity strategy from startup. The ids exist from startup.\n * A later change cannot move them to another store.\n */\n private keepBuiltIdentity(): void {\n const built = this.identityBuiltAs;\n\n if (this.config.identity === built) {\n return;\n }\n\n this.diagnostics.report(\n \"config.invalid\",\n `identity cannot change after startup. It stays ${built}.`,\n { requested: this.config.identity },\n );\n this.config.identity = built;\n }\n\n /** Initializes asynchronous subsystems and flushes the boot buffer. */\n private async init(): Promise<void> {\n // Start the capture imports at once. They download in parallel with the bus and the sender.\n const captures = this.installCaptures();\n\n try {\n const journeyReady = this.journey.bootstrap();\n\n if (this.config.bus.mode !== \"off\") {\n await this.ensureBus();\n }\n\n this.roleResolved = true;\n await this.syncSender();\n await journeyReady;\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 // Release the boot records before the captures load. The exit flush can then find them.\n this.ready = true;\n this.releaseBootBuffer();\n }\n\n await captures;\n }\n\n /**\n * Starts the load of the bus one time.\n * @returns Promise resolving to the started bus, or null if it did not load.\n */\n private ensureBus(): Promise<Bus | null> {\n this.busLoad ??= this.startBus();\n return this.busLoad;\n }\n\n /**\n * Loads and constructs the bus one time. It does not call start().\n * @returns Promise resolving to the constructed bus, or null if it did not load.\n */\n private constructBus(): Promise<Bus | null> {\n this.busBuilt ??= this.buildBus();\n return this.busBuilt;\n }\n\n /**\n * Starts the constructed bus. It never rejects.\n * @returns Promise resolving to the started bus, or null if it did not load or start.\n */\n private async startBus(): Promise<Bus | null> {\n const bus = await this.constructBus();\n\n if (!bus) {\n return null;\n }\n\n try {\n await bus.start();\n return bus;\n } catch (error) {\n this.diagnostics.report(\n \"pipeline.crashed\",\n \"the bus did not start. This context sends its own records.\",\n undefined,\n error,\n );\n\n return null;\n }\n }\n\n /** Imports and constructs the bus. It never rejects. */\n private async buildBus(): Promise<Bus | null> {\n try {\n const { Bus } = await import(\"../bus/bus\");\n\n // Guard against a shutdown during the load. A bus on a destroyed runtime leaks its links.\n if (this.destroyed) {\n return null;\n }\n\n const 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 this.bus = bus;\n\n return bus;\n } catch (error) {\n this.diagnostics.report(\n \"pipeline.crashed\",\n \"the bus did not load. This context sends its own records.\",\n undefined,\n error,\n );\n\n return null;\n }\n }\n\n /**\n * Reads the bus role. Without a bus, this context is the sender.\n * @returns Active bus role.\n */\n private role(): BusRole {\n return this.bus?.getRole() ?? \"sender\";\n }\n\n /**\n * Loads the delivery stack if this context is the sender and has an endpoint.\n * @returns Promise resolving when the load completes, or at once if nothing loads.\n */\n private syncSender(): Promise<void> {\n if (!this.config.endpoint || this.role() !== \"sender\") {\n return Promise.resolve();\n }\n\n return this.loadSender();\n }\n\n /**\n * Starts the load of the delivery stack one time.\n * @returns Promise resolving when the load completes or fails.\n */\n private loadSender(): Promise<void> {\n this.senderLoad ??= this.buildSender();\n return this.senderLoad;\n }\n\n /** Imports and builds the delivery stack. It then moves the held records into it. It never rejects. */\n private async buildSender(): Promise<void> {\n this.storageBuiltAs = this.config.storage;\n\n try {\n const { Sender } = await import(\"./sender\");\n const sender = this.destroyed\n ? null\n : await Sender.create({\n config: this.config,\n diagnostics: this.diagnostics,\n onGap: this.reportGap,\n });\n\n // Guard against a shutdown during the load. The stack must not outlive the runtime.\n if (!sender || this.destroyed) {\n await sender?.destroy();\n return;\n }\n\n this.sender = sender;\n } catch (error) {\n // Clear the load. A later configure() can then try again.\n this.senderLoad = undefined;\n this.diagnostics.report(\n \"pipeline.crashed\",\n \"the delivery stack did not load. Records are not sent.\",\n { held: this.pendingRecords.length },\n error,\n );\n }\n\n const held = this.pendingRecords;\n this.pendingRecords = [];\n\n for (const record of held) {\n this.sender?.push(record);\n }\n }\n\n /** Loads, builds and installs the enabled capture modules. It never rejects. */\n private async installCaptures(): Promise<void> {\n const generation = ++this.captureGeneration;\n const settings = this.config.capture;\n const names: CaptureName[] = [];\n\n if (settings.errors || settings.rejections || settings.resourceErrors) {\n names.push(\"errors\");\n }\n if (settings.fetch || settings.xhr) {\n names.push(\"network\");\n }\n if (settings.interactions || settings.navigation) {\n names.push(\"interactions\");\n }\n if (settings.webVitals) {\n names.push(\"webVitals\");\n }\n\n const classes = await Promise.all(names.map((name) => this.loadCapture(name)));\n\n // Guard against a later install or a shutdown during the load. A stale capture leaks its listeners.\n if (generation !== this.captureGeneration || this.destroyed) {\n return;\n }\n\n // Swap the old set for the new set in one synchronous step. No interval runs without capture.\n this.uninstallCaptures();\n\n const ctx: CaptureContext = {\n config: this.config,\n diagnostics: this.diagnostics,\n breadcrumbs: this.breadcrumbs,\n tracing: this.tracing,\n logger: new OneLogger(() => this, CAPTURE_NAMESPACE),\n once: this.captureOnce,\n };\n\n for (const CaptureModule of classes) {\n if (CaptureModule) {\n this.captures.push(new CaptureModule(ctx));\n }\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 the active capture modules. */\n private uninstallCaptures(): 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 }\n\n /**\n * Imports one capture module. A failed import reports and skips that module only.\n * @param name Capture module name.\n * @returns Promise resolving to the class, or undefined if the import failed.\n */\n private loadCapture(name: CaptureName): Promise<CaptureClass | undefined> {\n return this.diagnostics.guardAsync(\n \"capture.install_failed\",\n `loading the ${name} capture`,\n CAPTURE_LOADERS[name],\n );\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 // Attach on construction. The worker's handshake can time out while the bus starts.\n void this.constructBus().then((bus) => {\n if (!bus || this.destroyed) {\n return;\n }\n\n this.diagnostics.guard(\"bus.send_failed\", \"registering a worker\", () => {\n bus.attachWorker(worker);\n });\n\n // Start the bus in bus.mode \"off\", where startup did not start it.\n void this.ensureBus();\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 this.uninstallCaptures();\n\n // Sender.destroy runs its synchronous steps before its first await. The exit flush\n // then runs before the journey and the bus stop, as before.\n const closing = this.sender?.destroy();\n this.journey.destroy();\n this.bus?.destroy();\n this.forwardBuffer = [];\n this.pendingRecords = [];\n await closing;\n // A load in progress destroys its own stack. shutdown() resolves only after that.\n await this.senderLoad;\n\n if (ObservabilityRuntime.current() === this) {\n Reflect.deleteProperty(globalThis, RUNTIME_KEY);\n // Calls after shutdown() go to this runtime and do nothing.\n // A new default runtime would drop the app's settings.\n (globalThis as Record<symbol, unknown>)[STOPPED_KEY] = this;\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 this.sessionTouch.touch(this.identity.sessionId);\n\n if (!this.ready) {\n this.pushCapped(this.bootBuffer, 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.role() === \"forwarder\") {\n this.forward(record);\n return;\n }\n\n this.deliver(record);\n }\n\n /**\n * Hands a record to the delivery stack. Holds the record while the stack loads.\n * Drops the record when nothing loads, for example in console-only mode.\n * @param record Log record to deliver.\n */\n private deliver(record: LogRecord): void {\n if (this.sender) {\n this.sender.push(record);\n return;\n }\n\n if (!this.senderLoad) {\n return;\n }\n\n this.pushCapped(this.pendingRecords, record);\n }\n\n /**\n * Adds a record to a hold buffer. It drops the oldest record when the buffer is full.\n * @param buffer Hold buffer.\n * @param record Record to hold.\n */\n private pushCapped(buffer: LogRecord[], record: LogRecord): void {\n if (buffer.length >= BUS_MAX_BOOT_BUFFER_RECORDS) {\n buffer.shift();\n this.diagnostics.count(\"record.dropped_boot_buffer_full\");\n }\n\n buffer.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, samples and enqueues records received from child frames or workers.\n * A forwarded record arrives built, so this is the first point in this context\n * where sampling can run. A local record is sampled in RecordBuilder instead.\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 if (!shouldSample(record, this.config)) {\n this.diagnostics.count(\"record.dropped_by_sampling\");\n continue;\n }\n this.deliver(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(\n \"stored records were dropped before delivery\",\n {\n \"gap.batches\": result.batches,\n \"gap.records\": result.records,\n \"gap.reason\": result.reason,\n },\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 persistTabId(fresh, this.diagnostics, this.stores);\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 await this.senderLoad;\n return (await this.sender?.queueDepth()) ?? 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.role() === \"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 await this.senderLoad;\n await this.sender?.flush();\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/**\n * Cached logger instances keyed by namespace. Scoped loggers are never cached.\n * A logger finds the runtime on each write.\n * The cache stays valid across configure() and shutdown().\n */\nconst loggers = new Map<string, OneLogger>();\n\n/**\n * Retrieves the active runtime. After shutdown(), it returns the stopped runtime, which does nothing.\n * Before the first configure(), it starts a runtime with default settings.\n * @returns Runtime instance.\n */\nfunction requireRuntime(): ObservabilityRuntime {\n const runtime = ObservabilityRuntime.current() ?? ObservabilityRuntime.stopped();\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}\n\n/**\n * Retrieves a cached logger for a namespace, or builds an uncached scoped logger.\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, or a new one when options are given.\n */\nexport function getLogger(namespace: string, options?: OneLoggerOptions): OneLogger {\n // Caching a per-call scopedContext would hold it for the document lifetime.\n if (options) {\n return new OneLogger(requireRuntime, namespace, options);\n }\n\n let logger = loggers.get(namespace);\n\n if (!logger) {\n logger = new OneLogger(requireRuntime, namespace);\n loggers.set(namespace, 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 await ObservabilityRuntime.current()?.destroy();\n}\n"],"mappings":"2NAYA,SAASuF,EAAQ,EAA2B,CAC1C,OAAO,KAAK,OAAO,YAAY,IAAI,EAAIC,GAAaxF,EAAAA,CAAkB,EAAIA,EAAAA,CAC5E,CAUA,SAASyF,EACP,EACA,EACA,EACA,EACA,EACM,CACNC,EAAO,UAAU,GAAGC,EAAM,WAAYJ,EAAQC,CAAS,EAAG,KAAM,YAAa,CAC3E,SACA,GAAGI,CACL,CAAC,CACH,CAUA,SAASC,EACP,EACA,EACA,EACA,EACA,EACM,CACNH,EAAO,MAAM,GAAGC,EAAM,SAAUG,EAAO,CACrC,qBAAsBP,EAAQC,CAAS,EACvC,OAAQ,UACR,GAAGI,CACL,CAAC,CACH,CAUA,SAAgB3F,EACd,EACA,EACA,EACA,EACG,CACH,IAAMuF,EAAY,YAAY,IAAI,EAClC,GAAI,CACF,IAAMQ,EAASC,EAAG,EAElB,OADAR,EAAOC,EAAQC,EAAOH,EAAW,UAAWI,CAAU,EAC/CI,CACT,OAASF,EAAO,CAGd,MADAD,EAAKH,EAAQC,EAAOH,EAAWM,EAAOF,CAAU,EAC1CE,CACR,CACF,CAUA,eAAsB5F,EACpB,EACA,EACA,EACA,EACY,CACZ,IAAMsF,EAAY,YAAY,IAAI,EAClC,GAAI,CACF,IAAMQ,EAAS,MAAMC,EAAG,EAExB,OADAR,EAAOC,EAAQ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G,CACrC,CAQA,SAAgBsH,GAAa,EAAc,EAAyC,CAClF,OAAOjB,EAAe,CAAC,CAAC,QAAQ,MAAM/J,EAAMH,CAAO,CACrD,CAGA,SAAgBoL,IAAmB,CACjClB,EAAe,CAAC,CAAC,QAAQ,IAAI,CAC/B,CAMA,SAAgBmB,IAAiC,CAC/C,OAAOnB,EAAe,CAAC,CAAC,QAAQ,QAAQ,CAC1C,CAMA,SAAgBoB,IAAsC,CACpD,OAAOpB,EAAe,CAAC,CAAC,QAAQ,SAAS,CAC3C,CAOA,SAAgBqB,GAAa,EAAwB,CACnD,OAAOrB,EAAe,CAAC,CAAC,QAAQ,MAAM7D,EAAO,SAAU,EAAI,CAC7D,CAMA,SAAgBmF,GAAe,EAA0B,CACvDtB,EAAe,CAAC,CAAC,eAAeN,CAAM,CACxC,CAGA,SAAgB6B,IAAmB,CACjCvB,EAAe,CAAC,CAAC,QAAQ,OAAO,UAAU,CAC5C,CAMA,SAAgBwB,IAA0C,CACxD,OAAOxB,EAAe,CAAC,CAAC,QAAQ,QAAQ,CAC1C,CAMA,SAAgByB,IAAuB,CACrC,OAAOzB,EAAe,CAAC,CAAC,MAAM,CAChC,CAMA,SAAgB0B,IAAiC,CAC/C,OAAO1B,EAAe,CAAC,CAAC,WAAW,CACrC,CAMA,SAAgB2B,IAAgD,CAC9D,OAAO3B,EAAe,CAAC,CAAC,YAAY,SAAS,CAC/C,CAMA,eAAsB4B,IAA0B,CAC9C,MAAMrD,EAAqB,QAAQ,CAAC,EAAE,QAAQ,CAChD"}
|
|
1
|
+
{"version":3,"file":"index.cjs","names":["DURATION_PRECISION","timeSync","timeAsync","DEFAULT_METRIC_UNIT","timeSync","timeAsync","LEVEL_ORDER","sanitize","RECORD_LIMITS","randomHex","TRACE_MAX_AGE_MS","TRACEPARENT_HEADER","SERIALIZER_NAME_OTLP","CONSOLE_DEFAULT_STYLES","CONSOLE_DEFAULT_LEVEL","DEFAULT_CONFIG","UNKNOWN_SERVICE_NAME","UNDEFAULTED_CONFIG_KEYS","CONFIG_SECTIONS","UNDEFAULTED_SECTION_KEYS","DIAGNOSTIC_THROTTLE_MS","LIBRARY_LOG_PREFIX","JOURNEY_MAX_AGE_MS","JOURNEY_URL_PARAM","BASE64_PLUS_PATTERN","BASE64_SLASH_PATTERN","BASE64_PADDING_PATTERN","BROWSER_STORES","JOURNEY_STORAGE_KEY","newId","BASE64URL_DASH_PATTERN","BASE64URL_UNDERSCORE_PATTERN","withDeadline","OPENFIN_OPTIONS_TIMEOUT_MS","OPENFIN_JOURNEY_CUSTOM_DATA_KEY","LEVEL_ORDER","shouldSampleInput","currentUrl","stripUrlQuery","sanitizeWithSize","ATTR_SANITIZE_FAILED","ATTR_LOG_TYPE","ATTR_LOG_SEQ","ATTR_APP_NAMESPACE","ATTR_PAGE_URL","ATTR_JOURNEY_ID","ATTR_JOURNEY_NAME","ATTR_JOURNEY_PARENT_ID","truncate","nowUnixNano","SEVERITY_NUMBER","isLogRecord","ATTR_ATTRIBUTES_DROPPED","ATTR_ATTRIBUTES_BYTES","RESOURCE_SERVICE_NAME","RESOURCE_SERVICE_VERSION","RESOURCE_DEPLOYMENT_ENVIRONMENT","RESOURCE_TELEMETRY_SDK_NAME","TELEMETRY_SDK_NAME","RESOURCE_TELEMETRY_SDK_VERSION","TELEMETRY_SDK_VERSION","RESOURCE_TELEMETRY_SDK_LANGUAGE","TELEMETRY_SDK_LANGUAGE","RESOURCE_HOST_PLATFORM","RESOURCE_SESSION_ID","RESOURCE_TAB_ID","RESOURCE_CONTEXT_ID","RESOURCE_BROWSER_USER_AGENT","RESOURCE_OPENFIN_UUID","RESOURCE_OPENFIN_NAME","RUNTIME_GLOBAL_KEY","RUNTIME_STOPPED_KEY","detectPlatform","memoryStores","BROWSER_STORES","resolveIdentity","SessionTouch","RECORD_LIMITS","CAPTURE_NAMESPACE","isLogRecord","shouldSample","STORAGE_NAMESPACE","newId","require_constants","require_sampling","require_platform","require_unref","elapsed","startedAt","finish","logger","label","attributes","fail","error","timeSync$1","result","fn","timeAsync$1","toError","value","text","diagnostics","isPlainObject","proto","OneLogger","bind","namespace","options","message","payload","name","unit","type","runtime","level","body","dropped","record","ships","asPayload","asError","METHOD","ConsoleSink","settings","prefix","method","details","styles","Sequence","TRACE_ID_PATTERN","SPAN_ID_PATTERN","NON_ZERO","isUsableSpanContext","context","newTraceId","newSpanId","mintAmbient","toTraceContext","ambient","TraceEngine","maxAgeMs","load","fromOtel","otel","span","spanContext","carrier","\"traceparent\"","ctx","flags","BreadcrumbBuffer","capacity","crumb","isSerializer","resolveSerializer","requested","previous","CONSOLE_STYLE_KEYS","validStyles","valid","entries","key","resolveConsole","resolveConfig","base","merged","input","rate","rates","ns","r","url","reportUnknownKeys","known","section","values","sectionKeys","applyResolvedConfig","next","target","ContextStore","Diagnostics","handler","throttleMs","total","code","by","count","now","event","handlerError","JOURNEY_OPTIONS","readString","source","readNumber","journeyFromStorage","id","journeyFromTokenPayload","encodeToken","json","journey","bytes","binary","byte","JourneyEngine","contextId","onLocalChange","stores","fromUrl","fromStorage","fromOpenFin","opts","current","token","decoded","broadcast","ownerContextId","raw","standard","missing","padding","c","remaining","timer","me","getOptions","asAttributes","RecordBuilder","deps","config","traceCtx","tracing","activeJourney","seq","sequence","pageUrl","fromContext","limits","fromScope","fromPayload","redact","redacted","remeasured","kept","platform","identity","CAPTURE_LOADERS","RUNTIME_KEY","STOPPED_KEY","ObservabilityRuntime","bus","reply","existing","accepted","built","captures","journeyReady","Bus","records","sender","Sender","held","generation","names","classes","CaptureModule","capture","worker","closing","buffer","buffered","fresh","loggers","requireRuntime","configure","getLogger","root","trace","debug","info","warn","err","logAction","logEvent","logMetric","timeSync","timeAsync","setContext","setContextMap","removeContext","startJourney","endJourney","currentJourney","getJourneyToken","adoptJourney","registerWorker","startTrace","getTraceHeaders","flush","getQueueDepth","getDiagnosticCounters","shutdown"],"sources":["../src/utils/timer.ts","../src/core/logger.ts","../src/utils/console.ts","../src/utils/sequence.ts","../src/utils/tracing.ts","../src/core/breadcrumbs.ts","../src/core/config.ts","../src/core/context.ts","../src/core/diagnostics.ts","../src/core/journey.ts","../src/core/record.ts","../src/core/runtime.ts","../src/index.ts"],"sourcesContent":["// src/utils/timer.ts\n//\n// Logs the duration of 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 // Throw the error again. The caller keeps its 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 // Throw the error again. The caller keeps its control flow.\n fail(logger, label, startedAt, error, attributes);\n throw error;\n }\n}\n","// src/core/logger.ts\n//\n// This module gives a namespaced logger facade. It has scoped log methods and metric timers.\n\nimport { DEFAULT_METRIC_UNIT } from \"../constants\";\nimport type { LogLevel, LogRecord, LogType, MetricType } from \"../models/log-record\";\nimport { timeAsync, timeSync } from \"../utils/timer\";\nimport type { Diagnostics } from \"./diagnostics\";\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 * @param diagnostics Diagnostics reporter.\n * @returns Normalized Error instance.\n */\nfunction toError(value: unknown, diagnostics: Diagnostics): Error {\n if (value instanceof Error) {\n return value;\n }\n\n // String() throws on a null-prototype object and on a throwing toString.\n // log.error() runs inside a consumer catch block and must not throw out of it.\n const text = diagnostics.guard(\n \"record.sanitize_failed\",\n \"The library could not convert the error reason to text.\",\n () => String(value),\n );\n\n return new Error(text ?? typeof value);\n}\n\n/**\n * Tests if a value is an attribute bag, not an error reason. The test works across realms.\n * An object literal from an iframe has the Object.prototype of that realm.\n * The prototype of that Object.prototype is also null.\n * @param value Value found in the error slot.\n * @returns True if the value is a plain object.\n */\nfunction isPlainObject(value: unknown): value is Record<string, unknown> {\n if (typeof value !== \"object\" || value === null || Array.isArray(value)) {\n return false;\n }\n if (value instanceof Error) {\n return false;\n }\n\n const proto = Object.getPrototypeOf(value) as object | null;\n return proto === null || Object.getPrototypeOf(proto) === null;\n}\n\n/** Namespaced logger instance for recording structured events, metrics, and errors. */\nexport class OneLogger {\n /**\n * @param bind Returns the runtime for each write.\n * A logger that exists before configure() writes to the configured runtime.\n * @param namespace Application subsystem or module namespace.\n * @param options Scoped context options.\n */\n constructor(\n private readonly bind: () => 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.bind, `${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 the breadcrumb history. If payload is absent, a plain\n * object in the error slot becomes the payload.\n * @param message Error description.\n * @param error Caught error instance, reason, or payload.\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 error record. If payload is absent, a plain object in the error slot\n * becomes the payload.\n * @param message Error description.\n * @param error Caught error instance, reason, or payload.\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 one user 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 and emits a standard log record. It also prints the record to the console.\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 const runtime = this.bind();\n\n // Guard against a write after shutdown. The write must do nothing on the stopped runtime.\n if (runtime.isDestroyed()) {\n return;\n }\n\n // minLevel limits what the library sends. The console level limits what it prints.\n if (!runtime.builder.isEnabled(level)) {\n if (this.mirrors(runtime, level)) {\n this.print(runtime, level, body, payload, undefined, null);\n }\n\n return;\n }\n\n const { record, dropped } = runtime.builder.build({\n level,\n type,\n body,\n namespace: this.namespace,\n scoped: this.options.scopedContext,\n payload,\n });\n\n // Breadcrumbs stay in memory and have no delivery cost. A record that sampling drops\n // still adds a breadcrumb for the next error. Skip a record that redact drops.\n // Its breadcrumb sends the removed body with the next error.\n if (type !== \"metric\" && dropped !== \"redact\") {\n runtime.breadcrumbs.push({\n t: Date.now(),\n category: type === \"action\" ? \"action\" : type === \"event\" ? \"event\" : \"log\",\n message: body,\n });\n }\n\n this.print(runtime, level, body, payload, undefined, record);\n runtime.emit(record);\n }\n\n /**\n * Builds and emits an error record with breadcrumbs. It also prints the record to the console.\n * @param level Severity level (\"ERROR\" or \"FATAL\").\n * @param message Error description.\n * @param error Caught error instance, reason, or payload.\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 const runtime = this.bind();\n\n if (runtime.isDestroyed()) {\n return;\n }\n\n const ships = runtime.builder.isEnabled(level);\n\n if (!ships && !this.mirrors(runtime, level)) {\n return;\n }\n\n // All sibling methods take (name, payload?). Callers expect log.error(\"failed\", { id }).\n // As an error reason, that object puts \"[object Object]\" in error.message.\n // It also drops the caller fields.\n const asPayload = payload === undefined && isPlainObject(error);\n const attributes = asPayload ? error : payload;\n const asError =\n asPayload || error === undefined ? undefined : toError(error, runtime.diagnostics);\n\n if (!ships) {\n this.print(runtime, level, message, attributes, asError, null);\n return;\n }\n\n const { record } = runtime.builder.build({\n level,\n type: \"system\",\n body: message,\n namespace: this.namespace,\n scoped: this.options.scopedContext,\n payload: {\n ...attributes,\n ...(asError\n ? {\n \"error.type\": asError.name,\n \"error.message\": asError.message,\n \"error.stack_trace\": asError.stack,\n }\n : {}),\n breadcrumbs: runtime.breadcrumbs.snapshot(),\n },\n });\n\n this.print(runtime, level, message, attributes, asError, record);\n runtime.emit(record);\n }\n\n /**\n * Prints one log line. With a redact hook, the line shows only what redact returned.\n * A host can record console arguments. The console must not show what redact removes.\n * @param runtime Runtime of this write.\n * @param level Severity level.\n * @param message Primary message.\n * @param payload Caller payload.\n * @param error Error of an error call.\n * @param record Built record, or null if the library did not build it or redact dropped it.\n */\n private print(\n runtime: ObservabilityRuntime,\n level: LogLevel,\n message: string,\n payload: Record<string, unknown> | undefined,\n error: Error | undefined,\n record: LogRecord | null,\n ): void {\n if (!runtime.config.redact) {\n runtime.console.write(this.namespace, level, message, payload, error);\n return;\n }\n\n // The record attributes hold the error fields after redact.\n if (record) {\n runtime.console.write(this.namespace, level, record.body, record.attributes);\n return;\n }\n\n runtime.console.write(this.namespace, level, message, undefined, error);\n }\n\n /**\n * Tests whether the console prints a level that the library does not send.\n * @param runtime Runtime of this write.\n * @param level Severity level.\n * @returns True if logging is on and the console accepts the level.\n */\n private mirrors(runtime: ObservabilityRuntime, level: LogLevel): boolean {\n return runtime.config.enabled && runtime.console.accepts(level);\n }\n}\n","// src/utils/console.ts\n//\n// Formats and mirrors log records to the developer console during local execution\n\nimport { LEVEL_ORDER, RECORD_LIMITS } from \"../constants\";\nimport type { Diagnostics } from \"../core/diagnostics\";\nimport type { ResolvedConsole } from \"../models/config\";\nimport type { LogLevel } from \"../models/log-record\";\nimport { sanitize } from \"./sanitize\";\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 settings Console level and styles. A null level prints nothing.\n * @param diagnostics Diagnostics reporter.\n */\n constructor(\n private settings: ResolvedConsole,\n private diagnostics: Diagnostics,\n ) {}\n\n /**\n * Replaces the console level and styles.\n * @param settings Console level and styles. A null level prints nothing.\n */\n update(settings: ResolvedConsole): void {\n this.settings = settings;\n }\n\n /**\n * Tests whether a level clears the console threshold.\n * @param level Severity level of the record.\n * @returns True if the sink prints this level.\n */\n accepts(level: LogLevel): boolean {\n return this.settings.level !== null && LEVEL_ORDER[level] >= LEVEL_ORDER[this.settings.level];\n }\n\n /**\n * Prints a styled log line if the level clears the console threshold.\n * @param namespace Logger namespace, shown in the prefix.\n * @param level Severity level of the record.\n * @param message Primary log message.\n * @param payload Caller payload. The sink prints a sanitized copy.\n * @param error Error to print before the payload.\n */\n write(\n namespace: string,\n level: LogLevel,\n message: string,\n payload?: Record<string, unknown>,\n error?: Error,\n ): void {\n if (!this.accepts(level)) {\n return;\n }\n // Guard against a missing console. Some worker realms do not define it.\n if (typeof console === \"undefined\") {\n return;\n }\n\n // Pass the namespace as a %s argument. Then a %o or %c in the namespace prints as text.\n // The last %c resets the style. The message then prints in the default style.\n const prefix = `%c[%s]%c[${level}]%c`;\n const { styles } = this.settings;\n const method = METHOD[level];\n\n // A host can replace console methods with methods that throw. The guard stops that\n // error from breaking the log call of the caller.\n this.diagnostics.guard(\n \"handler.threw\",\n `The library could not print to console.${method}.`,\n () => {\n const details: unknown[] = [];\n\n if (error !== undefined) {\n details.push(error);\n }\n\n // Devtools keeps a reference to each logged object. A copy releases the caller's object.\n if (payload !== undefined) {\n details.push(sanitize(payload, RECORD_LIMITS, this.diagnostics));\n }\n\n console[method](\n prefix,\n styles.namespace,\n namespace,\n styles[level],\n \"\",\n message,\n ...details,\n );\n },\n );\n }\n}\n","// src/utils/sequence.ts\n//\n// Generates monotonic sequence numbers that order the records of each context.\n// Timestamps cannot order records. A clock can step, and two records can share a\n// millisecond. Each context has its own counter. A shared counter shows gaps, and\n// a gap looks like 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 when the runtime gets a new configuration.\n * A continued count shows a false link to the previous run.\n */\n reset(): void {\n this.value = 0;\n }\n}\n","// src/utils/tracing.ts\n//\n// Manages ambient distributed trace contexts, OpenTelemetry span integration, and W3C\n// traceparent headers. Consecutive records share one trace id. A new trace id for each\n// record gives each trace only one span.\n\nimport {\n SPAN_ID_BYTES,\n TRACE_FLAGS_MASK,\n TRACE_FLAGS_SAMPLED,\n TRACE_ID_BYTES,\n TRACE_MAX_AGE_MS,\n TRACEPARENT_HEADER,\n TRACEPARENT_VERSION,\n} from \"../constants\";\nimport type { Diagnostics } from \"../core/diagnostics\";\nimport type { OtelApi, OtelLoader, OtelSpanContext } from \"../models/config\";\nimport { randomHex } from \"./identity\";\n\n/** The W3C format sets these hex widths. A span context with a different width is not usable. */\nconst TRACE_ID_PATTERN = /^[0-9a-f]{32}$/;\nconst SPAN_ID_PATTERN = /^[0-9a-f]{16}$/;\n\n/** Matches a digit that is not zero. A span that has not started reports an all-zero id. */\nconst NON_ZERO = /[1-9a-f]/;\n\n/**\n * Evaluates whether a span context can carry correlation. It replaces isSpanContextValid\n * from the peer package. That function is not available when the peer is not installed.\n * @param context Span context reported by the host.\n * @returns True if both ids have the W3C width and neither is all zeros.\n */\nfunction isUsableSpanContext(context: OtelSpanContext): boolean {\n return (\n TRACE_ID_PATTERN.test(context.traceId) &&\n NON_ZERO.test(context.traceId) &&\n SPAN_ID_PATTERN.test(context.spanId) &&\n NON_ZERO.test(context.spanId)\n );\n}\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 in the W3C trace ID format.\n * Use it to start your own trace. The backend drops an id with the wrong width\n * and reports no error.\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 the sampled trace flag set. It always sets\n * the flag. Sampling runs before the library builds the record.\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. The instance keeps this state, not the module. Two\n * runtimes in one document must not share a trace id.\n */\n private ambient: AmbientTrace = mintAmbient();\n\n /** The optional peer after it loads. It is undefined while it loads or when it is absent. */\n private otel: OtelApi | undefined;\n\n /**\n * @param diagnostics Diagnostics reporter.\n * @param maxAgeMs Maximum lifetime of an un-rotated ambient trace in milliseconds.\n * @param load Loader for the OpenTelemetry API. If it is not set, OTel is off.\n * Do not import the peer by name. The Vite dev server fails if the peer is not installed.\n */\n constructor(\n private readonly diagnostics: Diagnostics,\n private readonly maxAgeMs = TRACE_MAX_AGE_MS,\n private readonly load?: OtelLoader,\n ) {}\n\n /**\n * Loads the OpenTelemetry API. Until the load completes, records use the ambient trace.\n * If there is no loader or the load fails, all records use the ambient trace.\n * @returns Promise resolving once the attempt has settled.\n */\n async loadOtel(): Promise<void> {\n if (!this.load) {\n return;\n }\n\n try {\n this.otel = await this.load();\n } catch (error) {\n this.diagnostics.report(\n \"trace.otel_failed\",\n \"The library could not load @opentelemetry/api. Records use the trace ids of the library.\",\n undefined,\n error,\n );\n }\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.activeSpanContext();\n if (fromOtel !== undefined) {\n return fromOtel;\n }\n\n // Rotate the ambient trace when its age exceeds maxAgeMs. The check runs on read,\n // not on a timer. A timer keeps 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 * Reads the host's active span, if the peer is loaded and a span is running.\n * @returns Trace context of the active span, or undefined.\n */\n private activeSpanContext(): TraceContext | undefined {\n const otel = this.otel;\n if (!otel) {\n return undefined;\n }\n\n return this.diagnostics.guard(\n \"trace.otel_failed\",\n \"The library could not read the active OpenTelemetry span.\",\n (): TraceContext | undefined => {\n const span = otel.trace.getActiveSpan();\n if (span === undefined) {\n return undefined;\n }\n const spanContext = span.spanContext();\n if (!isUsableSpanContext(spanContext)) {\n return undefined;\n }\n return {\n traceId: spanContext.traceId,\n spanId: spanContext.spanId,\n traceFlags: spanContext.traceFlags,\n };\n },\n );\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 with the registered OpenTelemetry propagators.\n * Without a traceparent from OpenTelemetry, it uses the ambient trace.\n * @returns Header map containing traceparent.\n */\n headers(): Record<string, string> {\n const carrier: Record<string, string> = {};\n const otel = this.otel;\n if (otel) {\n this.diagnostics.guard(\n \"trace.otel_failed\",\n \"The library could not add the OpenTelemetry headers.\",\n () => {\n otel.propagation.inject(otel.context.active(), carrier);\n },\n );\n }\n if (!carrier[TRACEPARENT_HEADER]) {\n const ctx = this.resolve();\n // Mask the trace flags to a 2-digit hex byte, as the W3C specification requires.\n // trace-flags is a bitfield, not a boolean. A fixed 00 or 01 discards upstream flags.\n const flags = (ctx.traceFlags & TRACE_FLAGS_MASK).toString(16).padStart(2, \"0\");\n carrier[TRACEPARENT_HEADER] = `${TRACEPARENT_VERSION}-${ctx.traceId}-${ctx.spanId}-${flags}`;\n }\n return carrier;\n }\n}\n","// src/core/breadcrumbs.ts\n//\n// This ring buffer keeps a bounded trail of recent user and system events in time order.\n// The buffer does not send breadcrumbs as records. Breadcrumbs go to the backend in the\n// payload of an error record. No function in this file throws.\n\nimport { BREADCRUMB_MIN_CAPACITY } from \"../constants\";\n\n/** Category of a breadcrumb event. */\nexport type BreadcrumbCategory =\n \"log\" | \"action\" | \"event\" | \"click\" | \"navigation\" | \"http\" | \"console\";\n\n/** Short summary of one event that the buffer keeps for an error record. */\nexport interface Breadcrumb {\n /** Timestamp in epoch milliseconds. */\n t: number;\n /** Category of the event. */\n category: BreadcrumbCategory;\n /** Description of the event for a person to read. */\n message: string;\n /** Optional contextual metadata. */\n data?: Record<string, unknown>;\n}\n\n/** Ring buffer of fixed size. It keeps recent breadcrumbs in time order. */\nexport class BreadcrumbBuffer {\n /** Storage array of the ring buffer. */\n private buffer: (Breadcrumb | undefined)[];\n\n /** Next write index in the circular buffer. */\n private pointer = 0;\n\n /**\n * It is true after the pointer wraps past the capacity. The pointer alone cannot\n * tell an empty ring from a ring that wrapped back to index 0.\n */\n private filled = false;\n\n /** Maximum number of breadcrumbs that the buffer keeps. */\n private readonly capacity: number;\n\n /**\n * @param capacity Maximum number of breadcrumbs. A smaller value changes to the minimum 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 * Adds a breadcrumb. When the buffer is full, the new breadcrumb replaces the oldest one.\n * @param crumb Breadcrumb to add.\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 List of breadcrumbs in time order.\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 /** Removes all breadcrumbs and resets the buffer. */\n clear(): void {\n this.buffer = new Array<Breadcrumb | undefined>(this.capacity);\n this.pointer = 0;\n this.filled = false;\n }\n}\n","// src/core/config.ts\n//\n// This module resolves partial consumer options into a validated config.\n// It also updates the live config. Obey the two rules below. A broken rule fails silently.\n// 1. Merge a reconfigure onto the config in force, not onto the defaults.\n// 2. Change the resolved object in place. Do not replace it. Subsystems keep the\n// reference from construction.\n// No function in this file throws to the caller.\n\nimport {\n CONFIG_SECTIONS,\n CONSOLE_DEFAULT_LEVEL,\n CONSOLE_DEFAULT_STYLES,\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 UNDEFAULTED_SECTION_KEYS,\n UNKNOWN_SERVICE_NAME,\n} from \"../constants\";\nimport type {\n ConsoleOption,\n ConsoleStyles,\n ObservabilityConfig,\n ResolvedConfig,\n ResolvedConsole,\n SerializerChoice,\n} from \"../models/config\";\nimport type { LogSerializer } from \"../models/serializer\";\nimport type { Diagnostics } from \"./diagnostics\";\n\n/**\n * Checks if a value 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 * Validates the serializer option. It does not change a name into an implementation.\n * The transport selects the implementation.\n * @param requested Serializer name or custom serializer implementation.\n * @param previous Serializer option in force.\n * @param diagnostics Diagnostics reporter.\n * @returns Valid serializer option.\n */\nfunction resolveSerializer(\n requested: unknown,\n previous: SerializerChoice | undefined,\n diagnostics: Diagnostics,\n): SerializerChoice {\n if (requested === undefined) {\n return previous ?? SERIALIZER_NAME_OTLP;\n }\n if (requested === SERIALIZER_NAME_OTLP || requested === SERIALIZER_NAME_ECS) {\n return requested;\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. The library uses \"${SERIALIZER_NAME_OTLP}\".`,\n );\n return SERIALIZER_NAME_OTLP;\n}\n\n/** Style keys that the console option accepts. */\nconst CONSOLE_STYLE_KEYS = new Set(Object.keys(CONSOLE_DEFAULT_STYLES));\n\n/**\n * Keeps the valid entries of a console styles object. It reports each entry that it drops.\n * @param styles Styles that the consumer passed.\n * @param diagnostics Diagnostics reporter.\n * @returns The valid styles.\n */\nfunction validStyles(styles: ConsoleStyles | undefined, diagnostics: Diagnostics): ConsoleStyles {\n const valid: Record<string, string> = {};\n const entries: [string, unknown][] = Object.entries(styles ?? {});\n\n for (const [key, value] of entries) {\n if (!CONSOLE_STYLE_KEYS.has(key)) {\n diagnostics.report(\n \"config.invalid\",\n `The library ignores the unknown console.styles key \"${key}\". Check the spelling.`,\n );\n continue;\n }\n\n if (typeof value !== \"string\") {\n diagnostics.report(\n \"config.invalid\",\n `console.styles.${key} must be a string. The library keeps the style in force.`,\n );\n continue;\n }\n\n valid[key] = value;\n }\n\n return valid;\n}\n\n/**\n * Normalizes the console option into a level and a set of styles.\n * @param requested Consumer console option.\n * @param previous Console settings in force.\n * @param diagnostics Diagnostics reporter.\n * @returns Console settings. The level is null when the console is off.\n */\nfunction resolveConsole(\n requested: ConsoleOption | undefined,\n previous: ResolvedConsole,\n diagnostics: Diagnostics,\n): ResolvedConsole {\n if (requested === undefined) {\n return previous;\n }\n if (requested === false) {\n return { level: null, styles: previous.styles };\n }\n if (requested === true) {\n return { level: CONSOLE_DEFAULT_LEVEL, styles: previous.styles };\n }\n if (typeof requested === \"string\") {\n return { level: requested, styles: previous.styles };\n }\n\n // Guard against null and other values that the type does not allow.\n if (typeof requested !== \"object\" || (requested as unknown) === null) {\n diagnostics.report(\n \"config.invalid\",\n \"console must be a boolean, a level or an object. The console settings in force stay.\",\n );\n return previous;\n }\n\n return {\n level: requested.level ?? previous.level ?? CONSOLE_DEFAULT_LEVEL,\n styles: { ...previous.styles, ...validStyles(requested.styles, diagnostics) },\n };\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 Complete, 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 // An unset environment variable gives undefined. Keep the current endpoint.\n endpoint: input.endpoint === undefined ? base.endpoint : input.endpoint,\n // A serializer instance replaces the string name after the object merge.\n serializer: resolveSerializer(input.serializer, previous?.serializer, diagnostics),\n console: resolveConsole(input.console, base.console, diagnostics),\n sampling: {\n ...base.sampling,\n ...input.sampling,\n rates: { ...base.sampling.rates, ...input.sampling?.rates },\n },\n bus: { ...base.bus, ...input.bus },\n capture: { ...base.capture, ...input.capture },\n };\n\n // null selects console-only mode. That value is valid. Report only an empty string.\n if (merged.endpoint === \"\") {\n diagnostics.report(\n \"config.invalid\",\n \"endpoint is missing. The library drops each record. Set endpoint: null for console-only mode.\",\n );\n } else if (merged.endpoint !== null) {\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 reports 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(\n \"config.invalid\",\n `sampling.defaultRate must be 0..1. The value is ${String(rate)}. The library uses ${String(SAMPLING_RATE_FALLBACK)}.`,\n );\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. The value is ${String(r)}. The library uses ${String(SAMPLING_RATE_FALLBACK)}.`,\n );\n merged.sampling.rates[ns] = SAMPLING_RATE_FALLBACK;\n }\n }\n\n // Replace the previous endpoint in the ignore list. This prevents a self-logging loop.\n // Without it, one failed POST logs another failed POST with no end.\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 reportUnknownKeys(input, diagnostics);\n\n return merged;\n}\n\n/**\n * Reports each config key that the schema does not know. It checks the top level and\n * one level inside each section. A typo passes the `Partial` type check and has no effect.\n * Examples are `remoteUrl` for `endpoint` and `capture.webVital` for `capture.webVitals`.\n * Namespace keys under `sampling.rates` are free-form and one level deeper. The check\n * skips them.\n * @param input Partial consumer configuration options.\n * @param diagnostics Diagnostics reporter.\n */\nfunction reportUnknownKeys(input: Partial<ObservabilityConfig>, diagnostics: Diagnostics): void {\n const known = new Set<string>([...Object.keys(DEFAULT_CONFIG), ...UNDEFAULTED_CONFIG_KEYS]);\n\n for (const key of Object.keys(input)) {\n if (!known.has(key)) {\n diagnostics.report(\n \"config.invalid\",\n `The library ignores the unknown config key \"${key}\". Check the spelling.`,\n );\n }\n }\n\n for (const section of CONFIG_SECTIONS) {\n const values: unknown = input[section];\n\n if (typeof values !== \"object\" || values === null) {\n continue;\n }\n\n const sectionKeys = new Set<string>([\n ...Object.keys(DEFAULT_CONFIG[section]),\n ...UNDEFAULTED_SECTION_KEYS[section],\n ]);\n\n for (const key of Object.keys(values)) {\n if (!sectionKeys.has(key)) {\n diagnostics.report(\n \"config.invalid\",\n `The library ignores the unknown config key \"${section}.${key}\". Check the spelling.`,\n );\n }\n }\n }\n}\n\n/**\n * Changes the active configuration object in place. Subsystems that hold a section\n * reference see the update.\n * @param target Active configuration object to change.\n * @param next Configuration object with the new values.\n */\nexport function applyResolvedConfig(target: ResolvedConfig, next: ResolvedConfig): void {\n for (const key of Object.keys(next) as (keyof ResolvedConfig)[]) {\n // The cast widens the tuple. Then includes accepts any string key. With satisfies,\n // the tuple stays narrow and each 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 // Merge each section object in place to keep its reference. A new object leaves\n // subsystems on the old section from 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// This store keeps ambient context attributes. The logger merges them into each later record.\n// Keep the store per instance, not at module level. All runtimes in a realm share a module Map.\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 copy of all ambient context attributes. The copy prevents a merge\n * target or a sanitizer from changing 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// This module reports internal errors of the library. It limits the emit rate.\n// It counts every event.\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_ceiling\"\n | \"record.dropped_by_redact\"\n | \"record.dropped_boot_buffer_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 | \"platform.api_blocked\"\n | \"handler.threw\";\n\n/** Diagnostic event payload dispatched to consumer handlers. */\nexport interface DiagnosticEvent {\n /** Diagnostic fault code. */\n code: DiagnosticCode;\n /** Description for a person to read. */\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 /** Total count of this code since startup. It includes 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/** Reports internal errors. It limits the dispatch rate but counts every event. */\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 count for a code. It does not call the handler.\n * @param code Diagnostic code to increment.\n * @param by Increment delta.\n * @returns New 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 the counter for the code. It sends the event to the handler when the\n * throttle window has passed. It 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 // Increment the counter directly. A call to report() recurses when the handler throws.\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(\n `${LIBRARY_LOG_PREFIX} The onDiagnostic handler threw an error.`,\n handlerError,\n );\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 ASD-STE100 sentence that states the failure. The handler gets it as the event message.\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 ASD-STE100 sentence that states the failure. The handler gets it as the event message.\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// This module manages the lifecycle of a user journey across windows. It encodes tokens,\n// stores the journey and ends it at expiry. Do not trust a value from storage or a token.\n// Any code on the origin can write to both.\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_END_ON_OWNER_CLOSE,\n JOURNEY_MAX_AGE_MS,\n JOURNEY_STORAGE_KEY,\n JOURNEY_TOKEN_MAX_CHARS,\n JOURNEY_TOKEN_NAME_MAX_CHARS,\n OPENFIN_JOURNEY_CUSTOM_DATA_KEY,\n JOURNEY_URL_PARAM,\n OPENFIN_OPTIONS_TIMEOUT_MS,\n} from \"../constants\";\nimport { withDeadline } from \"../utils/deadline\";\nimport { BROWSER_STORES, type IdentityStores, newId } from \"../utils/identity\";\nimport { unrefTimer } from \"../utils/unref\";\nimport type { Diagnostics } from \"./diagnostics\";\n\n/** Lifetime rules for a journey. A journey is one user task across several contexts. */\nexport interface JourneyOptions {\n /** Maximum open time of a journey, in milliseconds. After this time, the engine ends it. */\n maxAgeMs: number;\n /** Whether closing the owning context ends the journey for everyone. */\n endOnOwnerClose: boolean;\n /** Query parameter checked at boot for a seeded journey token. */\n urlParam: string;\n}\n\n/** Journey lifetime policy in force. Tests build an engine with shorter values. */\nexport const JOURNEY_OPTIONS: JourneyOptions = {\n maxAgeMs: JOURNEY_MAX_AGE_MS,\n endOnOwnerClose: JOURNEY_END_ON_OWNER_CLOSE,\n urlParam: JOURNEY_URL_PARAM,\n};\n\n/** User journey workflow context shared across windows and applications. */\nexport interface Journey {\n /** Unique journey correlation identifier. */\n id: string;\n /** Journey workflow name for a person to read. */\n name: string;\n /** Journey start timestamp in epoch milliseconds. */\n startedAt: number;\n /** Optional parent journey ID when the journey branches from an earlier journey. */\n parentId?: string;\n /** Context identifier of the document that started 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 * Reads 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 * Reads a finite number 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 // Convert the UTF-8 bytes to a binary string before btoa. btoa throws above U+00FF.\n // Without this step, a name in a non-Latin script fails.\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 * @param stores Identity stores that hold the journey.\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 private readonly stores: IdentityStores = BROWSER_STORES,\n ) {}\n\n /** Returns the active journey instance or null. */\n current(): Journey | null {\n return this.journey;\n }\n\n /**\n * Finds and adopts the initial journey. It checks the URL query, then sessionStorage,\n * then 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 \"The library could not read the persisted journey.\",\n () => this.stores.session().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 * Starts a new journey. It replaces the active journey and tells 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(this.diagnostics),\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 /** Ends 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 a journey update from a bus peer. It does not broadcast the update again.\n * An echo makes two windows send the change back and forth without end.\n * It ignores a journey with the same ID as the active journey. Thus an echo cannot\n * 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, or undefined when no journey is active or the token exceeds\n * the size limit.\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 \"The journey token is larger than the size limit. The library does not issue it.\",\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(\n \"journey.expired\",\n \"The library discarded a seeded journey older than maxAgeMs.\",\n {\n source,\n name: decoded.name,\n },\n );\n return false;\n }\n\n this.setJourney(decoded);\n this.diagnostics.report(\n \"journey.adopted\",\n `The library adopted the journey \"${decoded.name}\".`,\n {\n source,\n journeyId: decoded.id,\n },\n );\n if (broadcast) {\n this.onLocalChange(decoded);\n }\n return true;\n }\n\n /**\n * Ends the journey when endOnOwnerClose is on and the closed context owns the journey.\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 the engine restored the journey.\n */\n private restore(raw: string): boolean {\n const parsed = this.diagnostics.guard(\n \"storage.degraded\",\n \"The library could not parse 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 \"The library 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(\n \"journey.adopted\",\n `The library resumed the journey \"${journey.name}\".`,\n {\n source: \"sessionStorage\",\n journeyId: journey.id,\n },\n );\n return true;\n }\n\n /**\n * Decodes a base64url token into a validated Journey object. Anyone can edit the URL\n * that holds a token. Each step throws on bad input. The guard reports the failure\n * and does not throw it.\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 \"The library could not decode 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\", \"The library could not save the journey.\", () => {\n if (journey !== null) {\n this.stores.session().setItem(JOURNEY_STORAGE_KEY, JSON.stringify(journey));\n } else {\n this.stores.session().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 `The journey \"${journey.name}\" reached maxAgeMs. The library ended it.`,\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 the session store. */\n private clearStored(): void {\n this.diagnostics.guard(\n \"storage.unavailable\",\n \"The library could not clear the persisted journey.\",\n () => {\n this.stores.session().removeItem(JOURNEY_STORAGE_KEY);\n },\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 \"The library could not read 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 the customData of the OpenFin window options.\n * OPENFIN_OPTIONS_TIMEOUT_MS limits the wait. At the deadline, it reports\n * openfin.unavailable and returns no token. A window without a token gives the same result.\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 // Use call to keep the receiver of the native OpenFin method. A detached copy\n // throws when called.\n const options = await this.diagnostics.guardAsync(\n \"openfin.unavailable\",\n \"The library could not read fin.me.getOptions().\",\n () => withDeadline(getOptions.call(me), OPENFIN_OPTIONS_TIMEOUT_MS),\n );\n const token = options?.customData?.[OPENFIN_JOURNEY_CUSTOM_DATA_KEY];\n return typeof token === \"string\" ? token : null;\n }\n}\n","// src/core/record.ts\n//\n// This module builds structured log records from ambient context, journey data, trace\n// context and resource attributes. It never throws to the caller.\n// The builder caches the resource block. Call invalidateResource after a change to its inputs.\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, stripUrlQuery } from \"../utils/platform\";\nimport { type SanitizeLimits, 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\";\nimport { shouldSampleInput } from \"./sampling\";\n\n/** Injected dependencies required by RecordBuilder. */\nexport interface RecordBuilderDeps {\n /** Active configuration object reference. */\n config: ResolvedConfig;\n /** Per-record size caps. */\n limits: RecordLimits;\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. */\n identity: Identity;\n /** Detected host platform metadata. */\n platform: PlatformMetadata;\n}\n\n/** Size limits for each record. The builder applies them after sanitize and after redact. */\nexport interface RecordLimits extends SanitizeLimits {\n /** Max record body length, in characters. */\n maxBodyChars: number;\n /** Max total attribute bytes per record. */\n maxRecordBytes: number;\n}\n\n/** Reason a record was not built. */\nexport type DropReason = \"level\" | \"sampling\" | \"redact\";\n\n/** Outcome of one build call. */\nexport interface BuildResult {\n /** Completed record, or null when it was dropped. */\n record: LogRecord | null;\n /** Reason for the drop. It is absent when the builder built a record. */\n dropped?: DropReason;\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 /** Clears the cached resource attributes. The next build computes them again. */\n invalidateResource(): void {\n this.resourceCache = null;\n }\n\n /**\n * Checks if logging is on and the level is at or above minLevel.\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 the input. It sanitizes attributes and applies size limits.\n * @param input Logger call input parameters.\n * @returns The record, or null with the reason it was dropped.\n */\n build(input: BuildInput): BuildResult {\n const { config, diagnostics, tracing, journey, sequence, limits } = this.deps;\n\n if (!this.isEnabled(input.level)) {\n diagnostics.count(\"record.dropped_by_level\");\n return { record: null, dropped: \"level\" };\n }\n\n const traceCtx = tracing.resolve();\n const activeJourney = journey.current();\n\n // Sample before the attribute walk below. Do not sanitize, redact or build the\n // resource block for a record that the runtime does not send.\n const sampled = shouldSampleInput(\n {\n level: input.level,\n type: input.type,\n namespace: input.namespace,\n journeyId: activeJourney?.id ?? \"\",\n traceId: traceCtx.traceId,\n },\n config,\n );\n if (!sampled) {\n diagnostics.count(\"record.dropped_by_sampling\");\n return { record: null, dropped: \"sampling\" };\n }\n\n const seq = sequence.next();\n // The query and fragment can contain tokens and user input. The path groups records.\n const url = currentUrl(diagnostics);\n const pageUrl = config.capture.fullUrls ? url : stripUrlQuery(url);\n\n let attributes: Record<string, unknown>;\n let bytes = 0;\n try {\n const fromContext = sanitizeWithSize(this.deps.context.getAll(), limits, diagnostics);\n const fromScope = sanitizeWithSize(input.scoped ?? {}, limits, diagnostics);\n const fromPayload = sanitizeWithSize(input.payload ?? {}, limits, diagnostics);\n bytes = fromContext.bytes + fromScope.bytes + fromPayload.bytes;\n\n // Merge in increasing precedence. Scope overrides context. Payload overrides scope.\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 \"The library could not sanitize the attributes.\",\n undefined,\n error,\n );\n attributes = { [ATTR_SANITIZE_FAILED]: true };\n }\n\n // Set reserved attributes after the payload merge. If they merge first, a payload key\n // named journey.id replaces the ID that correlates the records.\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(\n \"record.sanitize_failed\",\n \"The redact hook threw an error.\",\n () => redact(record),\n );\n if (redacted === null) {\n diagnostics.count(\"record.dropped_by_redact\");\n return { record: null, dropped: \"redact\" };\n }\n\n if (redacted !== undefined && redacted !== record) {\n if (isLogRecord(redacted)) {\n // Sanitize the record from the redact hook again. The hook is consumer code.\n // A cycle, a hostile getter or a BigInt throws at serialization. The transport\n // then loses the batch.\n const remeasured = sanitizeWithSize(redacted.attributes, limits, diagnostics);\n record = { ...redacted, attributes: asAttributes(remeasured.value) };\n bytes = remeasured.bytes;\n } else {\n diagnostics.report(\n \"record.sanitize_failed\",\n \"The redact hook returned a value that is not a record. The library keeps the original record.\",\n );\n }\n }\n }\n\n // Drop the attributes when their size exceeds maxRecordBytes. Keep the index keys.\n // A search cannot find a record without journey.id and trace_id.\n if (bytes > limits.maxRecordBytes) {\n diagnostics.report(\n \"record.truncated\",\n \"The attributes are larger than the size limit. The library dropped them.\",\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// This runtime coordinates the subsystems. It manages their lifecycles, the configuration\n// and the routing of records.\n\nimport type { Bus } from \"../bus/bus\";\nimport type { Receive, WorkerLike } from \"../bus/links\";\nimport type { Capture, CaptureContext, CaptureOnce } from \"../capture/types\";\nimport {\n BUS_MAX_BOOT_BUFFER_RECORDS,\n CAPTURE_NAMESPACE,\n GAP_REPORT_THROTTLE_MS,\n MAX_BREADCRUMBS,\n RECORD_LIMITS,\n RUNTIME_GLOBAL_KEY,\n RUNTIME_STOPPED_KEY,\n STORAGE_NAMESPACE,\n} from \"../constants\";\nimport type { BusMessage, BusRole } from \"../models/bus\";\nimport type {\n IdentityStrategy,\n ObservabilityConfig,\n ResolvedConfig,\n StorageStrategy,\n} from \"../models/config\";\nimport { isLogRecord, type LogRecord } from \"../models/log-record\";\nimport type { PruneResult } from \"../models/storage\";\nimport { ConsoleSink } from \"../utils/console\";\nimport {\n BROWSER_STORES,\n type Identity,\n type IdentityStores,\n memoryStores,\n newId,\n persistTabId,\n resolveIdentity,\n SessionTouch,\n} 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, JOURNEY_OPTIONS } from \"./journey\";\nimport { OneLogger } from \"./logger\";\nimport { RecordBuilder } from \"./record\";\nimport { shouldSample } from \"./sampling\";\nimport type { Sender } from \"./sender\";\n\n/** Constructor of one capture module. */\ntype CaptureClass = new (ctx: CaptureContext) => Capture;\n\n/** Import of each capture module. Each import makes a separate chunk. */\nconst CAPTURE_LOADERS = {\n errors: async (): Promise<CaptureClass> => (await import(\"../capture/errors\")).ErrorCapture,\n network: async (): Promise<CaptureClass> => (await import(\"../capture/network\")).NetworkCapture,\n interactions: async (): Promise<CaptureClass> =>\n (await import(\"../capture/interactions\")).InteractionCapture,\n webVitals: async (): Promise<CaptureClass> =>\n (await import(\"../capture/web-vitals\")).WebVitalsCapture,\n};\n\n/** Name of one capture module. */\ntype CaptureName = keyof typeof CAPTURE_LOADERS;\n\n/** Global symbol key of the singleton runtime. All federated bundles share it. */\nconst RUNTIME_KEY = Symbol.for(RUNTIME_GLOBAL_KEY);\n\n/** Global symbol key of the runtime that shutdown() stopped. */\nconst STOPPED_KEY = Symbol.for(RUNTIME_STOPPED_KEY);\n\n/** Manages 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. A reconfigure changes it in place. */\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 /** Stores for identity and journey keys. The runtime sets them at startup. */\n private readonly stores: IdentityStores;\n\n /** Identity strategy that the runtime used to make the stores. */\n private readonly identityBuiltAs: IdentityStrategy;\n\n /** Throttled writer of the session's last-seen timestamp. */\n private readonly sessionTouch: SessionTouch;\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 /**\n * Cross-realm communication bus. It is null until its chunk loads.\n * In bus.mode \"off\", it loads only when a child frame or a worker needs it.\n */\n private bus: Bus | null = null;\n\n /** Load and construction of the bus. It is undefined until the first need. */\n private busBuilt?: Promise<Bus | null>;\n\n /** Load and start of the bus. It is undefined until the first need. */\n private busLoad?: Promise<Bus | null>;\n\n /** Storage strategy of the adapter. The runtime sets it when the build starts. */\n private storageBuiltAs?: StorageStrategy;\n\n /** Delivery stack. The runtime sets it in the sender role with an endpoint, after the chunk loads. */\n private sender?: Sender;\n\n /** Load of the delivery stack. It is undefined when nothing loads. A record then has no destination. */\n private senderLoad?: Promise<void>;\n\n /** Records that arrive while the delivery stack loads. */\n private pendingRecords: LogRecord[] = [];\n\n /** Active auto-capture instrumentation modules. */\n private readonly captures: Capture[] = [];\n\n /** Count of capture installs. An install that a later install replaced stops after its load. */\n private captureGeneration = 0;\n\n /** Capture work that a rebuild of the capture modules must not repeat. */\n private readonly captureOnce: CaptureOnce = { webVitals: false, navigationTiming: false };\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 startup has decided the bus role. A sender load waits for it. */\n private roleResolved = false;\n\n /** Indicates whether asynchronous initialization has completed. */\n private ready = false;\n\n /** Indicates whether shutdown stopped the runtime. */\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.identityBuiltAs = this.config.identity;\n this.stores = this.identityBuiltAs === \"memory\" ? memoryStores() : BROWSER_STORES;\n this.identity = resolveIdentity(this.diagnostics, this.stores);\n this.sessionTouch = new SessionTouch(this.diagnostics, this.stores);\n this.breadcrumbs = new BreadcrumbBuffer(MAX_BREADCRUMBS);\n this.tracing = new TraceEngine(this.diagnostics, undefined, this.config.otelLoader);\n // Do not await. Without OTel, records use the ambient trace. No record is lost.\n void this.tracing.loadOtel();\n this.console = new ConsoleSink(this.config.console, this.diagnostics);\n\n this.journey = new JourneyEngine(\n JOURNEY_OPTIONS,\n this.diagnostics,\n this.identity.contextId,\n (journey) => {\n this.bus?.broadcastJourney(journey);\n },\n this.stores,\n );\n\n this.builder = new RecordBuilder({\n config: this.config,\n limits: RECORD_LIMITS,\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\n /**\n * Receives direct messages from 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 // Messages wait for the bus in arrival order. A promise runs its callbacks in order.\n void this.ensureBus().then((bus) => {\n if (!bus || this.destroyed) {\n return;\n }\n\n this.diagnostics.guard(\n \"bus.send_failed\",\n \"The bus could not accept a direct message from a child frame.\",\n () => {\n bus.acceptDirect(message, reply);\n },\n );\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 * Returns the runtime that shutdown() stopped, until the next configure().\n * @returns Stopped runtime instance or null.\n */\n static stopped(): ObservabilityRuntime | null {\n return (\n ((globalThis as Record<symbol, unknown>)[STOPPED_KEY] as ObservabilityRuntime | undefined) ??\n null\n );\n }\n\n /**\n * Tests whether shutdown() stopped this runtime.\n * @returns True after destroy() starts.\n */\n isDestroyed(): boolean {\n return this.destroyed;\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 Reflect.deleteProperty(globalThis, STOPPED_KEY);\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 const accepted = this.keepEndpoint(input);\n applyResolvedConfig(this.config, resolveConfig(accepted, this.diagnostics, this.config));\n this.diagnostics.setHandler(this.config.onDiagnostic);\n\n this.builder.invalidateResource();\n this.console.update(this.config.console);\n this.keepBuiltStorage();\n this.keepBuiltIdentity();\n\n // A stale capture load stops at its generation check. A reinstall is safe at any time.\n void this.installCaptures();\n\n if (this.roleResolved) {\n void this.syncSender();\n }\n\n this.diagnostics.report(\"config.reconfigured\", \"A later configure() call updated the runtime.\");\n }\n\n /**\n * Restores the storage strategy of the built adapter. The runtime reads all other keys\n * live. It builds the adapter only one time. A new adapter strands the batches in the\n * old adapter. That loss is worse than a refused change.\n */\n private keepBuiltStorage(): void {\n const built = this.storageBuiltAs;\n\n if (built === undefined || this.config.storage === built) {\n return;\n }\n\n this.diagnostics.report(\n \"config.invalid\",\n `storage cannot change after startup. It stays ${built}.`,\n { requested: this.config.storage },\n );\n this.config.storage = built;\n }\n\n /**\n * Refuses to remove the endpoint once the delivery stack exists. Without an endpoint,\n * the retry engine removes each stored batch as delivered.\n * @param input Partial configuration to merge.\n * @returns Input with the endpoint removal taken out.\n */\n private keepEndpoint(input: Partial<ObservabilityConfig>): Partial<ObservabilityConfig> {\n if (this.senderLoad === undefined || (input.endpoint !== null && input.endpoint !== \"\")) {\n return input;\n }\n\n this.diagnostics.report(\n \"config.invalid\",\n \"You cannot remove the endpoint after the delivery stack loads. The endpoint in force stays.\",\n );\n\n // An undefined endpoint keeps the endpoint in force, and keeps it in ignoreUrls.\n return { ...input, endpoint: undefined };\n }\n\n /**\n * Restores the identity strategy from startup. The ids exist from startup.\n * A later change cannot move them to another store.\n */\n private keepBuiltIdentity(): void {\n const built = this.identityBuiltAs;\n\n if (this.config.identity === built) {\n return;\n }\n\n this.diagnostics.report(\n \"config.invalid\",\n `identity cannot change after startup. It stays ${built}.`,\n { requested: this.config.identity },\n );\n this.config.identity = built;\n }\n\n /** Initializes asynchronous subsystems and flushes the boot buffer. */\n private async init(): Promise<void> {\n // Start the capture imports now. They download in parallel with the bus and the sender.\n const captures = this.installCaptures();\n\n try {\n const journeyReady = this.journey.bootstrap();\n\n if (this.config.bus.mode !== \"off\") {\n await this.ensureBus();\n }\n\n this.roleResolved = true;\n await this.syncSender();\n await journeyReady;\n } catch (error) {\n this.diagnostics.report(\n \"pipeline.crashed\",\n \"Startup failed. The runtime continues with reduced function.\",\n undefined,\n error,\n );\n } finally {\n // Release the boot records before the captures load. The exit flush can then find them.\n this.ready = true;\n this.releaseBootBuffer();\n }\n\n await captures;\n }\n\n /**\n * Starts the load of the bus one time.\n * @returns Promise resolving to the started bus, or null if it did not load.\n */\n private ensureBus(): Promise<Bus | null> {\n this.busLoad ??= this.startBus();\n return this.busLoad;\n }\n\n /**\n * Loads and constructs the bus one time. It does not call start().\n * @returns Promise resolving to the constructed bus, or null if it did not load.\n */\n private constructBus(): Promise<Bus | null> {\n this.busBuilt ??= this.buildBus();\n return this.busBuilt;\n }\n\n /**\n * Starts the constructed bus. It never rejects.\n * @returns Promise resolving to the started bus, or null if it did not load or start.\n */\n private async startBus(): Promise<Bus | null> {\n const bus = await this.constructBus();\n\n if (!bus) {\n return null;\n }\n\n try {\n await bus.start();\n return bus;\n } catch (error) {\n this.diagnostics.report(\n \"pipeline.crashed\",\n \"The bus did not start. This context sends its own records.\",\n undefined,\n error,\n );\n\n return null;\n }\n }\n\n /** Imports and constructs the bus. It never rejects. */\n private async buildBus(): Promise<Bus | null> {\n try {\n const { Bus } = await import(\"../bus/bus\");\n\n // Guard against a shutdown during the load. A bus on a destroyed runtime leaks its links.\n if (this.destroyed) {\n return null;\n }\n\n const 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 this.bus = bus;\n\n return bus;\n } catch (error) {\n this.diagnostics.report(\n \"pipeline.crashed\",\n \"The bus did not load. This context sends its own records.\",\n undefined,\n error,\n );\n\n return null;\n }\n }\n\n /**\n * Reads the bus role. Without a bus, this context is the sender.\n * @returns Active bus role.\n */\n private role(): BusRole {\n return this.bus?.getRole() ?? \"sender\";\n }\n\n /**\n * Loads the delivery stack if this context is the sender and has an endpoint.\n * @returns Promise resolving when the load completes, or immediately when nothing loads.\n */\n private syncSender(): Promise<void> {\n if (!this.config.endpoint || this.role() !== \"sender\") {\n return Promise.resolve();\n }\n\n return this.loadSender();\n }\n\n /**\n * Starts the load of the delivery stack one time.\n * @returns Promise resolving when the load completes or fails.\n */\n private loadSender(): Promise<void> {\n this.senderLoad ??= this.buildSender();\n return this.senderLoad;\n }\n\n /** Imports and builds the delivery stack. It then moves the held records into it. It never rejects. */\n private async buildSender(): Promise<void> {\n this.storageBuiltAs = this.config.storage;\n\n try {\n const { Sender } = await import(\"./sender\");\n const sender = this.destroyed\n ? null\n : await Sender.create({\n config: this.config,\n diagnostics: this.diagnostics,\n onGap: this.reportGap,\n });\n\n // Guard against a shutdown during the load. The stack must not outlive the runtime.\n if (!sender || this.destroyed) {\n await sender?.destroy();\n return;\n }\n\n this.sender = sender;\n } catch (error) {\n // Clear the load. A later configure() can then try again.\n this.senderLoad = undefined;\n this.diagnostics.report(\n \"pipeline.crashed\",\n \"The delivery stack did not load. The library does not send records.\",\n { held: this.pendingRecords.length },\n error,\n );\n }\n\n const held = this.pendingRecords;\n this.pendingRecords = [];\n\n for (const record of held) {\n this.sender?.push(record);\n }\n }\n\n /** Loads, builds and installs the enabled capture modules. It never rejects. */\n private async installCaptures(): Promise<void> {\n const generation = ++this.captureGeneration;\n const settings = this.config.capture;\n const names: CaptureName[] = [];\n\n if (settings.errors || settings.rejections || settings.resourceErrors) {\n names.push(\"errors\");\n }\n if (settings.fetch || settings.xhr) {\n names.push(\"network\");\n }\n if (settings.interactions || settings.navigation) {\n names.push(\"interactions\");\n }\n if (settings.webVitals) {\n names.push(\"webVitals\");\n }\n\n const classes = await Promise.all(names.map((name) => this.loadCapture(name)));\n\n // Guard against a later install or a shutdown during the load. A stale capture leaks its listeners.\n if (generation !== this.captureGeneration || this.destroyed) {\n return;\n }\n\n // Swap the old set for the new set in one synchronous step. No interval runs without capture.\n this.uninstallCaptures();\n\n const ctx: CaptureContext = {\n config: this.config,\n diagnostics: this.diagnostics,\n breadcrumbs: this.breadcrumbs,\n tracing: this.tracing,\n logger: new OneLogger(() => this, CAPTURE_NAMESPACE),\n once: this.captureOnce,\n };\n\n for (const CaptureModule of classes) {\n if (CaptureModule) {\n this.captures.push(new CaptureModule(ctx));\n }\n }\n\n for (const capture of this.captures) {\n this.diagnostics.guard(\n \"capture.install_failed\",\n `The library could not install the ${capture.name} capture.`,\n () => {\n capture.install();\n },\n );\n }\n }\n\n /** Uninstalls the active capture modules. */\n private uninstallCaptures(): void {\n for (const capture of this.captures) {\n this.diagnostics.guard(\n \"capture.install_failed\",\n `The library could not uninstall the ${capture.name} capture.`,\n () => {\n capture.uninstall();\n },\n );\n }\n this.captures.length = 0;\n }\n\n /**\n * Imports one capture module. A failed import reports and skips that module only.\n * @param name Capture module name.\n * @returns Promise resolving to the class, or undefined if the import failed.\n */\n private loadCapture(name: CaptureName): Promise<CaptureClass | undefined> {\n return this.diagnostics.guardAsync(\n \"capture.install_failed\",\n `The library could not load the ${name} capture.`,\n CAPTURE_LOADERS[name],\n );\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 // Attach on construction. The worker's handshake can time out while the bus starts.\n void this.constructBus().then((bus) => {\n if (!bus || this.destroyed) {\n return;\n }\n\n this.diagnostics.guard(\n \"bus.send_failed\",\n \"The library could not register the worker.\",\n () => {\n bus.attachWorker(worker);\n },\n );\n\n // Start the bus in bus.mode \"off\", where startup did not start it.\n void this.ensureBus();\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 this.uninstallCaptures();\n\n // Sender.destroy runs its synchronous steps before its first await. Thus the exit\n // flush runs before the journey and the bus stop.\n const closing = this.sender?.destroy();\n this.journey.destroy();\n this.bus?.destroy();\n this.forwardBuffer = [];\n this.pendingRecords = [];\n await closing;\n // A load in progress destroys its own stack. shutdown() resolves only after that.\n await this.senderLoad;\n\n if (ObservabilityRuntime.current() === this) {\n Reflect.deleteProperty(globalThis, RUNTIME_KEY);\n // Calls after shutdown() go to this runtime and do nothing.\n // A new default runtime would drop the app's settings.\n (globalThis as Record<symbol, unknown>)[STOPPED_KEY] = this;\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 when the build dropped it.\n */\n emit(record: LogRecord | null): void {\n if (!record || this.destroyed) {\n return;\n }\n\n this.sessionTouch.touch(this.identity.sessionId);\n\n if (!this.ready) {\n this.pushCapped(this.bootBuffer, record);\n return;\n }\n\n this.route(record);\n }\n\n /**\n * Sends a record to the forward buffer or to the local pipeline. The bus role selects\n * the path.\n * @param record Log record to route.\n */\n private route(record: LogRecord): void {\n if (this.role() === \"forwarder\") {\n this.forward(record);\n return;\n }\n\n this.deliver(record);\n }\n\n /**\n * Hands a record to the delivery stack. Holds the record while the stack loads.\n * Drops the record when nothing loads, for example in console-only mode.\n * @param record Log record to deliver.\n */\n private deliver(record: LogRecord): void {\n if (this.sender) {\n this.sender.push(record);\n return;\n }\n\n if (!this.senderLoad) {\n return;\n }\n\n this.pushCapped(this.pendingRecords, record);\n }\n\n /**\n * Adds a record to a hold buffer. It drops the oldest record when the buffer is full.\n * @param buffer Hold buffer.\n * @param record Record to hold.\n */\n private pushCapped(buffer: LogRecord[], record: LogRecord): void {\n if (buffer.length >= BUS_MAX_BOOT_BUFFER_RECORDS) {\n buffer.shift();\n this.diagnostics.count(\"record.dropped_boot_buffer_full\");\n }\n\n buffer.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, samples and queues records from child frames or workers.\n * A forwarded record arrives built. This is the first point in this context where\n * sampling can run. RecordBuilder samples a local record.\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 if (!shouldSample(record, this.config)) {\n this.diagnostics.count(\"record.dropped_by_sampling\");\n continue;\n }\n this.deliver(record);\n }\n }\n\n /** Flushes the startup records. It adds the active journey to records without a journey. */\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 record when storage evicts batches.\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(\n \"stored records were dropped before delivery\",\n {\n \"gap.batches\": result.batches,\n \"gap.records\": result.records,\n \"gap.reason\": result.reason,\n },\n );\n };\n\n /** Makes and stores a new tab ID after a tab ID collision. */\n private regenerateTabId(): void {\n const fresh = newId(this.diagnostics);\n this.diagnostics.report(\n \"bus.role_resolved\",\n \"Another context uses this tab id. A duplicated tab is the usual cause. The library makes a new tab id.\",\n { was: this.identity.tabId, now: fresh },\n );\n\n (this.identity as { tabId: string }).tabId = fresh;\n persistTabId(fresh, this.diagnostics, this.stores);\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 stores\n * nothing and reports 0.\n */\n async queueDepth(): Promise<number> {\n await this.senderLoad;\n return (await this.sender?.queueDepth()) ?? 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.role() === \"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 await this.senderLoad;\n await this.sender?.flush();\n }\n}\n","// src/index.ts\n//\n// This file is the public entry point of the library. It exports the facade API,\n// 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 { ConsoleOptions, ConsoleStyles } from \"./models/config\";\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/**\n * Cached logger instances keyed by namespace. This map never holds a scoped logger.\n * A logger finds the runtime on each write.\n * The cache stays valid across configure() and shutdown().\n */\nconst loggers = new Map<string, OneLogger>();\n\n/**\n * Retrieves the active runtime. After shutdown(), it returns the stopped runtime.\n * The stopped runtime does nothing. Before the first configure(), it starts a runtime\n * with default settings.\n * @returns Runtime instance.\n */\nfunction requireRuntime(): ObservabilityRuntime {\n const runtime = ObservabilityRuntime.current() ?? ObservabilityRuntime.stopped();\n if (runtime) {\n return runtime;\n }\n\n // Start a default runtime. A log call before configure() then does not throw.\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}\n\n/**\n * Retrieves a cached logger for a namespace, or builds an uncached scoped logger.\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, or a new one when options are given.\n */\nexport function getLogger(namespace: string, options?: OneLoggerOptions): OneLogger {\n // Do not cache a scoped logger. The cache keeps its scopedContext for the life of the document.\n if (options) {\n return new OneLogger(requireRuntime, namespace, options);\n }\n\n let logger = loggers.get(namespace);\n\n if (!logger) {\n logger = new OneLogger(requireRuntime, namespace);\n loggers.set(namespace, 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 the ambient context. All later records include it.\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 the token is valid and the runtime adopts it.\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 that resolves after the pipeline processes the queued batches.\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.\n * A forwarder does not store batches.\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 stops all runtime subsystems.\n * @returns Promise resolving once shutdown completes.\n */\nexport async function shutdown(): Promise<void> {\n await ObservabilityRuntime.current()?.destroy();\n}\n"],"mappings":"2NAYA,SAASuF,EAAQ,EAA2B,CAC1C,OAAO,KAAK,OAAO,YAAY,IAAI,EAAIC,GAAaxF,EAAAA,CAAkB,EAAIA,EAAAA,CAC5E,CAUA,SAASyF,EACP,EACA,EACA,EACA,EACA,EACM,CACNC,EAAO,UAAU,GAAGC,EAAM,WAAYJ,EAAQC,CAAS,EAAG,KAAM,YAAa,CAC3E,SACA,GAAGI,CACL,CAAC,CACH,CAUA,SAASC,EACP,EACA,EACA,EACA,EACA,EACM,CACNH,EAAO,MAAM,GAAGC,EAAM,SAAUG,EAAO,CACrC,qBAAsBP,EAAQC,CAAS,EACvC,OAAQ,UACR,GAAGI,CACL,CAAC,CACH,CAUA,SAAgB3F,EACd,EACA,EACA,EACA,EACG,CACH,IAAMuF,EAAY,YAAY,IAAI,EAClC,GAAI,CACF,IAAMQ,EAASC,EAAG,EAElB,OADAR,EAAOC,EAAQC,EAAOH,EAAW,UAAWI,CAAU,EAC/CI,CACT,OAASF,EAAO,CAGd,MADAD,EAAKH,EAAQC,EAAOH,EAAWM,EAAOF,CAAU,EAC1CE,CACR,CACF,CAUA,eAAsB5F,EACpB,EACA,EACA,EACA,EACY,CACZ,IAAMsF,EAAY,YAAY,IAAI,EAClC,GAAI,CACF,IAAMQ,EAAS,MAAMC,EAAG,EAExB,OADAR,EAAOC,EAAQC,EAAOH,EAAW,UAAWI,CAAU,EAC/CI,CACT,OAASF,EAAO,CAGd,MADAD,EAAKH,EAAQC,EAAOH,EAAWM,EAAOF,CAAU,EAC1CE,CACR,CACF,CCvFA,SAASK,EAAQ,EAAgB,EAAiC,CAChE,GAAIC,aAAiB,MACnB,OAAOA,EAKT,IAAMC,EAAOC,EAAY,MACvB,yBACA,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