@utk09/ui-observability 0.9.1 → 0.9.3

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.
Files changed (172) hide show
  1. package/CHANGELOG.md +33 -0
  2. package/README.md +75 -64
  3. package/dist/batch-D5qvsMQ_.cjs +2 -0
  4. package/dist/batch-D5qvsMQ_.cjs.map +1 -0
  5. package/dist/{batch-DEK4bv9N.js → batch-DDgxg16_.js} +7 -4
  6. package/dist/batch-DDgxg16_.js.map +1 -0
  7. package/dist/bus/bus.d.ts +0 -4
  8. package/dist/{bus-HVQ8E72V.js → bus-C6RwKzPW.js} +63 -66
  9. package/dist/bus-C6RwKzPW.js.map +1 -0
  10. package/dist/bus-WPVDFw2y.cjs +2 -0
  11. package/dist/bus-WPVDFw2y.cjs.map +1 -0
  12. package/dist/capture/network.d.ts +2 -0
  13. package/dist/capture/storm.d.ts +2 -7
  14. package/dist/capture/types.d.ts +3 -0
  15. package/dist/{console-DssDxq1B.cjs → console-BSusX_M-.cjs} +2 -2
  16. package/dist/{console-DssDxq1B.cjs.map → console-BSusX_M-.cjs.map} +1 -1
  17. package/dist/{console-C9Y639mn.js → console-Dv5GfaNn.js} +3 -3
  18. package/dist/{console-C9Y639mn.js.map → console-Dv5GfaNn.js.map} +1 -1
  19. package/dist/constants-Cb92egPS.cjs +2 -0
  20. package/dist/constants-Cb92egPS.cjs.map +1 -0
  21. package/dist/{constants-N99w84xy.js → constants-DhH6VI5a.js} +39 -12
  22. package/dist/constants-DhH6VI5a.js.map +1 -0
  23. package/dist/constants.d.ts +28 -3
  24. package/dist/core/breadcrumbs.d.ts +1 -3
  25. package/dist/core/context.d.ts +0 -8
  26. package/dist/core/diagnostics.d.ts +1 -3
  27. package/dist/core/meter.d.ts +45 -0
  28. package/dist/core/pipeline.d.ts +5 -12
  29. package/dist/core/record.d.ts +7 -0
  30. package/dist/core/runtime.d.ts +17 -0
  31. package/dist/core/sampling.d.ts +3 -3
  32. package/dist/core/sender.d.ts +2 -0
  33. package/dist/deadline-CUrH0Hd8.cjs +2 -0
  34. package/dist/deadline-CUrH0Hd8.cjs.map +1 -0
  35. package/dist/deadline-DeqXEliN.js +31 -0
  36. package/dist/deadline-DeqXEliN.js.map +1 -0
  37. package/dist/{errors-CQusIGWJ.js → errors-DCZWcHkd.js} +4 -4
  38. package/dist/{errors-CQusIGWJ.js.map → errors-DCZWcHkd.js.map} +1 -1
  39. package/dist/{errors-BTWuVnHZ.cjs → errors-ERu-su8m.cjs} +3 -3
  40. package/dist/{errors-BTWuVnHZ.cjs.map → errors-ERu-su8m.cjs.map} +1 -1
  41. package/dist/fixed-window-BR0bu32Y.cjs +2 -0
  42. package/dist/fixed-window-BR0bu32Y.cjs.map +1 -0
  43. package/dist/fixed-window-Re7jIRJH.js +9 -0
  44. package/dist/fixed-window-Re7jIRJH.js.map +1 -0
  45. package/dist/{identity-B1GDS1Tb.cjs → identity-C1WLItSl.cjs} +2 -2
  46. package/dist/{identity-B1GDS1Tb.cjs.map → identity-C1WLItSl.cjs.map} +1 -1
  47. package/dist/{identity-D4DPjTM9.js → identity-Di-QXGCC.js} +2 -2
  48. package/dist/{identity-D4DPjTM9.js.map → identity-Di-QXGCC.js.map} +1 -1
  49. package/dist/index.cjs +1 -1
  50. package/dist/index.cjs.map +1 -1
  51. package/dist/index.d.ts +18 -0
  52. package/dist/index.js +522 -369
  53. package/dist/index.js.map +1 -1
  54. package/dist/indexeddb-storage-DX18p39D.cjs +2 -0
  55. package/dist/indexeddb-storage-DX18p39D.cjs.map +1 -0
  56. package/dist/{indexeddb-storage-B8SGUzSV.js → indexeddb-storage-T9YIYVYC.js} +48 -59
  57. package/dist/indexeddb-storage-T9YIYVYC.js.map +1 -0
  58. package/dist/{interactions-CnjfQgw3.js → interactions-BLH_tX87.js} +2 -2
  59. package/dist/{interactions-CnjfQgw3.js.map → interactions-BLH_tX87.js.map} +1 -1
  60. package/dist/{interactions-CcxrVzpg.cjs → interactions-_hfOerfC.cjs} +2 -2
  61. package/dist/{interactions-CcxrVzpg.cjs.map → interactions-_hfOerfC.cjs.map} +1 -1
  62. package/dist/journey-BRUj0hqD.cjs +2 -0
  63. package/dist/journey-BRUj0hqD.cjs.map +1 -0
  64. package/dist/{journey-DjvDzHyp.js → journey-yALMEWF7.js} +39 -38
  65. package/dist/journey-yALMEWF7.js.map +1 -0
  66. package/dist/library-request-BcAxuwsf.cjs +2 -0
  67. package/dist/library-request-BcAxuwsf.cjs.map +1 -0
  68. package/dist/library-request-CQD4HUiP.js +25 -0
  69. package/dist/library-request-CQD4HUiP.js.map +1 -0
  70. package/dist/{long-frames-BGik_Yhy.cjs → long-frames-D4Bm3Zkz.cjs} +2 -2
  71. package/dist/{long-frames-BGik_Yhy.cjs.map → long-frames-D4Bm3Zkz.cjs.map} +1 -1
  72. package/dist/{long-frames-CZk3XOkH.js → long-frames-DD_Um9_4.js} +3 -3
  73. package/dist/{long-frames-CZk3XOkH.js.map → long-frames-DD_Um9_4.js.map} +1 -1
  74. package/dist/models/batch.d.ts +6 -0
  75. package/dist/models/config.d.ts +23 -0
  76. package/dist/models/metric.d.ts +50 -0
  77. package/dist/network--GoE7_Or.js +211 -0
  78. package/dist/network--GoE7_Or.js.map +1 -0
  79. package/dist/network-DcuS2H1P.cjs +2 -0
  80. package/dist/network-DcuS2H1P.cjs.map +1 -0
  81. package/dist/openfin-BwEN0uj4.js +8 -0
  82. package/dist/openfin-BwEN0uj4.js.map +1 -0
  83. package/dist/openfin-DtH2f7zX.cjs +2 -0
  84. package/dist/openfin-DtH2f7zX.cjs.map +1 -0
  85. package/dist/platform-GaM6h7XM.js +52 -0
  86. package/dist/platform-GaM6h7XM.js.map +1 -0
  87. package/dist/platform-kIL5AZB7.cjs +2 -0
  88. package/dist/platform-kIL5AZB7.cjs.map +1 -0
  89. package/dist/{remote-rules-M-XZ1xbe.js → remote-rules-6ePq8CrI.js} +23 -25
  90. package/dist/remote-rules-6ePq8CrI.js.map +1 -0
  91. package/dist/remote-rules-CI3gbRCL.cjs +2 -0
  92. package/dist/remote-rules-CI3gbRCL.cjs.map +1 -0
  93. package/dist/sampling-C-M8p3FK.cjs +2 -0
  94. package/dist/sampling-C-M8p3FK.cjs.map +1 -0
  95. package/dist/sampling-Ud_WiuU9.js +65 -0
  96. package/dist/sampling-Ud_WiuU9.js.map +1 -0
  97. package/dist/{sanitize-DKp5MRsa.cjs → sanitize--_e4oOPX.cjs} +2 -2
  98. package/dist/{sanitize-DKp5MRsa.cjs.map → sanitize--_e4oOPX.cjs.map} +1 -1
  99. package/dist/{sanitize-Dwj9JCkI.js → sanitize-DP0xDPrt.js} +2 -2
  100. package/dist/{sanitize-Dwj9JCkI.js.map → sanitize-DP0xDPrt.js.map} +1 -1
  101. package/dist/sender-BESHz6my.cjs +3 -0
  102. package/dist/sender-BESHz6my.cjs.map +1 -0
  103. package/dist/{sender-BBY0IcUo.js → sender-BUBWLn5i.js} +425 -290
  104. package/dist/sender-BUBWLn5i.js.map +1 -0
  105. package/dist/storage/gap.d.ts +20 -0
  106. package/dist/storage/indexeddb-storage.d.ts +1 -7
  107. package/dist/storage/keys.d.ts +9 -0
  108. package/dist/storage/local-storage.d.ts +0 -6
  109. package/dist/storage/memory-storage.d.ts +1 -1
  110. package/dist/storm-DhHGHhOc.cjs +2 -0
  111. package/dist/storm-DhHGHhOc.cjs.map +1 -0
  112. package/dist/storm-OD5J6Ylm.js +10 -0
  113. package/dist/storm-OD5J6Ylm.js.map +1 -0
  114. package/dist/transport/custom-transport.d.ts +3 -2
  115. package/dist/transport/exit-flush.d.ts +13 -2
  116. package/dist/transport/http-transport.d.ts +6 -4
  117. package/dist/transport/retry-engine.d.ts +3 -1
  118. package/dist/transport/serializers/otlp-metrics.d.ts +3 -0
  119. package/dist/transport/serializers/otlp.d.ts +30 -0
  120. package/dist/transport/serializers/select.d.ts +20 -4
  121. package/dist/transport/status-transport.d.ts +19 -11
  122. package/dist/utils/fixed-window.d.ts +15 -0
  123. package/dist/utils/guards.d.ts +6 -0
  124. package/dist/utils/library-request.d.ts +12 -0
  125. package/dist/utils/openfin.d.ts +48 -0
  126. package/dist/utils/platform.d.ts +5 -0
  127. package/package.json +2 -3
  128. package/dist/batch-DEK4bv9N.js.map +0 -1
  129. package/dist/batch-DEVFs28i.cjs +0 -2
  130. package/dist/batch-DEVFs28i.cjs.map +0 -1
  131. package/dist/bus-DNFvTkif.cjs +0 -2
  132. package/dist/bus-DNFvTkif.cjs.map +0 -1
  133. package/dist/bus-HVQ8E72V.js.map +0 -1
  134. package/dist/constants-N99w84xy.js.map +0 -1
  135. package/dist/constants-X86IDwkC.cjs +0 -2
  136. package/dist/constants-X86IDwkC.cjs.map +0 -1
  137. package/dist/deadline-5_PecIl5.js +0 -26
  138. package/dist/deadline-5_PecIl5.js.map +0 -1
  139. package/dist/deadline-XSnm95pg.cjs +0 -2
  140. package/dist/deadline-XSnm95pg.cjs.map +0 -1
  141. package/dist/indexeddb-storage-B8SGUzSV.js.map +0 -1
  142. package/dist/indexeddb-storage-ukzC82dm.cjs +0 -2
  143. package/dist/indexeddb-storage-ukzC82dm.cjs.map +0 -1
  144. package/dist/journey-DjvDzHyp.js.map +0 -1
  145. package/dist/journey-DxlfdFJV.cjs +0 -2
  146. package/dist/journey-DxlfdFJV.cjs.map +0 -1
  147. package/dist/library-request-BZ1ekVtl.cjs +0 -2
  148. package/dist/library-request-BZ1ekVtl.cjs.map +0 -1
  149. package/dist/library-request-C8kc5YWv.js +0 -14
  150. package/dist/library-request-C8kc5YWv.js.map +0 -1
  151. package/dist/network-51iicpLl.js +0 -174
  152. package/dist/network-51iicpLl.js.map +0 -1
  153. package/dist/network-jBbjyAJP.cjs +0 -2
  154. package/dist/network-jBbjyAJP.cjs.map +0 -1
  155. package/dist/platform-Cjts-8k8.js +0 -48
  156. package/dist/platform-Cjts-8k8.js.map +0 -1
  157. package/dist/platform-DW3GFIUE.cjs +0 -2
  158. package/dist/platform-DW3GFIUE.cjs.map +0 -1
  159. package/dist/remote-rules-ByS34k4e.cjs +0 -2
  160. package/dist/remote-rules-ByS34k4e.cjs.map +0 -1
  161. package/dist/remote-rules-M-XZ1xbe.js.map +0 -1
  162. package/dist/sampling-BN3Oi6SV.js +0 -63
  163. package/dist/sampling-BN3Oi6SV.js.map +0 -1
  164. package/dist/sampling-b2ck5X98.cjs +0 -2
  165. package/dist/sampling-b2ck5X98.cjs.map +0 -1
  166. package/dist/sender-BBY0IcUo.js.map +0 -1
  167. package/dist/sender-BXoAZKum.cjs +0 -3
  168. package/dist/sender-BXoAZKum.cjs.map +0 -1
  169. package/dist/storm-CKuaBp7i.cjs +0 -2
  170. package/dist/storm-CKuaBp7i.cjs.map +0 -1
  171. package/dist/storm-DhtL2eVr.js +0 -10
  172. package/dist/storm-DhtL2eVr.js.map +0 -1
package/dist/index.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"file":"index.js","names":["timeSync","timeAsync","timeSync","timeAsync","CONSOLE_DEFAULT_STYLES","RESOURCE_TAB_ID","CAPTURE_NAMESPACE","RECORD_LIMITS","DEFAULT_METRIC_UNIT","RESOURCE_OPENFIN_NAME","RESOURCE_TELEMETRY_SDK_NAME","DIAGNOSTIC_THROTTLE_MS","RESOURCE_OPENFIN_UUID","RUNTIME_STOPPED_KEY","RESOURCE_SERVICE_NAME","RESOURCE_CONTEXT_ID","RESOURCE_DEPLOYMENT_ENVIRONMENT","CONFIG_SECTIONS","DEFAULT_CONFIG","RESOURCE_HOST_PLATFORM","DURATION_PRECISION","RESOURCE_SERVICE_VERSION","RESOURCE_TELEMETRY_SDK_VERSION","RESOURCE_TELEMETRY_SDK_LANGUAGE","SERIALIZER_NAME_OTLP","UNDEFAULTED_SECTION_KEYS","ATTR_BREADCRUMBS","ATTR_JOURNEY_NAME","LEVEL_BYPASS_TYPES","ATTR_LOG_TYPE","TELEMETRY_SDK_NAME","LIBRARY_LOG_PREFIX","SEVERITY_NUMBER","ATTR_PAGE_URL","TELEMETRY_SDK_VERSION","UNDEFAULTED_CONFIG_KEYS","ATTR_ATTRIBUTES_DROPPED","RESOURCE_BROWSER_USER_AGENT","CONSOLE_DEFAULT_LEVEL","ATTR_JOURNEY_PARENT_ID","LEVEL_ORDER","TRACE_MAX_AGE_MS","ATTR_APP_NAMESPACE","ATTR_ERROR_DATA","ATTR_SANITIZE_FAILED","TRACEPARENT_HEADER","RUNTIME_GLOBAL_KEY","ATTR_ATTRIBUTES_BYTES","STORAGE_NAMESPACE","ATTR_JOURNEY_ID","ATTR_LOG_SEQ","TELEMETRY_SDK_LANGUAGE","UNKNOWN_SERVICE_NAME","BEACON_LIMIT_BYTES","RESOURCE_SESSION_ID","isDataField","isErrorLike","ERROR_OWN_KEYS","isLogRecord","isLogLevel","shouldSample","nowUnixNano","shouldSampleInput","isLibraryConsole","truncate","sanitize","runAsLibraryConsole","sanitizeWithSize","persistTabId","newId","SessionTouch","randomHex","memoryStores","resolveIdentity","BROWSER_STORES","detectPlatform","stripUrlQuery","currentUrl","isActionRecord","attributeOf","runAsLibraryRequest","JourneyEngine","JOURNEY_OPTIONS","elapsed","startedAt","finish","label","duration","attributes","fail","logger","error","timeSync$1","result","fn","timeAsync$1","LIBRARY_NAMESPACES","toError","known","diagnostics","value","copy","text","consoleError","reason","errorData","source","errorLike","data","count","key","field","isPlainObject","proto","levelTypeFor","namespace","own","copyPayload","payload","OneLogger","bind","options","message","name","unit","type","runtime","level","body","copied","crumb","record","dropped","ships","asPayload","asError","shown","METHOD","ConsoleSink","settings","limits","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","LEVEL_NAMES","COMPRESSION_VALUES","CREDENTIALS_VALUES","STORAGE_VALUES","IDENTITY_VALUES","BUS_MODE_VALUES","OPENFIN_ROLE_VALUES","JOURNEY_SCOPE_VALUES","CONSOLE_METHOD_VALUES","RETENTION_MODE_VALUES","BATCHING_RANGES","RETENTION_RANGES","LIMIT_RANGES","JOURNEY_AGE_RANGE","CAPTURE_FLAG_KEYS","SANDBOX_ORIGIN","LEVEL_EXPECTED","listOf","CONSOLE_CAPTURE_EXPECTED","PATTERN_LIST_EXPECTED","TARGET_LIST_EXPECTED","ORIGIN_LIST_EXPECTED","STRING_LIST_EXPECTED","quoted","values","describeValue","reportInvalid","expected","kept","resolveChoice","fallback","match","accepted","entry","resolveBoolean","resolveNonNegative","resolveInteger","min","max","range","resolveRanges","given","input","keys","ranges","section","base","toLevel","upper","resolveLevel","resolveList","entries","accept","toStringEntry","toPattern","toConsoleMethod","toOrigin","origin","toTarget","isStringRecord","resolveHeaders","isSerializer","resolveSerializer","requested","previous","CONSOLE_STYLE_KEYS","validStyles","valid","resolveConsoleLevel","resolveConsole","resolveSampling","resolveBus","resolveJourney","resolveRetention","resolveCaptureConsole","resolveCapture","capture","resolveConfig","merged","rate","maxRate","rates","ns","r","url","reportUnknownKeys","sectionKeys","applyResolvedConfig","next","target","ContextStore","Diagnostics","handler","throttleMs","total","code","by","now","event","handlerError","addCapped","list","DropReporter","config","records","batchIds","summary","id","journey","summaries","onDrop","HoldBuffer","action","oldest","one","ERROR_ATTR_PREFIX","REDACTABLE_INDEX_KEYS","asAttributes","RecordBuilder","deps","minLevel","traceCtx","tracing","activeJourney","remote","seq","sequence","pageUrl","bytes","fromContext","fromScope","fromPayload","redact","redacted","candidate","remeasured","keptBytes","breadcrumbs","crumbBytes","platform","identity","CAPTURE_LOADERS","RUNTIME_KEY","STOPPED_KEY","SENDER_SECTIONS","captureKey","consoleOnly","ownVersion","ObservabilityRuntime","degraded","bus","reply","local","pinned","stopped","implicit","foundText","found","capturesBefore","sections","built","captures","journeyReady","Bus","sender","Sender","generation","names","classes","CaptureModule","worker","closing","buffered","batch","fresh","createMemoryTransport","sent","answer","request","retryAfterMs","loggers","requireRuntime","configure","getLogger","root","trace","debug","info","warn","err","fatal","logAction","logEvent","logMetric","timeSync","timeAsync","setContext","setContextMap","removeContext","startJourney","endJourney","currentJourney","getJourneyToken","adoptJourney","token","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/drops.ts","../src/core/hold-buffer.ts","../src/core/record.ts","../src/core/runtime.ts","../src/transport/memory-transport.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 the operation duration as a histogram metric, for each outcome.\n * @param logger Target telemetry logger.\n * @param label Metric name prefix.\n * @param duration Elapsed duration in milliseconds.\n * @param status Outcome status string.\n * @param attributes Optional contextual attributes.\n */\nfunction finish(\n logger: CaptureLogger,\n label: string,\n duration: number,\n status: string,\n attributes?: Record<string, unknown>,\n): void {\n logger.logMetric(`${label}.duration`, duration, \"ms\", \"histogram\", {\n status,\n ...attributes,\n });\n}\n\n/**\n * Logs an operation failure and its FAILURE duration histogram.\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 // Read the duration one time. The error record and the metric then give the same value.\n const duration = elapsed(startedAt);\n logger.error(`${label} failed`, error, {\n \"action.duration_ms\": duration,\n status: \"FAILURE\",\n ...attributes,\n });\n finish(logger, label, duration, \"FAILURE\", attributes);\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, elapsed(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 that resolves 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, elapsed(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 {\n ATTR_BREADCRUMBS,\n ATTR_ERROR_DATA,\n ATTR_SANITIZE_FAILED,\n CAPTURE_NAMESPACE,\n DEFAULT_METRIC_UNIT,\n STORAGE_NAMESPACE,\n} from \"../constants\";\nimport type { LogLevel, LogRecord, LogType, MetricType } from \"../models/log-record\";\nimport { ERROR_OWN_KEYS, isDataField, isErrorLike } from \"../utils/error-like\";\nimport { timeAsync, timeSync } from \"../utils/timer\";\nimport type { Diagnostics } from \"./diagnostics\";\nimport type { DropReason } from \"./record\";\nimport type { ObservabilityRuntime } from \"./runtime\";\n\n/** Namespaces of the library. Their records have log.type \"system\". */\nconst LIBRARY_NAMESPACES: readonly string[] = [CAPTURE_NAMESPACE, STORAGE_NAMESPACE];\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 * An error becomes a copy with its name, message and stack.\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 // A Proxy reason can throw from instanceof and from each property read. A Proxy around\n // an Error passes instanceof. Read its fields here, inside the guard.\n const known = diagnostics.guard(\n \"record.sanitize_failed\",\n \"The library could not read the error reason.\",\n (): Error | undefined => {\n if (!(value instanceof Error) && !isErrorLike(value)) {\n return undefined;\n }\n\n const copy = new Error(value.message);\n copy.name = value.name;\n copy.stack = value.stack;\n return copy;\n },\n );\n\n if (known) {\n return known;\n }\n\n // String() throws on a null-prototype object and on a toString that throws.\n // log.error() runs inside a consumer catch block. It 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 * Gives the error that the console prints. The console shows the cause and the own fields\n * of a real Error. The record keeps the copy from toError().\n * @param reason Error reason.\n * @param copy Normalized copy of the reason.\n * @param diagnostics Diagnostics reporter.\n * @returns The reason if it is an Error, or the copy.\n */\nfunction consoleError(reason: unknown, copy: Error, diagnostics: Diagnostics): Error {\n // A Proxy reason can throw from instanceof.\n const original = diagnostics.guard(\n \"record.sanitize_failed\",\n \"The library could not read the error reason.\",\n () => (reason instanceof Error ? reason : copy),\n );\n\n return original ?? copy;\n}\n\n/**\n * Reads the data of an error reason for the error.data attribute.\n * It keeps only the own fields with a string, number or boolean value.\n * @param value Error reason.\n * @param diagnostics Diagnostics reporter.\n * @returns The fields of an object reason, a primitive reason, or undefined.\n * A string reason gives undefined. error.message already holds it.\n */\nfunction errorData(value: unknown, diagnostics: Diagnostics): unknown {\n if (typeof value === \"number\" || typeof value === \"boolean\") {\n return value;\n }\n\n if (typeof value === \"bigint\" || typeof value === \"symbol\") {\n return value;\n }\n\n if (typeof value !== \"object\" || value === null) {\n return undefined;\n }\n\n return diagnostics.guard(\n \"record.sanitize_failed\",\n \"The library could not read the properties of the error reason.\",\n () => {\n const source = value as Record<string, unknown>;\n const errorLike = isErrorLike(value);\n const data: Record<string, unknown> = {};\n let count = 0;\n\n // An object field, for example the config of an AxiosError, holds credentials.\n for (const key of Object.keys(source)) {\n const field = source[key];\n if ((!errorLike || !ERROR_OWN_KEYS.has(key)) && isDataField(field)) {\n data[key] = field;\n count++;\n }\n }\n\n return count === 0 ? undefined : data;\n },\n );\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/**\n * Selects the log.type of the level methods for a namespace.\n * @param namespace Logger namespace.\n * @returns \"system\" for a namespace of the library, \"log\" for each other namespace.\n */\nfunction levelTypeFor(namespace: string): LogType {\n const library = LIBRARY_NAMESPACES.some(\n (own) => namespace === own || namespace.startsWith(`${own}.`),\n );\n\n return library ? \"system\" : \"log\";\n}\n\n/**\n * Copies a caller payload. A Proxy with a throwing trap must not throw out of a log call.\n * @param payload Caller payload.\n * @param diagnostics Diagnostics reporter.\n * @returns The copy, or a marker attribute when the library cannot read the payload.\n */\nfunction copyPayload(\n payload: Record<string, unknown> | undefined,\n diagnostics: Diagnostics,\n): Record<string, unknown> {\n if (payload === undefined) {\n return {};\n }\n\n const copied = diagnostics.guard(\n \"record.sanitize_failed\",\n \"The library could not read the payload.\",\n () => ({ ...payload }),\n );\n\n return copied ?? { [ATTR_SANITIZE_FAILED]: true };\n}\n\n/** Namespaced logger instance for recording structured events, metrics, and errors. */\nexport class OneLogger {\n /** log.type of the level methods. It is \"system\" only for the namespaces of the library. */\n private readonly levelType: LogType;\n\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 this.levelType = levelTypeFor(namespace);\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\", this.levelType, 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\", this.levelType, 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\", this.levelType, 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\", this.levelType, 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 // NaN and Infinity become null in JSON. A backend then reads a false zero.\n if (!Number.isFinite(value)) {\n this.bind().diagnostics.report(\n \"record.dropped_malformed\",\n \"The metric value is not a finite number. The library dropped the metric.\",\n { \"metric.name\": name },\n );\n return;\n }\n\n // Spread the caller attributes first. The metric fields then win over a key of the same name.\n const payload = {\n ...copyPayload(attributes, this.bind().diagnostics),\n \"metric.name\": name,\n \"metric.value\": value,\n \"metric.unit\": unit,\n \"metric.type\": type,\n };\n this.write(\"INFO\", \"metric\", name, payload, true);\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 that resolves 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 * @param copied True when the payload is a copy that the library made. write() does not copy it.\n */\n private write(\n level: LogLevel,\n type: LogType,\n body: string,\n payload?: Record<string, unknown>,\n copied = false,\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 // minLevel does not apply to an action or a metric.\n if (!runtime.builder.isEnabled(level, type)) {\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: copied ? payload : copyPayload(payload, runtime.diagnostics),\n });\n\n // Breadcrumbs stay in memory and have no delivery cost. A breadcrumb keeps the body\n // after redact. A record that sampling drops did not go through redact. It keeps its\n // body, and redact sees it later inside the error record. A record that redact or\n // the shape check drops adds no breadcrumb.\n const crumb = record ? record.body : dropped === \"sampling\" ? body : undefined;\n if (type !== \"metric\" && crumb !== undefined) {\n runtime.breadcrumbs.push({\n t: Date.now(),\n category: type === \"action\" ? \"action\" : type === \"event\" ? \"event\" : \"log\",\n message: crumb,\n });\n }\n\n this.print(runtime, level, body, payload, undefined, record, dropped);\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. A Proxy in the error slot can throw on the test.\n const asPayload =\n payload === undefined &&\n (runtime.diagnostics.guard(\n \"record.sanitize_failed\",\n \"The library could not read the error slot.\",\n () => isPlainObject(error),\n ) ??\n false);\n const attributes = asPayload ? (error as Record<string, unknown>) : payload;\n const reason = asPayload ? undefined : error;\n const asError = reason === undefined ? undefined : toError(reason, runtime.diagnostics);\n const shown =\n asError === undefined ? undefined : consoleError(reason, asError, runtime.diagnostics);\n\n if (!ships) {\n this.print(runtime, level, message, attributes, shown, null);\n return;\n }\n\n const data = asError ? errorData(reason, runtime.diagnostics) : undefined;\n\n const { record, dropped } = runtime.builder.build({\n level,\n type: this.levelType,\n body: message,\n namespace: this.namespace,\n scoped: this.options.scopedContext,\n payload: {\n ...copyPayload(attributes, runtime.diagnostics),\n ...(asError\n ? {\n \"error.type\": asError.name,\n \"error.message\": asError.message,\n \"error.stack_trace\": asError.stack,\n }\n : {}),\n ...(data === undefined ? {} : { [ATTR_ERROR_DATA]: data }),\n [ATTR_BREADCRUMBS]: runtime.breadcrumbs.snapshot(),\n },\n });\n\n this.print(runtime, level, message, attributes, shown, record, dropped);\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 * @param dropped Reason of the drop when the builder dropped the record.\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 dropped?: DropReason,\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 // A record that redact or the shape check dropped prints no line. Its text did not pass redact.\n if (dropped === \"redact\" || dropped === \"malformed\") {\n return;\n }\n\n runtime.console.write(this.namespace, level, message, undefined, error);\n }\n\n /**\n * Tests if 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 { isLibraryConsole, runAsLibraryConsole } from \"./library-console\";\nimport { type SanitizeLimits, 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 * @param limits Size limits of the printed payload. They are the record limits.\n */\n constructor(\n private settings: ResolvedConsole,\n private diagnostics: Diagnostics,\n private readonly limits: SanitizeLimits = RECORD_LIMITS,\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 if 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 if (this.settings.level === null) {\n return false;\n }\n\n // Guard against a level that is not a key of LEVEL_ORDER, for example \"toString\".\n if (!Object.hasOwn(LEVEL_ORDER, this.settings.level)) {\n return false;\n }\n\n return 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 // Guard against a loop. A host console wrapper can call the logger. The logger then prints again.\n // The console capture also records inside this scope. Its line is already in devtools.\n if (isLibraryConsole()) {\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, this.limits, this.diagnostics));\n }\n\n // The console capture skips a call in this scope. It must not record a mirrored line.\n runAsLibraryConsole(() => {\n console[method](\n prefix,\n styles.namespace,\n namespace,\n styles[level],\n \"\",\n message,\n ...details,\n );\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. The counter does not reset. A reset repeats\n// numbers in one context.\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","// 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 * Tests if 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/** Cause of a rotation of 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 that resolves when the attempt settles.\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 active span of the host if the peer module loaded and a span runs.\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\" | \"frame\";\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 BEACON_LIMIT_BYTES,\n CONFIG_SECTIONS,\n CONSOLE_DEFAULT_LEVEL,\n CONSOLE_DEFAULT_STYLES,\n DEFAULT_CONFIG,\n LEVEL_ORDER,\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 BatchingOptions,\n BusOptions,\n CaptureOptions,\n CapturedConsoleMethod,\n ConsoleOption,\n ConsoleStyles,\n JourneyOptions,\n LimitOptions,\n ObservabilityConfig,\n ResolvedConfig,\n ResolvedConsole,\n RetentionOptions,\n SamplingOptions,\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/** Level names in severity order. */\nconst LEVEL_NAMES = Object.keys(LEVEL_ORDER) as readonly LogLevel[];\n\n/** Accepted values of each choice option. */\nconst COMPRESSION_VALUES = [\"gzip\", \"none\"] as const;\nconst CREDENTIALS_VALUES = [\"omit\", \"same-origin\", \"include\"] as const;\nconst STORAGE_VALUES = [\"auto\", \"indexeddb\", \"localstorage\", \"memory\", \"none\"] as const;\nconst IDENTITY_VALUES = [\"storage\", \"memory\"] as const;\nconst BUS_MODE_VALUES = [\"auto\", \"sender\", \"forwarder\", \"off\"] as const;\nconst OPENFIN_ROLE_VALUES = [\"auto\", \"provider\", \"client\"] as const;\nconst JOURNEY_SCOPE_VALUES = [\"auto\", \"context\", \"tab\", \"origin\"] as const;\nconst CONSOLE_METHOD_VALUES = [\"error\", \"warn\", \"info\", \"log\"] as const;\nconst RETENTION_MODE_VALUES = [\"limited\", \"until-delivered\"] as const;\n\n/** Lowest and highest accepted value of an integer option. */\ntype Range = readonly [min: number, max: number];\n\n/** Accepted range of each batching key. */\nconst BATCHING_RANGES: Record<keyof BatchingOptions, Range> = {\n logFlushIntervalMs: [100, 60_000],\n logBatchSize: [1, 1000],\n metricFlushIntervalMs: [100, 60_000],\n metricBatchSize: [1, 1000],\n};\n\n/** Accepted range of each numeric retention key. */\nconst RETENTION_RANGES: Record<Exclude<keyof RetentionOptions, \"mode\">, Range> = {\n maxBatches: [1, 5000],\n maxAgeMs: [60_000, 7 * 24 * 60 * 60 * 1000],\n maxAttempts: [1, 20],\n};\n\n/**\n * Accepted range of each record limit. The maximum of maxRecordBytes is one beacon. The body and\n * the error fields are outside maxRecordBytes. An exit batch larger than one beacon goes to the\n * emergency queue.\n */\nconst LIMIT_RANGES: Record<keyof LimitOptions, Range> = {\n maxBodyChars: [256, 65_536],\n maxAttributeChars: [256, 65_536],\n maxAttributeCount: [1, 1024],\n maxStackChars: [256, 65_536],\n maxDepth: [1, 16],\n maxArrayLength: [1, 10_000],\n maxNodes: [100, 100_000],\n maxRecordBytes: [1024, BEACON_LIMIT_BYTES],\n};\n\n/** Accepted range of journey.maxAgeMs. */\nconst JOURNEY_AGE_RANGE: Range = [60_000, 24 * 60 * 60 * 1000];\n\n/** Boolean keys of the capture section. */\nconst CAPTURE_FLAG_KEYS = [\n \"errors\",\n \"rejections\",\n \"resourceErrors\",\n \"fetch\",\n \"xhr\",\n \"interactions\",\n \"navigation\",\n \"webVitals\",\n \"longFrames\",\n \"fullUrls\",\n] as const;\n\n/** Origin of a sandboxed frame without allow-same-origin. */\nconst SANDBOX_ORIGIN = \"null\";\n\n/** Text of each expected value in a config.invalid message. */\nconst LEVEL_EXPECTED = `a level name: ${listOf(LEVEL_NAMES)}`;\nconst CONSOLE_CAPTURE_EXPECTED = `true, false or a list of ${listOf(CONSOLE_METHOD_VALUES)}`;\nconst PATTERN_LIST_EXPECTED = \"a list of strings and RegExp patterns\";\nconst TARGET_LIST_EXPECTED =\n 'a list of origin URLs such as \"https://api.example\" and RegExp patterns';\nconst ORIGIN_LIST_EXPECTED =\n 'a list of origin URLs such as \"https://app.example\". For a sandboxed frame, set bus.mode: \"sender\" in the frame';\nconst STRING_LIST_EXPECTED = \"a list of strings\";\n\n/** Function form of the headers option. */\ntype HeadersFunction = () => Record<string, string> | Promise<Record<string, string>>;\n\n/** The headers option. */\ntype HeadersOption = ObservabilityConfig[\"headers\"];\n\n/**\n * Writes a list of values as text, for example `\"a\", \"b\" or \"c\"`.\n * @param values Values to list.\n * @returns The text.\n */\nfunction listOf(values: readonly string[]): string {\n const quoted = values.map((value) => `\"${value}\"`);\n return `${quoted.slice(0, -1).join(\", \")} or ${quoted[quoted.length - 1]}`;\n}\n\n/**\n * Describes a config value for a message. It does not print an object or a function.\n * @param value Value that the consumer passed.\n * @returns Short text for the value.\n */\nfunction describeValue(value: unknown): string {\n if (typeof value === \"string\") {\n return `\"${value}\"`;\n }\n\n if (typeof value === \"function\") {\n return \"a function\";\n }\n\n if (typeof value === \"object\" && value !== null) {\n return \"an object\";\n }\n\n return String(value);\n}\n\n/**\n * Reports a value that the option does not accept.\n * @param diagnostics Diagnostics reporter.\n * @param key Config key, for example `bus.mode`.\n * @param expected Text of the accepted values.\n * @param value Value that the consumer passed.\n * @param kept Text of the value that stays in force.\n */\nfunction reportInvalid(\n diagnostics: Diagnostics,\n key: string,\n expected: string,\n value: unknown,\n kept: string,\n): void {\n diagnostics.report(\n \"config.invalid\",\n `${key} must be ${expected}. The value is ${describeValue(value)}. The library keeps ${kept}.`,\n );\n}\n\n/**\n * Reads an option that accepts one value from a fixed list.\n * @param key Config key.\n * @param value Value that the consumer passed.\n * @param accepted Accepted values.\n * @param fallback Value in force.\n * @param diagnostics Diagnostics reporter.\n * @returns The value, or the fallback when the value is not accepted.\n */\nfunction resolveChoice<T extends string>(\n key: string,\n value: unknown,\n accepted: readonly T[],\n fallback: T,\n diagnostics: Diagnostics,\n): T {\n if (value === undefined) {\n return fallback;\n }\n\n const match = accepted.find((entry) => entry === value);\n if (match !== undefined) {\n return match;\n }\n\n reportInvalid(diagnostics, key, listOf(accepted), value, `\"${fallback}\"`);\n return fallback;\n}\n\n/**\n * Reads a boolean option.\n * @param key Config key.\n * @param value Value that the consumer passed.\n * @param fallback Value in force.\n * @param diagnostics Diagnostics reporter.\n * @returns The value, or the fallback when the value is not a boolean.\n */\nfunction resolveBoolean(\n key: string,\n value: unknown,\n fallback: boolean,\n diagnostics: Diagnostics,\n): boolean {\n if (value === undefined) {\n return fallback;\n }\n\n if (typeof value === \"boolean\") {\n return value;\n }\n\n reportInvalid(diagnostics, key, \"true or false\", value, String(fallback));\n return fallback;\n}\n\n/**\n * Reads an option that accepts a finite number of 0 or more.\n * @param key Config key.\n * @param value Value that the consumer passed.\n * @param fallback Value in force.\n * @param diagnostics Diagnostics reporter.\n * @returns The value, or the fallback when the value is not accepted.\n */\nfunction resolveNonNegative(\n key: string,\n value: unknown,\n fallback: number,\n diagnostics: Diagnostics,\n): number {\n if (value === undefined) {\n return fallback;\n }\n\n if (typeof value === \"number\" && Number.isFinite(value) && value >= 0) {\n return value;\n }\n\n reportInvalid(diagnostics, key, \"a finite number of 0 or more\", value, String(fallback));\n return fallback;\n}\n\n/**\n * Reads an option that accepts an integer in a range.\n * @param key Config key.\n * @param value Value that the consumer passed.\n * @param range Lowest and highest accepted value.\n * @param fallback Value in force.\n * @param diagnostics Diagnostics reporter.\n * @returns The value, or the fallback when the value is not accepted.\n */\nfunction resolveInteger(\n key: string,\n value: unknown,\n range: Range,\n fallback: number,\n diagnostics: Diagnostics,\n): number {\n if (value === undefined) {\n return fallback;\n }\n\n const [min, max] = range;\n if (typeof value === \"number\" && Number.isInteger(value) && value >= min && value <= max) {\n return value;\n }\n\n const expected = `an integer from ${String(min)} to ${String(max)}`;\n reportInvalid(diagnostics, key, expected, value, String(fallback));\n return fallback;\n}\n\n/**\n * Merges and checks a section of integer options. The keys come from `ranges` only.\n * @param section Section name, for example `batching`.\n * @param input Values that the consumer passed.\n * @param base Values in force.\n * @param ranges Accepted range of each key.\n * @param diagnostics Diagnostics reporter.\n * @returns The value of each key in `ranges`.\n */\nfunction resolveRanges<K extends string>(\n section: string,\n input: Partial<Record<NoInfer<K>, unknown>> | undefined,\n base: Record<NoInfer<K>, number>,\n ranges: Record<K, Range>,\n diagnostics: Diagnostics,\n): Record<K, number> {\n const given: Partial<Record<K, unknown>> = input ?? {};\n const keys = Object.keys(ranges) as K[];\n\n return Object.fromEntries(\n keys.map((key): [K, number] => [\n key,\n resolveInteger(`${section}.${key}`, given[key], ranges[key], base[key], diagnostics),\n ]),\n ) as Record<K, number>;\n}\n\n/**\n * Reads a level name in any case.\n * @param value Value that the consumer passed.\n * @returns The level, or undefined when the value is not a level name.\n */\nfunction toLevel(value: unknown): LogLevel | undefined {\n if (typeof value !== \"string\") {\n return undefined;\n }\n\n const upper = value.toUpperCase();\n return LEVEL_NAMES.find((level) => level === upper);\n}\n\n/**\n * Reads a level option. Without this check, an unknown level drops each record with no message.\n * @param key Config key.\n * @param value Value that the consumer passed.\n * @param fallback Level in force.\n * @param diagnostics Diagnostics reporter.\n * @returns The level, or the fallback when the value is not a level name.\n */\nfunction resolveLevel(\n key: string,\n value: unknown,\n fallback: LogLevel,\n diagnostics: Diagnostics,\n): LogLevel {\n if (value === undefined) {\n return fallback;\n }\n\n const level = toLevel(value);\n if (level !== undefined) {\n return level;\n }\n\n reportInvalid(diagnostics, key, LEVEL_EXPECTED, value, `\"${fallback}\"`);\n return fallback;\n}\n\n/**\n * Reads a list option. It keeps each accepted entry and reports each other entry.\n * @param key Config key.\n * @param value Value that the consumer passed.\n * @param fallback List in force.\n * @param expected Text of the accepted list.\n * @param accept Converts an entry, or returns undefined to reject it.\n * @param diagnostics Diagnostics reporter.\n * @returns The accepted entries, or the fallback when the value is not a list.\n */\nfunction resolveList<T>(\n key: string,\n value: unknown,\n fallback: T[],\n expected: string,\n accept: (entry: unknown) => T | undefined,\n diagnostics: Diagnostics,\n): T[] {\n if (value === undefined) {\n return fallback;\n }\n\n if (!Array.isArray(value)) {\n reportInvalid(diagnostics, key, expected, value, \"the list in force\");\n return fallback;\n }\n\n const kept: T[] = [];\n const entries: unknown[] = value;\n\n for (const entry of entries) {\n const accepted = accept(entry);\n if (accepted === undefined) {\n diagnostics.report(\n \"config.invalid\",\n `The library ignores the ${key} entry ${describeValue(entry)}. ${key} must be ${expected}.`,\n );\n continue;\n }\n kept.push(accepted);\n }\n\n return kept;\n}\n\n/**\n * Accepts a string entry.\n * @param entry List entry.\n * @returns The entry, or undefined.\n */\nfunction toStringEntry(entry: unknown): string | undefined {\n return typeof entry === \"string\" ? entry : undefined;\n}\n\n/**\n * Accepts a string or a RegExp entry.\n * @param entry List entry.\n * @returns The entry, or undefined.\n */\nfunction toPattern(entry: unknown): string | RegExp | undefined {\n return typeof entry === \"string\" || entry instanceof RegExp ? entry : undefined;\n}\n\n/**\n * Accepts a console method name.\n * @param entry List entry.\n * @returns The method, or undefined.\n */\nfunction toConsoleMethod(entry: unknown): CapturedConsoleMethod | undefined {\n return CONSOLE_METHOD_VALUES.find((method) => method === entry);\n}\n\n/**\n * Reads an origin entry. A URL with a path gives its origin.\n * @param entry List entry.\n * @returns The origin, or undefined. resolveList reports the rejected entry.\n */\nfunction toOrigin(entry: unknown): string | undefined {\n if (typeof entry !== \"string\") {\n return undefined;\n }\n\n // Each sandboxed and data: document has the opaque origin \"null\". One entry trusts all of them.\n try {\n const { origin } = new URL(entry);\n return origin === SANDBOX_ORIGIN ? undefined : origin;\n } catch {\n return undefined;\n }\n}\n\n/**\n * Reads a trace header target. A string gives its origin. A RegExp stays as it is.\n * @param entry List entry.\n * @returns The target, or undefined. resolveList reports the rejected entry.\n */\nfunction toTarget(entry: unknown): string | RegExp | undefined {\n return entry instanceof RegExp ? entry : toOrigin(entry);\n}\n\n/**\n * Tests if a value is an object of string values.\n * @param value Value to test.\n * @returns True for an object whose values are all strings.\n */\nfunction isStringRecord(value: unknown): value is Record<string, string> {\n if (typeof value !== \"object\" || value === null || Array.isArray(value)) {\n return false;\n }\n\n const values: unknown[] = Object.values(value);\n return values.every((entry) => typeof entry === \"string\");\n}\n\n/**\n * Reads the headers option.\n * @param value Value that the consumer passed.\n * @param fallback Headers in force.\n * @param diagnostics Diagnostics reporter.\n * @returns The headers, undefined for an explicit undefined, or the fallback for a bad value.\n */\nfunction resolveHeaders(\n value: unknown,\n fallback: HeadersOption,\n diagnostics: Diagnostics,\n): HeadersOption {\n // An explicit undefined clears the headers. After logout, the old token must not go on a send.\n if (value === undefined) {\n return undefined;\n }\n\n if (typeof value === \"function\") {\n return value as HeadersFunction;\n }\n\n if (isStringRecord(value)) {\n return value;\n }\n\n reportInvalid(\n diagnostics,\n \"headers\",\n \"an object of strings or a function\",\n value,\n \"the headers in force\",\n );\n return fallback;\n}\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 * Reads the level of the console object form.\n * @param requested Level that the consumer passed.\n * @param previous Console level in force. Null means the console is off.\n * @param diagnostics Diagnostics reporter.\n * @returns The level. An unknown level keeps the level in force.\n */\nfunction resolveConsoleLevel(\n requested: unknown,\n previous: LogLevel | null,\n diagnostics: Diagnostics,\n): LogLevel | null {\n if (requested === undefined) {\n return previous ?? CONSOLE_DEFAULT_LEVEL;\n }\n\n const level = toLevel(requested);\n if (level !== undefined) {\n return level;\n }\n\n reportInvalid(\n diagnostics,\n \"console.level\",\n LEVEL_EXPECTED,\n requested,\n \"the console level in force\",\n );\n return previous;\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 const level = toLevel(requested);\n if (level === undefined) {\n reportInvalid(\n diagnostics,\n \"console\",\n LEVEL_EXPECTED,\n requested,\n \"the console level in force\",\n );\n return previous;\n }\n\n return { level, styles: previous.styles };\n }\n\n // Guard against null and other values that the type does not accept.\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: resolveConsoleLevel(requested.level, previous.level, diagnostics),\n styles: { ...previous.styles, ...validStyles(requested.styles, diagnostics) },\n };\n}\n\n/**\n * Merges and checks the sampling section. resolveConfig checks the rates after the merge.\n * @param input Sampling options that the consumer passed.\n * @param base Sampling options in force.\n * @param diagnostics Diagnostics reporter.\n * @returns The sampling options.\n */\nfunction resolveSampling(\n input: Partial<SamplingOptions> | undefined,\n base: SamplingOptions,\n diagnostics: Diagnostics,\n): SamplingOptions {\n const given = input ?? {};\n\n return {\n ...base,\n ...given,\n rates: { ...base.rates, ...given.rates },\n alwaysSampleTypes: resolveList(\n \"sampling.alwaysSampleTypes\",\n given.alwaysSampleTypes,\n base.alwaysSampleTypes,\n STRING_LIST_EXPECTED,\n toStringEntry,\n diagnostics,\n ),\n remote: resolveBoolean(\"sampling.remote\", given.remote, base.remote, diagnostics),\n };\n}\n\n/**\n * Merges and checks the bus section.\n * @param input Bus options that the consumer passed.\n * @param base Bus options in force.\n * @param diagnostics Diagnostics reporter.\n * @returns The bus options. Each trusted origin is a bare origin.\n */\nfunction resolveBus(\n input: Partial<BusOptions> | undefined,\n base: BusOptions,\n diagnostics: Diagnostics,\n): BusOptions {\n const given = input ?? {};\n\n return {\n mode: resolveChoice(\"bus.mode\", given.mode, BUS_MODE_VALUES, base.mode, diagnostics),\n // Compare origins, not URLs. If not, an entry with a path never matches event.origin.\n trustedOrigins: resolveList(\n \"bus.trustedOrigins\",\n given.trustedOrigins,\n base.trustedOrigins,\n ORIGIN_LIST_EXPECTED,\n toOrigin,\n diagnostics,\n ),\n openFinRole: resolveChoice(\n \"bus.openFinRole\",\n given.openFinRole,\n OPENFIN_ROLE_VALUES,\n base.openFinRole,\n diagnostics,\n ),\n };\n}\n\n/**\n * Merges and checks the journey section.\n * @param input Journey options that the consumer passed.\n * @param base Journey options in force.\n * @param diagnostics Diagnostics reporter.\n * @returns The journey options.\n */\nfunction resolveJourney(\n input: Partial<JourneyOptions> | undefined,\n base: JourneyOptions,\n diagnostics: Diagnostics,\n): JourneyOptions {\n const given = input ?? {};\n\n return {\n scope: resolveChoice(\n \"journey.scope\",\n given.scope,\n JOURNEY_SCOPE_VALUES,\n base.scope,\n diagnostics,\n ),\n maxAgeMs: resolveInteger(\n \"journey.maxAgeMs\",\n given.maxAgeMs,\n JOURNEY_AGE_RANGE,\n base.maxAgeMs,\n diagnostics,\n ),\n };\n}\n\n/**\n * Merges and checks the retention section.\n * @param input Retention options that the consumer passed.\n * @param base Retention options in force.\n * @param diagnostics Diagnostics reporter.\n * @returns The retention options.\n */\nfunction resolveRetention(\n input: Partial<RetentionOptions> | undefined,\n base: RetentionOptions,\n diagnostics: Diagnostics,\n): RetentionOptions {\n const given = input ?? {};\n\n return {\n mode: resolveChoice(\n \"retention.mode\",\n given.mode,\n RETENTION_MODE_VALUES,\n base.mode,\n diagnostics,\n ),\n ...resolveRanges(\"retention\", given, base, RETENTION_RANGES, diagnostics),\n };\n}\n\n/**\n * Reads capture.console.\n * @param value Value that the consumer passed.\n * @param fallback Value in force.\n * @param diagnostics Diagnostics reporter.\n * @returns A boolean, or the accepted method names.\n */\nfunction resolveCaptureConsole(\n value: unknown,\n fallback: boolean | CapturedConsoleMethod[],\n diagnostics: Diagnostics,\n): boolean | CapturedConsoleMethod[] {\n if (value === undefined) {\n return fallback;\n }\n\n if (typeof value === \"boolean\") {\n return value;\n }\n\n if (!Array.isArray(value)) {\n reportInvalid(\n diagnostics,\n \"capture.console\",\n CONSOLE_CAPTURE_EXPECTED,\n value,\n \"the value in force\",\n );\n return fallback;\n }\n\n return resolveList(\n \"capture.console\",\n value,\n [],\n CONSOLE_CAPTURE_EXPECTED,\n toConsoleMethod,\n diagnostics,\n );\n}\n\n/**\n * Merges and checks the capture section.\n * @param input Capture options that the consumer passed.\n * @param base Capture options in force.\n * @param diagnostics Diagnostics reporter.\n * @returns The capture options.\n */\nfunction resolveCapture(\n input: Partial<CaptureOptions> | undefined,\n base: CaptureOptions,\n diagnostics: Diagnostics,\n): CaptureOptions {\n const given = input ?? {};\n const capture: CaptureOptions = {\n ...base,\n ...given,\n console: resolveCaptureConsole(given.console, base.console, diagnostics),\n longFrameThresholdMs: resolveNonNegative(\n \"capture.longFrameThresholdMs\",\n given.longFrameThresholdMs,\n base.longFrameThresholdMs,\n diagnostics,\n ),\n ignoreUrls: resolveList(\n \"capture.ignoreUrls\",\n given.ignoreUrls,\n base.ignoreUrls,\n PATTERN_LIST_EXPECTED,\n toPattern,\n diagnostics,\n ),\n // A string target is an origin. A substring test also matches a query value or a longer host.\n propagateTraceHeaderTo: resolveList(\n \"capture.propagateTraceHeaderTo\",\n given.propagateTraceHeaderTo,\n base.propagateTraceHeaderTo,\n TARGET_LIST_EXPECTED,\n toTarget,\n diagnostics,\n ),\n };\n\n for (const key of CAPTURE_FLAG_KEYS) {\n capture[key] = resolveBoolean(`capture.${key}`, given[key], base[key], diagnostics);\n }\n\n return capture;\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 bad value reports config.invalid. The value in force stays. Without this check, a bad\n // minLevel drops each record with no message.\n enabled: resolveBoolean(\"enabled\", input.enabled, base.enabled, diagnostics),\n minLevel: resolveLevel(\"minLevel\", input.minLevel, base.minLevel, diagnostics),\n compression: resolveChoice(\n \"compression\",\n input.compression,\n COMPRESSION_VALUES,\n base.compression,\n diagnostics,\n ),\n credentials: resolveChoice(\n \"credentials\",\n input.credentials,\n CREDENTIALS_VALUES,\n base.credentials,\n diagnostics,\n ),\n headers:\n \"headers\" in input ? resolveHeaders(input.headers, base.headers, diagnostics) : base.headers,\n storage: resolveChoice(\"storage\", input.storage, STORAGE_VALUES, base.storage, diagnostics),\n identity: resolveChoice(\n \"identity\",\n input.identity,\n IDENTITY_VALUES,\n base.identity,\n diagnostics,\n ),\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: resolveSampling(input.sampling, base.sampling, diagnostics),\n bus: resolveBus(input.bus, base.bus, diagnostics),\n batching: resolveRanges(\n \"batching\",\n input.batching,\n base.batching,\n BATCHING_RANGES,\n diagnostics,\n ),\n retention: resolveRetention(input.retention, base.retention, diagnostics),\n limits: resolveRanges(\"limits\", input.limits, base.limits, LIMIT_RANGES, diagnostics),\n journey: resolveJourney(input.journey, base.journey, diagnostics),\n capture: resolveCapture(input.capture, base.capture, diagnostics),\n };\n\n // Guard against a value that cannot send. Keep the function in force.\n // Without a transport, the pipeline drops each batch.\n if (merged.transport !== undefined && typeof merged.transport !== \"function\") {\n diagnostics.report(\n \"config.invalid\",\n \"transport must be a function. The library ignores the value.\",\n );\n merged.transport = base.transport;\n }\n\n if (merged.onDrop !== undefined && typeof merged.onDrop !== \"function\") {\n diagnostics.report(\n \"config.invalid\",\n \"onDrop must be a function. The library ignores the value.\",\n );\n merged.onDrop = base.onDrop;\n }\n\n if (merged.transportOnExit !== undefined && typeof merged.transportOnExit !== \"function\") {\n diagnostics.report(\n \"config.invalid\",\n \"transportOnExit must be a function. The library ignores the value.\",\n );\n merged.transportOnExit = base.transportOnExit;\n }\n\n // null selects console-only mode. That value is valid. Report only an empty string.\n // A custom transport needs no endpoint.\n if (merged.endpoint === \"\") {\n if (merged.transport === undefined) {\n diagnostics.report(\n \"config.invalid\",\n \"endpoint is missing. The library drops each record. Set endpoint: null for console-only mode.\",\n );\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 maxRate: unknown = merged.sampling.remoteMaxRate;\n // The negated range test also rejects NaN.\n if (\n typeof maxRate !== \"number\" ||\n !(maxRate >= SAMPLING_RATE_MIN && maxRate <= SAMPLING_RATE_MAX)\n ) {\n diagnostics.report(\n \"config.invalid\",\n `sampling.remoteMaxRate must be 0..1. The value is ${String(maxRate)}. The library uses ${String(SAMPLING_RATE_FALLBACK)}.`,\n );\n merged.sampling.remoteMaxRate = 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\";\nimport { runAsLibraryConsole } from \"../utils/library-console\";\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 | \"record.dropped_no_destination\"\n | \"runtime.version_mismatch\"\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 const { handler } = this;\n\n if (!handler) {\n return;\n }\n try {\n // The console capture skips a console call of the handler. Without the scope, the line\n // gives a record, and a failed send of that record gives a new diagnostic.\n runAsLibraryConsole(() => {\n handler(event);\n });\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 // The console capture skips a call in this scope.\n runAsLibraryConsole(() => {\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 /**\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 that resolves 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/drops.ts\n//\n// This module collects lost records into onDrop summaries. It sends one summary for each\n// reason after the current task. A storm of losses then gives one call, not one per record.\n\nimport { ATTR_JOURNEY_ID, DROP_SUMMARY_MAX_ITEMS } from \"../constants\";\nimport { attributeOf, isActionRecord } from \"../models/batch\";\nimport type { ResolvedConfig } from \"../models/config\";\nimport type { DropSummary, LossReason } from \"../models/drop\";\nimport type { LogRecord } from \"../models/log-record\";\nimport { runAsLibraryConsole } from \"../utils/library-console\";\nimport { runAsLibraryRequest } from \"../utils/library-request\";\nimport type { Diagnostics } from \"./diagnostics\";\n\n/**\n * Adds a value to a summary list. The list keeps each value one time, up to the limit.\n * @param list Summary list.\n * @param value Value to add.\n */\nfunction addCapped(list: string[], value: string): void {\n if (list.length < DROP_SUMMARY_MAX_ITEMS && !list.includes(value)) {\n list.push(value);\n }\n}\n\n/** Collects lost records and gives one summary for each reason to the onDrop hook. */\nexport class DropReporter {\n /** Summaries that wait for the end of the task, one for each reason. */\n private readonly pending = new Map<LossReason, DropSummary>();\n\n /** True while a microtask waits to send the summaries. */\n private scheduled = false;\n\n /** True while the hook runs. A loss that the hook causes is not reported again. */\n private reporting = false;\n\n /**\n * @param config Active configuration. The reporter reads `onDrop` from it at each call.\n * @param diagnostics Diagnostics reporter.\n */\n constructor(\n private readonly config: ResolvedConfig,\n private readonly diagnostics: Diagnostics,\n ) {}\n\n /**\n * Adds lost records to the summary of their reason. Without an onDrop hook, it does nothing.\n * @param reason Cause of the loss.\n * @param records Lost records.\n * @param batchIds Ids of the lost batches.\n */\n add(reason: LossReason, records: readonly LogRecord[], batchIds: readonly string[] = []): void {\n // A hook that logs can fill a buffer again. A report of that loss starts a loop.\n if (!this.config.onDrop || this.reporting) {\n return;\n }\n\n // A failed load with an empty buffer loses nothing. A corrupt entry has no id to report.\n if (records.length === 0 && batchIds.length === 0) {\n return;\n }\n\n let summary = this.pending.get(reason);\n if (!summary) {\n summary = { reason, records: 0, batchIds: [], journeyIds: [], actions: [] };\n this.pending.set(reason, summary);\n }\n\n summary.records += records.length;\n for (const id of batchIds) {\n addCapped(summary.batchIds, id);\n }\n\n for (const record of records) {\n // A record from storage can be corrupt. It can be null or have no attributes.\n const journey = attributeOf(record, ATTR_JOURNEY_ID);\n if (typeof journey === \"string\") {\n addCapped(summary.journeyIds, journey);\n }\n\n const body: unknown = isActionRecord(record) ? record.body : undefined;\n if (typeof body === \"string\") {\n addCapped(summary.actions, body);\n }\n }\n\n if (!this.scheduled) {\n this.scheduled = true;\n queueMicrotask(() => {\n this.flush();\n });\n }\n }\n\n /** Gives each waiting summary to the hook. A hook that throws does not stop the others. */\n private flush(): void {\n this.scheduled = false;\n const summaries = [...this.pending.values()];\n this.pending.clear();\n\n const onDrop = this.config.onDrop;\n if (!onDrop) {\n return;\n }\n\n this.reporting = true;\n for (const summary of summaries) {\n this.diagnostics.guard(\"handler.threw\", \"The onDrop hook threw an error.\", () => {\n // The capture modules skip a request or a console line of the hook. A captured line\n // gives a record. That record can evict one more stored batch.\n runAsLibraryRequest(() => {\n runAsLibraryConsole(() => {\n onDrop(summary);\n });\n });\n });\n }\n this.reporting = false;\n }\n}\n","// src/core/hold-buffer.ts\n//\n// This module holds records while the runtime cannot deliver them. An action is an audit fact.\n// Actions have their own cap. A storm of other records cannot push an action out.\n\nimport { BUS_MAX_BOOT_BUFFER_ACTIONS, BUS_MAX_BOOT_BUFFER_RECORDS } from \"../constants\";\nimport { isActionRecord } from \"../models/batch\";\nimport type { LogRecord } from \"../models/log-record\";\n\n/** Holds records in arrival order. A full buffer drops its oldest record of the same kind. */\nexport class HoldBuffer {\n /** Held records in arrival order. */\n private held: LogRecord[] = [];\n\n /** Number of held actions. A count finds a full buffer without a scan at each push. */\n private actions = 0;\n\n /**\n * @param onDrop Receives the record that a full buffer drops.\n */\n constructor(private readonly onDrop: (record: LogRecord) => void) {}\n\n /** Held records in arrival order. */\n get records(): readonly LogRecord[] {\n return this.held;\n }\n\n /** Number of held records. */\n get length(): number {\n return this.held.length;\n }\n\n /**\n * Adds a record. A full buffer drops its oldest record of the same kind.\n * @param record Record to hold.\n */\n push(record: LogRecord): void {\n const action = isActionRecord(record);\n const count = action ? this.actions : this.held.length - this.actions;\n const cap = action ? BUS_MAX_BOOT_BUFFER_ACTIONS : BUS_MAX_BOOT_BUFFER_RECORDS;\n\n if (count < cap) {\n this.actions += action ? 1 : 0;\n } else {\n // Scan only at the cap. A scan at each push is quadratic in a log storm.\n const oldest = this.held.findIndex((one) => isActionRecord(one) === action);\n const [dropped] = this.held.splice(oldest, 1);\n this.onDrop(dropped);\n }\n\n this.held.push(record);\n }\n\n /**\n * Removes the held records.\n * @returns The records in arrival order.\n */\n take(): LogRecord[] {\n const records = this.held;\n this.held = [];\n this.actions = 0;\n return records;\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_BREADCRUMBS,\n ATTR_ERROR_DATA,\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_BYPASS_TYPES,\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 isLogLevel,\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 type { RemoteSlot } from \"./remote-sampling\";\nimport { shouldSampleInput } from \"./sampling\";\n\n/** Prefix of the error fields. An oversized error record keeps them. */\nconst ERROR_ATTR_PREFIX = \"error.\";\n\n/** Index keys that an oversized record keeps in the form that redact gave them. */\nconst REDACTABLE_INDEX_KEYS = [ATTR_PAGE_URL, ATTR_JOURNEY_ID, ATTR_JOURNEY_NAME] as const;\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 /** Slot of the sampling rules from the ingest server. */\n remote: RemoteSlot;\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/**\n * Reason a record was not built. \"malformed\" means the redact hook broke the record shape\n * or set an unknown severityText.\n */\nexport type DropReason = \"level\" | \"sampling\" | \"redact\" | \"malformed\";\n\n/** Outcome of one build call. */\nexport interface BuildResult {\n /** Completed record, or null when the builder drops it. */\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 * minLevel does not apply to an action or a metric.\n * @param level Target log severity level.\n * @param type Record type. Without it, the check applies minLevel.\n * @returns True if the library builds a record of this level and type.\n */\n isEnabled(level: LogLevel, type?: LogType): boolean {\n const { config } = this.deps;\n if (!config.enabled) {\n return false;\n }\n\n if (type !== undefined && LEVEL_BYPASS_TYPES.includes(type)) {\n return true;\n }\n\n // A remote rule can lower minLevel during an incident.\n const minLevel = this.deps.remote.sampling?.minLevel() ?? config.minLevel;\n\n return LEVEL_ORDER[level] >= LEVEL_ORDER[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 of the drop.\n */\n build(input: BuildInput): BuildResult {\n const { config, diagnostics, tracing, journey, sequence, limits, remote } = this.deps;\n\n if (!this.isEnabled(input.level, input.type)) {\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 remote.sampling?.current() ?? null,\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 // A plain JavaScript hook can edit the record in place without a return value.\n let redacted: unknown;\n try {\n redacted = redact(record);\n } catch (error) {\n // Drop the record. A record that redact did not clean must not leave the page.\n diagnostics.report(\n \"record.dropped_by_redact\",\n \"The redact hook threw an error. The library dropped the record.\",\n undefined,\n error,\n );\n return { record: null, dropped: \"redact\" };\n }\n\n if (redacted === null) {\n diagnostics.count(\"record.dropped_by_redact\");\n return { record: null, dropped: \"redact\" };\n }\n\n const candidate: unknown = redacted ?? record;\n\n if (!isLogRecord(candidate)) {\n // The hook changed the record in place. The library has no intact copy.\n if (candidate === record) {\n diagnostics.report(\n \"record.dropped_malformed\",\n \"The redact hook changed the record to a shape that is not a record. The library dropped it.\",\n );\n return { record: null, dropped: \"malformed\" };\n }\n\n // A plain JavaScript hook can return a string or a Promise. The record did not pass redact.\n diagnostics.report(\n \"record.dropped_by_redact\",\n \"The redact hook returned a value that is not a record. The library dropped the record.\",\n );\n return { record: null, dropped: \"redact\" };\n } else if (!isLogLevel(candidate.severityText)) {\n // An unknown level has no severity number. The serializer cannot map it.\n diagnostics.report(\n \"record.dropped_malformed\",\n \"The redact hook set a severityText that is not a log level. The library dropped the record.\",\n );\n return { record: null, dropped: \"malformed\" };\n } else {\n if (candidate !== record) {\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(candidate.attributes, limits, diagnostics);\n record = { ...candidate, attributes: asAttributes(remeasured.value) };\n bytes = remeasured.bytes;\n }\n\n // The hook can change severityText. Keep the number in step with the text.\n record.severityNumber = SEVERITY_NUMBER[record.severityText];\n }\n }\n\n // Drop the caller attributes when their size exceeds maxRecordBytes. Keep the index keys.\n // A search cannot find a record without journey.id and trace_id. Keep the error fields,\n // then the breadcrumbs if they fit. They tell why the record exists.\n if (bytes > limits.maxRecordBytes) {\n diagnostics.report(\n \"record.truncated\",\n \"The attributes are larger than the size limit. The library dropped the caller attributes.\",\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_ATTRIBUTES_DROPPED]: true,\n [ATTR_ATTRIBUTES_BYTES]: bytes,\n };\n\n // Read these keys after redact. The hook can remove a token from page.url.\n for (const key of REDACTABLE_INDEX_KEYS) {\n if (key in record.attributes) {\n kept[key] = record.attributes[key];\n }\n }\n\n for (const [key, value] of Object.entries(record.attributes)) {\n if (key.startsWith(ERROR_ATTR_PREFIX)) {\n kept[key] = value;\n }\n }\n\n // error.data can be large. Drop it first, before the other error fields.\n let keptBytes = sanitizeWithSize(kept, limits, diagnostics).bytes;\n if (keptBytes > limits.maxRecordBytes && ATTR_ERROR_DATA in kept) {\n Reflect.deleteProperty(kept, ATTR_ERROR_DATA);\n keptBytes = sanitizeWithSize(kept, limits, diagnostics).bytes;\n }\n\n const breadcrumbs = record.attributes[ATTR_BREADCRUMBS];\n if (breadcrumbs !== undefined) {\n const crumbBytes = sanitizeWithSize(breadcrumbs, limits, diagnostics).bytes;\n if (keptBytes + crumbBytes <= limits.maxRecordBytes) {\n kept[ATTR_BREADCRUMBS] = breadcrumbs;\n }\n }\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 CAPTURE_NAMESPACE,\n GAP_REPORT_THROTTLE_MS,\n MAX_BREADCRUMBS,\n RUNTIME_GLOBAL_KEY,\n RUNTIME_STOPPED_KEY,\n STORAGE_NAMESPACE,\n TELEMETRY_SDK_VERSION,\n} from \"../constants\";\nimport type { LogBatch } from \"../models/batch\";\nimport type { BusMessage, BusRole } from \"../models/bus\";\nimport type {\n CaptureOptions,\n IdentityStrategy,\n ObservabilityConfig,\n ResolvedConfig,\n StorageStrategy,\n} from \"../models/config\";\nimport type { LossReporter } from \"../models/drop\";\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 { DropReporter } from \"./drops\";\nimport { HoldBuffer } from \"./hold-buffer\";\nimport { JourneyEngine, JOURNEY_OPTIONS, type JourneyOptions } from \"./journey\";\nimport { OneLogger } from \"./logger\";\nimport { RecordBuilder } from \"./record\";\nimport type { RemoteSlot } from \"./remote-sampling\";\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 longFrames: async (): Promise<CaptureClass> =>\n (await import(\"../capture/long-frames\")).LongFrameCapture,\n console: async (): Promise<CaptureClass> => (await import(\"../capture/console\")).ConsoleCapture,\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/** Config sections that the delivery stack reads one time, when it loads. */\nconst SENDER_SECTIONS = [\"batching\", \"retention\"] as const;\n\n/** Config sections that a later configure() cannot change. */\ntype StartupSection = (typeof SENDER_SECTIONS)[number] | \"limits\";\n\n/**\n * Makes a text key of the capture section. A later configure() reinstalls the capture\n * modules only when the key changes. A reinstall unpatches and patches each host function.\n * @param capture Capture section.\n * @returns The key. A function and a RegExp give a fixed text.\n */\nfunction captureKey(capture: CaptureOptions): string {\n return JSON.stringify({\n ...capture,\n webVitalsLoader: capture.webVitalsLoader !== undefined,\n ignoreUrls: capture.ignoreUrls.map(String),\n propagateTraceHeaderTo: capture.propagateTraceHeaderTo.map(String),\n });\n}\n\n/**\n * Removes the delivery settings from a configuration. A console-only runtime must not send\n * or join a bus. The runtime of the other version does both.\n * @param input Consumer configuration options.\n * @returns The options with no endpoint, no transport and bus mode \"off\".\n */\nfunction consoleOnly(input: Partial<ObservabilityConfig>): Partial<ObservabilityConfig> {\n return {\n ...input,\n endpoint: null,\n transport: undefined,\n transportOnExit: undefined,\n bus: { ...input.bus, mode: \"off\" },\n };\n}\n\n/**\n * Tests if a runtime on a global key comes from this version of the library.\n * @param runtime Runtime on the global key. A runtime before 0.9.0 has no sdkVersion.\n * @returns True if this copy can call the methods of the runtime.\n */\nfunction ownVersion(runtime: ObservabilityRuntime): boolean {\n return runtime.sdkVersion === TELEMETRY_SDK_VERSION;\n}\n\n/** Manages subsystem lifecycles, bus coordination and record delivery. */\nexport class ObservabilityRuntime {\n /**\n * Runtime of this copy of the library when another version owns the page runtime.\n * It stays off the global key.\n */\n private static local: ObservabilityRuntime | null = null;\n\n /**\n * Library version of this runtime. Another copy reads it from the global key.\n * Two versions with one runtime call methods that the other version does not have.\n */\n readonly sdkVersion: string = TELEMETRY_SDK_VERSION;\n\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 /** Slot of the remote sampling rules. The sender or the bus fills it. */\n private readonly remote: RemoteSlot = { sampling: null };\n\n /** Console sink for local developer output. */\n readonly console: ConsoleSink;\n\n /** Collects lost records into onDrop summaries. */\n private readonly drops: DropReporter;\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 readonly pendingRecords = new HoldBuffer((record) => {\n this.dropHeld(record);\n });\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 = {\n webVitals: false,\n navigationTiming: false,\n longFrames: false,\n };\n\n /** Queue buffering records created before bus role resolution. */\n private readonly bootBuffer = new HoldBuffer((record) => {\n this.dropHeld(record);\n });\n\n /** Batch buffer staging records for microtask forwarding. */\n private forwardBuffer: LogRecord[] = [];\n\n /** True if a microtask drain of the forward buffer is pending. */\n private forwardScheduled = false;\n\n /** True if startup has decided the bus role. A sender load waits for it. */\n private roleResolved = false;\n\n /** Resolves when startup releases the boot records. flush() waits for it. init() sets it. */\n private started: Promise<void> = Promise.resolve();\n\n /** True if asynchronous initialization is complete. */\n private ready = false;\n\n /** True if 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 /** Record limits of the builder and the console. The first configure() of the app sets them. */\n private readonly limits: ResolvedConfig[\"limits\"];\n\n /** Lifetime rules of the journey engine. The first configure() of the app sets the age. */\n private readonly journeyOptions: JourneyOptions;\n\n /** False in a runtime that an early log call started. The first configure() then sets limits. */\n private tunablesLocked = true;\n\n /**\n * @param input Initial consumer configuration options.\n * @param degraded True for a console-only runtime next to another version. It installs\n * no capture.\n */\n private constructor(\n input: Partial<ObservabilityConfig>,\n private readonly degraded = false,\n ) {\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. The library loses no record.\n void this.tracing.loadOtel();\n // The startup values stay. A later configure() cannot change the limits or the journey age.\n this.limits = { ...this.config.limits };\n this.console = new ConsoleSink(this.config.console, this.diagnostics, this.limits);\n this.drops = new DropReporter(this.config, this.diagnostics);\n this.journeyOptions = { ...JOURNEY_OPTIONS, maxAgeMs: this.config.journey.maxAgeMs };\n\n this.journey = new JourneyEngine(\n this.journeyOptions,\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 remote: this.remote,\n config: this.config,\n limits: this.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 runtime on the global key of this realm. Another copy of the library can own it.\n * @returns Pinned runtime instance or null.\n */\n private static pinned(): ObservabilityRuntime | null {\n return (\n ((globalThis as Record<symbol, unknown>)[RUNTIME_KEY] as ObservabilityRuntime | undefined) ??\n null\n );\n }\n\n /**\n * Returns the local runtime of this copy. Without one, it returns the pinned runtime.\n * A pinned runtime of another version gives null. A log call then starts the local runtime.\n * @returns Active runtime instance or null.\n */\n static current(): ObservabilityRuntime | null {\n const local = ObservabilityRuntime.local;\n if (local) {\n return local.destroyed ? null : local;\n }\n\n const pinned = ObservabilityRuntime.pinned();\n return pinned && ownVersion(pinned) ? pinned : null;\n }\n\n /**\n * Returns the runtime that shutdown() stopped, until the next configure().\n * A stopped runtime of another version gives null.\n * @returns Stopped runtime instance or null.\n */\n static stopped(): ObservabilityRuntime | null {\n const local = ObservabilityRuntime.local;\n if (local?.destroyed) {\n return local;\n }\n\n const stopped = (globalThis as Record<symbol, unknown>)[STOPPED_KEY] as\n ObservabilityRuntime | undefined;\n return stopped && ownVersion(stopped) ? stopped : null;\n }\n\n /**\n * Tests if 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 * @param implicit True for the default runtime that an early log call starts.\n * @returns Active runtime instance.\n */\n static configure(input: Partial<ObservabilityConfig>, implicit = false): ObservabilityRuntime {\n const local = ObservabilityRuntime.local;\n if (local && !local.destroyed) {\n // The local runtime stays console-only. React StrictMode calls configure() two times.\n local.reconfigure(consoleOnly(input));\n return local;\n }\n ObservabilityRuntime.local = null;\n\n const pinned = ObservabilityRuntime.pinned();\n if (pinned) {\n // A runtime before 0.9.0 has no sdkVersion. It is also another version.\n if (!ownVersion(pinned)) {\n return ObservabilityRuntime.startDegraded(input, pinned.sdkVersion);\n }\n\n if (!pinned.destroyed) {\n pinned.reconfigure(input);\n return pinned;\n }\n }\n\n const runtime = new ObservabilityRuntime(input);\n // The first configure() of the app sets the limits of a default runtime.\n runtime.tunablesLocked = !implicit;\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 * Starts a console-only runtime next to the runtime of another version. It sends nothing,\n * joins no bus and installs no capture. The other version keeps the page runtime.\n * @param input Consumer configuration options.\n * @param found sdkVersion of the pinned runtime. A runtime before 0.9.0 has none.\n * @returns The local runtime.\n */\n private static startDegraded(\n input: Partial<ObservabilityConfig>,\n found: unknown,\n ): ObservabilityRuntime {\n const runtime = new ObservabilityRuntime(consoleOnly(input), true);\n ObservabilityRuntime.local = runtime;\n\n const foundText = typeof found === \"string\" ? found : \"before 0.9.0\";\n runtime.diagnostics.report(\n \"runtime.version_mismatch\",\n `Another copy of the library, version ${foundText}, owns the page runtime. This copy, version ${TELEMETRY_SDK_VERSION}, runs in console-only mode and installs no capture. Load one version of the library on the page.`,\n { found: foundText, own: TELEMETRY_SDK_VERSION },\n );\n\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.keepDestination(input);\n const capturesBefore = captureKey(this.config.capture);\n const next = resolveConfig(accepted, this.diagnostics, this.config);\n this.keepStartupTunables(next);\n applyResolvedConfig(this.config, next);\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 // Reinstall only on a change. A reinstall unpatches and patches each host function.\n // A stale capture load stops at its generation check. A reinstall is safe at any time.\n if (captureKey(this.config.capture) !== capturesBefore) {\n void this.installCaptures();\n }\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 startup tunables in the next config. A part of the runtime reads each tunable\n * one time. A later change has no effect. The runtime then refuses it.\n * @param next Resolved config of a later configure() call.\n */\n private keepStartupTunables(next: ResolvedConfig): void {\n if (this.senderLoad !== undefined) {\n this.keepSections(next, SENDER_SECTIONS);\n }\n\n // An early log call starts a runtime with defaults. The first configure() of the app sets\n // the limits and the journey age of that runtime.\n if (!this.tunablesLocked) {\n this.tunablesLocked = true;\n Object.assign(this.limits, next.limits);\n this.journeyOptions.maxAgeMs = next.journey.maxAgeMs;\n return;\n }\n\n this.keepSections(next, [\"limits\"]);\n\n const { maxAgeMs } = this.config.journey;\n if (next.journey.maxAgeMs !== maxAgeMs) {\n this.diagnostics.report(\n \"config.invalid\",\n `journey.maxAgeMs cannot change after startup. It stays ${String(maxAgeMs)}.`,\n { requested: next.journey.maxAgeMs },\n );\n next.journey.maxAgeMs = maxAgeMs;\n }\n }\n\n /**\n * Refuses a change of config sections. It restores the values in force in the next config.\n * @param next Resolved config of a later configure() call.\n * @param sections Sections that cannot change.\n */\n private keepSections(next: ResolvedConfig, sections: readonly StartupSection[]): void {\n for (const section of sections) {\n if (JSON.stringify(next[section]) === JSON.stringify(this.config[section])) {\n continue;\n }\n\n this.diagnostics.report(\n \"config.invalid\",\n `${section} cannot change after startup. The values in force stay.`,\n { requested: next[section] },\n );\n Object.assign(next, { [section]: this.config[section] });\n }\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 a change that leaves the built delivery stack with no destination.\n * Without a destination, the retry engine removes each stored batch as delivered.\n * @param input Partial configuration to merge.\n * @returns Input without the refused changes.\n */\n private keepDestination(input: Partial<ObservabilityConfig>): Partial<ObservabilityConfig> {\n if (this.senderLoad === undefined) {\n return input;\n }\n\n let accepted = input;\n const addsOrRemoves =\n \"transport\" in input &&\n (input.transport === undefined) !== (this.config.transport === undefined);\n\n // The stack selects HTTP or the custom transport one time. It cannot change to the other.\n if (addsOrRemoves) {\n this.diagnostics.report(\n \"config.invalid\",\n \"You cannot add or remove transport after the delivery stack loads. The transport in force stays.\",\n );\n accepted = { ...accepted };\n delete accepted.transport;\n }\n\n const removesEndpoint = accepted.endpoint === null || accepted.endpoint === \"\";\n\n if (removesEndpoint && this.config.transport === undefined) {\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 // An undefined endpoint keeps the endpoint in force, and keeps it in ignoreUrls.\n accepted = { ...accepted, endpoint: undefined };\n }\n\n return accepted;\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 // Set before the first await. A flush() directly after configure() then waits for it.\n this.started = this.boot();\n await this.started;\n await captures;\n }\n\n /** Resolves the bus role, loads the delivery stack and releases the boot records. It never rejects. */\n private async boot(): Promise<void> {\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\n /**\n * Starts the load of the bus one time.\n * @returns Promise that resolves 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 that resolves 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 that resolves 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 remote: this.remote,\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 that resolves when the load completes, or immediately when nothing loads.\n */\n private syncSender(): Promise<void> {\n if (!this.hasDestination() || this.role() !== \"sender\") {\n return Promise.resolve();\n }\n\n return this.loadSender();\n }\n\n /**\n * Tests if the config names a destination for the records.\n * @returns True with an endpoint or a custom transport.\n */\n private hasDestination(): boolean {\n return Boolean(this.config.endpoint) || this.config.transport !== undefined;\n }\n\n /**\n * Starts the load of the delivery stack one time.\n * @returns Promise that resolves 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 onLoss: this.reportLoss,\n remote: this.remote,\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 this.drops.add(\"load_failed\", this.pendingRecords.records);\n }\n\n for (const record of this.pendingRecords.take()) {\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 // A console-only runtime next to another version patches nothing. The other version does.\n if (this.degraded) {\n return;\n }\n\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 if (settings.longFrames) {\n names.push(\"longFrames\");\n }\n // An empty list wraps nothing. Do not load the chunk for it.\n const consoleOn = Array.isArray(settings.console)\n ? settings.console.length > 0\n : settings.console;\n\n if (consoleOn) {\n names.push(\"console\");\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 that resolves 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 awaits a normal flush, then runs the exit flush. The records hold\n // their journey already. The journey and the bus can stop first.\n const closing = this.sender?.destroy();\n this.journey.destroy();\n // A record in the forward buffer waits for its microtask. The bus takes it before it stops.\n this.sendForwarded();\n this.bus?.destroy();\n // The delivery stack did not load before shutdown(). The held records are lost.\n this.drops.add(\"load_failed\", this.pendingRecords.take());\n await closing;\n // A load in progress destroys its own stack. shutdown() resolves only after that.\n await this.senderLoad;\n\n // A local runtime must not remove the runtime of the other version from the global key.\n if (ObservabilityRuntime.pinned() === this) {\n Reflect.deleteProperty(globalThis, RUNTIME_KEY);\n // Calls after shutdown() go to this runtime and do nothing.\n // A new default runtime drops the settings of the app.\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.bootBuffer.push(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 // Console-only mode has no destination. Count the drop. If not, no counter shows the loss.\n if (!this.senderLoad) {\n this.diagnostics.count(\"record.dropped_no_destination\");\n // After a failed load, the config has a destination but no delivery stack.\n if (this.hasDestination()) {\n this.drops.add(\"load_failed\", [record]);\n }\n return;\n }\n\n this.pendingRecords.push(record);\n }\n\n /**\n * Counts a record that a full hold buffer drops. It gives the record to the onDrop report.\n * @param record Dropped record.\n */\n private dropHeld(record: LogRecord): void {\n this.diagnostics.count(\"record.dropped_boot_buffer_full\");\n this.drops.add(\"buffer_full\", [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 this.sendForwarded();\n });\n }\n\n /** Gives the records of the forward buffer to the bus. */\n private sendForwarded(): void {\n const records = this.forwardBuffer;\n this.forwardBuffer = [];\n if (records.length > 0) {\n this.bus?.sendRecords(records);\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, this.remote.sampling?.current() ?? null)) {\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.take();\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 * Gives lost records to the onDrop report.\n * @param reason Cause of the loss.\n * @param records Lost records.\n * @param batchIds Ids of the lost batches.\n */\n private readonly reportLoss: LossReporter = (reason, records, batchIds) => {\n this.drops.add(reason, records, batchIds);\n };\n\n /**\n * Gives the evicted batches to the onDrop report. It also emits a warning record. A throttle\n * limits the warning records.\n * @param result Storage prune summary metrics.\n * @param dropped The evicted batches.\n */\n private readonly reportGap = (result: PruneResult, dropped: readonly LogBatch[]): void => {\n this.drops.add(\n result.reason,\n dropped.flatMap((batch) => batch.records),\n dropped.map((batch) => batch.id),\n );\n\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 that resolves 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 that resolves when the library sends or hands off the queued records.\n */\n async flush(): Promise<void> {\n // A record logged during startup waits in the boot buffer. Without this wait, flush() misses it.\n // After startup, do not wait. The handover of the forward buffer then stays synchronous.\n if (!this.ready) {\n await this.started;\n }\n\n if (this.role() === \"forwarder\") {\n this.sendForwarded();\n return;\n }\n\n await this.senderLoad;\n await this.sender?.flush();\n }\n}\n","// src/transport/memory-transport.ts\n//\n// Gives tests a transport that keeps each batch in memory. A test then checks the records that\n// the library sends, with no network and no fetch mock.\n\nimport { HTTP_SUCCESS_END, HTTP_SUCCESS_MIN } from \"../constants\";\nimport type { Transport, TransportRequest, TransportResponse } from \"../models/config\";\nimport type { LogRecord } from \"../models/log-record\";\n\n/** A transport that keeps each batch in memory, for tests. */\nexport interface MemoryTransport {\n /** Pass this function as `transport` to `configure()`. */\n transport: Transport;\n /**\n * Returns the records of each accepted batch, in send order.\n * @returns The accepted records.\n */\n records(): LogRecord[];\n /**\n * Returns each request, accepted or refused, in send order.\n * @returns The requests.\n */\n batches(): TransportRequest[];\n /** Forgets each batch. The answer that respondWith set stays. */\n clear(): void;\n /**\n * Sets the answer for each later batch. The default answer is 200.\n * @param status Status code to answer with, for example 413, 429 or 500.\n * @param retryAfterMs Delay to answer with, for 429 and 503.\n */\n respondWith(status: number, retryAfterMs?: number): void;\n}\n\n/**\n * Creates a transport that keeps each batch in memory. Use it in tests, with `configure()`.\n * @returns The memory transport.\n */\nexport function createMemoryTransport(): MemoryTransport {\n const sent: TransportRequest[] = [];\n const accepted: TransportRequest[] = [];\n let answer: TransportResponse = { status: HTTP_SUCCESS_MIN };\n\n return {\n transport: (request) => {\n sent.push(request);\n\n if (answer.status >= HTTP_SUCCESS_MIN && answer.status < HTTP_SUCCESS_END) {\n accepted.push(request);\n }\n\n return Promise.resolve({ ...answer });\n },\n records: () => accepted.flatMap((request) => [...request.records]),\n batches: () => [...sent],\n clear: () => {\n sent.length = 0;\n accepted.length = 0;\n },\n respondWith: (status, retryAfterMs) => {\n answer = retryAfterMs === undefined ? { status } : { status, retryAfterMs };\n },\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 { createMemoryTransport, type MemoryTransport } from \"./transport/memory-transport\";\nexport type { Journey, ObservabilityConfig, OneLoggerOptions };\nexport type {\n ConsoleOptions,\n ConsoleStyles,\n ExitTransport,\n Transport,\n TransportRequest,\n TransportResponse,\n} from \"./models/config\";\nexport type { WorkerLike } from \"./bus/links\";\nexport type { DiagnosticCode, DiagnosticEvent } from \"./core/diagnostics\";\nexport type { DropSummary, LossReason } from \"./models/drop\";\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({}, true);\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 the call gives options.\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 fatal record with causal error and breadcrumbs.\n * @param message Fatal error summary.\n * @param err Caught error instance or reason.\n * @param payload Optional contextual attributes.\n */\nexport function fatal(message: string, err?: unknown, payload?: Record<string, unknown>): void {\n root().fatal(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 that resolves 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 that resolves 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 that resolves when shutdown completes.\n */\nexport async function shutdown(): Promise<void> {\n await ObservabilityRuntime.current()?.destroy();\n}\n"],"mappings":";;;;;;;;;;AAYA,SAASmF,EAAQ,GAA2B;CAC1C,OAAO,KAAK,OAAO,YAAY,IAAI,IAAIC,KAAahE,CAAkB,IAAIA;AAC5E;AAUA,SAASiE,EACP,GACA,GACA,GACA,GACA,GACM;CACN,EAAO,UAAU,GAAGC,EAAM,YAAYC,GAAU,MAAM,aAAa;EACjE;EACA,GAAGC;CACL,CAAC;AACH;AAUA,SAASC,GACP,GACA,GACA,GACA,GACA,GACM;CAEN,IAAMF,IAAWJ,EAAQC,CAAS;CAMlC,AALAM,EAAO,MAAM,GAAGJ,EAAM,UAAUK,GAAO;EACrC,sBAAsBJ;EACtB,QAAQ;EACR,GAAGC;CACL,CAAC,GACDH,EAAOK,GAAQJ,GAAOC,GAAU,WAAWC,CAAU;AACvD;AAUA,SAAgBxF,GACd,GACA,GACA,GACA,GACG;CACH,IAAMoF,IAAY,YAAY,IAAI;CAClC,IAAI;EACF,IAAMS,IAASC,EAAG;EAElB,OADAT,EAAOK,GAAQJ,GAAOH,EAAQC,CAAS,GAAG,WAAWI,CAAU,GACxDK;CACT,SAASF,GAAO;EAGd,MADAF,GAAKC,GAAQJ,GAAOF,GAAWO,GAAOH,CAAU,GAC1CG;CACR;AACF;AAUA,eAAsB1F,GACpB,GACA,GACA,GACA,GACY;CACZ,IAAMmF,IAAY,YAAY,IAAI;CAClC,IAAI;EACF,IAAMS,IAAS,MAAMC,EAAG;EAExB,OADAT,EAAOK,GAAQJ,GAAOH,EAAQC,CAAS,GAAG,WAAWI,CAAU,GACxDK;CACT,SAASF,GAAO;EAGd,MADAF,GAAKC,GAAQJ,GAAOF,GAAWO,GAAOH,CAAU,GAC1CG;CACR;AACF;;;AC5FA,IAAMK,KAAwC,CAAC1F,GAAmB0C,EAAiB;AAenF,SAASiD,GAAQ,GAAgB,GAAiC;CAGhE,IAAMC,IAAQC,EAAY,MACxB,0BACA,sDACyB;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C/C;AAMA,eAAsB8B,KAA0B;CAC9C,MAAM/D,EAAqB,QAAQ,CAAC,EAAE,QAAQ;AAChD"}
1
+ {"version":3,"file":"index.js","names":["timeSync","timeAsync","timeSync","timeAsync","CONSOLE_DEFAULT_LEVEL","RECORD_LIMITS","RESOURCE_OPENFIN_UUID","UNKNOWN_SERVICE_NAME","CAPTURE_NAMESPACE","DEFAULT_CONFIG","RESOURCE_BROWSER_USER_AGENT","RESOURCE_TELEMETRY_SDK_LANGUAGE","RESOURCE_SERVICE_VERSION","DEFAULT_METRIC_UNIT","RESOURCE_CONTEXT_ID","RESOURCE_TELEMETRY_SDK_NAME","DIAGNOSTIC_THROTTLE_MS","RESOURCE_DEPLOYMENT_ENVIRONMENT","RUNTIME_STOPPED_KEY","RESOURCE_HOST_PLATFORM","BEACON_LIMIT_BYTES","UNDEFAULTED_SECTION_KEYS","RESOURCE_SESSION_ID","RESOURCE_SERVICE_NAME","RESOURCE_TAB_ID","RUNTIME_GLOBAL_KEY","TRACEPARENT_HEADER","METRIC_DEFAULT_BOUNDARIES","ATTR_BREADCRUMBS","ATTR_JOURNEY_NAME","ATTR_LOG_TYPE","SERIALIZER_NAME_OTLP","ATTR_METRIC_OVERFLOW","LIBRARY_LOG_PREFIX","TELEMETRY_SDK_VERSION","TELEMETRY_SDK_NAME","ATTR_ATTRIBUTES_DROPPED","SEVERITY_NUMBER","CONSOLE_DEFAULT_STYLES","CONFIG_SECTIONS","ATTR_JOURNEY_PARENT_ID","LEVEL_BYPASS_TYPES","ATTR_SANITIZE_FAILED","TELEMETRY_SDK_LANGUAGE","ATTR_APP_NAMESPACE","ATTR_ERROR_DATA","ATTR_PAGE_URL","RESOURCE_TELEMETRY_SDK_VERSION","ATTR_ATTRIBUTES_BYTES","ATTR_JOURNEY_ID","STORAGE_NAMESPACE","ATTR_LOG_SEQ","LEVEL_ORDER","TRACE_MAX_AGE_MS","METRIC_KEYS","UNDEFAULTED_CONFIG_KEYS","METRIC_NAMESPACE","DURATION_PRECISION","RESOURCE_OPENFIN_NAME","isDataField","isErrorLike","ERROR_OWN_KEYS","isObject","unrefTimer","isLogRecord","isLogLevel","shouldSample","nowUnixNano","shouldSampleInput","isLibraryConsole","truncate","sanitize","runAsLibraryConsole","sanitizeWithSize","persistTabId","newId","SessionTouch","randomHex","memoryStores","resolveIdentity","BROWSER_STORES","stripUrlQuery","detectPlatform","currentUrl","isActionRecord","attributeOf","runAsLibraryRequest","JourneyEngine","JOURNEY_OPTIONS","elapsed","startedAt","finish","label","duration","attributes","fail","logger","error","timeSync$1","result","fn","timeAsync$1","LIBRARY_NAMESPACES","toError","known","diagnostics","value","copy","text","consoleError","reason","errorData","source","errorLike","data","count","key","field","isPlainObject","proto","levelTypeFor","namespace","own","copyPayload","payload","OneLogger","bind","options","message","name","copied","unit","type","runtime","level","body","crumb","record","dropped","ships","asPayload","asError","shown","METHOD","ConsoleSink","settings","limits","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","LEVEL_NAMES","COMPRESSION_VALUES","CREDENTIALS_VALUES","STORAGE_VALUES","IDENTITY_VALUES","BUS_MODE_VALUES","OPENFIN_ROLE_VALUES","JOURNEY_SCOPE_VALUES","CONSOLE_METHOD_VALUES","RETENTION_MODE_VALUES","BATCHING_RANGES","RETENTION_RANGES","LIMIT_RANGES","JOURNEY_AGE_RANGE","CAPTURE_FLAG_KEYS","SANDBOX_ORIGIN","LEVEL_EXPECTED","listOf","CONSOLE_CAPTURE_EXPECTED","PATTERN_LIST_EXPECTED","TARGET_LIST_EXPECTED","ORIGIN_LIST_EXPECTED","STRING_LIST_EXPECTED","quoted","values","describeValue","reportInvalid","expected","kept","resolveChoice","fallback","match","accepted","entry","resolveBoolean","resolveNonNegative","resolveInteger","min","max","range","resolveRanges","given","input","keys","ranges","section","base","toLevel","upper","resolveLevel","resolveList","entries","accept","toStringEntry","toPattern","toConsoleMethod","toOrigin","origin","toTarget","isStringRecord","resolveHeaders","isSerializer","resolveSerializer","requested","previous","CONSOLE_STYLE_KEYS","validStyles","valid","resolveConsoleLevel","resolveConsole","resolveSampling","resolveBus","resolveJourney","resolveRetention","resolveCaptureConsole","resolveCapture","capture","resolveMetricsEndpoint","url","serializer","resolveConfig","merged","rate","maxRate","rates","ns","r","reportUnknownKeys","sectionKeys","applyResolvedConfig","next","target","ContextStore","Diagnostics","handler","throttleMs","total","code","by","now","event","handlerError","addCapped","list","DropReporter","config","records","batchIds","summary","id","journey","summaries","onDrop","HoldBuffer","action","oldest","one","OVERFLOW_KEY","RECORD_KEYS","cleanAttributes","clean","copyBounds","bounds","i","isAscending","bound","fieldsOf","point","def","start","series","Meter","intervalMs","emit","instrument","instruments","found","set","size","buckets","index","ERROR_ATTR_PREFIX","REDACTABLE_INDEX_KEYS","asAttributes","RecordBuilder","deps","minLevel","traceCtx","tracing","activeJourney","remote","seq","sequence","pageUrl","bytes","fromContext","fromScope","fromPayload","redact","redacted","candidate","remeasured","keptBytes","breadcrumbs","crumbBytes","platform","identity","CAPTURE_LOADERS","RUNTIME_KEY","STOPPED_KEY","SENDER_SECTIONS","captureKey","consoleOnly","ownVersion","ObservabilityRuntime","degraded","fields","bus","reply","local","pinned","stopped","implicit","foundText","capturesBefore","sections","built","captures","journeyReady","Bus","sender","Sender","generation","names","classes","CaptureModule","worker","closing","buffered","batch","fresh","createMemoryTransport","sent","answer","request","retryAfterMs","loggers","requireRuntime","configure","getLogger","root","trace","debug","info","warn","err","fatal","logAction","logEvent","logMetric","counter","histogram","timeSync","timeAsync","setContext","setContextMap","removeContext","startJourney","endJourney","currentJourney","getJourneyToken","adoptJourney","token","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/drops.ts","../src/core/hold-buffer.ts","../src/core/meter.ts","../src/core/record.ts","../src/core/runtime.ts","../src/transport/memory-transport.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 the operation duration as a histogram metric, for each outcome.\n * @param logger Target telemetry logger.\n * @param label Metric name prefix.\n * @param duration Elapsed duration in milliseconds.\n * @param status Outcome status string.\n * @param attributes Optional contextual attributes.\n */\nfunction finish(\n logger: CaptureLogger,\n label: string,\n duration: number,\n status: string,\n attributes?: Record<string, unknown>,\n): void {\n logger.logMetric(`${label}.duration`, duration, \"ms\", \"histogram\", {\n status,\n ...attributes,\n });\n}\n\n/**\n * Logs an operation failure and its FAILURE duration histogram.\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 // Read the duration one time. The error record and the metric then give the same value.\n const duration = elapsed(startedAt);\n logger.error(`${label} failed`, error, {\n \"action.duration_ms\": duration,\n status: \"FAILURE\",\n ...attributes,\n });\n finish(logger, label, duration, \"FAILURE\", attributes);\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, elapsed(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 that resolves 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, elapsed(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 {\n ATTR_BREADCRUMBS,\n ATTR_ERROR_DATA,\n ATTR_SANITIZE_FAILED,\n CAPTURE_NAMESPACE,\n DEFAULT_METRIC_UNIT,\n METRIC_KEYS,\n STORAGE_NAMESPACE,\n} from \"../constants\";\nimport type { LogLevel, LogRecord, LogType, MetricType } from \"../models/log-record\";\nimport { ERROR_OWN_KEYS, isDataField, isErrorLike } from \"../utils/error-like\";\nimport { isObject } from \"../utils/guards\";\nimport { timeAsync, timeSync } from \"../utils/timer\";\nimport type { Diagnostics } from \"./diagnostics\";\nimport type { DropReason } from \"./record\";\nimport type { ObservabilityRuntime } from \"./runtime\";\n\n/** Namespaces of the library. Their records have log.type \"system\". */\nconst LIBRARY_NAMESPACES: readonly string[] = [CAPTURE_NAMESPACE, STORAGE_NAMESPACE];\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 * An error becomes a copy with its name, message and stack.\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 // A Proxy reason can throw from instanceof and from each property read. A Proxy around\n // an Error passes instanceof. Read its fields here, inside the guard.\n const known = diagnostics.guard(\n \"record.sanitize_failed\",\n \"The library could not read the error reason.\",\n (): Error | undefined => {\n if (!(value instanceof Error) && !isErrorLike(value)) {\n return undefined;\n }\n\n const copy = new Error(value.message);\n copy.name = value.name;\n copy.stack = value.stack;\n return copy;\n },\n );\n\n if (known) {\n return known;\n }\n\n // String() throws on a null-prototype object and on a toString that throws.\n // log.error() runs inside a consumer catch block. It 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 * Gives the error that the console prints. The console shows the cause and the own fields\n * of a real Error. The record keeps the copy from toError().\n * @param reason Error reason.\n * @param copy Normalized copy of the reason.\n * @param diagnostics Diagnostics reporter.\n * @returns The reason if it is an Error, or the copy.\n */\nfunction consoleError(reason: unknown, copy: Error, diagnostics: Diagnostics): Error {\n // A Proxy reason can throw from instanceof.\n const original = diagnostics.guard(\n \"record.sanitize_failed\",\n \"The library could not read the error reason.\",\n () => (reason instanceof Error ? reason : copy),\n );\n\n return original ?? copy;\n}\n\n/**\n * Reads the data of an error reason for the error.data attribute.\n * It keeps only the own fields with a string, number or boolean value.\n * @param value Error reason.\n * @param diagnostics Diagnostics reporter.\n * @returns The fields of an object reason, a primitive reason, or undefined.\n * A string reason gives undefined. error.message already holds it.\n */\nfunction errorData(value: unknown, diagnostics: Diagnostics): unknown {\n if (typeof value === \"number\" || typeof value === \"boolean\") {\n return value;\n }\n\n if (typeof value === \"bigint\" || typeof value === \"symbol\") {\n return value;\n }\n\n if (typeof value !== \"object\" || value === null) {\n return undefined;\n }\n\n return diagnostics.guard(\n \"record.sanitize_failed\",\n \"The library could not read the properties of the error reason.\",\n () => {\n const source = value as Record<string, unknown>;\n const errorLike = isErrorLike(value);\n const data: Record<string, unknown> = {};\n let count = 0;\n\n // An object field, for example the config of an AxiosError, holds credentials.\n for (const key of Object.keys(source)) {\n const field = source[key];\n if ((!errorLike || !ERROR_OWN_KEYS.has(key)) && isDataField(field)) {\n data[key] = field;\n count++;\n }\n }\n\n return count === 0 ? undefined : data;\n },\n );\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 (!isObject(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/**\n * Selects the log.type of the level methods for a namespace.\n * @param namespace Logger namespace.\n * @returns \"system\" for a namespace of the library, \"log\" for each other namespace.\n */\nfunction levelTypeFor(namespace: string): LogType {\n const library = LIBRARY_NAMESPACES.some(\n (own) => namespace === own || namespace.startsWith(`${own}.`),\n );\n\n return library ? \"system\" : \"log\";\n}\n\n/**\n * Copies a caller payload. A Proxy with a throwing trap must not throw out of a log call.\n * @param payload Caller payload.\n * @param diagnostics Diagnostics reporter.\n * @returns The copy, or a marker attribute when the library cannot read the payload.\n */\nfunction copyPayload(\n payload: Record<string, unknown> | undefined,\n diagnostics: Diagnostics,\n): Record<string, unknown> {\n if (payload === undefined) {\n return {};\n }\n\n const copied = diagnostics.guard(\n \"record.sanitize_failed\",\n \"The library could not read the payload.\",\n () => ({ ...payload }),\n );\n\n return copied ?? { [ATTR_SANITIZE_FAILED]: true };\n}\n\n/** Namespaced logger instance for recording structured events, metrics, and errors. */\nexport class OneLogger {\n /** log.type of the level methods. It is \"system\" only for the namespaces of the library. */\n private readonly levelType: LogType;\n\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 this.levelType = levelTypeFor(namespace);\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\", this.levelType, 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\", this.levelType, 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\", this.levelType, 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\", this.levelType, 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 // NaN and Infinity become null in JSON. A backend then reads a false zero.\n if (!Number.isFinite(value)) {\n this.bind().diagnostics.report(\n \"record.dropped_malformed\",\n \"The metric value is not a finite number. The library dropped the metric.\",\n { \"metric.name\": name },\n );\n return;\n }\n\n // Spread the caller attributes first. The metric fields then win over a key of the same name.\n // The OTLP metrics serializer reads the caller keys. The context keys stay off the point.\n const copied = copyPayload(attributes, this.bind().diagnostics);\n const payload = {\n ...copied,\n \"metric.name\": name,\n \"metric.value\": value,\n \"metric.unit\": unit,\n \"metric.type\": type,\n [METRIC_KEYS.attributeKeys]: Object.keys(copied),\n };\n this.write(\"INFO\", \"metric\", name, payload, true);\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 that resolves 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 * @param copied True when the payload is a copy that the library made. write() does not copy it.\n */\n private write(\n level: LogLevel,\n type: LogType,\n body: string,\n payload?: Record<string, unknown>,\n copied = false,\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 // minLevel does not apply to an action or a metric.\n if (!runtime.builder.isEnabled(level, type)) {\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: copied ? payload : copyPayload(payload, runtime.diagnostics),\n });\n\n // Breadcrumbs stay in memory and have no delivery cost. A breadcrumb keeps the body\n // after redact. A record that sampling drops did not go through redact. It keeps its\n // body, and redact sees it later inside the error record. A record that redact or\n // the shape check drops adds no breadcrumb.\n const crumb = record ? record.body : dropped === \"sampling\" ? body : undefined;\n if (type !== \"metric\" && crumb !== undefined) {\n runtime.breadcrumbs.push({\n t: Date.now(),\n category: type === \"action\" ? \"action\" : type === \"event\" ? \"event\" : \"log\",\n message: crumb,\n });\n }\n\n this.print(runtime, level, body, payload, undefined, record, dropped);\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. A Proxy in the error slot can throw on the test.\n const asPayload =\n payload === undefined &&\n (runtime.diagnostics.guard(\n \"record.sanitize_failed\",\n \"The library could not read the error slot.\",\n () => isPlainObject(error),\n ) ??\n false);\n const attributes = asPayload ? (error as Record<string, unknown>) : payload;\n const reason = asPayload ? undefined : error;\n const asError = reason === undefined ? undefined : toError(reason, runtime.diagnostics);\n const shown =\n asError === undefined ? undefined : consoleError(reason, asError, runtime.diagnostics);\n\n if (!ships) {\n this.print(runtime, level, message, attributes, shown, null);\n return;\n }\n\n const data = asError ? errorData(reason, runtime.diagnostics) : undefined;\n\n const { record, dropped } = runtime.builder.build({\n level,\n type: this.levelType,\n body: message,\n namespace: this.namespace,\n scoped: this.options.scopedContext,\n payload: {\n ...copyPayload(attributes, runtime.diagnostics),\n ...(asError\n ? {\n \"error.type\": asError.name,\n \"error.message\": asError.message,\n \"error.stack_trace\": asError.stack,\n }\n : {}),\n ...(data === undefined ? {} : { [ATTR_ERROR_DATA]: data }),\n [ATTR_BREADCRUMBS]: runtime.breadcrumbs.snapshot(),\n },\n });\n\n this.print(runtime, level, message, attributes, shown, record, dropped);\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 * @param dropped Reason of the drop when the builder dropped the record.\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 dropped?: DropReason,\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 // A record that redact or the shape check dropped prints no line. Its text did not pass redact.\n if (dropped === \"redact\" || dropped === \"malformed\") {\n return;\n }\n\n runtime.console.write(this.namespace, level, message, undefined, error);\n }\n\n /**\n * Tests if 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 { isLibraryConsole, runAsLibraryConsole } from \"./library-console\";\nimport { type SanitizeLimits, 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 * @param limits Size limits of the printed payload. They are the record limits.\n */\n constructor(\n private settings: ResolvedConsole,\n private diagnostics: Diagnostics,\n private readonly limits: SanitizeLimits = RECORD_LIMITS,\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 if 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 if (this.settings.level === null) {\n return false;\n }\n\n // Guard against a level that is not a key of LEVEL_ORDER, for example \"toString\".\n if (!Object.hasOwn(LEVEL_ORDER, this.settings.level)) {\n return false;\n }\n\n return 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 // Guard against a loop. A host console wrapper can call the logger. The logger then prints again.\n // The console capture also records inside this scope. Its line is already in devtools.\n if (isLibraryConsole()) {\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, this.limits, this.diagnostics));\n }\n\n // The console capture skips a call in this scope. It must not record a mirrored line.\n runAsLibraryConsole(() => {\n console[method](\n prefix,\n styles.namespace,\n namespace,\n styles[level],\n \"\",\n message,\n ...details,\n );\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. The counter does not reset. A reset repeats\n// numbers in one context.\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","// 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 * Tests if 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/** Cause of a rotation of 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 that resolves when the attempt settles.\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 active span of the host if the peer module loaded and a span runs.\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\" | \"frame\";\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 readonly 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","// 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 BEACON_LIMIT_BYTES,\n CONFIG_SECTIONS,\n CONSOLE_DEFAULT_LEVEL,\n CONSOLE_DEFAULT_STYLES,\n DEFAULT_CONFIG,\n LEVEL_ORDER,\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 BatchingOptions,\n BusOptions,\n CaptureOptions,\n CapturedConsoleMethod,\n ConsoleOption,\n ConsoleStyles,\n JourneyOptions,\n LimitOptions,\n ObservabilityConfig,\n ResolvedConfig,\n ResolvedConsole,\n RetentionOptions,\n SamplingOptions,\n SerializerChoice,\n} from \"../models/config\";\nimport type { LogLevel } from \"../models/log-record\";\nimport type { LogSerializer } from \"../models/serializer\";\nimport { isObject } from \"../utils/guards\";\nimport type { Diagnostics } from \"./diagnostics\";\n\n/** Level names in severity order. */\nconst LEVEL_NAMES = Object.keys(LEVEL_ORDER) as readonly LogLevel[];\n\n/** Accepted values of each choice option. */\nconst COMPRESSION_VALUES = [\"gzip\", \"none\"] as const;\nconst CREDENTIALS_VALUES = [\"omit\", \"same-origin\", \"include\"] as const;\nconst STORAGE_VALUES = [\"auto\", \"indexeddb\", \"localstorage\", \"memory\", \"none\"] as const;\nconst IDENTITY_VALUES = [\"storage\", \"memory\"] as const;\nconst BUS_MODE_VALUES = [\"auto\", \"sender\", \"forwarder\", \"off\"] as const;\nconst OPENFIN_ROLE_VALUES = [\"auto\", \"provider\", \"client\"] as const;\nconst JOURNEY_SCOPE_VALUES = [\"auto\", \"context\", \"tab\", \"origin\"] as const;\nconst CONSOLE_METHOD_VALUES = [\"error\", \"warn\", \"info\", \"log\"] as const;\nconst RETENTION_MODE_VALUES = [\"limited\", \"until-delivered\"] as const;\n\n/** Lowest and highest accepted value of an integer option. */\ntype Range = readonly [min: number, max: number];\n\n/** Accepted range of each batching key. */\nconst BATCHING_RANGES: Record<keyof BatchingOptions, Range> = {\n logFlushIntervalMs: [100, 60_000],\n logBatchSize: [1, 1000],\n metricFlushIntervalMs: [100, 60_000],\n metricBatchSize: [1, 1000],\n};\n\n/** Accepted range of each numeric retention key. */\nconst RETENTION_RANGES: Record<Exclude<keyof RetentionOptions, \"mode\">, Range> = {\n maxBatches: [1, 5000],\n maxAgeMs: [60_000, 7 * 24 * 60 * 60 * 1000],\n maxAttempts: [1, 20],\n};\n\n/**\n * Accepted range of each record limit. The maximum of maxRecordBytes is one beacon. The body and\n * the error fields are outside maxRecordBytes. An exit batch larger than one beacon goes to the\n * emergency queue.\n */\nconst LIMIT_RANGES: Record<keyof LimitOptions, Range> = {\n maxBodyChars: [256, 65_536],\n maxAttributeChars: [256, 65_536],\n maxAttributeCount: [1, 1024],\n maxStackChars: [256, 65_536],\n maxDepth: [1, 16],\n maxArrayLength: [1, 10_000],\n maxNodes: [100, 100_000],\n maxRecordBytes: [1024, BEACON_LIMIT_BYTES],\n};\n\n/** Accepted range of journey.maxAgeMs. */\nconst JOURNEY_AGE_RANGE: Range = [60_000, 24 * 60 * 60 * 1000];\n\n/** Boolean keys of the capture section. */\nconst CAPTURE_FLAG_KEYS = [\n \"errors\",\n \"rejections\",\n \"resourceErrors\",\n \"fetch\",\n \"xhr\",\n \"httpMetrics\",\n \"interactions\",\n \"navigation\",\n \"webVitals\",\n \"longFrames\",\n \"fullUrls\",\n] as const;\n\n/** Origin of a sandboxed frame without allow-same-origin. */\nconst SANDBOX_ORIGIN = \"null\";\n\n/** Text of each expected value in a config.invalid message. */\nconst LEVEL_EXPECTED = `a level name: ${listOf(LEVEL_NAMES)}`;\nconst CONSOLE_CAPTURE_EXPECTED = `true, false or a list of ${listOf(CONSOLE_METHOD_VALUES)}`;\nconst PATTERN_LIST_EXPECTED = \"a list of strings and RegExp patterns\";\nconst TARGET_LIST_EXPECTED =\n 'a list of origin URLs such as \"https://api.example\" and RegExp patterns';\nconst ORIGIN_LIST_EXPECTED =\n 'a list of origin URLs such as \"https://app.example\". For a sandboxed frame, set bus.mode: \"sender\" in the frame';\nconst STRING_LIST_EXPECTED = \"a list of strings\";\n\n/** Function form of the headers option. */\ntype HeadersFunction = () => Record<string, string> | Promise<Record<string, string>>;\n\n/** The headers option. */\ntype HeadersOption = ObservabilityConfig[\"headers\"];\n\n/**\n * Writes a list of values as text, for example `\"a\", \"b\" or \"c\"`.\n * @param values Values to list.\n * @returns The text.\n */\nfunction listOf(values: readonly string[]): string {\n const quoted = values.map((value) => `\"${value}\"`);\n return `${quoted.slice(0, -1).join(\", \")} or ${quoted[quoted.length - 1]}`;\n}\n\n/**\n * Describes a config value for a message. It does not print an object or a function.\n * @param value Value that the consumer passed.\n * @returns Short text for the value.\n */\nfunction describeValue(value: unknown): string {\n if (typeof value === \"string\") {\n return `\"${value}\"`;\n }\n\n if (typeof value === \"function\") {\n return \"a function\";\n }\n\n if (typeof value === \"object\" && value !== null) {\n return \"an object\";\n }\n\n return String(value);\n}\n\n/**\n * Reports a value that the option does not accept.\n * @param diagnostics Diagnostics reporter.\n * @param key Config key, for example `bus.mode`.\n * @param expected Text of the accepted values.\n * @param value Value that the consumer passed.\n * @param kept Text of the value that stays in force.\n */\nfunction reportInvalid(\n diagnostics: Diagnostics,\n key: string,\n expected: string,\n value: unknown,\n kept: string,\n): void {\n diagnostics.report(\n \"config.invalid\",\n `${key} must be ${expected}. The value is ${describeValue(value)}. The library keeps ${kept}.`,\n );\n}\n\n/**\n * Reads an option that accepts one value from a fixed list.\n * @param key Config key.\n * @param value Value that the consumer passed.\n * @param accepted Accepted values.\n * @param fallback Value in force.\n * @param diagnostics Diagnostics reporter.\n * @returns The value, or the fallback when the value is not accepted.\n */\nfunction resolveChoice<T extends string>(\n key: string,\n value: unknown,\n accepted: readonly T[],\n fallback: T,\n diagnostics: Diagnostics,\n): T {\n if (value === undefined) {\n return fallback;\n }\n\n const match = accepted.find((entry) => entry === value);\n if (match !== undefined) {\n return match;\n }\n\n reportInvalid(diagnostics, key, listOf(accepted), value, `\"${fallback}\"`);\n return fallback;\n}\n\n/**\n * Reads a boolean option.\n * @param key Config key.\n * @param value Value that the consumer passed.\n * @param fallback Value in force.\n * @param diagnostics Diagnostics reporter.\n * @returns The value, or the fallback when the value is not a boolean.\n */\nfunction resolveBoolean(\n key: string,\n value: unknown,\n fallback: boolean,\n diagnostics: Diagnostics,\n): boolean {\n if (value === undefined) {\n return fallback;\n }\n\n if (typeof value === \"boolean\") {\n return value;\n }\n\n reportInvalid(diagnostics, key, \"true or false\", value, String(fallback));\n return fallback;\n}\n\n/**\n * Reads an option that accepts a finite number of 0 or more.\n * @param key Config key.\n * @param value Value that the consumer passed.\n * @param fallback Value in force.\n * @param diagnostics Diagnostics reporter.\n * @returns The value, or the fallback when the value is not accepted.\n */\nfunction resolveNonNegative(\n key: string,\n value: unknown,\n fallback: number,\n diagnostics: Diagnostics,\n): number {\n if (value === undefined) {\n return fallback;\n }\n\n if (typeof value === \"number\" && Number.isFinite(value) && value >= 0) {\n return value;\n }\n\n reportInvalid(diagnostics, key, \"a finite number of 0 or more\", value, String(fallback));\n return fallback;\n}\n\n/**\n * Reads an option that accepts an integer in a range.\n * @param key Config key.\n * @param value Value that the consumer passed.\n * @param range Lowest and highest accepted value.\n * @param fallback Value in force.\n * @param diagnostics Diagnostics reporter.\n * @returns The value, or the fallback when the value is not accepted.\n */\nfunction resolveInteger(\n key: string,\n value: unknown,\n range: Range,\n fallback: number,\n diagnostics: Diagnostics,\n): number {\n if (value === undefined) {\n return fallback;\n }\n\n const [min, max] = range;\n if (typeof value === \"number\" && Number.isInteger(value) && value >= min && value <= max) {\n return value;\n }\n\n const expected = `an integer from ${String(min)} to ${String(max)}`;\n reportInvalid(diagnostics, key, expected, value, String(fallback));\n return fallback;\n}\n\n/**\n * Merges and checks a section of integer options. The keys come from `ranges` only.\n * @param section Section name, for example `batching`.\n * @param input Values that the consumer passed.\n * @param base Values in force.\n * @param ranges Accepted range of each key.\n * @param diagnostics Diagnostics reporter.\n * @returns The value of each key in `ranges`.\n */\nfunction resolveRanges<K extends string>(\n section: string,\n input: Partial<Record<NoInfer<K>, unknown>> | undefined,\n base: Record<NoInfer<K>, number>,\n ranges: Record<K, Range>,\n diagnostics: Diagnostics,\n): Record<K, number> {\n const given: Partial<Record<K, unknown>> = input ?? {};\n const keys = Object.keys(ranges) as K[];\n\n return Object.fromEntries(\n keys.map((key): [K, number] => [\n key,\n resolveInteger(`${section}.${key}`, given[key], ranges[key], base[key], diagnostics),\n ]),\n ) as Record<K, number>;\n}\n\n/**\n * Reads a level name in any case.\n * @param value Value that the consumer passed.\n * @returns The level, or undefined when the value is not a level name.\n */\nfunction toLevel(value: unknown): LogLevel | undefined {\n if (typeof value !== \"string\") {\n return undefined;\n }\n\n const upper = value.toUpperCase();\n return LEVEL_NAMES.find((level) => level === upper);\n}\n\n/**\n * Reads a level option. Without this check, an unknown level drops each record with no message.\n * @param key Config key.\n * @param value Value that the consumer passed.\n * @param fallback Level in force.\n * @param diagnostics Diagnostics reporter.\n * @returns The level, or the fallback when the value is not a level name.\n */\nfunction resolveLevel(\n key: string,\n value: unknown,\n fallback: LogLevel,\n diagnostics: Diagnostics,\n): LogLevel {\n if (value === undefined) {\n return fallback;\n }\n\n const level = toLevel(value);\n if (level !== undefined) {\n return level;\n }\n\n reportInvalid(diagnostics, key, LEVEL_EXPECTED, value, `\"${fallback}\"`);\n return fallback;\n}\n\n/**\n * Reads a list option. It keeps each accepted entry and reports each other entry.\n * @param key Config key.\n * @param value Value that the consumer passed.\n * @param fallback List in force.\n * @param expected Text of the accepted list.\n * @param accept Converts an entry, or returns undefined to reject it.\n * @param diagnostics Diagnostics reporter.\n * @returns The accepted entries, or the fallback when the value is not a list.\n */\nfunction resolveList<T>(\n key: string,\n value: unknown,\n fallback: T[],\n expected: string,\n accept: (entry: unknown) => T | undefined,\n diagnostics: Diagnostics,\n): T[] {\n if (value === undefined) {\n return fallback;\n }\n\n if (!Array.isArray(value)) {\n reportInvalid(diagnostics, key, expected, value, \"the list in force\");\n return fallback;\n }\n\n const kept: T[] = [];\n const entries: unknown[] = value;\n\n for (const entry of entries) {\n const accepted = accept(entry);\n if (accepted === undefined) {\n diagnostics.report(\n \"config.invalid\",\n `The library ignores the ${key} entry ${describeValue(entry)}. ${key} must be ${expected}.`,\n );\n continue;\n }\n kept.push(accepted);\n }\n\n return kept;\n}\n\n/**\n * Accepts a string entry.\n * @param entry List entry.\n * @returns The entry, or undefined.\n */\nfunction toStringEntry(entry: unknown): string | undefined {\n return typeof entry === \"string\" ? entry : undefined;\n}\n\n/**\n * Accepts a string or a RegExp entry.\n * @param entry List entry.\n * @returns The entry, or undefined.\n */\nfunction toPattern(entry: unknown): string | RegExp | undefined {\n return typeof entry === \"string\" || entry instanceof RegExp ? entry : undefined;\n}\n\n/**\n * Accepts a console method name.\n * @param entry List entry.\n * @returns The method, or undefined.\n */\nfunction toConsoleMethod(entry: unknown): CapturedConsoleMethod | undefined {\n return CONSOLE_METHOD_VALUES.find((method) => method === entry);\n}\n\n/**\n * Reads an origin entry. A URL with a path gives its origin.\n * @param entry List entry.\n * @returns The origin, or undefined. resolveList reports the rejected entry.\n */\nfunction toOrigin(entry: unknown): string | undefined {\n if (typeof entry !== \"string\") {\n return undefined;\n }\n\n // Each sandboxed and data: document has the opaque origin \"null\". One entry trusts all of them.\n try {\n const { origin } = new URL(entry);\n return origin === SANDBOX_ORIGIN ? undefined : origin;\n } catch {\n return undefined;\n }\n}\n\n/**\n * Reads a trace header target. A string gives its origin. A RegExp stays as it is.\n * @param entry List entry.\n * @returns The target, or undefined. resolveList reports the rejected entry.\n */\nfunction toTarget(entry: unknown): string | RegExp | undefined {\n return entry instanceof RegExp ? entry : toOrigin(entry);\n}\n\n/**\n * Tests if a value is an object of string values.\n * @param value Value to test.\n * @returns True for an object whose values are all strings.\n */\nfunction isStringRecord(value: unknown): value is Record<string, string> {\n if (!isObject(value)) {\n return false;\n }\n\n const values: unknown[] = Object.values(value);\n return values.every((entry) => typeof entry === \"string\");\n}\n\n/**\n * Reads the headers option.\n * @param value Value that the consumer passed.\n * @param fallback Headers in force.\n * @param diagnostics Diagnostics reporter.\n * @returns The headers, undefined for an explicit undefined, or the fallback for a bad value.\n */\nfunction resolveHeaders(\n value: unknown,\n fallback: HeadersOption,\n diagnostics: Diagnostics,\n): HeadersOption {\n // An explicit undefined clears the headers. After logout, the old token must not go on a send.\n if (value === undefined) {\n return undefined;\n }\n\n if (typeof value === \"function\") {\n return value as HeadersFunction;\n }\n\n if (isStringRecord(value)) {\n return value;\n }\n\n reportInvalid(\n diagnostics,\n \"headers\",\n \"an object of strings or a function\",\n value,\n \"the headers in force\",\n );\n return fallback;\n}\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 * Reads the level of the console object form.\n * @param requested Level that the consumer passed.\n * @param previous Console level in force. Null means the console is off.\n * @param diagnostics Diagnostics reporter.\n * @returns The level. An unknown level keeps the level in force.\n */\nfunction resolveConsoleLevel(\n requested: unknown,\n previous: LogLevel | null,\n diagnostics: Diagnostics,\n): LogLevel | null {\n if (requested === undefined) {\n return previous ?? CONSOLE_DEFAULT_LEVEL;\n }\n\n const level = toLevel(requested);\n if (level !== undefined) {\n return level;\n }\n\n reportInvalid(\n diagnostics,\n \"console.level\",\n LEVEL_EXPECTED,\n requested,\n \"the console level in force\",\n );\n return previous;\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 const level = toLevel(requested);\n if (level === undefined) {\n reportInvalid(\n diagnostics,\n \"console\",\n LEVEL_EXPECTED,\n requested,\n \"the console level in force\",\n );\n return previous;\n }\n\n return { level, styles: previous.styles };\n }\n\n // Guard against null and other values that the type does not accept.\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: resolveConsoleLevel(requested.level, previous.level, diagnostics),\n styles: { ...previous.styles, ...validStyles(requested.styles, diagnostics) },\n };\n}\n\n/**\n * Merges and checks the sampling section. resolveConfig checks the rates after the merge.\n * @param input Sampling options that the consumer passed.\n * @param base Sampling options in force.\n * @param diagnostics Diagnostics reporter.\n * @returns The sampling options.\n */\nfunction resolveSampling(\n input: Partial<SamplingOptions> | undefined,\n base: SamplingOptions,\n diagnostics: Diagnostics,\n): SamplingOptions {\n const given = input ?? {};\n\n return {\n ...base,\n ...given,\n rates: { ...base.rates, ...given.rates },\n alwaysSampleTypes: resolveList(\n \"sampling.alwaysSampleTypes\",\n given.alwaysSampleTypes,\n base.alwaysSampleTypes,\n STRING_LIST_EXPECTED,\n toStringEntry,\n diagnostics,\n ),\n remote: resolveBoolean(\"sampling.remote\", given.remote, base.remote, diagnostics),\n };\n}\n\n/**\n * Merges and checks the bus section.\n * @param input Bus options that the consumer passed.\n * @param base Bus options in force.\n * @param diagnostics Diagnostics reporter.\n * @returns The bus options. Each trusted origin is a bare origin.\n */\nfunction resolveBus(\n input: Partial<BusOptions> | undefined,\n base: BusOptions,\n diagnostics: Diagnostics,\n): BusOptions {\n const given = input ?? {};\n\n return {\n mode: resolveChoice(\"bus.mode\", given.mode, BUS_MODE_VALUES, base.mode, diagnostics),\n // Compare origins, not URLs. If not, an entry with a path never matches event.origin.\n trustedOrigins: resolveList(\n \"bus.trustedOrigins\",\n given.trustedOrigins,\n base.trustedOrigins,\n ORIGIN_LIST_EXPECTED,\n toOrigin,\n diagnostics,\n ),\n openFinRole: resolveChoice(\n \"bus.openFinRole\",\n given.openFinRole,\n OPENFIN_ROLE_VALUES,\n base.openFinRole,\n diagnostics,\n ),\n };\n}\n\n/**\n * Merges and checks the journey section.\n * @param input Journey options that the consumer passed.\n * @param base Journey options in force.\n * @param diagnostics Diagnostics reporter.\n * @returns The journey options.\n */\nfunction resolveJourney(\n input: Partial<JourneyOptions> | undefined,\n base: JourneyOptions,\n diagnostics: Diagnostics,\n): JourneyOptions {\n const given = input ?? {};\n\n return {\n scope: resolveChoice(\n \"journey.scope\",\n given.scope,\n JOURNEY_SCOPE_VALUES,\n base.scope,\n diagnostics,\n ),\n maxAgeMs: resolveInteger(\n \"journey.maxAgeMs\",\n given.maxAgeMs,\n JOURNEY_AGE_RANGE,\n base.maxAgeMs,\n diagnostics,\n ),\n };\n}\n\n/**\n * Merges and checks the retention section.\n * @param input Retention options that the consumer passed.\n * @param base Retention options in force.\n * @param diagnostics Diagnostics reporter.\n * @returns The retention options.\n */\nfunction resolveRetention(\n input: Partial<RetentionOptions> | undefined,\n base: RetentionOptions,\n diagnostics: Diagnostics,\n): RetentionOptions {\n const given = input ?? {};\n\n return {\n mode: resolveChoice(\n \"retention.mode\",\n given.mode,\n RETENTION_MODE_VALUES,\n base.mode,\n diagnostics,\n ),\n ...resolveRanges(\"retention\", given, base, RETENTION_RANGES, diagnostics),\n };\n}\n\n/**\n * Reads capture.console.\n * @param value Value that the consumer passed.\n * @param fallback Value in force.\n * @param diagnostics Diagnostics reporter.\n * @returns A boolean, or the accepted method names.\n */\nfunction resolveCaptureConsole(\n value: unknown,\n fallback: boolean | CapturedConsoleMethod[],\n diagnostics: Diagnostics,\n): boolean | CapturedConsoleMethod[] {\n if (value === undefined) {\n return fallback;\n }\n\n if (typeof value === \"boolean\") {\n return value;\n }\n\n if (!Array.isArray(value)) {\n reportInvalid(\n diagnostics,\n \"capture.console\",\n CONSOLE_CAPTURE_EXPECTED,\n value,\n \"the value in force\",\n );\n return fallback;\n }\n\n return resolveList(\n \"capture.console\",\n value,\n [],\n CONSOLE_CAPTURE_EXPECTED,\n toConsoleMethod,\n diagnostics,\n );\n}\n\n/**\n * Merges and checks the capture section.\n * @param input Capture options that the consumer passed.\n * @param base Capture options in force.\n * @param diagnostics Diagnostics reporter.\n * @returns The capture options.\n */\nfunction resolveCapture(\n input: Partial<CaptureOptions> | undefined,\n base: CaptureOptions,\n diagnostics: Diagnostics,\n): CaptureOptions {\n const given = input ?? {};\n const capture: CaptureOptions = {\n ...base,\n ...given,\n console: resolveCaptureConsole(given.console, base.console, diagnostics),\n longFrameThresholdMs: resolveNonNegative(\n \"capture.longFrameThresholdMs\",\n given.longFrameThresholdMs,\n base.longFrameThresholdMs,\n diagnostics,\n ),\n ignoreUrls: resolveList(\n \"capture.ignoreUrls\",\n given.ignoreUrls,\n base.ignoreUrls,\n PATTERN_LIST_EXPECTED,\n toPattern,\n diagnostics,\n ),\n // A string target is an origin. A substring test also matches a query value or a longer host.\n propagateTraceHeaderTo: resolveList(\n \"capture.propagateTraceHeaderTo\",\n given.propagateTraceHeaderTo,\n base.propagateTraceHeaderTo,\n TARGET_LIST_EXPECTED,\n toTarget,\n diagnostics,\n ),\n };\n\n for (const key of CAPTURE_FLAG_KEYS) {\n capture[key] = resolveBoolean(`capture.${key}`, given[key], base[key], diagnostics);\n }\n\n return capture;\n}\n\n/**\n * Validates the metrics endpoint. Only the OTLP serializer has a metrics format.\n * @param value Value that the consumer passed.\n * @param fallback Value in force.\n * @param serializer Resolved serializer option.\n * @param diagnostics Diagnostics reporter.\n * @returns A valid absolute URL, or \"\" to send metric records as log records.\n */\nfunction resolveMetricsEndpoint(\n value: unknown,\n fallback: string,\n serializer: SerializerChoice,\n diagnostics: Diagnostics,\n): string {\n let url = fallback;\n\n if (typeof value === \"string\" && value !== \"\") {\n try {\n new URL(value);\n url = value;\n } catch (error) {\n diagnostics.report(\n \"config.invalid\",\n `metricsEndpoint is not a valid absolute URL: ${value}. The library keeps the value in force.`,\n undefined,\n error,\n );\n }\n } else if (value === \"\") {\n url = \"\";\n } else if (value !== undefined) {\n reportInvalid(diagnostics, \"metricsEndpoint\", \"a URL string\", value, \"the value in force\");\n }\n\n // A custom or ECS serializer cannot encode a metrics request.\n if (url !== \"\" && serializer !== SERIALIZER_NAME_OTLP) {\n diagnostics.report(\n \"config.invalid\",\n `metricsEndpoint needs serializer \"${SERIALIZER_NAME_OTLP}\". The library sends metric records as log records.`,\n );\n return \"\";\n }\n\n return url;\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 bad value reports config.invalid. The value in force stays. Without this check, a bad\n // minLevel drops each record with no message.\n enabled: resolveBoolean(\"enabled\", input.enabled, base.enabled, diagnostics),\n minLevel: resolveLevel(\"minLevel\", input.minLevel, base.minLevel, diagnostics),\n compression: resolveChoice(\n \"compression\",\n input.compression,\n COMPRESSION_VALUES,\n base.compression,\n diagnostics,\n ),\n credentials: resolveChoice(\n \"credentials\",\n input.credentials,\n CREDENTIALS_VALUES,\n base.credentials,\n diagnostics,\n ),\n headers:\n \"headers\" in input ? resolveHeaders(input.headers, base.headers, diagnostics) : base.headers,\n storage: resolveChoice(\"storage\", input.storage, STORAGE_VALUES, base.storage, diagnostics),\n identity: resolveChoice(\n \"identity\",\n input.identity,\n IDENTITY_VALUES,\n base.identity,\n diagnostics,\n ),\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: resolveSampling(input.sampling, base.sampling, diagnostics),\n bus: resolveBus(input.bus, base.bus, diagnostics),\n batching: resolveRanges(\n \"batching\",\n input.batching,\n base.batching,\n BATCHING_RANGES,\n diagnostics,\n ),\n retention: resolveRetention(input.retention, base.retention, diagnostics),\n limits: resolveRanges(\"limits\", input.limits, base.limits, LIMIT_RANGES, diagnostics),\n journey: resolveJourney(input.journey, base.journey, diagnostics),\n capture: resolveCapture(input.capture, base.capture, diagnostics),\n };\n\n merged.metricsEndpoint = resolveMetricsEndpoint(\n input.metricsEndpoint,\n base.metricsEndpoint,\n merged.serializer,\n diagnostics,\n );\n\n // Guard against a value that cannot send. Keep the function in force.\n // Without a transport, the pipeline drops each batch.\n if (merged.transport !== undefined && typeof merged.transport !== \"function\") {\n diagnostics.report(\n \"config.invalid\",\n \"transport must be a function. The library ignores the value.\",\n );\n merged.transport = base.transport;\n }\n\n if (merged.onDrop !== undefined && typeof merged.onDrop !== \"function\") {\n diagnostics.report(\n \"config.invalid\",\n \"onDrop must be a function. The library ignores the value.\",\n );\n merged.onDrop = base.onDrop;\n }\n\n if (merged.transportOnExit !== undefined && typeof merged.transportOnExit !== \"function\") {\n diagnostics.report(\n \"config.invalid\",\n \"transportOnExit must be a function. The library ignores the value.\",\n );\n merged.transportOnExit = base.transportOnExit;\n }\n\n // null selects console-only mode. That value is valid. Report only an empty string.\n // A custom transport needs no endpoint.\n if (merged.endpoint === \"\") {\n if (merged.transport === undefined) {\n diagnostics.report(\n \"config.invalid\",\n \"endpoint is missing. The library drops each record. Set endpoint: null for console-only mode.\",\n );\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 // Only the delivery stack sends. It loads only with an endpoint or a custom transport.\n if (merged.metricsEndpoint !== \"\" && merged.endpoint === null && !merged.transport) {\n diagnostics.report(\n \"config.invalid\",\n \"metricsEndpoint needs endpoint or transport. The library sends nothing to metricsEndpoint.\",\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 maxRate: unknown = merged.sampling.remoteMaxRate;\n // The negated range test also rejects NaN.\n if (\n typeof maxRate !== \"number\" ||\n !(maxRate >= SAMPLING_RATE_MIN && maxRate <= SAMPLING_RATE_MAX)\n ) {\n diagnostics.report(\n \"config.invalid\",\n `sampling.remoteMaxRate must be 0..1. The value is ${String(maxRate)}. The library uses ${String(SAMPLING_RATE_FALLBACK)}.`,\n );\n merged.sampling.remoteMaxRate = 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 endpoints 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(\n (url) => url !== previous?.endpoint && url !== previous?.metricsEndpoint,\n );\n for (const url of [merged.endpoint, merged.metricsEndpoint]) {\n if (url && !merged.capture.ignoreUrls.includes(url)) {\n merged.capture.ignoreUrls = [...merged.capture.ignoreUrls, url];\n }\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 * 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 /**\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\";\nimport { runAsLibraryConsole } from \"../utils/library-console\";\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 | \"record.dropped_no_destination\"\n | \"runtime.version_mismatch\"\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 | \"capture.transport_request\"\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 const { handler } = this;\n\n if (!handler) {\n return;\n }\n try {\n // The console capture skips a console call of the handler. Without the scope, the line\n // gives a record, and a failed send of that record gives a new diagnostic.\n runAsLibraryConsole(() => {\n handler(event);\n });\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 // The console capture skips a call in this scope.\n runAsLibraryConsole(() => {\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 /**\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 that resolves 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","// src/core/drops.ts\n//\n// This module collects lost records into onDrop summaries. It sends one summary for each\n// reason after the current task. A storm of losses then gives one call, not one per record.\n\nimport { ATTR_JOURNEY_ID, DROP_SUMMARY_MAX_ITEMS } from \"../constants\";\nimport { attributeOf, isActionRecord } from \"../models/batch\";\nimport type { ResolvedConfig } from \"../models/config\";\nimport type { DropSummary, LossReason } from \"../models/drop\";\nimport type { LogRecord } from \"../models/log-record\";\nimport { runAsLibraryConsole } from \"../utils/library-console\";\nimport { runAsLibraryRequest } from \"../utils/library-request\";\nimport type { Diagnostics } from \"./diagnostics\";\n\n/**\n * Adds a value to a summary list. The list keeps each value one time, up to the limit.\n * @param list Summary list.\n * @param value Value to add.\n */\nfunction addCapped(list: string[], value: string): void {\n if (list.length < DROP_SUMMARY_MAX_ITEMS && !list.includes(value)) {\n list.push(value);\n }\n}\n\n/** Collects lost records and gives one summary for each reason to the onDrop hook. */\nexport class DropReporter {\n /** Summaries that wait for the end of the task, one for each reason. */\n private readonly pending = new Map<LossReason, DropSummary>();\n\n /** True while a microtask waits to send the summaries. */\n private scheduled = false;\n\n /** True while the hook runs. A loss that the hook causes is not reported again. */\n private reporting = false;\n\n /**\n * @param config Active configuration. The reporter reads `onDrop` from it at each call.\n * @param diagnostics Diagnostics reporter.\n */\n constructor(\n private readonly config: ResolvedConfig,\n private readonly diagnostics: Diagnostics,\n ) {}\n\n /**\n * Adds lost records to the summary of their reason. Without an onDrop hook, it does nothing.\n * @param reason Cause of the loss.\n * @param records Lost records.\n * @param batchIds Ids of the lost batches.\n */\n add(reason: LossReason, records: readonly LogRecord[], batchIds: readonly string[] = []): void {\n // A hook that logs can fill a buffer again. A report of that loss starts a loop.\n if (!this.config.onDrop || this.reporting) {\n return;\n }\n\n // A failed load with an empty buffer loses nothing. A corrupt entry has no id to report.\n if (records.length === 0 && batchIds.length === 0) {\n return;\n }\n\n let summary = this.pending.get(reason);\n if (!summary) {\n summary = { reason, records: 0, batchIds: [], journeyIds: [], actions: [] };\n this.pending.set(reason, summary);\n }\n\n summary.records += records.length;\n for (const id of batchIds) {\n addCapped(summary.batchIds, id);\n }\n\n for (const record of records) {\n // A record from storage can be corrupt. It can be null or have no attributes.\n const journey = attributeOf(record, ATTR_JOURNEY_ID);\n if (typeof journey === \"string\") {\n addCapped(summary.journeyIds, journey);\n }\n\n const body: unknown = isActionRecord(record) ? record.body : undefined;\n if (typeof body === \"string\") {\n addCapped(summary.actions, body);\n }\n }\n\n if (!this.scheduled) {\n this.scheduled = true;\n queueMicrotask(() => {\n this.flush();\n });\n }\n }\n\n /** Gives each waiting summary to the hook. A hook that throws does not stop the others. */\n private flush(): void {\n this.scheduled = false;\n const summaries = [...this.pending.values()];\n this.pending.clear();\n\n const onDrop = this.config.onDrop;\n if (!onDrop) {\n return;\n }\n\n this.reporting = true;\n for (const summary of summaries) {\n this.diagnostics.guard(\"handler.threw\", \"The onDrop hook threw an error.\", () => {\n // The capture modules skip a request or a console line of the hook. A captured line\n // gives a record. That record can evict one more stored batch.\n runAsLibraryRequest(() => {\n runAsLibraryConsole(() => {\n onDrop(summary);\n });\n });\n });\n }\n this.reporting = false;\n }\n}\n","// src/core/hold-buffer.ts\n//\n// This module holds records while the runtime cannot deliver them. An action is an audit fact.\n// Actions have their own cap. A storm of other records cannot push an action out.\n\nimport { BUS_MAX_BOOT_BUFFER_ACTIONS, BUS_MAX_BOOT_BUFFER_RECORDS } from \"../constants\";\nimport { isActionRecord } from \"../models/batch\";\nimport type { LogRecord } from \"../models/log-record\";\n\n/** Holds records in arrival order. A full buffer drops its oldest record of the same kind. */\nexport class HoldBuffer {\n /** Held records in arrival order. */\n private held: LogRecord[] = [];\n\n /** Number of held actions. A count finds a full buffer without a scan at each push. */\n private actions = 0;\n\n /**\n * @param onDrop Receives the record that a full buffer drops.\n */\n constructor(private readonly onDrop: (record: LogRecord) => void) {}\n\n /** Held records in arrival order. */\n get records(): readonly LogRecord[] {\n return this.held;\n }\n\n /** Number of held records. */\n get length(): number {\n return this.held.length;\n }\n\n /**\n * Adds a record. A full buffer drops its oldest record of the same kind.\n * @param record Record to hold.\n */\n push(record: LogRecord): void {\n const action = isActionRecord(record);\n const count = action ? this.actions : this.held.length - this.actions;\n const cap = action ? BUS_MAX_BOOT_BUFFER_ACTIONS : BUS_MAX_BOOT_BUFFER_RECORDS;\n\n if (count < cap) {\n this.actions += action ? 1 : 0;\n } else {\n // Scan only at the cap. A scan at each push is quadratic in a log storm.\n const oldest = this.held.findIndex((one) => isActionRecord(one) === action);\n const [dropped] = this.held.splice(oldest, 1);\n this.onDrop(dropped);\n }\n\n this.held.push(record);\n }\n\n /**\n * Removes the held records.\n * @returns The records in arrival order.\n */\n take(): LogRecord[] {\n const records = this.held;\n this.held = [];\n this.actions = 0;\n return records;\n }\n}\n","// src/core/meter.ts\n//\n// This module sums counter and histogram values in memory. At each interval, it gives one point\n// for each instrument and attribute set. A thousand adds then give one record, not a thousand.\n\nimport {\n ATTR_APP_NAMESPACE,\n ATTR_JOURNEY_ID,\n ATTR_JOURNEY_NAME,\n ATTR_JOURNEY_PARENT_ID,\n ATTR_LOG_SEQ,\n ATTR_LOG_TYPE,\n ATTR_METRIC_OVERFLOW,\n ATTR_PAGE_URL,\n METRIC_DEFAULT_BOUNDARIES,\n METRIC_KEYS,\n METRIC_MAX_BOUNDARIES,\n METRIC_MAX_SERIES,\n} from \"../constants\";\nimport type { InstrumentDef, MetricAttributes } from \"../models/metric\";\nimport { unrefTimer } from \"../utils/unref\";\nimport type { Diagnostics } from \"./diagnostics\";\n\n/** Sums of one attribute set in the current interval. */\ninterface Series {\n /** Attribute set of the series. */\n attributes: MetricAttributes;\n /** Number of values. */\n count: number;\n /** Sum of the values. */\n sum: number;\n /** Smallest value. */\n min: number;\n /** Largest value. */\n max: number;\n /** Count of each histogram bucket. A counter has none. */\n buckets: number[];\n}\n\n/** Series of one instrument in the current interval. */\ninterface Instrument {\n /** Definition from the first value of the interval. */\n def: InstrumentDef;\n /** Series by attribute set key. */\n series: Map<string, Series>;\n}\n\n/** Key of the overflow series. The key of an attribute set is JSON text. It starts with \"{\". */\nconst OVERFLOW_KEY = \"overflow\";\n\n/** Keys that the record builder sets. It replaces a call attribute of the same name. */\nconst RECORD_KEYS = new Set<string>([\n ATTR_LOG_TYPE,\n ATTR_LOG_SEQ,\n ATTR_APP_NAMESPACE,\n ATTR_PAGE_URL,\n ATTR_JOURNEY_ID,\n ATTR_JOURNEY_NAME,\n ATTR_JOURNEY_PARENT_ID,\n]);\n\n/**\n * Keeps the string, finite number and boolean attributes in key order. Two calls with one set in\n * another key order then share one series.\n * @param attributes Attribute set of the call.\n * @returns The clean attribute set.\n */\nfunction cleanAttributes(attributes: MetricAttributes = {}): MetricAttributes {\n const clean: MetricAttributes = {};\n\n for (const key of Object.keys(attributes).sort()) {\n // The builder and the serializer replace or remove these keys. Each value then makes a\n // series with the same output.\n if (key.startsWith(\"metric.\") || RECORD_KEYS.has(key)) {\n continue;\n }\n\n const value: unknown = attributes[key];\n const finite = typeof value === \"number\" && Number.isFinite(value);\n if (typeof value === \"string\" || typeof value === \"boolean\" || finite) {\n clean[key] = value;\n }\n }\n\n return clean;\n}\n\n/**\n * Copies a list of boundaries by index. A custom iterator of the array of the app has no effect.\n * @param bounds Value of the boundaries option.\n * @returns A plain array with at most one value more than the limit, or null for a value that is\n * not an array.\n */\nfunction copyBounds(bounds: unknown): unknown[] | null {\n if (!Array.isArray(bounds)) {\n return null;\n }\n\n // One value more than the limit. isAscending then refuses a list that is too long.\n const count = Math.min(bounds.length, METRIC_MAX_BOUNDARIES + 1);\n return Array.from({ length: count }, (_unused, i): unknown => bounds[i]);\n}\n\n/**\n * Tests a list of histogram boundaries.\n * @param bounds Value of the boundaries option.\n * @returns True for at most 50 finite numbers in ascending order.\n */\nfunction isAscending(bounds: unknown): bounds is number[] {\n return (\n Array.isArray(bounds) &&\n bounds.length <= METRIC_MAX_BOUNDARIES &&\n bounds.every(\n (bound: unknown, i) =>\n typeof bound === \"number\" &&\n Number.isFinite(bound) &&\n (i === 0 || bound > (bounds[i - 1] as number)),\n )\n );\n}\n\n/**\n * Builds the metric fields of one point. The attributes of the call stay out.\n * @param def Definition of the instrument.\n * @param series Sums of the attribute set.\n * @param start Start of the interval, in Unix nanoseconds.\n * @returns The metric fields of the point.\n */\nfunction fieldsOf(def: InstrumentDef, series: Series, start: string): Record<string, unknown> {\n const point: Record<string, unknown> = {\n \"metric.name\": def.name,\n \"metric.unit\": def.unit,\n \"metric.type\": def.kind,\n [METRIC_KEYS.start]: start,\n [METRIC_KEYS.attributeKeys]: Object.keys(series.attributes),\n };\n\n if (def.kind === \"counter\") {\n point[\"metric.value\"] = series.sum;\n return point;\n }\n\n return {\n ...point,\n [METRIC_KEYS.count]: series.count,\n [METRIC_KEYS.sum]: series.sum,\n [METRIC_KEYS.min]: series.min,\n [METRIC_KEYS.max]: series.max,\n [METRIC_KEYS.bounds]: def.boundaries,\n [METRIC_KEYS.buckets]: series.buckets,\n };\n}\n\n/** Sums the values of the counter and histogram instruments for one interval. */\nexport class Meter {\n /** Instruments with a value in the current interval. */\n private readonly instruments = new Map<string, Instrument>();\n\n /** Timer of the current interval. It runs only while a value waits. */\n private timer: ReturnType<typeof setTimeout> | null = null;\n\n /** Time of the first value of the interval, in epoch milliseconds. */\n private startedAt = 0;\n\n /**\n * @param intervalMs Gives the interval length, in milliseconds.\n * @param emit Builds and sends the record of one point from the call attributes and the\n * metric fields.\n * @param diagnostics Diagnostics reporter.\n */\n constructor(\n private readonly intervalMs: () => number,\n private readonly emit: (\n name: string,\n attributes: MetricAttributes,\n fields: Record<string, unknown>,\n ) => void,\n private readonly diagnostics: Diagnostics,\n ) {}\n\n /**\n * Adds a value to the series of its attribute set. It never throws into the call of the app.\n * @param def Definition of the instrument.\n * @param value Value to add.\n * @param attributes Attribute set of the value.\n */\n record(def: InstrumentDef, value: number, attributes?: MetricAttributes): void {\n // NaN and Infinity become null in JSON. A negative add breaks the sum of a counter.\n if (!Number.isFinite(value) || (def.kind === \"counter\" && value < 0)) {\n this.diagnostics.report(\n \"record.dropped_malformed\",\n `The value of the metric ${def.name} is not valid. The library dropped it.`,\n { \"metric.name\": def.name },\n );\n return;\n }\n\n // A getter or a Proxy trap of the attributes can throw.\n this.diagnostics.guard(\n \"record.sanitize_failed\",\n `The library could not read the attributes of the metric ${def.name}.`,\n () => {\n const instrument = this.instrumentOf(def);\n if (instrument) {\n this.add(instrument, value, cleanAttributes(attributes));\n this.arm();\n }\n },\n );\n }\n\n /** Sends one point for each series of the interval. It then starts a new interval. */\n collect(): void {\n if (this.timer !== null) {\n clearTimeout(this.timer);\n this.timer = null;\n }\n\n const start = `${String(this.startedAt)}000000`;\n const instruments = [...this.instruments.values()];\n this.instruments.clear();\n\n for (const { def, series } of instruments) {\n for (const one of series.values()) {\n this.emit(def.name, one.attributes, fieldsOf(def, one, start));\n }\n }\n }\n\n /**\n * Finds the instrument of the interval. The first value of the interval sets its definition.\n * @param def Definition of the call.\n * @returns The instrument, or null when the name has another kind.\n */\n private instrumentOf(def: InstrumentDef): Instrument | null {\n const found = this.instruments.get(def.name);\n\n if (found) {\n if (found.def.kind === def.kind) {\n return found;\n }\n\n this.diagnostics.report(\n \"record.dropped_malformed\",\n `The metric ${def.name} is a counter and a histogram. The library dropped the value.`,\n { \"metric.name\": def.name },\n );\n return null;\n }\n\n // Copy before the check. A later change of the array of the app must not change the buckets.\n const copy = copyBounds(def.boundaries);\n const valid = isAscending(copy);\n if (def.kind === \"histogram\" && !valid) {\n this.diagnostics.report(\n \"config.invalid\",\n `The boundaries of the metric ${def.name} must be at most 50 finite numbers in ascending order. The library uses the default boundaries.`,\n );\n }\n\n const instrument: Instrument = {\n def: { ...def, boundaries: valid ? copy : [...METRIC_DEFAULT_BOUNDARIES] },\n series: new Map(),\n };\n this.instruments.set(def.name, instrument);\n return instrument;\n }\n\n /**\n * Adds a value to the series of an attribute set.\n * @param instrument Instrument of the value.\n * @param value Value to add.\n * @param attributes Clean attribute set.\n */\n private add(instrument: Instrument, value: number, attributes: MetricAttributes): void {\n let key = JSON.stringify(attributes);\n let series = instrument.series.get(key);\n let set = attributes;\n\n // A storm of attribute sets cannot grow the memory and the payload without a limit.\n if (!series && instrument.series.size >= METRIC_MAX_SERIES) {\n key = OVERFLOW_KEY;\n series = instrument.series.get(key);\n set = { [ATTR_METRIC_OVERFLOW]: true };\n }\n\n if (!series) {\n // A histogram has one bucket more than boundaries. The last bucket has no upper bound.\n const size = instrument.def.kind === \"histogram\" ? instrument.def.boundaries.length + 1 : 0;\n const buckets = new Array<number>(size).fill(0);\n series = { attributes: set, count: 0, sum: 0, min: value, max: value, buckets };\n instrument.series.set(key, series);\n }\n\n series.count += 1;\n series.sum += value;\n series.min = Math.min(series.min, value);\n series.max = Math.max(series.max, value);\n\n if (series.buckets.length > 0) {\n const index = instrument.def.boundaries.findIndex((bound) => value <= bound);\n series.buckets[index === -1 ? series.buckets.length - 1 : index] += 1;\n }\n }\n\n /** Starts the timer of the interval at its first value. An idle meter has no timer. */\n private arm(): void {\n if (this.timer !== null) {\n return;\n }\n\n this.startedAt = Date.now();\n this.timer = setTimeout(() => {\n this.collect();\n }, this.intervalMs());\n unrefTimer(this.timer);\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_BREADCRUMBS,\n ATTR_ERROR_DATA,\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_BYPASS_TYPES,\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 isLogLevel,\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 type { RemoteSlot } from \"./remote-sampling\";\nimport { shouldSampleInput } from \"./sampling\";\n\n/** Prefix of the error fields. An oversized error record keeps them. */\nconst ERROR_ATTR_PREFIX = \"error.\";\n\n/** Index keys that an oversized record keeps in the form that redact gave them. */\nconst REDACTABLE_INDEX_KEYS = [ATTR_PAGE_URL, ATTR_JOURNEY_ID, ATTR_JOURNEY_NAME] as const;\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 /** Slot of the sampling rules from the ingest server. */\n remote: RemoteSlot;\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/**\n * Reason a record was not built. \"malformed\" means the redact hook broke the record shape\n * or set an unknown severityText.\n */\nexport type DropReason = \"level\" | \"sampling\" | \"redact\" | \"malformed\";\n\n/** Outcome of one build call. */\nexport interface BuildResult {\n /** Completed record, or null when the builder drops it. */\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 * Fields that the library builds with a fixed size bound, for example the buckets of a point.\n * The record limits do not cut them. They override a payload key of the same name.\n */\n fixed?: Record<string, unknown>;\n /** True for a point of a counter or histogram. Sampling keeps it. */\n aggregated?: boolean;\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 * minLevel does not apply to an action or a metric.\n * @param level Target log severity level.\n * @param type Record type. Without it, the check applies minLevel.\n * @returns True if the library builds a record of this level and type.\n */\n isEnabled(level: LogLevel, type?: LogType): boolean {\n const { config } = this.deps;\n if (!config.enabled) {\n return false;\n }\n\n if (type !== undefined && LEVEL_BYPASS_TYPES.includes(type)) {\n return true;\n }\n\n // A remote rule can lower minLevel during an incident.\n const minLevel = this.deps.remote.sampling?.minLevel() ?? config.minLevel;\n\n return LEVEL_ORDER[level] >= LEVEL_ORDER[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 of the drop.\n */\n build(input: BuildInput): BuildResult {\n const { config, diagnostics, tracing, journey, sequence, limits, remote } = this.deps;\n\n if (!this.isEnabled(input.level, input.type)) {\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 aggregated: input.aggregated,\n },\n config,\n remote.sampling?.current() ?? null,\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 // A cut bucket list makes the serializer drop the point.\n Object.assign(attributes, input.fixed);\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 // A plain JavaScript hook can edit the record in place without a return value.\n let redacted: unknown;\n try {\n redacted = redact(record);\n } catch (error) {\n // Drop the record. A record that redact did not clean must not leave the page.\n diagnostics.report(\n \"record.dropped_by_redact\",\n \"The redact hook threw an error. The library dropped the record.\",\n undefined,\n error,\n );\n return { record: null, dropped: \"redact\" };\n }\n\n if (redacted === null) {\n diagnostics.count(\"record.dropped_by_redact\");\n return { record: null, dropped: \"redact\" };\n }\n\n const candidate: unknown = redacted ?? record;\n\n if (!isLogRecord(candidate)) {\n // The hook changed the record in place. The library has no intact copy.\n if (candidate === record) {\n diagnostics.report(\n \"record.dropped_malformed\",\n \"The redact hook changed the record to a shape that is not a record. The library dropped it.\",\n );\n return { record: null, dropped: \"malformed\" };\n }\n\n // A plain JavaScript hook can return a string or a Promise. The record did not pass redact.\n diagnostics.report(\n \"record.dropped_by_redact\",\n \"The redact hook returned a value that is not a record. The library dropped the record.\",\n );\n return { record: null, dropped: \"redact\" };\n } else if (!isLogLevel(candidate.severityText)) {\n // An unknown level has no severity number. The serializer cannot map it.\n diagnostics.report(\n \"record.dropped_malformed\",\n \"The redact hook set a severityText that is not a log level. The library dropped the record.\",\n );\n return { record: null, dropped: \"malformed\" };\n } else {\n if (candidate !== record) {\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(candidate.attributes, limits, diagnostics);\n record = { ...candidate, attributes: asAttributes(remeasured.value) };\n bytes = remeasured.bytes;\n // The limits must not cut the fields that the library builds. The hook cannot change them.\n Object.assign(record.attributes, input.fixed);\n }\n\n // The hook can change severityText. Keep the number in step with the text.\n record.severityNumber = SEVERITY_NUMBER[record.severityText];\n }\n }\n\n // Drop the caller attributes when their size exceeds maxRecordBytes. Keep the index keys.\n // A search cannot find a record without journey.id and trace_id. Keep the error fields,\n // then the breadcrumbs if they fit. They tell why the record exists.\n if (bytes > limits.maxRecordBytes) {\n diagnostics.report(\n \"record.truncated\",\n \"The attributes are larger than the size limit. The library dropped the caller attributes.\",\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_ATTRIBUTES_DROPPED]: true,\n [ATTR_ATTRIBUTES_BYTES]: bytes,\n };\n\n // Read these keys after redact. The hook can remove a token from page.url.\n for (const key of REDACTABLE_INDEX_KEYS) {\n if (key in record.attributes) {\n kept[key] = record.attributes[key];\n }\n }\n\n for (const [key, value] of Object.entries(record.attributes)) {\n if (key.startsWith(ERROR_ATTR_PREFIX)) {\n kept[key] = value;\n }\n }\n\n // error.data can be large. Drop it first, before the other error fields.\n let keptBytes = sanitizeWithSize(kept, limits, diagnostics).bytes;\n if (keptBytes > limits.maxRecordBytes && ATTR_ERROR_DATA in kept) {\n Reflect.deleteProperty(kept, ATTR_ERROR_DATA);\n keptBytes = sanitizeWithSize(kept, limits, diagnostics).bytes;\n }\n\n const breadcrumbs = record.attributes[ATTR_BREADCRUMBS];\n if (breadcrumbs !== undefined) {\n const crumbBytes = sanitizeWithSize(breadcrumbs, limits, diagnostics).bytes;\n if (keptBytes + crumbBytes <= limits.maxRecordBytes) {\n kept[ATTR_BREADCRUMBS] = breadcrumbs;\n }\n }\n\n // A point without its metric fields is lost.\n Object.assign(kept, input.fixed);\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 CAPTURE_NAMESPACE,\n GAP_REPORT_THROTTLE_MS,\n MAX_BREADCRUMBS,\n METRIC_NAMESPACE,\n RUNTIME_GLOBAL_KEY,\n RUNTIME_STOPPED_KEY,\n STORAGE_NAMESPACE,\n TELEMETRY_SDK_VERSION,\n} from \"../constants\";\nimport type { LogBatch } from \"../models/batch\";\nimport type { BusMessage, BusRole } from \"../models/bus\";\nimport type {\n CaptureOptions,\n IdentityStrategy,\n ObservabilityConfig,\n ResolvedConfig,\n StorageStrategy,\n} from \"../models/config\";\nimport type { LossReporter } from \"../models/drop\";\nimport type { InstrumentDef, MetricAttributes } from \"../models/metric\";\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 { DropReporter } from \"./drops\";\nimport { HoldBuffer } from \"./hold-buffer\";\nimport { JourneyEngine, JOURNEY_OPTIONS, type JourneyOptions } from \"./journey\";\nimport { OneLogger } from \"./logger\";\nimport { Meter } from \"./meter\";\nimport { RecordBuilder } from \"./record\";\nimport type { RemoteSlot } from \"./remote-sampling\";\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 longFrames: async (): Promise<CaptureClass> =>\n (await import(\"../capture/long-frames\")).LongFrameCapture,\n console: async (): Promise<CaptureClass> => (await import(\"../capture/console\")).ConsoleCapture,\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/** Config sections that the delivery stack reads one time, when it loads. */\nconst SENDER_SECTIONS = [\"batching\", \"retention\"] as const;\n\n/** Config sections that a later configure() cannot change. */\ntype StartupSection = (typeof SENDER_SECTIONS)[number] | \"limits\";\n\n/**\n * Makes a text key of the capture section. A later configure() reinstalls the capture\n * modules only when the key changes. A reinstall unpatches and patches each host function.\n * @param capture Capture section.\n * @returns The key. A function and a RegExp give a fixed text.\n */\nfunction captureKey(capture: CaptureOptions): string {\n return JSON.stringify({\n ...capture,\n webVitalsLoader: capture.webVitalsLoader !== undefined,\n ignoreUrls: capture.ignoreUrls.map(String),\n propagateTraceHeaderTo: capture.propagateTraceHeaderTo.map(String),\n });\n}\n\n/**\n * Removes the delivery settings from a configuration. A console-only runtime must not send\n * or join a bus. The runtime of the other version does both.\n * @param input Consumer configuration options.\n * @returns The options with no endpoint, no transport and bus mode \"off\".\n */\nfunction consoleOnly(input: Partial<ObservabilityConfig>): Partial<ObservabilityConfig> {\n return {\n ...input,\n endpoint: null,\n transport: undefined,\n transportOnExit: undefined,\n bus: { ...input.bus, mode: \"off\" },\n };\n}\n\n/**\n * Tests if a runtime on a global key comes from this version of the library.\n * @param runtime Runtime on the global key. A runtime before 0.9.0 has no sdkVersion.\n * @returns True if this copy can call the methods of the runtime.\n */\nfunction ownVersion(runtime: ObservabilityRuntime): boolean {\n return runtime.sdkVersion === TELEMETRY_SDK_VERSION;\n}\n\n/** Manages subsystem lifecycles, bus coordination and record delivery. */\nexport class ObservabilityRuntime {\n /**\n * Runtime of this copy of the library when another version owns the page runtime.\n * It stays off the global key.\n */\n private static local: ObservabilityRuntime | null = null;\n\n /**\n * Library version of this runtime. Another copy reads it from the global key.\n * Two versions with one runtime call methods that the other version does not have.\n */\n readonly sdkVersion: string = TELEMETRY_SDK_VERSION;\n\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 /** Slot of the remote sampling rules. The sender or the bus fills it. */\n private readonly remote: RemoteSlot = { sampling: null };\n\n /** Console sink for local developer output. */\n readonly console: ConsoleSink;\n\n /** Collects lost records into onDrop summaries. */\n private readonly drops: DropReporter;\n\n /** Sums the values of the counter and histogram instruments. */\n private readonly meter: Meter;\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 readonly pendingRecords = new HoldBuffer((record) => {\n this.dropHeld(record);\n });\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 = {\n webVitals: false,\n navigationTiming: false,\n longFrames: false,\n };\n\n /** Queue buffering records created before bus role resolution. */\n private readonly bootBuffer = new HoldBuffer((record) => {\n this.dropHeld(record);\n });\n\n /** Batch buffer staging records for microtask forwarding. */\n private forwardBuffer: LogRecord[] = [];\n\n /** True if a microtask drain of the forward buffer is pending. */\n private forwardScheduled = false;\n\n /** True if startup has decided the bus role. A sender load waits for it. */\n private roleResolved = false;\n\n /** Resolves when startup releases the boot records. flush() waits for it. init() sets it. */\n private started: Promise<void> = Promise.resolve();\n\n /** True if asynchronous initialization is complete. */\n private ready = false;\n\n /** True if 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 /** Record limits of the builder and the console. The first configure() of the app sets them. */\n private readonly limits: ResolvedConfig[\"limits\"];\n\n /** Lifetime rules of the journey engine. The first configure() of the app sets the age. */\n private readonly journeyOptions: JourneyOptions;\n\n /** False in a runtime that an early log call started. The first configure() then sets limits. */\n private tunablesLocked = true;\n\n /**\n * @param input Initial consumer configuration options.\n * @param degraded True for a console-only runtime next to another version. It installs\n * no capture.\n */\n private constructor(\n input: Partial<ObservabilityConfig>,\n private readonly degraded = false,\n ) {\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. The library loses no record.\n void this.tracing.loadOtel();\n // The startup values stay. A later configure() cannot change the limits or the journey age.\n this.limits = { ...this.config.limits };\n this.console = new ConsoleSink(this.config.console, this.diagnostics, this.limits);\n this.drops = new DropReporter(this.config, this.diagnostics);\n this.journeyOptions = { ...JOURNEY_OPTIONS, maxAgeMs: this.config.journey.maxAgeMs };\n\n this.journey = new JourneyEngine(\n this.journeyOptions,\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 remote: this.remote,\n config: this.config,\n limits: this.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 this.meter = new Meter(\n () => this.config.batching.metricFlushIntervalMs,\n (name, attributes, fields) => {\n this.emitPoint(name, attributes, fields);\n },\n this.diagnostics,\n );\n }\n\n /**\n * Adds a value to a counter or a histogram. The meter sends one point at each interval.\n * @param def Definition of the instrument.\n * @param value Value to add.\n * @param attributes Attribute set of the value.\n */\n recordMetric(def: InstrumentDef, value: number, attributes?: MetricAttributes): void {\n // Guard against a value after shutdown. Its interval timer would outlive the runtime.\n if (!this.destroyed) {\n this.meter.record(def, value, attributes);\n }\n }\n\n /**\n * Builds and emits the record of one aggregated point. The console does not print it.\n * @param name Metric name.\n * @param attributes Attributes of the call. The record limits apply to them.\n * @param fields Metric fields of the point. The record limits do not cut them.\n */\n private emitPoint(\n name: string,\n attributes: MetricAttributes,\n fields: Record<string, unknown>,\n ): void {\n const { record } = this.builder.build({\n level: \"INFO\",\n type: \"metric\",\n body: name,\n namespace: METRIC_NAMESPACE,\n payload: attributes,\n fixed: fields,\n aggregated: true,\n });\n this.emit(record);\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 runtime on the global key of this realm. Another copy of the library can own it.\n * @returns Pinned runtime instance or null.\n */\n private static pinned(): ObservabilityRuntime | null {\n return (\n ((globalThis as Record<symbol, unknown>)[RUNTIME_KEY] as ObservabilityRuntime | undefined) ??\n null\n );\n }\n\n /**\n * Returns the local runtime of this copy. Without one, it returns the pinned runtime.\n * A pinned runtime of another version gives null. A log call then starts the local runtime.\n * @returns Active runtime instance or null.\n */\n static current(): ObservabilityRuntime | null {\n const local = ObservabilityRuntime.local;\n if (local) {\n return local.destroyed ? null : local;\n }\n\n const pinned = ObservabilityRuntime.pinned();\n return pinned && ownVersion(pinned) ? pinned : null;\n }\n\n /**\n * Returns the runtime that shutdown() stopped, until the next configure().\n * A stopped runtime of another version gives null.\n * @returns Stopped runtime instance or null.\n */\n static stopped(): ObservabilityRuntime | null {\n const local = ObservabilityRuntime.local;\n if (local?.destroyed) {\n return local;\n }\n\n const stopped = (globalThis as Record<symbol, unknown>)[STOPPED_KEY] as\n ObservabilityRuntime | undefined;\n return stopped && ownVersion(stopped) ? stopped : null;\n }\n\n /**\n * Tests if 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 * @param implicit True for the default runtime that an early log call starts.\n * @returns Active runtime instance.\n */\n static configure(input: Partial<ObservabilityConfig>, implicit = false): ObservabilityRuntime {\n const local = ObservabilityRuntime.local;\n if (local && !local.destroyed) {\n // The local runtime stays console-only. React StrictMode calls configure() two times.\n local.reconfigure(consoleOnly(input));\n return local;\n }\n ObservabilityRuntime.local = null;\n\n const pinned = ObservabilityRuntime.pinned();\n if (pinned) {\n // A runtime before 0.9.0 has no sdkVersion. It is also another version.\n if (!ownVersion(pinned)) {\n return ObservabilityRuntime.startDegraded(input, pinned.sdkVersion);\n }\n\n if (!pinned.destroyed) {\n pinned.reconfigure(input);\n return pinned;\n }\n }\n\n const runtime = new ObservabilityRuntime(input);\n // The first configure() of the app sets the limits of a default runtime.\n runtime.tunablesLocked = !implicit;\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 * Starts a console-only runtime next to the runtime of another version. It sends nothing,\n * joins no bus and installs no capture. The other version keeps the page runtime.\n * @param input Consumer configuration options.\n * @param found sdkVersion of the pinned runtime. A runtime before 0.9.0 has none.\n * @returns The local runtime.\n */\n private static startDegraded(\n input: Partial<ObservabilityConfig>,\n found: unknown,\n ): ObservabilityRuntime {\n const runtime = new ObservabilityRuntime(consoleOnly(input), true);\n ObservabilityRuntime.local = runtime;\n\n const foundText = typeof found === \"string\" ? found : \"before 0.9.0\";\n runtime.diagnostics.report(\n \"runtime.version_mismatch\",\n `Another copy of the library, version ${foundText}, owns the page runtime. This copy, version ${TELEMETRY_SDK_VERSION}, runs in console-only mode and installs no capture. Load one version of the library on the page.`,\n { found: foundText, own: TELEMETRY_SDK_VERSION },\n );\n\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.keepDestination(input);\n const capturesBefore = captureKey(this.config.capture);\n const next = resolveConfig(accepted, this.diagnostics, this.config);\n this.keepStartupTunables(next);\n applyResolvedConfig(this.config, next);\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 // Reinstall only on a change. A reinstall unpatches and patches each host function.\n // A stale capture load stops at its generation check. A reinstall is safe at any time.\n if (captureKey(this.config.capture) !== capturesBefore) {\n void this.installCaptures();\n }\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 startup tunables in the next config. A part of the runtime reads each tunable\n * one time. A later change has no effect. The runtime then refuses it.\n * @param next Resolved config of a later configure() call.\n */\n private keepStartupTunables(next: ResolvedConfig): void {\n if (this.senderLoad !== undefined) {\n this.keepSections(next, SENDER_SECTIONS);\n }\n\n // An early log call starts a runtime with defaults. The first configure() of the app sets\n // the limits and the journey age of that runtime.\n if (!this.tunablesLocked) {\n this.tunablesLocked = true;\n Object.assign(this.limits, next.limits);\n this.journeyOptions.maxAgeMs = next.journey.maxAgeMs;\n return;\n }\n\n this.keepSections(next, [\"limits\"]);\n\n const { maxAgeMs } = this.config.journey;\n if (next.journey.maxAgeMs !== maxAgeMs) {\n this.diagnostics.report(\n \"config.invalid\",\n `journey.maxAgeMs cannot change after startup. It stays ${String(maxAgeMs)}.`,\n { requested: next.journey.maxAgeMs },\n );\n next.journey.maxAgeMs = maxAgeMs;\n }\n }\n\n /**\n * Refuses a change of config sections. It restores the values in force in the next config.\n * @param next Resolved config of a later configure() call.\n * @param sections Sections that cannot change.\n */\n private keepSections(next: ResolvedConfig, sections: readonly StartupSection[]): void {\n for (const section of sections) {\n if (JSON.stringify(next[section]) === JSON.stringify(this.config[section])) {\n continue;\n }\n\n this.diagnostics.report(\n \"config.invalid\",\n `${section} cannot change after startup. The values in force stay.`,\n { requested: next[section] },\n );\n Object.assign(next, { [section]: this.config[section] });\n }\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 a change that leaves the built delivery stack with no destination.\n * Without a destination, the retry engine removes each stored batch as delivered.\n * @param input Partial configuration to merge.\n * @returns Input without the refused changes.\n */\n private keepDestination(input: Partial<ObservabilityConfig>): Partial<ObservabilityConfig> {\n if (this.senderLoad === undefined) {\n return input;\n }\n\n let accepted = input;\n const addsOrRemoves =\n \"transport\" in input &&\n (input.transport === undefined) !== (this.config.transport === undefined);\n\n // The stack selects HTTP or the custom transport one time. It cannot change to the other.\n if (addsOrRemoves) {\n this.diagnostics.report(\n \"config.invalid\",\n \"You cannot add or remove transport after the delivery stack loads. The transport in force stays.\",\n );\n accepted = { ...accepted };\n delete accepted.transport;\n }\n\n const removesEndpoint = accepted.endpoint === null || accepted.endpoint === \"\";\n\n if (removesEndpoint && this.config.transport === undefined) {\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 // An undefined endpoint keeps the endpoint in force, and keeps it in ignoreUrls.\n accepted = { ...accepted, endpoint: undefined };\n }\n\n return accepted;\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 // Set before the first await. A flush() directly after configure() then waits for it.\n this.started = this.boot();\n await this.started;\n await captures;\n }\n\n /** Resolves the bus role, loads the delivery stack and releases the boot records. It never rejects. */\n private async boot(): Promise<void> {\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\n /**\n * Starts the load of the bus one time.\n * @returns Promise that resolves 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 that resolves 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 that resolves 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 remote: this.remote,\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 that resolves when the load completes, or immediately when nothing loads.\n */\n private syncSender(): Promise<void> {\n if (!this.hasDestination() || this.role() !== \"sender\") {\n return Promise.resolve();\n }\n\n return this.loadSender();\n }\n\n /**\n * Tests if the config names a destination for the records.\n * @returns True with an endpoint or a custom transport.\n */\n private hasDestination(): boolean {\n return Boolean(this.config.endpoint) || this.config.transport !== undefined;\n }\n\n /**\n * Starts the load of the delivery stack one time.\n * @returns Promise that resolves 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 onLoss: this.reportLoss,\n remote: this.remote,\n beforeExit: () => {\n this.meter.collect();\n },\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 this.drops.add(\"load_failed\", this.pendingRecords.records);\n }\n\n for (const record of this.pendingRecords.take()) {\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 // A console-only runtime next to another version patches nothing. The other version does.\n if (this.degraded) {\n return;\n }\n\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 if (settings.longFrames) {\n names.push(\"longFrames\");\n }\n // An empty list wraps nothing. Do not load the chunk for it.\n const consoleOn = Array.isArray(settings.console)\n ? settings.console.length > 0\n : settings.console;\n\n if (consoleOn) {\n names.push(\"console\");\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 recordMetric: (def, value, attributes) => {\n this.recordMetric(def, value, attributes);\n },\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 that resolves 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\n // The points of the open interval go out with the final flush.\n this.meter.collect();\n this.destroyed = true;\n\n this.uninstallCaptures();\n\n // Sender.destroy awaits a normal flush, then runs the exit flush. The records hold\n // their journey already. The journey and the bus can stop first.\n const closing = this.sender?.destroy();\n this.journey.destroy();\n // A record in the forward buffer waits for its microtask. The bus takes it before it stops.\n this.sendForwarded();\n this.bus?.destroy();\n // The delivery stack did not load before shutdown(). The held records are lost.\n this.drops.add(\"load_failed\", this.pendingRecords.take());\n await closing;\n // A load in progress destroys its own stack. shutdown() resolves only after that.\n await this.senderLoad;\n\n // A local runtime must not remove the runtime of the other version from the global key.\n if (ObservabilityRuntime.pinned() === this) {\n Reflect.deleteProperty(globalThis, RUNTIME_KEY);\n // Calls after shutdown() go to this runtime and do nothing.\n // A new default runtime drops the settings of the app.\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.bootBuffer.push(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 // Console-only mode has no destination. Count the drop. If not, no counter shows the loss.\n if (!this.senderLoad) {\n this.diagnostics.count(\"record.dropped_no_destination\");\n // After a failed load, the config has a destination but no delivery stack.\n if (this.hasDestination()) {\n this.drops.add(\"load_failed\", [record]);\n }\n return;\n }\n\n this.pendingRecords.push(record);\n }\n\n /**\n * Counts a record that a full hold buffer drops. It gives the record to the onDrop report.\n * @param record Dropped record.\n */\n private dropHeld(record: LogRecord): void {\n this.diagnostics.count(\"record.dropped_boot_buffer_full\");\n this.drops.add(\"buffer_full\", [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 this.sendForwarded();\n });\n }\n\n /** Gives the records of the forward buffer to the bus. */\n private sendForwarded(): void {\n const records = this.forwardBuffer;\n this.forwardBuffer = [];\n if (records.length > 0) {\n this.bus?.sendRecords(records);\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, this.remote.sampling?.current() ?? null)) {\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.take();\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 * Gives lost records to the onDrop report.\n * @param reason Cause of the loss.\n * @param records Lost records.\n * @param batchIds Ids of the lost batches.\n */\n private readonly reportLoss: LossReporter = (reason, records, batchIds) => {\n this.drops.add(reason, records, batchIds);\n };\n\n /**\n * Gives the evicted batches to the onDrop report. It also emits a warning record. A throttle\n * limits the warning records.\n * @param result Storage prune summary metrics.\n * @param dropped The evicted batches.\n */\n private readonly reportGap = (result: PruneResult, dropped: readonly LogBatch[]): void => {\n this.drops.add(\n result.reason,\n dropped.flatMap((batch) => batch.records),\n dropped.map((batch) => batch.id),\n );\n\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 that resolves 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 that resolves when the library sends or hands off the queued records.\n */\n async flush(): Promise<void> {\n this.meter.collect();\n\n // A record logged during startup waits in the boot buffer. Without this wait, flush() misses it.\n // After startup, do not wait. The handover of the forward buffer then stays synchronous.\n if (!this.ready) {\n await this.started;\n }\n\n if (this.role() === \"forwarder\") {\n this.sendForwarded();\n return;\n }\n\n await this.senderLoad;\n await this.sender?.flush();\n }\n}\n","// src/transport/memory-transport.ts\n//\n// Gives tests a transport that keeps each batch in memory. A test then checks the records that\n// the library sends, with no network and no fetch mock.\n\nimport { HTTP_SUCCESS_END, HTTP_SUCCESS_MIN } from \"../constants\";\nimport type { Transport, TransportRequest, TransportResponse } from \"../models/config\";\nimport type { LogRecord } from \"../models/log-record\";\n\n/** A transport that keeps each batch in memory, for tests. */\nexport interface MemoryTransport {\n /** Pass this function as `transport` to `configure()`. */\n transport: Transport;\n /**\n * Returns the records of each accepted batch, in send order.\n * @returns The accepted records.\n */\n records(): LogRecord[];\n /**\n * Returns each request, accepted or refused, in send order.\n * @returns The requests.\n */\n batches(): TransportRequest[];\n /** Forgets each batch. The answer that respondWith set stays. */\n clear(): void;\n /**\n * Sets the answer for each later batch. The default answer is 200.\n * @param status Status code to answer with, for example 413, 429 or 500.\n * @param retryAfterMs Delay to answer with, for 429 and 503.\n */\n respondWith(status: number, retryAfterMs?: number): void;\n}\n\n/**\n * Creates a transport that keeps each batch in memory. Use it in tests, with `configure()`.\n * @returns The memory transport.\n */\nexport function createMemoryTransport(): MemoryTransport {\n const sent: TransportRequest[] = [];\n const accepted: TransportRequest[] = [];\n let answer: TransportResponse = { status: HTTP_SUCCESS_MIN };\n\n return {\n transport: (request) => {\n sent.push(request);\n\n if (answer.status >= HTTP_SUCCESS_MIN && answer.status < HTTP_SUCCESS_END) {\n accepted.push(request);\n }\n\n return Promise.resolve({ ...answer });\n },\n records: () => accepted.flatMap((request) => [...request.records]),\n batches: () => [...sent],\n clear: () => {\n sent.length = 0;\n accepted.length = 0;\n },\n respondWith: (status, retryAfterMs) => {\n answer = retryAfterMs === undefined ? { status } : { status, retryAfterMs };\n },\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 { DEFAULT_METRIC_UNIT, METRIC_DEFAULT_BOUNDARIES } from \"./constants\";\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\";\nimport type {\n Counter,\n Histogram,\n HistogramOptions,\n InstrumentDef,\n InstrumentOptions,\n} from \"./models/metric\";\n\nexport { OneLogger };\nexport { createMemoryTransport, type MemoryTransport } from \"./transport/memory-transport\";\nexport type { Journey, ObservabilityConfig, OneLoggerOptions };\nexport type {\n ConsoleOptions,\n ConsoleStyles,\n ExitTransport,\n Transport,\n TransportRequest,\n TransportResponse,\n} from \"./models/config\";\nexport type { WorkerLike } from \"./bus/links\";\nexport type { DiagnosticCode, DiagnosticEvent } from \"./core/diagnostics\";\nexport type { DropSummary, LossReason } from \"./models/drop\";\nexport type { LogLevel, LogRecord, LogType, MetricType } from \"./models/log-record\";\nexport type {\n Counter,\n Histogram,\n HistogramOptions,\n InstrumentOptions,\n MetricAttributes,\n} from \"./models/metric\";\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({}, true);\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 the call gives options.\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 fatal record with causal error and breadcrumbs.\n * @param message Fatal error summary.\n * @param err Caught error instance or reason.\n * @param payload Optional contextual attributes.\n */\nexport function fatal(message: string, err?: unknown, payload?: Record<string, unknown>): void {\n root().fatal(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 * Gives a counter. The library sums its values in memory. It sends one point for each attribute\n * set at each interval. A handle stays valid across configure() and shutdown().\n * @param name Metric name.\n * @param options Unit of the values.\n * @returns The counter.\n */\nexport function counter(name: string, options: InstrumentOptions = {}): Counter {\n const def: InstrumentDef = {\n name,\n kind: \"counter\",\n unit: options.unit ?? DEFAULT_METRIC_UNIT,\n boundaries: [],\n };\n\n return {\n add: (value, attributes) => {\n requireRuntime().recordMetric(def, value, attributes);\n },\n };\n}\n\n/**\n * Gives a histogram. The library counts its values in buckets in memory. It sends one point for\n * each attribute set at each interval. A handle stays valid across configure() and shutdown().\n * @param name Metric name.\n * @param options Unit of the values and the bucket boundaries.\n * @returns The histogram.\n */\nexport function histogram(name: string, options: HistogramOptions = {}): Histogram {\n const def: InstrumentDef = {\n name,\n kind: \"histogram\",\n unit: options.unit ?? DEFAULT_METRIC_UNIT,\n boundaries: options.boundaries ?? METRIC_DEFAULT_BOUNDARIES,\n };\n\n return {\n record: (value, attributes) => {\n requireRuntime().recordMetric(def, value, attributes);\n },\n };\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 that resolves 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 that resolves 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 that resolves when shutdown completes.\n */\nexport async function shutdown(): Promise<void> {\n await ObservabilityRuntime.current()?.destroy();\n}\n"],"mappings":";;;;;;;;;;;AAYA,SAASyF,EAAQ,GAA2B;CAC1C,OAAO,KAAK,OAAO,YAAY,IAAI,IAAIC,KAAajC,EAAkB,IAAIA;AAC5E;AAUA,SAASkC,EACP,GACA,GACA,GACA,GACA,GACM;CACN,EAAO,UAAU,GAAGC,EAAM,YAAYC,GAAU,MAAM,aAAa;EACjE;EACA,GAAGC;CACL,CAAC;AACH;AAUA,SAASC,GACP,GACA,GACA,GACA,GACA,GACM;CAEN,IAAMF,IAAWJ,EAAQC,CAAS;CAMlC,AALAM,EAAO,MAAM,GAAGJ,EAAM,UAAUK,GAAO;EACrC,sBAAsBJ;EACtB,QAAQ;EACR,GAAGC;CACL,CAAC,GACDH,EAAOK,GAAQJ,GAAOC,GAAU,WAAWC,CAAU;AACvD;AAUA,SAAgB9F,GACd,GACA,GACA,GACA,GACG;CACH,IAAM0F,IAAY,YAAY,IAAI;CAClC,IAAI;EACF,IAAMS,IAASC,EAAG;EAElB,OADAT,EAAOK,GAAQJ,GAAOH,EAAQC,CAAS,GAAG,WAAWI,CAAU,GACxDK;CACT,SAASF,GAAO;EAGd,MADAF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