@utk09/ui-observability 0.9.3 → 0.9.5

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 (227) hide show
  1. package/CHANGELOG.md +90 -0
  2. package/README.md +199 -96
  3. package/dist/batch-BQFtb3i5.cjs +2 -0
  4. package/dist/batch-BQFtb3i5.cjs.map +1 -0
  5. package/dist/{batch-DDgxg16_.js → batch-BUJh-1jZ.js} +6 -4
  6. package/dist/batch-BUJh-1jZ.js.map +1 -0
  7. package/dist/bus/bus.d.ts +76 -2
  8. package/dist/bus/links.d.ts +9 -2
  9. package/dist/bus/validation.d.ts +7 -0
  10. package/dist/bus-BW6N-pY8.cjs +2 -0
  11. package/dist/bus-BW6N-pY8.cjs.map +1 -0
  12. package/dist/bus-DeOPHWaD.js +647 -0
  13. package/dist/bus-DeOPHWaD.js.map +1 -0
  14. package/dist/capture/network.d.ts +1 -0
  15. package/dist/capture/storm.d.ts +2 -1
  16. package/dist/capture/types.d.ts +5 -0
  17. package/dist/capture/web-socket.d.ts +40 -0
  18. package/dist/{console-BSusX_M-.cjs → console-Ce6heqZZ.cjs} +2 -2
  19. package/dist/console-Ce6heqZZ.cjs.map +1 -0
  20. package/dist/{console-Dv5GfaNn.js → console-DbAZYJuy.js} +4 -4
  21. package/dist/console-DbAZYJuy.js.map +1 -0
  22. package/dist/constants-CN7GE1Lt.js +246 -0
  23. package/dist/constants-CN7GE1Lt.js.map +1 -0
  24. package/dist/constants-CW-MlHdY.cjs +2 -0
  25. package/dist/constants-CW-MlHdY.cjs.map +1 -0
  26. package/dist/constants.d.ts +63 -11
  27. package/dist/context-storage-BjzeBSxH.cjs +2 -0
  28. package/dist/context-storage-BjzeBSxH.cjs.map +1 -0
  29. package/dist/context-storage-DxZf4Gfh.js +52 -0
  30. package/dist/context-storage-DxZf4Gfh.js.map +1 -0
  31. package/dist/core/breadcrumbs.d.ts +10 -3
  32. package/dist/core/context.d.ts +2 -0
  33. package/dist/core/diagnostics.d.ts +11 -3
  34. package/dist/core/journey.d.ts +7 -0
  35. package/dist/core/meter.d.ts +25 -2
  36. package/dist/core/pipeline.d.ts +41 -6
  37. package/dist/core/record.d.ts +42 -9
  38. package/dist/core/remote-sampling.d.ts +7 -3
  39. package/dist/core/runtime.d.ts +153 -6
  40. package/dist/core/sampling.d.ts +35 -2
  41. package/dist/core/sender.d.ts +43 -1
  42. package/dist/core/spans.d.ts +34 -0
  43. package/dist/deadline-5_PecIl5.js +26 -0
  44. package/dist/deadline-5_PecIl5.js.map +1 -0
  45. package/dist/deadline-XSnm95pg.cjs +2 -0
  46. package/dist/deadline-XSnm95pg.cjs.map +1 -0
  47. package/dist/emergency-queue-BYUyDHGD.js +69 -0
  48. package/dist/emergency-queue-BYUyDHGD.js.map +1 -0
  49. package/dist/emergency-queue-Cs1hrjsC.cjs +2 -0
  50. package/dist/emergency-queue-Cs1hrjsC.cjs.map +1 -0
  51. package/dist/{errors-DCZWcHkd.js → errors-BhC7HTSt.js} +8 -9
  52. package/dist/errors-BhC7HTSt.js.map +1 -0
  53. package/dist/errors-CgY633cG.cjs +3 -0
  54. package/dist/errors-CgY633cG.cjs.map +1 -0
  55. package/dist/factory-C5TujXlU.js +280 -0
  56. package/dist/factory-C5TujXlU.js.map +1 -0
  57. package/dist/factory-CNj4DH3n.cjs +2 -0
  58. package/dist/factory-CNj4DH3n.cjs.map +1 -0
  59. package/dist/fixed-window-CtaFHanJ.js +12 -0
  60. package/dist/fixed-window-CtaFHanJ.js.map +1 -0
  61. package/dist/fixed-window-CvESpFYV.cjs +2 -0
  62. package/dist/fixed-window-CvESpFYV.cjs.map +1 -0
  63. package/dist/identity-8vKkyAWm.js +103 -0
  64. package/dist/identity-8vKkyAWm.js.map +1 -0
  65. package/dist/identity-Da9TkuKd.cjs +2 -0
  66. package/dist/identity-Da9TkuKd.cjs.map +1 -0
  67. package/dist/index.cjs +1 -1
  68. package/dist/index.cjs.map +1 -1
  69. package/dist/index.d.ts +66 -6
  70. package/dist/index.js +1253 -595
  71. package/dist/index.js.map +1 -1
  72. package/dist/indexeddb-storage-BTfIFRHF.cjs +2 -0
  73. package/dist/indexeddb-storage-BTfIFRHF.cjs.map +1 -0
  74. package/dist/{indexeddb-storage-T9YIYVYC.js → indexeddb-storage-CCA1LvtO.js} +45 -30
  75. package/dist/indexeddb-storage-CCA1LvtO.js.map +1 -0
  76. package/dist/{interactions-BLH_tX87.js → interactions-BUDLxbv1.js} +16 -12
  77. package/dist/interactions-BUDLxbv1.js.map +1 -0
  78. package/dist/interactions-NHbLKrqe.cjs +2 -0
  79. package/dist/interactions-NHbLKrqe.cjs.map +1 -0
  80. package/dist/{journey-yALMEWF7.js → journey-BUJ4WJxP.js} +37 -34
  81. package/dist/journey-BUJ4WJxP.js.map +1 -0
  82. package/dist/journey-B_tTnvac.cjs +2 -0
  83. package/dist/journey-B_tTnvac.cjs.map +1 -0
  84. package/dist/keys-BHhw_0Wh.cjs +2 -0
  85. package/dist/keys-BHhw_0Wh.cjs.map +1 -0
  86. package/dist/keys-D5r_GH9q.js +17 -0
  87. package/dist/keys-D5r_GH9q.js.map +1 -0
  88. package/dist/{library-request-CQD4HUiP.js → library-request-BKOcaKtQ.js} +3 -3
  89. package/dist/{library-request-CQD4HUiP.js.map → library-request-BKOcaKtQ.js.map} +1 -1
  90. package/dist/{library-request-BcAxuwsf.cjs → library-request-BaZOi4eg.cjs} +2 -2
  91. package/dist/{library-request-BcAxuwsf.cjs.map → library-request-BaZOi4eg.cjs.map} +1 -1
  92. package/dist/{long-frames-D4Bm3Zkz.cjs → long-frames-CF3qiSAX.cjs} +2 -2
  93. package/dist/long-frames-CF3qiSAX.cjs.map +1 -0
  94. package/dist/{long-frames-DD_Um9_4.js → long-frames-DI5ypfAF.js} +5 -5
  95. package/dist/long-frames-DI5ypfAF.js.map +1 -0
  96. package/dist/models/batch.d.ts +4 -0
  97. package/dist/models/bus.d.ts +32 -9
  98. package/dist/models/config.d.ts +401 -12
  99. package/dist/models/drop.d.ts +1 -1
  100. package/dist/models/health.d.ts +27 -0
  101. package/dist/models/log-record.d.ts +1 -1
  102. package/dist/models/plugin.d.ts +47 -0
  103. package/dist/models/stats.d.ts +11 -0
  104. package/dist/models/storage.d.ts +13 -0
  105. package/dist/network-CF8UO5PK.cjs +2 -0
  106. package/dist/network-CF8UO5PK.cjs.map +1 -0
  107. package/dist/{network--GoE7_Or.js → network-DdzXDI3J.js} +47 -31
  108. package/dist/network-DdzXDI3J.js.map +1 -0
  109. package/dist/openfin-BwEN0uj4.js.map +1 -1
  110. package/dist/openfin-DtH2f7zX.cjs.map +1 -1
  111. package/dist/{platform-GaM6h7XM.js → platform-Bw1btWCT.js} +21 -10
  112. package/dist/platform-Bw1btWCT.js.map +1 -0
  113. package/dist/platform-DBSKTvFn.cjs +2 -0
  114. package/dist/platform-DBSKTvFn.cjs.map +1 -0
  115. package/dist/remote-rules-DIcC5vVC.js +91 -0
  116. package/dist/remote-rules-DIcC5vVC.js.map +1 -0
  117. package/dist/remote-rules-DpFmOef2.cjs +2 -0
  118. package/dist/remote-rules-DpFmOef2.cjs.map +1 -0
  119. package/dist/sampling-BVjspJWu.cjs +2 -0
  120. package/dist/sampling-BVjspJWu.cjs.map +1 -0
  121. package/dist/sampling-Cm3WhI0a.js +76 -0
  122. package/dist/sampling-Cm3WhI0a.js.map +1 -0
  123. package/dist/{sanitize-DP0xDPrt.js → sanitize-C-ahCFsG.js} +2 -2
  124. package/dist/{sanitize-DP0xDPrt.js.map → sanitize-C-ahCFsG.js.map} +1 -1
  125. package/dist/{sanitize--_e4oOPX.cjs → sanitize-DHucKGdi.cjs} +2 -2
  126. package/dist/{sanitize--_e4oOPX.cjs.map → sanitize-DHucKGdi.cjs.map} +1 -1
  127. package/dist/sender-D3fRCR8d.cjs +3 -0
  128. package/dist/sender-D3fRCR8d.cjs.map +1 -0
  129. package/dist/sender-DUUmSglb.js +1163 -0
  130. package/dist/sender-DUUmSglb.js.map +1 -0
  131. package/dist/storage/context-storage.d.ts +89 -0
  132. package/dist/storage/emergency-queue.d.ts +9 -1
  133. package/dist/storage/factory.d.ts +7 -1
  134. package/dist/storage/idb-driver.d.ts +13 -0
  135. package/dist/storage/indexeddb-storage.d.ts +13 -0
  136. package/dist/storage/local-storage.d.ts +21 -1
  137. package/dist/storage/memory-storage.d.ts +13 -0
  138. package/dist/storage-BA9RqRO-.cjs +2 -0
  139. package/dist/storage-BA9RqRO-.cjs.map +1 -0
  140. package/dist/storage-w7Tslvlq.js +17 -0
  141. package/dist/storage-w7Tslvlq.js.map +1 -0
  142. package/dist/storm-CNZjsw4T.cjs +2 -0
  143. package/dist/storm-CNZjsw4T.cjs.map +1 -0
  144. package/dist/storm-Daq2jGHU.js +10 -0
  145. package/dist/storm-Daq2jGHU.js.map +1 -0
  146. package/dist/transport/exit-flush.d.ts +6 -0
  147. package/dist/transport/http-transport.d.ts +2 -1
  148. package/dist/transport/retry-engine.d.ts +7 -2
  149. package/dist/transport/serializers/otlp-traces.d.ts +3 -0
  150. package/dist/transport/serializers/select.d.ts +8 -5
  151. package/dist/transport/status-transport.d.ts +24 -0
  152. package/dist/types-BR9t_w28.js +8 -0
  153. package/dist/types-BR9t_w28.js.map +1 -0
  154. package/dist/types-C7WNpnG1.cjs +2 -0
  155. package/dist/types-C7WNpnG1.cjs.map +1 -0
  156. package/dist/utils/fixed-window.d.ts +9 -0
  157. package/dist/utils/identity.d.ts +20 -2
  158. package/dist/utils/lock.d.ts +8 -0
  159. package/dist/utils/openfin.d.ts +1 -1
  160. package/dist/utils/platform.d.ts +10 -0
  161. package/dist/utils/tracing.d.ts +82 -4
  162. package/dist/web-socket-BacvKOvD.cjs +2 -0
  163. package/dist/web-socket-BacvKOvD.cjs.map +1 -0
  164. package/dist/web-socket-CpsD8WAa.js +105 -0
  165. package/dist/web-socket-CpsD8WAa.js.map +1 -0
  166. package/package.json +1 -1
  167. package/dist/batch-D5qvsMQ_.cjs +0 -2
  168. package/dist/batch-D5qvsMQ_.cjs.map +0 -1
  169. package/dist/batch-DDgxg16_.js.map +0 -1
  170. package/dist/bus-C6RwKzPW.js +0 -478
  171. package/dist/bus-C6RwKzPW.js.map +0 -1
  172. package/dist/bus-WPVDFw2y.cjs +0 -2
  173. package/dist/bus-WPVDFw2y.cjs.map +0 -1
  174. package/dist/console-BSusX_M-.cjs.map +0 -1
  175. package/dist/console-Dv5GfaNn.js.map +0 -1
  176. package/dist/constants-Cb92egPS.cjs +0 -2
  177. package/dist/constants-Cb92egPS.cjs.map +0 -1
  178. package/dist/constants-DhH6VI5a.js +0 -144
  179. package/dist/constants-DhH6VI5a.js.map +0 -1
  180. package/dist/deadline-CUrH0Hd8.cjs +0 -2
  181. package/dist/deadline-CUrH0Hd8.cjs.map +0 -1
  182. package/dist/deadline-DeqXEliN.js +0 -31
  183. package/dist/deadline-DeqXEliN.js.map +0 -1
  184. package/dist/errors-DCZWcHkd.js.map +0 -1
  185. package/dist/errors-ERu-su8m.cjs +0 -3
  186. package/dist/errors-ERu-su8m.cjs.map +0 -1
  187. package/dist/fixed-window-BR0bu32Y.cjs +0 -2
  188. package/dist/fixed-window-BR0bu32Y.cjs.map +0 -1
  189. package/dist/fixed-window-Re7jIRJH.js +0 -9
  190. package/dist/fixed-window-Re7jIRJH.js.map +0 -1
  191. package/dist/identity-C1WLItSl.cjs +0 -2
  192. package/dist/identity-C1WLItSl.cjs.map +0 -1
  193. package/dist/identity-Di-QXGCC.js +0 -88
  194. package/dist/identity-Di-QXGCC.js.map +0 -1
  195. package/dist/indexeddb-storage-DX18p39D.cjs +0 -2
  196. package/dist/indexeddb-storage-DX18p39D.cjs.map +0 -1
  197. package/dist/indexeddb-storage-T9YIYVYC.js.map +0 -1
  198. package/dist/interactions-BLH_tX87.js.map +0 -1
  199. package/dist/interactions-_hfOerfC.cjs +0 -2
  200. package/dist/interactions-_hfOerfC.cjs.map +0 -1
  201. package/dist/journey-BRUj0hqD.cjs +0 -2
  202. package/dist/journey-BRUj0hqD.cjs.map +0 -1
  203. package/dist/journey-yALMEWF7.js.map +0 -1
  204. package/dist/long-frames-D4Bm3Zkz.cjs.map +0 -1
  205. package/dist/long-frames-DD_Um9_4.js.map +0 -1
  206. package/dist/network--GoE7_Or.js.map +0 -1
  207. package/dist/network-DcuS2H1P.cjs +0 -2
  208. package/dist/network-DcuS2H1P.cjs.map +0 -1
  209. package/dist/platform-GaM6h7XM.js.map +0 -1
  210. package/dist/platform-kIL5AZB7.cjs +0 -2
  211. package/dist/platform-kIL5AZB7.cjs.map +0 -1
  212. package/dist/remote-rules-6ePq8CrI.js +0 -84
  213. package/dist/remote-rules-6ePq8CrI.js.map +0 -1
  214. package/dist/remote-rules-CI3gbRCL.cjs +0 -2
  215. package/dist/remote-rules-CI3gbRCL.cjs.map +0 -1
  216. package/dist/sampling-C-M8p3FK.cjs +0 -2
  217. package/dist/sampling-C-M8p3FK.cjs.map +0 -1
  218. package/dist/sampling-Ud_WiuU9.js +0 -65
  219. package/dist/sampling-Ud_WiuU9.js.map +0 -1
  220. package/dist/sender-BESHz6my.cjs +0 -3
  221. package/dist/sender-BESHz6my.cjs.map +0 -1
  222. package/dist/sender-BUBWLn5i.js +0 -1244
  223. package/dist/sender-BUBWLn5i.js.map +0 -1
  224. package/dist/storm-DhHGHhOc.cjs +0 -2
  225. package/dist/storm-DhHGHhOc.cjs.map +0 -1
  226. package/dist/storm-OD5J6Ylm.js +0 -10
  227. package/dist/storm-OD5J6Ylm.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_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,GAAKC,GAAQJ,GAAOF,GAAWO,GAAOH,CAAU,GAC1CG;CACR;AACF;AAUA,eAAsBhG,GACpB,GACA,GACA,GACA,GACY;CACZ,IAAMyF,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;;;AC1FA,IAAMK,KAAwC,CAAC9F,GAAmB0C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AO7R,CAAG;AACrC;AAQA,SAAgB8R,GAAa,GAAc,GAAyC;CAClF,OAAOpB,EAAe,CAAC,CAAC,QAAQ,MAAM7P,GAAMF,CAAO;AACrD;AAGA,SAAgBoR,KAAmB;CACjC,EAAe,CAAC,CAAC,QAAQ,IAAI;AAC/B;AAMA,SAAgBC,KAAiC;CAC/C,OAAOtB,EAAe,CAAC,CAAC,QAAQ,QAAQ;AAC1C;AAMA,SAAgBuB,KAAsC;CACpD,OAAOvB,EAAe,CAAC,CAAC,QAAQ,SAAS;AAC3C;AAOA,SAAgBwB,GAAa,GAAwB;CACnD,OAAOxB,EAAe,CAAC,CAAC,QAAQ,MAAMyB,GAAO,UAAU,EAAI;AAC7D;AAMA,SAAgBC,GAAe,GAA0B;CACvD,EAAe,CAAC,CAAC,eAAerC,CAAM;AACxC;AAGA,SAAgBsC,KAAmB;CACjC,EAAe,CAAC,CAAC,QAAQ,OAAO,UAAU;AAC5C;AAMA,SAAgBC,KAA0C;CACxD,OAAO5B,EAAe,CAAC,CAAC,QAAQ,QAAQ;AAC1C;AAMA,SAAgB6B,KAAuB;CACrC,OAAO7B,EAAe,CAAC,CAAC,MAAM;AAChC;AAOA,SAAgB8B,KAAiC;CAC/C,OAAO9B,EAAe,CAAC,CAAC,WAAW;AACrC;AAMA,SAAgB+B,KAAgD;CAC9D,OAAO/B,EAAe,CAAC,CAAC,YAAY,SAAS;AAC/C;AAMA,eAAsBgC,KAA0B;CAC9C,MAAMjE,EAAqB,QAAQ,CAAC,EAAE,QAAQ;AAChD"}
1
+ {"version":3,"file":"index.js","names":["timeSync","timeAsync","timeSync","timeAsync","RUNTIME_STOPPED_KEY","RESOURCE_CONTEXT_ID","BEACON_LIMIT_BYTES","METRIC_KEYS","UNKNOWN_SERVICE_NAME","RECORD_LIMITS","RESOURCE_SERVICE_NAME","RESOURCE_HOST_PLATFORM","RESOURCE_TAB_ID","RESOURCE_SERVICE_VERSION","DEFAULT_CONFIG","CONSOLE_DEFAULT_LEVEL","CONSOLE_DEFAULT_STYLES","RUNTIME_GLOBAL_KEY","DEFAULT_METRIC_UNIT","METRIC_DEFAULT_BOUNDARIES","UNDEFAULTED_SECTION_KEYS","RESOURCE_OPENFIN_NAME","DURATION_PRECISION","RESOURCE_DEPLOYMENT_ENVIRONMENT","RESOURCE_OPENFIN_UUID","RESOURCE_TELEMETRY_SDK_NAME","RESOURCE_TELEMETRY_SDK_LANGUAGE","RESOURCE_TELEMETRY_SDK_VERSION","TELEMETRY_SDK_NAME","ATTR_ATTRIBUTES_DROPPED","SEVERITY_NUMBER","TRACE_MAX_AGE_MS","ATTR_JOURNEY_ID","ATTR_LOG_SEQ","ATTR_LOG_TYPE","TELEMETRY_SDK_LANGUAGE","LIBRARY_LOG_PREFIX","ATTR_SANITIZE_FAILED","ATTR_ATTRIBUTES_BYTES","CONFIG_SECTIONS","CAPTURE_NAMESPACE","ATTR_JOURNEY_NAME","STORAGE_NAMESPACE","ATTR_PAGE_URL","LEVEL_ORDER","ATTR_BREADCRUMBS","SPAN_KEYS","ATTR_METRIC_OVERFLOW","LEVEL_BYPASS_TYPES","RESOURCE_SESSION_ID","ATTR_APP_NAMESPACE","ATTR_ERROR_DATA","SERIALIZER_NAME_OTLP","ATTR_JOURNEY_PARENT_ID","TELEMETRY_SDK_VERSION","UNDEFAULTED_CONFIG_KEYS","METRIC_NAMESPACE","TRACE_NAMESPACE","TRACEPARENT_HEADER","DIAGNOSTIC_THROTTLE_MS","RESOURCE_BROWSER_USER_AGENT","isDataField","isErrorLike","ERROR_OWN_KEYS","shouldSample","isLogRecord","sampleKey","nowUnixNano","levelFor","shouldSampleInput","isLogLevel","isObject","unrefTimer","isLibraryConsole","truncate","sanitize","runAsLibraryConsole","sanitizeWithSize","persistTabId","newId","SessionTouch","randomHex","memoryStores","resolveIdentity","BROWSER_STORES","runAsLibraryRequest","recordedUrl","detectPlatform","currentUrl","isActionRecord","attributeOf","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","input","hooks","keepsCrumb","protectedCrumb","dropped","safe","record","crumb","ships","asPayload","asError","shown","clean","OVERFLOW_KEY","RECORD_KEYS","cleanAttributes","copyBounds","bounds","limit","i","isAscending","bound","fieldsOf","point","def","start","series","makeCounter","makeHistogram","Meter","intervalMs","emit","policy","instrument","instruments","one","found","valid","set","size","buckets","index","METHOD","ConsoleSink","settings","limits","prefix","method","details","styles","Sequence","TRACE_ID_PATTERN","SPAN_ID_PATTERN","NON_ZERO","isUsableSpanContext","context","newTraceId","newSpanId","mintAmbient","traceparent","traceId","spanId","traceFlags","toTraceContext","ambient","TraceEngine","maxAgeMs","load","spans","otel","span","spanContext","old","next","carrier","\"traceparent\"","fromOtel","ctx","kept","flags","client","BreadcrumbBuffer","capacity","recent","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","DURATION_RANGE","COUNT_RANGE","POSITIVE_RANGE","POLICY_RULES","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","resolveChoice","fallback","match","accepted","entry","resolveBoolean","resolveNonNegative","resolveInteger","min","max","range","resolveCacheLimit","previous","resolveRanges","given","keys","ranges","section","base","toLevel","upper","resolveLevel","resolveMinLevels","levels","raw","resolveList","entries","accept","toProcessor","toPlugin","toStringEntry","toPattern","toConsoleMethod","toOrigin","origin","toTarget","isStringRecord","resolveHeaders","isSerializer","resolveSerializer","requested","CONSOLE_STYLE_KEYS","validStyles","resolveConsoleLevel","resolveConsole","resolveSampling","resolveBus","resolveJourney","resolveRetention","resolveCaptureConsole","resolveCapture","capture","resolveInteractions","ignore","ignoreSelector","actionAttribute","SIGNAL_OFF","resolveSignalEndpoint","url","serializer","resolvePolicy","rules","choice","resolved","resolveConfig","policies","merged","rate","maxRate","rates","ns","r","reportUnknownKeys","sectionKeys","applyResolvedConfig","target","ContextStore","Diagnostics","handler","throttleMs","consoleFallback","total","code","by","now","event","addCapped","list","DropReporter","config","records","batchIds","summary","id","journey","summaries","onDrop","HoldBuffer","action","oldest","ERROR_ATTR_PREFIX","REDACTABLE_INDEX_KEYS","HOOK_STAGES","FIXED_KEYS","fixedOf","asAttributes","RecordBuilder","deps","minLevel","forConsole","traceCtx","tracing","activeJourney","sampled","remote","seq","sequence","pageUrl","bytes","fromContext","fromProvider","fromScope","fromPayload","stages","hook","outcome","keptBytes","breadcrumbs","crumbBytes","redact","current","stage","remeasured","fixed","changed","candidate","provider","platform","identity","US_PER_MS","ROOT_NAMES","unixNano","ms","rootSpan","ended","spanFields","CAPTURE_LOADERS","pluginIds","lastPluginId","pluginId","plugin","RUNTIME_KEY","STOPPED_KEY","SENDER_SECTIONS","DELIVERY_RESET","ROUTING_KEYS","captureKey","consoleOnly","sends","ownVersion","ObservabilityRuntime","locked","mismatch","keeps","fields","bus","reply","local","pinned","stopped","implicit","foundText","sameConfig","capturesBefore","probe","refused","sections","built","captures","journeyReady","Bus","rotating","shared","sender","Sender","storage","generation","names","classes","WebSocketCapture","CaptureModule","plugins","metric","cancelled","detach","worker","frame","closing","redacted","buffered","processors","batch","fresh","sessionId","pending","timeoutMs","update","nextId","delivery","before","oldUrls","newUrls","held","retired","live","stored","issues","scope","backing","createStorage","storageName","storageLimits","store","ContextStorage","clearEmergencyContext","a","b","seen","ak","bk","createMemoryTransport","sent","answer","request","retryAfterMs","loggers","requireRuntime","clearPersistedLogs","configure","trimLoggerCache","setConfigurationLocked","rotateSecurityContext","getHealth","getLogger","root","trace","debug","info","warn","err","fatal","logAction","logEvent","logMetric","counter","histogram","timeSync","timeAsync","addBreadcrumb","setContext","setContextMap","removeContext","startJourney","endJourney","currentJourney","getJourneyToken","adoptJourney","token","registerWorker","registerFrame","startTrace","getTraceHeaders","flush","getQueueDepth","getStats","newSession","getDiagnosticCounters","shutdown"],"sources":["../src/utils/timer.ts","../src/core/logger.ts","../src/core/meter.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/spans.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()) return;\n if (runtime.isRotating()) {\n runtime.diagnostics.count(\"record.dropped_during_rotation\");\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, this.namespace, type)) {\n if (this.mirrors(runtime, level)) {\n this.print(runtime, level, body, payload, undefined, null);\n }\n\n return;\n }\n\n const input = {\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 const { record, dropped } = runtime.builder.build(input);\n const hooks = Boolean(runtime.config.redact) || runtime.config.processors.length > 0;\n // Run the hooks on a sampled-out record only if a breadcrumb keeps its message.\n const keepsCrumb = type !== \"metric\" && runtime.config.capturePolicy.breadcrumbs > 0;\n const protectedCrumb =\n dropped === \"sampling\" && hooks && keepsCrumb\n ? runtime.builder.build(input, true)\n : undefined;\n const safe = record ?? protectedCrumb?.record ?? null;\n const crumb = safe ? safe.body : dropped === \"sampling\" && !hooks ? body : undefined;\n if (keepsCrumb && 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 this.print(runtime, level, body, payload, undefined, safe, protectedCrumb?.dropped ?? 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()) return;\n if (runtime.isRotating()) {\n runtime.diagnostics.count(\"record.dropped_during_rotation\");\n return;\n }\n\n const ships = runtime.builder.isEnabled(level, this.namespace);\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 && runtime.config.processors.length === 0) {\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 a hook or the shape check dropped prints no line. Its text did not pass redact.\n if (dropped === \"processor\" || dropped === \"redact\" || dropped === \"malformed\") {\n return;\n }\n\n if (!runtime.config.enabled || !runtime.console.accepts(level)) return;\n // Use the record builder without the delivery level and sampling checks. Do not process\n // a record again if a hook refused it. Do not send this record or add it as a breadcrumb.\n const clean = runtime.builder.build(\n {\n level,\n type: this.levelType,\n body: message,\n namespace: this.namespace,\n scoped: this.options.scopedContext,\n payload: {\n ...copyPayload(payload, runtime.diagnostics),\n ...(error\n ? {\n \"error.type\": error.name,\n \"error.message\": error.message,\n \"error.stack_trace\": error.stack,\n }\n : {}),\n },\n },\n true,\n ).record;\n if (clean) runtime.console.write(this.namespace, level, clean.body, clean.attributes);\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/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 DEFAULT_METRIC_UNIT,\n METRIC_DEFAULT_BOUNDARIES,\n METRIC_KEYS,\n} from \"../constants\";\nimport type {\n Counter,\n Histogram,\n HistogramOptions,\n InstrumentDef,\n InstrumentOptions,\n MetricAttributes,\n} 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, limit: number): 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 = limit === 0 ? bounds.length : Math.min(bounds.length, limit + 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, limit: number): bounds is number[] {\n return (\n Array.isArray(bounds) &&\n (limit === 0 || bounds.length <= limit) &&\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/** Adds a value to an instrument of the runtime. */\nexport type RecordMetric = (\n def: InstrumentDef,\n value: number,\n attributes?: MetricAttributes,\n) => void;\n\n/**\n * Makes a counter handle.\n * @param name Metric name.\n * @param options Unit of the values.\n * @param record Adds a value to the instrument.\n * @returns The counter.\n */\nexport function makeCounter(\n name: string,\n options: InstrumentOptions,\n record: RecordMetric,\n): 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 record(def, value, attributes);\n },\n };\n}\n\n/**\n * Makes a histogram handle.\n * @param name Metric name.\n * @param options Unit of the values and the bucket boundaries.\n * @param record Adds a value to the instrument.\n * @returns The histogram.\n */\nexport function makeHistogram(\n name: string,\n options: HistogramOptions,\n record: RecordMetric,\n): 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 record(def, value, attributes);\n },\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 private readonly policy = { maxSeries: 100, maxInstruments: 1000, maxHistogramBoundaries: 50 },\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 if (this.policy.maxInstruments && this.instruments.size >= this.policy.maxInstruments) {\n this.diagnostics.count(\"record.dropped_by_ceiling\");\n return null;\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, this.policy.maxHistogramBoundaries);\n const valid = isAscending(copy, this.policy.maxHistogramBoundaries);\n if (def.kind === \"histogram\" && !valid) {\n this.diagnostics.report(\n \"config.invalid\",\n `The boundaries of the metric ${def.name} must meet metrics.maxHistogramBoundaries and contain 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 && this.policy.maxSeries > 0 && instrument.series.size >= this.policy.maxSeries) {\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/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/** Ambient trace that ended. Its root span covers it. */\nexport interface EndedTrace {\n /** Trace ID. */\n traceId: string;\n /** Span ID of the root span. */\n spanId: string;\n /** Cause of the start of the trace. */\n reason: RotateReason;\n /** Start time in epoch milliseconds. */\n startedAt: number;\n /** End time in epoch milliseconds. */\n endedAt: number;\n}\n\n/** Client span that a traceparent header names. */\nexport interface ClientSpan {\n /** Trace ID. */\n traceId: string;\n /** Span ID of the client span. */\n spanId: string;\n /** Span ID of the root span of the trace. */\n parentSpanId: string;\n}\n\n/** Headers of one request, and the client span that they name. */\nexport interface RequestTrace {\n /** Header map containing traceparent. */\n headers: Record<string, string>;\n /** Client span of the request. It is undefined when the library records no span for it. */\n span?: ClientSpan;\n}\n\n/** Span decisions of the runtime. */\nexport interface SpanHooks {\n /**\n * Tests if the library records spans.\n * @returns True with a traces endpoint.\n */\n enabled(): boolean;\n /**\n * Tests if sampling keeps the spans of a trace.\n * @param traceId Trace ID.\n * @returns True if the library sends the spans of the trace.\n */\n keeps(traceId: string): boolean;\n /**\n * Receives an ambient trace that ended.\n * @param ended The trace.\n */\n onEnd(ended: EndedTrace): void;\n}\n\n/** Internal trace context tracking creation timestamp for expiration. */\ninterface AmbientTrace extends TraceContext {\n /** Creation timestamp in epoch milliseconds. */\n startedAt: number;\n /** Cause of the start of the trace. */\n reason: RotateReason;\n /** True after the root span ended. It ends one time. */\n ended: boolean;\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 * @param reason Cause of the start of the trace.\n * @returns Initialized AmbientTrace object.\n */\nfunction mintAmbient(reason: RotateReason): AmbientTrace {\n return {\n traceId: newTraceId(),\n spanId: newSpanId(),\n traceFlags: TRACE_FLAGS_SAMPLED,\n startedAt: Date.now(),\n reason,\n ended: false,\n };\n}\n\n/**\n * Formats a W3C traceparent value.\n * @param traceId Trace ID.\n * @param spanId Span ID of the caller.\n * @param traceFlags Trace flags.\n * @returns The traceparent value.\n */\nfunction traceparent(traceId: string, spanId: string, traceFlags: number): string {\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 = (traceFlags & TRACE_FLAGS_MASK).toString(16).padStart(2, \"0\");\n return `${TRACEPARENT_VERSION}-${traceId}-${spanId}-${flags}`;\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(\"start\");\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 * @param spans Span decisions of the runtime. Without them, the library records no span.\n */\n constructor(\n private readonly diagnostics: Diagnostics,\n private readonly maxAgeMs = TRACE_MAX_AGE_MS,\n private readonly load?: OtelLoader,\n private readonly spans?: SpanHooks,\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 return this.activeSpanContext() ?? this.ambientContext();\n }\n\n /**\n * Reads the ambient trace. It rotates a trace that is too old.\n * @returns Ambient TraceContext.\n */\n private ambientContext(): TraceContext {\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. It ends the\n * root span of the old trace.\n * @param reason Event reason triggering the rotation.\n * @returns Newly created TraceContext.\n */\n rotate(reason: RotateReason): TraceContext {\n // Set the new trace first. A record that a hook makes inside onEnd then joins the new trace.\n // If not, that record rotates again, and its trace gets no root span.\n const old = this.ambient;\n this.ambient = mintAmbient(reason);\n const next = toTraceContext(this.ambient);\n this.finish(old);\n return next;\n }\n\n /**\n * Ends the root span of the ambient trace one time. Later records can still use the trace.\n * The exit flush calls it. A closing document has no later rotation.\n */\n end(): void {\n this.finish(this.ambient);\n }\n\n /**\n * Ends the root span of a trace one time.\n * @param ambient Trace to end.\n */\n private finish(ambient: AmbientTrace): void {\n if (ambient.ended) {\n return;\n }\n\n ambient.ended = true;\n this.spans?.onEnd({\n traceId: ambient.traceId,\n spanId: ambient.spanId,\n reason: ambient.reason,\n startedAt: ambient.startedAt,\n endedAt: Date.now(),\n });\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 return this.trace(false).headers;\n }\n\n /**\n * Generates the headers of one request of the network capture. With spans on, the traceparent\n * names a new client span of the ambient trace.\n * @returns The headers, and the client span that the library records.\n */\n request(): RequestTrace {\n return this.trace(true);\n }\n\n /**\n * Generates the trace headers.\n * @param client True to name a new client span in the traceparent.\n * @returns The headers, and the client span that the library records.\n */\n private trace(client: boolean): RequestTrace {\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 return { headers: carrier };\n }\n\n // The peer keeps its own spans. The library records no span for a trace of the peer.\n const fromOtel = this.activeSpanContext();\n const ctx = fromOtel ?? this.ambientContext();\n const spans = fromOtel ? undefined : this.spans;\n\n if (!spans?.enabled()) {\n carrier[TRACEPARENT_HEADER] = traceparent(ctx.traceId, ctx.spanId, ctx.traceFlags);\n return { headers: carrier };\n }\n\n // Clear the sampled flag of a trace that sampling drops. A downstream service then drops\n // its spans too. The whole trace stays or goes.\n const kept = spans.keeps(ctx.traceId);\n const flags = kept ? ctx.traceFlags : ctx.traceFlags & ~TRACE_FLAGS_SAMPLED;\n const spanId = client ? newSpanId() : ctx.spanId;\n carrier[TRACEPARENT_HEADER] = traceparent(ctx.traceId, spanId, flags);\n\n if (!client || !kept) {\n return { headers: carrier };\n }\n\n return { headers: carrier, span: { traceId: ctx.traceId, spanId, parentSpanId: ctx.spanId } };\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\" | \"custom\";\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 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 = capacity === 0 ? 0 : Math.max(capacity, BREADCRUMB_MIN_CAPACITY);\n this.buffer = new Array<Breadcrumb | undefined>(this.capacity);\n }\n\n /**\n * Changes the capacity and keeps the most recent breadcrumbs that fit.\n * @param capacity New capacity. Set 0 to remove and disable stored breadcrumbs.\n */\n resize(capacity: number): void {\n const recent = this.snapshot().slice(-capacity);\n this.capacity = capacity;\n this.buffer = new Array<Breadcrumb | undefined>(capacity);\n this.pointer = 0;\n this.filled = false;\n if (capacity) for (const crumb of recent) this.push(crumb);\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 if (this.capacity === 0) return;\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 /** Removes all breadcrumbs. A new session must not carry the trail of the previous user. */\n clear(): void {\n this.buffer.fill(undefined);\n this.pointer = 0;\n this.filled = false;\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 ACTION_ATTRIBUTE_DEFAULT,\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 { CapturePlugin } from \"../models/plugin\";\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/** Range of a duration. The maximum is the largest delay that a browser timer accepts. */\nconst DURATION_RANGE: Range = [0, 2_147_483_647];\n\n/** Range of a count. Zero turns the limit off. */\nconst COUNT_RANGE: Range = [0, Number.MAX_SAFE_INTEGER];\n\n/** Range of a count that must be at least 1. */\nconst POSITIVE_RANGE: Range = [1, Number.MAX_SAFE_INTEGER];\n\n/** Keys of a policy section that have number values. */\ntype NumberKeys<T> = { [K in keyof T]: T[K] extends number ? K : never }[keyof T];\n\n/** Policy sections that resolvePolicy() checks. */\ntype PolicySection =\n | \"capturePolicy\"\n | \"metadata\"\n | \"persistence\"\n | \"diagnostics\"\n | \"correlation\"\n | \"metrics\"\n | \"buffering\"\n | \"delivery\";\n\n/** Rules of one policy section. Each number key must have a range. */\ninterface PolicyRules<T> {\n /** Accepted range of each number key. */\n ranges: Record<NumberKeys<T>, Range>;\n /** Accepted values of each choice key. */\n choices?: Partial<Record<keyof T, readonly string[]>>;\n}\n\n/** Rules of each policy section. A new number key without a range does not compile. */\nconst POLICY_RULES: { [K in PolicySection]: PolicyRules<ResolvedConfig[K]> } = {\n capturePolicy: {\n ranges: {\n // A larger capacity gives an invalid array allocation.\n breadcrumbs: [0, 1_000_000],\n errorDedupeMs: DURATION_RANGE,\n maxErrorSignatures: COUNT_RANGE,\n errorsPerWindow: COUNT_RANGE,\n consolePerWindow: COUNT_RANGE,\n longFramesPerWindow: COUNT_RANGE,\n webSocketPerWindow: COUNT_RANGE,\n windowMs: DURATION_RANGE,\n errorCeiling: COUNT_RANGE,\n },\n },\n metadata: { ranges: {} },\n persistence: { ranges: {} },\n diagnostics: { ranges: { throttleMs: DURATION_RANGE } },\n correlation: {\n ranges: {\n sessionIdleMs: DURATION_RANGE,\n sessionTouchMs: DURATION_RANGE,\n traceMaxAgeMs: DURATION_RANGE,\n },\n },\n metrics: {\n ranges: {\n maxSeries: COUNT_RANGE,\n maxInstruments: COUNT_RANGE,\n maxHistogramBoundaries: COUNT_RANGE,\n },\n },\n buffering: {\n ranges: { maxPendingRecords: COUNT_RANGE, maxPendingBytes: COUNT_RANGE },\n choices: { overflow: [\"drop-oldest\", \"drop-newest\", \"persist\"] },\n },\n delivery: {\n ranges: {\n requestTimeoutMs: [1, DURATION_RANGE[1]],\n maxConcurrentRequests: POSITIVE_RANGE,\n retryBaseDelayMs: DURATION_RANGE,\n retryMaxDelayMs: DURATION_RANGE,\n retryIdleDelayMs: DURATION_RANGE,\n batchesPerDrain: POSITIVE_RANGE,\n },\n },\n};\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 \"navigation\",\n \"webVitals\",\n \"longFrames\",\n \"fullUrls\",\n \"webSocket\",\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 * Checks the logger cache limit. An invalid value keeps the limit in force, including null.\n * @param value Limit that the app supplied.\n * @param previous Limit in force. Null permits a cache with no limit.\n * @param diagnostics Diagnostics reporter.\n * @returns The valid limit, or the limit in force.\n */\nfunction resolveCacheLimit(\n value: unknown,\n previous: number | null,\n diagnostics: Diagnostics,\n): number | null {\n if (value === undefined) return previous;\n if (value === null) return null;\n if (typeof value === \"number\" && Number.isSafeInteger(value) && value >= 0) return value;\n reportInvalid(\n diagnostics,\n \"loggerCache.maxEntries\",\n \"a nonnegative safe integer or null\",\n value,\n String(previous),\n );\n return previous;\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 the minLevels option. It keeps each valid prefix and reports each other entry. A new map\n * replaces the map in force.\n * @param value Value that the consumer passed.\n * @param fallback Levels in force.\n * @param diagnostics Diagnostics reporter.\n * @returns The level for each namespace prefix.\n */\nfunction resolveMinLevels(\n value: unknown,\n fallback: Record<string, LogLevel>,\n diagnostics: Diagnostics,\n): Record<string, LogLevel> {\n if (value === undefined) {\n return fallback;\n }\n\n if (!isObject(value)) {\n reportInvalid(\n diagnostics,\n \"minLevels\",\n \"an object of level names\",\n value,\n \"the value in force\",\n );\n return fallback;\n }\n\n const levels: [string, LogLevel][] = [];\n for (const [prefix, raw] of Object.entries(value)) {\n const level = toLevel(raw);\n if (prefix !== \"\" && level !== undefined) {\n levels.push([prefix, level]);\n } else {\n reportInvalid(diagnostics, `minLevels[\"${prefix}\"]`, LEVEL_EXPECTED, raw, \"minLevel for it\");\n }\n }\n\n // fromEntries makes own properties. A \"__proto__\" key then cannot change the prototype.\n return Object.fromEntries(levels);\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 function entry.\n * @param entry List entry.\n * @returns The entry, or undefined.\n */\nfunction toProcessor(entry: unknown): ResolvedConfig[\"processors\"][number] | undefined {\n return typeof entry === \"function\" ? (entry as ResolvedConfig[\"processors\"][number]) : undefined;\n}\n\n/**\n * Accepts a capture plugin entry.\n * @param entry List entry.\n * @returns The entry, or undefined.\n */\nfunction toPlugin(entry: unknown): CapturePlugin | undefined {\n const valid =\n isObject(entry) &&\n typeof entry.name === \"string\" &&\n entry.name !== \"\" &&\n typeof entry.install === \"function\" &&\n typeof entry.uninstall === \"function\";\n\n return valid ? (entry as unknown as CapturePlugin) : undefined;\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 maxTrackedSources: resolveInteger(\n \"bus.maxTrackedSources\",\n given.maxTrackedSources,\n [0, Number.MAX_SAFE_INTEGER],\n base.maxTrackedSources,\n diagnostics,\n ),\n sourcePolicy: resolveChoice(\n \"bus.sourcePolicy\",\n given.sourcePolicy,\n [\"registered\", \"trusted-origin\"],\n base.sourcePolicy,\n diagnostics,\n ),\n validation: resolveChoice(\n \"bus.validation\",\n given.validation,\n [\"strict\", \"envelope\"],\n base.validation,\n diagnostics,\n ),\n maxMessageBytes: resolveInteger(\n \"bus.maxMessageBytes\",\n given.maxMessageBytes,\n [0, Number.MAX_SAFE_INTEGER],\n base.maxMessageBytes,\n diagnostics,\n ),\n maxRecordsPerMessage: resolveInteger(\n \"bus.maxRecordsPerMessage\",\n given.maxRecordsPerMessage,\n [0, Number.MAX_SAFE_INTEGER],\n base.maxRecordsPerMessage,\n diagnostics,\n ),\n maxMessagesPerSecond: resolveInteger(\n \"bus.maxMessagesPerSecond\",\n given.maxMessagesPerSecond,\n [0, Number.MAX_SAFE_INTEGER],\n base.maxMessagesPerSecond,\n diagnostics,\n ),\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 interactions: resolveInteractions(given.interactions, base.interactions, diagnostics),\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 plugins: resolveList(\n \"capture.plugins\",\n given.plugins,\n base.plugins,\n \"a list of objects with a name, install() and uninstall()\",\n toPlugin,\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 * Checks the click settings. An invalid value does not turn on text or selector capture.\n * @param value Settings that the app supplied.\n * @param base Settings in force.\n * @param diagnostics Diagnostics reporter.\n * @returns The valid settings, with invalid values replaced by the values in force.\n */\nfunction resolveInteractions(\n value: CaptureOptions[\"interactions\"] | undefined,\n base: CaptureOptions[\"interactions\"],\n diagnostics: Diagnostics,\n): CaptureOptions[\"interactions\"] {\n if (value === undefined) return base;\n if (typeof value === \"boolean\") return value;\n if (!isObject(value)) {\n diagnostics.report(\n \"config.invalid\",\n \"capture.interactions must be a boolean or an options object.\",\n );\n return base;\n }\n const previous = typeof base === \"object\" ? base : {};\n const ignore = value.ignoreSelector;\n let ignoreSelector = ignore === undefined ? previous.ignoreSelector : ignore;\n if (ignoreSelector !== undefined && ignoreSelector !== null) {\n try {\n if (typeof ignoreSelector !== \"string\") throw new Error(\"Invalid selector\");\n if (typeof document !== \"undefined\") document.createElement(\"div\").matches(ignoreSelector);\n } catch {\n diagnostics.report(\n \"config.invalid\",\n \"capture.interactions.ignoreSelector must be a valid CSS selector or null.\",\n );\n ignoreSelector = previous.ignoreSelector;\n }\n }\n // The name goes into a CSS attribute selector. Letters, digits, hyphens and underscores need no\n // escape. Another name keeps the attribute in force.\n let actionAttribute = previous.actionAttribute ?? ACTION_ATTRIBUTE_DEFAULT;\n if (value.actionAttribute !== undefined) {\n if (typeof value.actionAttribute === \"string\" && /^[a-z][\\w-]*$/i.test(value.actionAttribute)) {\n actionAttribute = value.actionAttribute;\n } else {\n reportInvalid(\n diagnostics,\n \"capture.interactions.actionAttribute\",\n \"an attribute name of letters, digits, hyphens and underscores\",\n value.actionAttribute,\n `\"${actionAttribute}\"`,\n );\n }\n }\n return {\n actionAttribute,\n text: resolveBoolean(\n \"capture.interactions.text\",\n value.text,\n previous.text ?? false,\n diagnostics,\n ),\n selector: resolveBoolean(\n \"capture.interactions.selector\",\n value.selector,\n previous.selector ?? false,\n diagnostics,\n ),\n ignoreSelector:\n typeof ignoreSelector === \"string\" || ignoreSelector === null ? ignoreSelector : undefined,\n maxTextChars: resolveInteger(\n \"capture.interactions.maxTextChars\",\n value.maxTextChars,\n [0, Number.MAX_SAFE_INTEGER],\n previous.maxTextChars ?? 50,\n diagnostics,\n ),\n };\n}\n\n/** Result of a signal endpoint that is off, for each key. */\nconst SIGNAL_OFF = {\n metricsEndpoint: \"The library sends metric records as log records.\",\n tracesEndpoint: \"The library sends no span.\",\n} as const;\n\n/**\n * Validates the metrics or traces endpoint. Only the OTLP serializer has these formats.\n * @param key Config key.\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 turn the endpoint off.\n */\nfunction resolveSignalEndpoint(\n key: keyof typeof SIGNAL_OFF,\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 `${key} 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, key, \"a URL string\", value, \"the value in force\");\n }\n\n // A custom or ECS serializer cannot encode a metrics or traces request.\n if (url !== \"\" && serializer !== SERIALIZER_NAME_OTLP) {\n diagnostics.report(\n \"config.invalid\",\n `${key} needs serializer \"${SERIALIZER_NAME_OTLP}\". ${SIGNAL_OFF[key]}`,\n );\n return \"\";\n }\n\n return url;\n}\n\n/** Rules in the form that resolvePolicy() reads. POLICY_RULES holds the typed form. */\ninterface PolicyLookup {\n /** Accepted range of each number key. */\n ranges: Partial<Record<string, Range>>;\n /** Accepted values of each choice key. */\n choices?: Partial<Record<string, readonly string[]>>;\n}\n\n/**\n * Checks one policy section. An invalid value keeps the value in force.\n * @param name Section name for diagnostic messages.\n * @param input Settings that the app supplied.\n * @param base Settings in force.\n * @param rules Ranges and choices of the section.\n * @param diagnostics Diagnostics reporter.\n * @returns The valid section.\n */\nfunction resolvePolicy<T extends object>(\n name: string,\n input: Partial<T> | undefined,\n base: T,\n rules: PolicyLookup,\n diagnostics: Diagnostics,\n): T {\n const next = { ...base };\n for (const key of Object.keys(base) as (keyof T & string)[]) {\n const value: unknown = input?.[key];\n const fallback: unknown = base[key];\n const range = rules.ranges[key];\n const choice = rules.choices?.[key];\n let resolved: unknown = fallback;\n if (typeof fallback === \"number\" && range) {\n resolved = resolveInteger(`${name}.${key}`, value, range, fallback, diagnostics);\n } else if (typeof fallback === \"boolean\") {\n resolved = resolveBoolean(`${name}.${key}`, value, fallback, diagnostics);\n } else if (choice) {\n resolved = resolveChoice(`${name}.${key}`, value, choice, String(fallback), diagnostics);\n } else if (value === undefined || typeof value === \"string\") {\n resolved = value ?? fallback;\n } else {\n reportInvalid(diagnostics, `${name}.${key}`, \"a string\", value, String(fallback));\n }\n Object.assign(next, { [key]: resolved });\n }\n return next;\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 // Check each policy section with its own rules. The key order of POLICY_RULES sets the report order.\n const policies = Object.fromEntries(\n (Object.keys(POLICY_RULES) as PolicySection[]).map((key) => [\n key,\n resolvePolicy(key, input[key], base[key], POLICY_RULES[key], diagnostics),\n ]),\n ) as Pick<ResolvedConfig, PolicySection>;\n const merged: ResolvedConfig = {\n ...base,\n ...input,\n ...policies,\n\n lockConfiguration: resolveBoolean(\n \"lockConfiguration\",\n input.lockConfiguration,\n base.lockConfiguration,\n diagnostics,\n ),\n loggerCache: {\n maxEntries: resolveCacheLimit(\n input.loggerCache?.maxEntries,\n base.loggerCache.maxEntries,\n diagnostics,\n ),\n },\n securityContext: {\n id:\n typeof input.securityContext?.id === \"string\"\n ? input.securityContext.id || base.securityContext.id\n : base.securityContext.id,\n isolation: resolveBoolean(\n \"securityContext.isolation\",\n input.securityContext?.isolation,\n base.securityContext.isolation,\n diagnostics,\n ),\n },\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 minLevels: resolveMinLevels(input.minLevels, base.minLevels, diagnostics),\n processors: resolveList(\n \"processors\",\n input.processors,\n base.processors,\n \"a list of functions\",\n toProcessor,\n diagnostics,\n ),\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 for (const key of [\"metricsEndpoint\", \"tracesEndpoint\"] as const) {\n merged[key] = resolveSignalEndpoint(key, input[key], base[key], merged.serializer, 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.contextProvider !== undefined && typeof merged.contextProvider !== \"function\") {\n diagnostics.report(\n \"config.invalid\",\n \"contextProvider must be a function. The library ignores the value.\",\n );\n merged.contextProvider = base.contextProvider;\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 for (const key of [\"metricsEndpoint\", \"tracesEndpoint\"] as const) {\n if (merged[key] !== \"\" && merged.endpoint === null && !merged.transport) {\n diagnostics.report(\n \"config.invalid\",\n `${key} needs endpoint or transport. The library sends nothing to ${key}.`,\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 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) =>\n url !== previous?.endpoint &&\n url !== previous?.metricsEndpoint &&\n url !== previous?.tracesEndpoint,\n );\n for (const url of [merged.endpoint, merged.metricsEndpoint, merged.tracesEndpoint]) {\n if (url && !merged.capture.ignoreUrls.includes(url)) {\n merged.capture.ignoreUrls = [...merged.capture.ignoreUrls, url];\n }\n }\n\n if (merged.delivery.retryMaxDelayMs < merged.delivery.retryBaseDelayMs) {\n diagnostics.report(\n \"config.invalid\",\n \"delivery.retryMaxDelayMs must be at least retryBaseDelayMs.\",\n );\n merged.delivery.retryBaseDelayMs = base.delivery.retryBaseDelayMs;\n merged.delivery.retryMaxDelayMs = base.delivery.retryMaxDelayMs;\n }\n if (\n merged.capture.urlTransform !== undefined &&\n typeof merged.capture.urlTransform !== \"function\"\n ) {\n diagnostics.report(\"config.invalid\", \"capture.urlTransform must be a function.\");\n merged.capture.urlTransform = base.capture.urlTransform;\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 /** Removes all ambient context attributes. */\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.locked\"\n | \"security.rotated\"\n | \"security.context_mismatch\"\n | \"record.dropped_during_rotation\"\n | \"bus.rejected_message\"\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_processor\"\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 * @param consoleFallback True to print a fixed warning if the diagnostic handler throws.\n */\n constructor(\n private handler?: DiagnosticHandler,\n private throttleMs = DIAGNOSTIC_THROTTLE_MS,\n private consoleFallback = false,\n ) {}\n\n /**\n * Changes the report interval and the console fallback rule.\n * @param throttleMs Minimum wait between reports of one code, in milliseconds.\n * @param consoleFallback True to print a fixed warning if the handler throws.\n */\n setPolicy(throttleMs: number, consoleFallback: boolean): void {\n this.throttleMs = throttleMs;\n this.consoleFallback = consoleFallback;\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 (this.consoleFallback && 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(`${LIBRARY_LOG_PREFIX} The onDiagnostic handler threw an error.`);\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/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 METRIC_KEYS,\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 SPAN_KEYS,\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 { isObject } from \"../utils/guards\";\nimport type { Identity } from \"../utils/identity\";\nimport { currentUrl, type PlatformMetadata, recordedUrl } from \"../utils/platform\";\nimport { type SanitizeLimits, sanitizeWithSize, truncate } from \"../utils/sanitize\";\nimport type { Sequence } from \"../utils/sequence\";\nimport type { TraceContext, 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 { levelFor, 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 a processor or the redact hook broke the\n * record shape or set an unknown severityText.\n */\nexport type DropReason = \"level\" | \"sampling\" | \"processor\" | \"redact\" | \"malformed\";\n\n/** Consumer hook that changes or drops a record. */\ntype RecordHook = (record: LogRecord) => LogRecord | null;\n\n/** Stage of a consumer hook. */\ntype HookStage = \"processor\" | \"redact\";\n\n/** Message subject and drop code of each hook stage. */\nconst HOOK_STAGES = {\n processor: { label: \"A processor\", code: \"record.dropped_by_processor\" },\n redact: { label: \"The redact hook\", code: \"record.dropped_by_redact\" },\n} as const;\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 /** Trace IDs of a span. Without them, the builder reads the active trace. */\n trace?: TraceContext;\n}\n\n/** Keys of the fields that the library builds for a metric point or a span. */\nconst FIXED_KEYS: readonly string[] = [\n \"metric.name\",\n \"metric.unit\",\n \"metric.type\",\n \"metric.value\",\n ...Object.values(METRIC_KEYS),\n ...Object.values(SPAN_KEYS),\n];\n\n/**\n * Reads the fields that the library built in another context. A hook of the sender cannot change\n * them, and the limits cannot cut them.\n * @param attributes Attributes of a forwarded record.\n * @returns The fields that the record has.\n */\nfunction fixedOf(attributes: Record<string, unknown>): Record<string, unknown> {\n return Object.fromEntries(\n FIXED_KEYS.filter((key) => key in attributes).map((key) => [key, attributes[key]]),\n );\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 the minimum level of the namespace.\n * The minimum level does not apply to an action or a metric.\n * @param level Target log severity level.\n * @param namespace Logger namespace. `minLevels` can set its level.\n * @param type Record type. Without it, the check applies the minimum level.\n * @returns True if the library builds a record of this level and type.\n */\n isEnabled(level: LogLevel, namespace: string, 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 the level during an incident.\n const minLevel =\n this.deps.remote.sampling?.minLevelFor(namespace) ?? levelFor(namespace, config);\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 * @param forConsole True to skip delivery sampling and level checks. Privacy hooks still run.\n * @returns The record, or null with the reason of the drop.\n */\n build(input: BuildInput, forConsole = false): BuildResult {\n const { config, diagnostics, tracing, journey, sequence, limits, remote } = this.deps;\n\n if (!forConsole && !this.isEnabled(input.level, input.namespace, input.type)) {\n diagnostics.count(\"record.dropped_by_level\");\n return { record: null, dropped: \"level\" };\n }\n\n const traceCtx = input.trace ?? tracing.resolve();\n const activeJourney = journey.current();\n\n // Sample delivery records before the attribute walk. A record for the console or a\n // breadcrumb skips this check. The privacy hooks process that record, but do not send it.\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 (!forConsole && !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.metadata.pageUrl\n ? recordedUrl(url, config.capture.fullUrls, config.capture.urlTransform, diagnostics)\n : \"\";\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 fromProvider = sanitizeWithSize(this.provided(), limits, diagnostics);\n const fromScope = sanitizeWithSize(input.scoped ?? {}, limits, diagnostics);\n const fromPayload = sanitizeWithSize(input.payload ?? {}, limits, diagnostics);\n bytes = fromContext.bytes + fromProvider.bytes + fromScope.bytes + fromPayload.bytes;\n\n // Merge in increasing precedence. The provider overrides the context. Scope overrides the\n // provider. Payload overrides scope.\n attributes = {\n ...asAttributes(fromContext.value),\n ...asAttributes(fromProvider.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 // The processors run first. redact is the last privacy gate.\n const stages = config.processors.map((hook): [RecordHook, HookStage] => [hook, \"processor\"]);\n if (config.redact) {\n stages.push([config.redact, \"redact\"]);\n }\n\n if (stages.length > 0) {\n const outcome = this.applyHooks(record, stages, input.fixed);\n if (typeof outcome === \"string\") {\n return { record: null, dropped: outcome };\n }\n\n ({ record, bytes } = outcome);\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 * Runs the redact hook on a record from another context. A child context without redact\n * forwards raw records. The sender is the last privacy gate.\n * @param record Forwarded record.\n * @returns The record to deliver, or null when the hook drops it.\n */\n redactForwarded(record: LogRecord): LogRecord | null {\n const { redact } = this.deps.config;\n if (!redact) {\n return record;\n }\n\n const stages: [RecordHook, HookStage][] = [[redact, \"redact\"]];\n const outcome = this.applyHooks(record, stages, fixedOf(record.attributes));\n return typeof outcome === \"string\" ? null : outcome.record;\n }\n\n /**\n * Runs the hooks in order. Then it sanitizes and measures the attributes again.\n * @param record Built record.\n * @param stages Hooks and their stages.\n * @param fixed Fields that the library builds. The hooks cannot change them.\n * @returns The record and the size of its attributes, or the reason of the drop.\n */\n private applyHooks(\n record: LogRecord,\n stages: readonly [RecordHook, HookStage][],\n fixed: Record<string, unknown> | undefined,\n ): { record: LogRecord; bytes: number } | DropReason {\n let current = record;\n\n for (const [hook, stage] of stages) {\n const outcome = this.runHook(hook, stage, current);\n if (typeof outcome === \"string\") {\n return outcome;\n }\n current = outcome;\n }\n\n // A hook can change the attributes in place or replace them. A cycle, a hostile getter or a\n // BigInt from a hook throws at serialization. The transport then loses the batch.\n const { diagnostics, limits } = this.deps;\n const remeasured = sanitizeWithSize(current.attributes, limits, diagnostics);\n const attributes = asAttributes(remeasured.value);\n // The limits must not cut the fields that the library builds.\n Object.assign(attributes, fixed);\n\n return { record: { ...current, attributes }, bytes: remeasured.bytes };\n }\n\n /**\n * Runs one consumer hook on a record. A processor and the redact hook have the same contract.\n * @param hook Processor or redact hook.\n * @param stage Stage of the hook.\n * @param record Record before the hook.\n * @returns The record after the hook, or the reason of the drop.\n */\n private runHook(hook: RecordHook, stage: HookStage, record: LogRecord): LogRecord | DropReason {\n const { diagnostics } = this.deps;\n const { label, code } = HOOK_STAGES[stage];\n\n // A plain JavaScript hook can edit the record in place without a return value.\n let changed: unknown;\n try {\n changed = hook(record);\n } catch (error) {\n // Drop the record. A record that the hook did not clean must not leave the page.\n diagnostics.report(\n code,\n `${label} threw an error. The library dropped the record.`,\n undefined,\n error,\n );\n return stage;\n }\n\n if (changed === null) {\n diagnostics.count(code);\n return stage;\n }\n\n const candidate: unknown = changed ?? 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 `${label} changed the record to a shape that is not a record. The library dropped it.`,\n );\n return \"malformed\";\n }\n\n // A plain JavaScript hook can return a string or a Promise. The record did not pass the hook.\n diagnostics.report(\n code,\n `${label} returned a value that is not a record. The library dropped the record.`,\n );\n return stage;\n }\n\n 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 `${label} set a severityText that is not a log level. The library dropped the record.`,\n );\n return \"malformed\";\n }\n\n // The hook can change severityText. Keep the number in step with the text.\n return { ...candidate, severityNumber: SEVERITY_NUMBER[candidate.severityText] };\n }\n\n /**\n * Calls the contextProvider of the config. A provider that throws or gives a value that is not\n * an object adds nothing. The record is still built. undefined means no attributes.\n * @returns The attributes from the provider, or an empty object.\n */\n private provided(): unknown {\n const provider = this.deps.config.contextProvider;\n if (!provider) {\n return {};\n }\n\n const { diagnostics } = this.deps;\n const value = diagnostics.guard(\n \"handler.threw\",\n \"The contextProvider threw an error. The record has no attributes from it.\",\n () => {\n const given: unknown = provider();\n if (given === undefined) {\n return {};\n }\n\n // A promise is an object. Its fields are not attributes.\n return isObject(given) && typeof given.then !== \"function\" ? given : null;\n },\n );\n\n if (value === null) {\n diagnostics.report(\n \"config.invalid\",\n \"contextProvider must return an object of attributes. The library ignores the value.\",\n );\n }\n\n return value ?? {};\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 ...(config.metadata.userAgent ? { [RESOURCE_BROWSER_USER_AGENT]: platform.userAgent } : {}),\n // Omits undefined OpenFin properties from resource attributes.\n ...(!config.metadata.openfin || platform.openfinUuid === undefined\n ? {}\n : { [RESOURCE_OPENFIN_UUID]: platform.openfinUuid }),\n ...(!config.metadata.openfin || platform.openfinName === undefined\n ? {}\n : { [RESOURCE_OPENFIN_NAME]: platform.openfinName }),\n };\n return this.resourceCache;\n }\n}\n","// src/core/spans.ts\n//\n// Builds the span data of a root span and the span fields of a span record. The runtime builds\n// each span as a record with the type \"span\". The traces serializer reads the span fields.\n\nimport { SPAN_KEYS } from \"../constants\";\nimport type { EndedTrace, RotateReason } from \"../utils/tracing\";\n\n/** Microseconds in one millisecond. */\nconst US_PER_MS = 1000;\n\n/** Name of the root span for each cause of the start of a trace. */\nconst ROOT_NAMES: Record<RotateReason, string> = {\n start: \"ui.start\",\n interaction: \"ui.interaction\",\n navigation: \"ui.navigation\",\n explicit: \"ui.trace\",\n maxAge: \"ui.trace\",\n};\n\n/** One span that the runtime records. */\nexport interface SpanData {\n /** Span name. */\n name: string;\n /** \"internal\" for a root span, \"client\" for a request. */\n kind: \"internal\" | \"client\";\n /** Trace ID. */\n traceId: string;\n /** Span ID. */\n spanId: string;\n /** Span ID of the parent, or \"\" for a root span. */\n parentSpanId: string;\n /** Start time in epoch milliseconds. */\n startMs: number;\n /** End time in epoch milliseconds. */\n endMs: number;\n /** True for a failed operation. */\n error: boolean;\n /** Attributes of the span. */\n attributes: Record<string, unknown>;\n}\n\n/**\n * Converts epoch milliseconds to nanoseconds, as a decimal string. It keeps microseconds.\n * @param ms Epoch time in milliseconds. It can have a fraction.\n * @returns Epoch time in nanoseconds.\n */\nfunction unixNano(ms: number): string {\n return `${String(Math.round(ms * US_PER_MS))}000`;\n}\n\n/**\n * Builds the root span of an ambient trace that ended.\n * @param ended The trace.\n * @returns The span data.\n */\nexport function rootSpan(ended: EndedTrace): SpanData {\n return {\n name: ROOT_NAMES[ended.reason],\n kind: \"internal\",\n traceId: ended.traceId,\n spanId: ended.spanId,\n parentSpanId: \"\",\n startMs: ended.startedAt,\n endMs: ended.endedAt,\n error: false,\n attributes: {},\n };\n}\n\n/**\n * Builds the span fields of a span record. The record limits do not cut them.\n * @param span The span data.\n * @returns The fields.\n */\nexport function spanFields(span: SpanData): Record<string, unknown> {\n return {\n [SPAN_KEYS.kind]: span.kind,\n [SPAN_KEYS.parentId]: span.parentSpanId,\n [SPAN_KEYS.start]: unixNano(span.startMs),\n [SPAN_KEYS.end]: unixNano(span.endMs),\n [SPAN_KEYS.status]: span.error ? \"error\" : \"unset\",\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 METRIC_NAMESPACE,\n RUNTIME_GLOBAL_KEY,\n RUNTIME_STOPPED_KEY,\n STORAGE_NAMESPACE,\n TELEMETRY_SDK_VERSION,\n TRACE_FLAGS_SAMPLED,\n TRACE_NAMESPACE,\n} from \"../constants\";\nimport type { LogBatch } from \"../models/batch\";\nimport type { BusMessage, BusRole } from \"../models/bus\";\nimport type { FrameOptions, SourceOptions } from \"../models/bus\";\nimport type {\n CaptureOptions,\n IdentityStrategy,\n ObservabilityConfig,\n ResolvedConfig,\n StorageStrategy,\n SecurityContextUpdate,\n SecurityContextRotationOptions,\n} from \"../models/config\";\nimport type { LossReporter } from \"../models/drop\";\nimport type { InstrumentDef, MetricAttributes } from \"../models/metric\";\nimport type { CapturePlugin, PluginContext } from \"../models/plugin\";\nimport { isLogRecord, type LogRecord } from \"../models/log-record\";\nimport type { DeliveryStats } from \"../models/stats\";\nimport type { ObservabilityHealth } from \"../models/health\";\nimport type { PruneResult, StorageAdapter } from \"../models/storage\";\nimport { ConsoleSink } from \"../utils/console\";\nimport { isObject } from \"../utils/guards\";\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 { runAsLibraryRequest } from \"../utils/library-request\";\nimport { detectPlatform, type PlatformMetadata } from \"../utils/platform\";\nimport { sanitize, truncate } from \"../utils/sanitize\";\nimport { Sequence } from \"../utils/sequence\";\nimport { TraceEngine } from \"../utils/tracing\";\nimport { type Breadcrumb, 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 { makeCounter, makeHistogram, Meter, type RecordMetric } from \"./meter\";\nimport { RecordBuilder } from \"./record\";\nimport type { RemoteSlot } from \"./remote-sampling\";\nimport { sampleKey, shouldSample } from \"./sampling\";\nimport type { Sender } from \"./sender\";\nimport { rootSpan, type SpanData, spanFields } from \"./spans\";\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/** Constructor of the WebSocket capture plugin. */\ntype WebSocketClass = new (diagnostics: Diagnostics, config: ResolvedConfig) => CapturePlugin;\n\n/** Id of each plugin object. A new plugin object then changes the capture key. */\nconst pluginIds = new WeakMap<object, number>();\n\n/** Last plugin id that pluginId() gave. */\nlet lastPluginId = 0;\n\n/**\n * Gives the id of a plugin object. The capture key must not hold the plugin. A plugin can hold\n * a cycle, and JSON.stringify then throws.\n * @param plugin Plugin of the app.\n * @returns The id of the object.\n */\nfunction pluginId(plugin: object): number {\n let id = pluginIds.get(plugin);\n\n if (id === undefined) {\n id = ++lastPluginId;\n pluginIds.set(plugin, id);\n }\n\n return id;\n}\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/** Delivery settings that a rotation resets when the update omits them. */\nconst DELIVERY_RESET = {\n endpoint: null,\n metricsEndpoint: \"\",\n tracesEndpoint: \"\",\n headers: undefined,\n credentials: \"omit\",\n transport: undefined,\n transportOnExit: undefined,\n} as const;\n\n/** Delivery settings that configure() cannot change while isolation is on. */\nconst ROUTING_KEYS = Object.keys(DELIVERY_RESET) as (keyof typeof DELIVERY_RESET)[];\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 urlTransform: capture.urlTransform ? pluginId(capture.urlTransform) : undefined,\n webVitalsLoader: capture.webVitalsLoader !== undefined,\n ignoreUrls: capture.ignoreUrls.map(String),\n propagateTraceHeaderTo: capture.propagateTraceHeaderTo.map(String),\n plugins: capture.plugins.map(pluginId),\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 metricsEndpoint: \"\",\n tracesEndpoint: \"\",\n transport: undefined,\n transportOnExit: undefined,\n bus: { ...input.bus, mode: \"off\" },\n };\n}\n\n/**\n * Tests if a configuration names a destination.\n * @param input Consumer configuration options.\n * @returns True with an endpoint, a signal endpoint or a transport.\n */\nfunction sends(input: Partial<ObservabilityConfig>): boolean {\n return (\n Boolean(input.endpoint) ||\n Boolean(input.metricsEndpoint) ||\n Boolean(input.tracesEndpoint) ||\n input.transport !== undefined\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 /** True while the runtime changes the security context. */\n private rotating = false;\n /** True while the runtime collects the last records of the old context. */\n private closingContext = false;\n /** Version of another SDK copy that owns the page runtime, or null. */\n private mismatchVersion: string | null = null;\n /** True if the configured context id differs from the owner context id. */\n private contextMismatch = false;\n /** Current context change. Shutdown waits for this promise. */\n private rotation?: Promise<void>;\n /** Memory store kept for later context changes. */\n private memoryStorage?: StorageAdapter;\n /** True if the app supplied a context id at startup. */\n private explicitSecurityContext: boolean;\n /** True after this forwarder takes a context id from its owner. */\n private ownerAdopted = false;\n\n /**\n * Checks if a security context change is in progress.\n * @returns True until the current change completes.\n */\n isRotating(): boolean {\n return this.rotating;\n }\n\n /**\n * Locks or unlocks configuration at the request of the app. Other code of this origin can\n * call this method. The lock does not control access.\n * @param locked True to refuse changes through configure().\n */\n setConfigurationLocked(locked: boolean): void {\n if (typeof locked === \"boolean\") this.config.lockConfiguration = locked;\n }\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 * True for a console-only runtime. It sends nothing, joins no bus and installs no capture.\n * Another version of the library on the page, or a server, makes it console-only.\n */\n private readonly degraded: boolean;\n\n /** True after the report of a destination on a server. The runtime reports it one time. */\n private serverReported = false;\n\n /**\n * Ends the root span of a forwarder when its document unloads. The exit flush ends it only in\n * the sender. Without this, the client spans of a frame or a view have no parent.\n */\n private readonly onPageHide = (): void => {\n if (this.role() !== \"forwarder\") {\n return;\n }\n\n this.tracing.end();\n this.sendForwarded();\n };\n\n /**\n * @param input Initial consumer configuration options.\n * @param mismatch True for a console-only runtime next to another version.\n */\n private constructor(input: Partial<ObservabilityConfig>, mismatch = false) {\n this.diagnostics = new Diagnostics(input.onDiagnostic);\n\n this.platform = detectPlatform(this.diagnostics);\n // A server has no page to capture and no storage. It writes to the console only.\n this.degraded = mismatch || this.onServer();\n this.config = resolveConfig(this.allowed(input), this.diagnostics);\n this.explicitSecurityContext = Boolean(input.securityContext?.id);\n this.config.securityContext.id ||= newId(this.diagnostics);\n this.diagnostics.setPolicy(\n this.config.diagnostics.throttleMs,\n this.config.diagnostics.consoleFallback,\n );\n this.identityBuiltAs = this.config.identity;\n this.stores =\n this.identityBuiltAs === \"memory\" || this.onServer() ? memoryStores() : BROWSER_STORES;\n this.identity = resolveIdentity(\n this.diagnostics,\n this.stores,\n this.config.correlation.sessionIdleMs,\n );\n this.sessionTouch = new SessionTouch(\n this.diagnostics,\n this.stores,\n this.config.correlation.sessionTouchMs,\n this.config.correlation.sessionIdleMs,\n );\n this.breadcrumbs = new BreadcrumbBuffer(this.config.capturePolicy.breadcrumbs);\n // Sample a span by its trace. The whole trace stays or goes.\n const keeps = (traceId: string): boolean =>\n sampleKey(traceId, this.config.sampling.defaultRate);\n this.tracing = new TraceEngine(\n this.diagnostics,\n this.config.correlation.traceMaxAgeMs || Infinity,\n this.config.otelLoader,\n {\n enabled: () => this.config.tracesEndpoint !== \"\",\n keeps,\n onEnd: (ended) => {\n if (keeps(ended.traceId)) {\n this.recordSpan(rootSpan(ended));\n }\n },\n },\n );\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 this.config.metrics,\n );\n }\n\n /**\n * Adds a breadcrumb from app code. It copies the data now. A later change of the object of the\n * app then does not change the trail.\n * @param message Description of the event. A JavaScript caller can pass a value that is not a\n * string. The library converts it.\n * @param data Optional metadata.\n */\n addBreadcrumb(message: unknown, data?: Record<string, unknown>): void {\n if (this.rotating || this.destroyed) return;\n // A message with a toString() that throws, or a data getter that throws, must not throw\n // into the call of the app.\n this.diagnostics.guard(\n \"record.sanitize_failed\",\n \"The library could not add the breadcrumb.\",\n () => {\n const crumb: Breadcrumb = {\n t: Date.now(),\n category: \"custom\",\n message: truncate(String(message), this.limits.maxBodyChars),\n };\n\n if (data !== undefined) {\n const clean = sanitize(data, this.limits, this.diagnostics);\n crumb.data = isObject(clean) ? clean : { value: clean };\n }\n\n this.breadcrumbs.push(crumb);\n },\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 && !this.rotating) {\n this.meter.record(def, value, attributes);\n }\n }\n\n /**\n * Builds and emits the record of one span. The console does not print it. minLevel does not\n * drop it. The trace engine sampled the trace before the span existed.\n * @param span The span data.\n */\n private recordSpan(span: SpanData): void {\n if (this.config.tracesEndpoint === \"\") {\n return;\n }\n\n const { record } = this.builder.build({\n level: \"INFO\",\n type: \"span\",\n body: span.name,\n namespace: TRACE_NAMESPACE,\n payload: span.attributes,\n fixed: spanFields(span),\n trace: { traceId: span.traceId, spanId: span.spanId, traceFlags: TRACE_FLAGS_SAMPLED },\n });\n this.emit(record);\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 * Checks the source policy before a direct child link opens.\n * @param source Child window.\n * @param origin Origin of the child window.\n * @returns True if the bus permits this source.\n */\n readonly busCanAccept = (source: Window, origin: string): boolean =>\n this.bus?.isRegistered(source, origin) ?? false;\n\n /**\n * Receives direct messages from same-origin child frames.\n * @param message Inbound bus message.\n * @param reply Direct response callback.\n * @param source Window of the child frame.\n */\n readonly busAccept = (message: BusMessage, reply: Receive, source?: Window): 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, source);\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(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(input, true);\n ObservabilityRuntime.local = runtime;\n\n const foundText = typeof found === \"string\" ? found : \"before 0.9.0\";\n runtime.mismatchVersion = foundText;\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 if (this.rotating) {\n this.diagnostics.report(\n \"config.locked\",\n \"Configuration cannot change during security-context rotation.\",\n );\n return;\n }\n if (this.config.lockConfiguration) {\n const next = resolveConfig(input, this.diagnostics, this.config);\n if (!sameConfig(this.config, next))\n this.diagnostics.report(\n \"config.locked\",\n \"Runtime configuration is locked. Use setConfigurationLocked(false) to unlock it explicitly.\",\n );\n return;\n }\n const accepted = this.keepDestination(this.keepRouting(this.allowed(input)));\n // The first configure() after an implicit start is the startup of the app. Its id is explicit.\n if (!this.tunablesLocked && accepted.securityContext?.id) {\n this.explicitSecurityContext = true;\n }\n for (const key of [\"correlation\", \"persistence\"] as const) {\n // The sender reads the namespace when it loads. Before that, the first configure() can set it.\n if (key === \"persistence\" && !this.tunablesLocked && this.senderLoad === undefined) {\n continue;\n }\n if (\n accepted[key] &&\n !sameConfig({ ...this.config[key], ...accepted[key] }, this.config[key])\n ) {\n this.diagnostics.report(\"config.invalid\", `${key} cannot change after startup.`);\n Object.assign(accepted, { [key]: this.config[key] });\n }\n }\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.breadcrumbs.resize(this.config.capturePolicy.breadcrumbs);\n this.diagnostics.setHandler(this.config.onDiagnostic);\n this.diagnostics.setPolicy(\n this.config.diagnostics.throttleMs,\n this.config.diagnostics.consoleFallback,\n );\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 * Tests if the runtime runs on a server, for example Node during server-side rendering.\n * @returns True on Node.\n */\n private onServer(): boolean {\n return this.platform.platform === \"node\";\n }\n\n /**\n * Removes the delivery settings from the input of a console-only runtime. On a server, it\n * reports a destination one time.\n * @param input Consumer configuration options.\n * @returns The options that the runtime accepts.\n */\n private allowed(input: Partial<ObservabilityConfig>): Partial<ObservabilityConfig> {\n if (!this.degraded) {\n return input;\n }\n\n if (this.onServer() && !this.serverReported && sends(input)) {\n this.serverReported = true;\n this.diagnostics.report(\n \"config.invalid\",\n \"The library runs console-only on Node. It sends no record and installs no capture. It ignores endpoint, metricsEndpoint, tracesEndpoint and transport.\",\n );\n }\n\n return consoleOnly(input);\n }\n\n /**\n * Removes delivery and identity changes while isolation is on. The other settings still apply.\n * @param input Consumer configuration options.\n * @returns The options without the refused delivery or identity changes.\n */\n private keepRouting(input: Partial<ObservabilityConfig>): Partial<ObservabilityConfig> {\n if (!this.tunablesLocked || this.degraded || !this.config.securityContext.isolation) {\n return input;\n }\n\n // Compare resolved values. An unset endpoint keeps the endpoint in force. It is not a change.\n // A separate reporter prevents a second count of the diagnostics of the real resolve.\n const probe = resolveConfig(input, new Diagnostics(), this.config);\n const refused: string[] = ROUTING_KEYS.filter(\n (key) => !sameConfig(probe[key], this.config[key]),\n );\n if (probe.securityContext.id !== this.config.securityContext.id) {\n refused.push(\"securityContext.id\");\n }\n if (refused.length === 0) {\n return input;\n }\n\n const kept: Partial<ObservabilityConfig> = { ...input };\n for (const key of ROUTING_KEYS) {\n if (refused.includes(key)) {\n Reflect.deleteProperty(kept, key);\n }\n }\n if (refused.includes(\"securityContext.id\")) {\n const context = { ...input.securityContext };\n Reflect.deleteProperty(context, \"id\");\n kept.securityContext = context;\n }\n\n this.diagnostics.report(\n \"config.invalid\",\n `Isolation refuses changes to ${refused.join(\", \")}. Use rotateSecurityContext() for these changes. To permit them, set securityContext.isolation: false in a separate configure() call. The other settings apply.`,\n );\n return kept;\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 (sameConfig(next[section], 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 // A console-only runtime never forwards. Node has no addEventListener.\n if (!this.degraded) {\n addEventListener(\"pagehide\", this.onPageHide);\n }\n\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 onSecurityContext: (id) => {\n if (this.explicitSecurityContext && this.config.securityContext.id !== id) {\n this.contextMismatch = true;\n this.diagnostics.report(\n \"security.context_mismatch\",\n \"The configured security context differs from the upstream owner.\",\n );\n return false;\n }\n this.contextMismatch = false;\n if (this.config.securityContext.id !== id) {\n // The first owner id keeps the startup records and the context of the app. Those\n // records had no other identity. A later change retires them, also before ready.\n if (this.ownerAdopted) {\n this.drops.add(\"security_context\", [\n ...this.bootBuffer.take(),\n ...this.pendingRecords.take(),\n ...this.forwardBuffer,\n ]);\n this.forwardBuffer = [];\n this.context.clear();\n this.breadcrumbs.clear();\n // collect() removes the open measurements. emit() refuses them during this reset.\n const rotating = this.rotating;\n this.rotating = true;\n this.meter.collect();\n // A same-origin owner stores its new session before it sends the new id. Use that\n // session. Without it, each frame starts a different session.\n const shared = this.sessionTouch.stored();\n this.resetSession(\n shared !== undefined && shared !== this.identity.sessionId\n ? shared\n : newId(this.diagnostics),\n );\n this.rotating = rotating;\n }\n this.config.securityContext.id = id;\n }\n this.ownerAdopted = true;\n return true;\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 storage: this.memoryStorage,\n onStorage: (storage) => {\n if (storage.name === \"memory\") this.memoryStorage = storage;\n },\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 this.tracing.end();\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, WebSocketCapture] = await Promise.all([\n Promise.all(names.map((name) => this.loadCapture(name))),\n settings.webSocket ? this.loadWebSocket() : undefined,\n ]);\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 isActive: () => !this.destroyed && !this.rotating,\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 recordSpan: (span) => {\n this.recordSpan(span);\n },\n };\n\n for (const CaptureModule of classes) {\n if (CaptureModule) {\n this.captures.push(new CaptureModule(ctx));\n }\n }\n\n const plugins = WebSocketCapture\n ? [...settings.plugins, new WebSocketCapture(this.diagnostics, this.config)]\n : settings.plugins;\n\n for (const plugin of plugins) {\n this.captures.push(this.pluginCapture(plugin));\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 the WebSocket capture plugin. A failed import reports and skips it.\n * @returns Promise that resolves to the class, or undefined if the import failed.\n */\n private loadWebSocket(): Promise<WebSocketClass | undefined> {\n return this.diagnostics.guardAsync(\n \"capture.install_failed\",\n \"The library could not load the webSocket capture.\",\n async () => (await import(\"../capture/web-socket\")).WebSocketCapture,\n );\n }\n\n /**\n * Wraps a plugin as a capture module. The plugin gets public tools only.\n * @param plugin Plugin of the app, or a built-in plugin.\n * @returns The capture module.\n */\n private pluginCapture(plugin: CapturePlugin): Capture {\n const { name } = plugin;\n const record: RecordMetric = (def, value, attributes) => {\n this.recordMetric(def, value, attributes);\n };\n const ctx: PluginContext = {\n logger: new OneLogger(() => this, `${CAPTURE_NAMESPACE}.${name}`),\n counter: (metric, options = {}) => makeCounter(metric, options, record),\n histogram: (metric, options = {}) => makeHistogram(metric, options, record),\n addBreadcrumb: (message, data) => {\n this.addBreadcrumb(message, data);\n },\n ownRequest: runAsLibraryRequest,\n };\n\n return {\n name,\n install: () => {\n plugin.install(ctx);\n },\n uninstall: () => {\n plugin.uninstall();\n },\n };\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, options: SourceOptions = {}): () => void {\n let cancelled = false;\n let detach: (() => void) | undefined;\n if (this.destroyed) {\n return () => undefined;\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 || cancelled) {\n return;\n }\n\n this.diagnostics.guard(\n \"bus.send_failed\",\n \"The library could not register the worker.\",\n () => {\n detach = bus.attachWorker(worker, options);\n },\n );\n\n // Start the bus in bus.mode \"off\", where startup did not start it.\n void this.ensureBus();\n });\n return () => {\n cancelled = true;\n detach?.();\n };\n }\n\n /**\n * Registers a frame after the bus loads. Early removal cancels the registration.\n * @param frame Child frame or window.\n * @param options Expected origin and source permissions.\n * @returns Function that removes this registration.\n */\n registerFrame(frame: HTMLIFrameElement | Window, options: FrameOptions): () => void {\n let cancelled = false;\n let detach: (() => void) | undefined;\n void this.constructBus().then((bus) => {\n if (!bus || this.destroyed || cancelled) return;\n detach = this.diagnostics.guard(\"bus.send_failed\", \"The frame could not be registered.\", () =>\n bus.registerFrame(frame, options),\n );\n void this.ensureBus();\n });\n return () => {\n cancelled = true;\n detach?.();\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 and the root span go out with the final flush.\n this.meter.collect();\n this.tracing.end();\n this.destroyed = true;\n\n if (!this.degraded) {\n removeEventListener(\"pagehide\", this.onPageHide);\n }\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 await this.rotation?.catch(() => undefined);\n await this.memoryStorage?.close();\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 || (this.rotating && !this.closingContext)) {\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 (this.destroyed) return;\n if (!Array.isArray(records)) {\n this.diagnostics.count(\"record.dropped_malformed\");\n return;\n }\n const accepted: LogRecord[] = [];\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\n // A child context without redact forwards raw records. The sender is the last gate.\n const redacted = this.builder.redactForwarded(record);\n if (redacted) {\n accepted.push(redacted);\n }\n }\n\n // Records that arrive while the context changes belong to neither identity. Report the loss\n // after sampling and redact. onDrop must not get action names or journey ids that redact masks.\n if (this.rotating) {\n this.drops.add(\"security_context\", accepted);\n return;\n }\n\n for (const record of accepted) {\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 // A hook already saw each record. A key added now does not pass redact.\n const { processors, redact } = this.config;\n const journey = processors.length === 0 && redact === undefined ? this.journey.current() : null;\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 * Starts a new session in this context. It sends the open metric points, starts a new trace,\n * ends the active journey and clears the breadcrumbs. Other tabs read the new id at their next\n * startup.\n */\n newSession(): void {\n if (this.destroyed) {\n return;\n }\n\n this.resetSession(newId(this.diagnostics));\n }\n\n /**\n * Closes the work of the old session and starts the given session.\n * @param sessionId Id of the session to start.\n */\n private resetSession(sessionId: string): void {\n // Close the work of the old session first. Its points and its root span keep the old id.\n this.meter.collect();\n this.tracing.rotate(\"explicit\");\n this.journey.end();\n // A shared machine: the next user must not see the trail of the previous user.\n this.breadcrumbs.clear();\n\n (this.identity as { sessionId: string }).sessionId = sessionId;\n this.sessionTouch.restart(sessionId);\n this.builder.invalidateResource();\n }\n\n /**\n * Changes the delivery context in one operation. A second change must wait for this change.\n * @param update New identity, delivery settings and context attributes.\n * @param options Rule for records of the old context and the flush deadline.\n * @returns Promise that resolves when the change completes. Invalid settings reject it.\n */\n rotateSecurityContext(\n update: SecurityContextUpdate,\n options: SecurityContextRotationOptions = {},\n ): Promise<void> {\n // Check the promise, not the flag. \"carry\" clears the flag before it stores old batches again.\n if (this.rotation)\n return Promise.reject(new Error(\"A security-context rotation is already running.\"));\n const pending = options.pending ?? \"discard\";\n const timeoutMs = options.timeoutMs ?? 5000;\n if (\n !isObject(update) ||\n !isObject(update.delivery) ||\n ![\"discard\", \"flush\", \"retain\", \"carry\"].includes(pending) ||\n !Number.isFinite(timeoutMs) ||\n timeoutMs < 0 ||\n (update.id !== undefined && (typeof update.id !== \"string\" || update.id.length === 0))\n ) {\n return Promise.reject(new Error(\"Invalid security-context rotation options.\"));\n }\n if (this.destroyed) return Promise.reject(new Error(\"The runtime has stopped.\"));\n this.rotating = true;\n this.rotation = this.rotateContext(update, pending, timeoutMs).finally(() => {\n this.rotating = false;\n this.rotation = undefined;\n });\n return this.rotation;\n }\n\n /**\n * Checks new settings, stops old delivery and starts the new context.\n * @param update New identity, delivery settings and attributes.\n * @param pending Rule for the old records.\n * @param timeoutMs Maximum wait for an old-context flush, in milliseconds.\n * @returns Promise that resolves when the context change completes.\n */\n private async rotateContext(\n update: SecurityContextUpdate,\n pending: \"discard\" | \"flush\" | \"retain\" | \"carry\",\n timeoutMs: number,\n ): Promise<void> {\n await this.started;\n if (this.role() === \"forwarder\")\n throw new Error(\n \"Rotate the security context on the upstream owner, or use bus.mode: sender for an independent identity.\",\n );\n await this.senderLoad;\n const previous = this.config.securityContext.id;\n const nextId = update.id ?? newId(this.diagnostics);\n if (nextId === previous)\n throw new Error(\"A rotation requires a different security-context id.\");\n // Check the new settings before the old sender stops. Invalid settings keep the old sender.\n const delivery = { ...DELIVERY_RESET, ...update.delivery };\n const before = this.diagnostics.snapshot()[\"config.invalid\"] ?? 0;\n // The base has no old delivery values. An invalid new value cannot fall back to an old one.\n const next = resolveConfig(\n this.allowed({ ...delivery, securityContext: { id: nextId } }),\n this.diagnostics,\n { ...this.config, ...DELIVERY_RESET },\n );\n if ((this.diagnostics.snapshot()[\"config.invalid\"] ?? 0) !== before)\n throw new Error(\"Invalid delivery settings for the next security context.\");\n // Copy the context now. A getter that throws then rejects before the old sender stops.\n const context = update.context ? Object.fromEntries(Object.entries(update.context)) : undefined;\n\n // The base above has no endpoints. Remove the old endpoints from the ignore list here.\n // If they stay, network capture ignores calls to the old destination.\n const oldUrls = new Set<unknown>([\n this.config.endpoint,\n this.config.metricsEndpoint,\n this.config.tracesEndpoint,\n ]);\n const newUrls = new Set<unknown>([next.endpoint, next.metricsEndpoint, next.tracesEndpoint]);\n next.capture.ignoreUrls = next.capture.ignoreUrls.filter(\n (url) => !oldUrls.has(url) || newUrls.has(url),\n );\n\n this.closingContext = true;\n try {\n this.meter.collect();\n this.tracing.end();\n this.journey.end();\n } finally {\n this.closingContext = false;\n }\n const held = [...this.bootBuffer.take(), ...this.pendingRecords.take(), ...this.forwardBuffer];\n this.forwardBuffer = [];\n const old = this.sender;\n this.sender = undefined;\n this.senderLoad = undefined;\n const retired = (await old?.retire(pending, timeoutMs, previous)) ?? {\n buffered: [],\n stored: [],\n };\n if (this.destroyed) return;\n const live = [...held, ...retired.buffered];\n const stored = retired.stored.flatMap((batch) => batch.records);\n if (pending !== \"retain\" && pending !== \"carry\") {\n this.drops.add(\"security_context\", [...live, ...stored]);\n }\n // Keep a lock change that the app made during the rotation.\n next.lockConfiguration = this.config.lockConfiguration;\n // Replace all delivery settings together. Do not keep old credentials or signal endpoints.\n applyResolvedConfig(this.config, next);\n this.remote.sampling = null;\n this.context.clear();\n if (context) this.context.setMany(context);\n this.breadcrumbs.clear();\n this.newSession();\n this.builder.invalidateResource();\n await this.syncSender();\n this.bus?.rotateContext();\n if (pending === \"carry\") {\n // New calls go to the new sender while it stores the old batches again. A long carry then\n // drops no logger call.\n this.rotating = false;\n await this.carry(live, retired.stored);\n }\n this.diagnostics.report(\"security.rotated\", \"The runtime rotated its security context.\", {\n pending,\n });\n }\n\n /**\n * Moves the records of the old context into the new context.\n * @param live Records that were in memory. They go through the live buffer.\n * @param stored Batches that were stored. The new sender stores them again.\n * @returns Promise that resolves when the stored batches are stored again.\n */\n private async carry(live: LogRecord[], stored: LogBatch[]): Promise<void> {\n for (const record of live) {\n this.route(record);\n }\n\n // The live buffer does not take the stored backlog. It would exceed the buffer budget.\n // Without a new sender, the stored batches stay parked under the old id. Nothing is lost.\n if (this.sender) {\n await this.sender.adopt(stored, this.config.securityContext.id);\n }\n }\n\n /**\n * Reads the state of this runtime. It does not wait for startup or the sender to load.\n * @returns State, delivery counts and policies. The facade adds the logger cache counts.\n */\n async health(): Promise<Omit<ObservabilityHealth, \"loggerCache\">> {\n const delivery = this.sender?.stats() ?? { pending: 0, inFlight: 0, lastSendAt: null };\n const issues: ObservabilityHealth[\"issues\"] = [];\n if (this.mismatchVersion) issues.push(\"runtime.version_mismatch\");\n if (this.contextMismatch) issues.push(\"security.context_mismatch\");\n if (this.ready && this.hasDestination() && this.role() === \"sender\" && !this.sender)\n issues.push(\"sender.unavailable\");\n const {\n sourcePolicy,\n validation,\n maxMessageBytes,\n maxRecordsPerMessage,\n maxMessagesPerSecond,\n maxTrackedSources,\n } = this.config.bus;\n return {\n ...delivery,\n pending:\n delivery.pending +\n this.bootBuffer.length +\n this.pendingRecords.length +\n this.forwardBuffer.length,\n stored: (await this.sender?.queueDepth()) ?? 0,\n sdkVersion: this.sdkVersion,\n owningSdkVersion: this.mismatchVersion,\n status: this.destroyed\n ? \"stopped\"\n : this.rotating\n ? \"rotating\"\n : issues.length\n ? \"degraded\"\n : !this.ready\n ? \"starting\"\n : \"ready\",\n mode:\n this.role() === \"forwarder\"\n ? \"forwarder\"\n : this.hasDestination()\n ? \"sender\"\n : \"console-only\",\n senderReady: this.sender !== undefined && !this.destroyed && !this.rotating,\n configurationLocked: this.config.lockConfiguration,\n issues,\n securityContext: { ...this.config.securityContext },\n bus: {\n sourcePolicy,\n validation,\n maxMessageBytes,\n maxRecordsPerMessage,\n maxMessagesPerSecond,\n maxTrackedSources,\n },\n };\n }\n\n /**\n * Reads the delivery state of this context.\n * @returns Promise that resolves to the counts and the time of the last accepted send.\n */\n async stats(): Promise<DeliveryStats> {\n // queueDepth() waits for a loading delivery stack. The held records are then in the pipeline.\n const stored = await this.queueDepth();\n const delivery = this.sender?.stats() ?? { pending: 0, inFlight: 0, lastSendAt: null };\n const held = this.bootBuffer.length + this.pendingRecords.length + this.forwardBuffer.length;\n\n return { ...delivery, pending: delivery.pending + held, stored };\n }\n\n /**\n * Removes stored records of one context or all contexts in the application namespace.\n * @param scope Part of storage to clear.\n * @returns Promise that resolves when removal completes.\n */\n async clearPersisted(scope: \"context\" | \"namespace\"): Promise<void> {\n await this.senderLoad;\n if (this.sender) {\n await this.sender.clearPersisted(scope, this.config.securityContext.id);\n return;\n }\n const [\n { createStorage, storageName },\n { ContextStorage },\n { storageLimits },\n { clearEmergencyContext },\n ] = await Promise.all([\n import(\"../storage/factory\"),\n import(\"../storage/context-storage\"),\n import(\"../models/storage\"),\n import(\"../storage/emergency-queue\"),\n ]);\n const namespace = this.config.persistence.namespace;\n const backing =\n this.memoryStorage ??\n (await createStorage(\n this.config.storage,\n storageName(namespace),\n storageLimits(this.config.retention),\n this.diagnostics,\n undefined,\n namespace,\n ));\n const store = new ContextStorage(backing, this.config.securityContext, namespace);\n try {\n if (scope === \"namespace\") await store.clearNamespace();\n else await store.clear();\n clearEmergencyContext(\n this.config.securityContext.id,\n this.diagnostics,\n namespace,\n scope === \"namespace\",\n );\n } finally {\n if (backing !== this.memoryStorage) await store.close();\n }\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\n/**\n * Compares resolved settings without JSON conversion. Functions keep their object identity.\n * The seen map stops a cycle from causing a repeated comparison.\n * @param a First value.\n * @param b Second value.\n * @param seen Object pairs already compared.\n * @returns True if the values are equal.\n */\nfunction sameConfig(a: unknown, b: unknown, seen = new WeakMap<object, object>()): boolean {\n if (Object.is(a, b)) return true;\n if (a instanceof RegExp && b instanceof RegExp) return String(a) === String(b);\n if (typeof a !== \"object\" || a === null || typeof b !== \"object\" || b === null) return false;\n if (seen.has(a)) return seen.get(a) === b;\n seen.set(a, b);\n const ak = Object.keys(a);\n const bk = Object.keys(b);\n return (\n ak.length === bk.length &&\n ak.every(\n (key) => Object.hasOwn(b, key) && sameConfig(Reflect.get(a, key), Reflect.get(b, key), seen),\n )\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 { makeCounter, makeHistogram } from \"./core/meter\";\nimport { ObservabilityRuntime } from \"./core/runtime\";\nimport type { ObservabilityConfig } from \"./models/config\";\nimport type { SecurityContextUpdate, SecurityContextRotationOptions } from \"./models/config\";\nimport type { ObservabilityHealth } from \"./models/health\";\nimport type { FrameOptions, SourceOptions } from \"./models/bus\";\nexport type { FrameOptions, SourceOptions, BusPermission } from \"./models/bus\";\nimport type { MetricType } from \"./models/log-record\";\nimport type { DeliveryStats } from \"./models/stats\";\nimport type { Counter, Histogram, HistogramOptions, InstrumentOptions } from \"./models/metric\";\n\nexport { OneLogger };\nexport { createMemoryTransport, type MemoryTransport } from \"./transport/memory-transport\";\nexport type { Journey, ObservabilityConfig, OneLoggerOptions };\nexport type {\n DeliveryPolicy,\n BufferingPolicy,\n MetricsPolicy,\n CorrelationPolicy,\n DiagnosticsPolicy,\n PersistencePolicy,\n MetadataPolicy,\n CapturePolicy,\n BusOptions,\n CaptureOptions,\n InteractionOptions,\n LoggerCacheOptions,\n SecurityContextOptions,\n SecurityContextUpdate,\n SecurityContextRotationOptions,\n DeliveryOptions,\n ConsoleOptions,\n ConsoleStyles,\n ExitTransport,\n Transport,\n TransportRequest,\n TransportResponse,\n} from \"./models/config\";\nexport type { ObservabilityHealth } from \"./models/health\";\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 { CapturePlugin, PluginContext } from \"./models/plugin\";\nexport type { LogSerializer, SerializedBatch } from \"./models/serializer\";\nexport type { DeliveryStats } from \"./models/stats\";\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 * Removes stored logs. Pending records and requests can write to storage again.\n * @param scope Context or namespace whose stored records to remove.\n * @returns Promise that resolves when removal completes.\n */\nexport function clearPersistedLogs(scope: \"context\" | \"namespace\" = \"context\"): Promise<void> {\n if (![\"context\", \"namespace\"].includes(scope))\n return Promise.reject(new Error(\"Invalid persistence scope.\"));\n return requireRuntime().clearPersisted(scope);\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 trimLoggerCache();\n}\n\n/**\n * Locks or unlocks configuration. The lock does not control access by other code of this origin.\n * @param locked True to refuse changes through configure().\n */\nexport function setConfigurationLocked(locked: boolean): void {\n requireRuntime().setConfigurationLocked(locked);\n}\n\n/**\n * Stops delivery for the old context and starts delivery for the new context.\n * @param update New identity, delivery settings and context attributes.\n * @param options Rule for old records and the flush deadline.\n * @returns Promise that resolves when the change completes.\n */\nexport function rotateSecurityContext(\n update: SecurityContextUpdate,\n options?: SecurityContextRotationOptions,\n): Promise<void> {\n return requireRuntime().rotateSecurityContext(update, options);\n}\n\n/**\n * Reads the runtime state, delivery counts and policies of this SDK copy.\n * @returns Promise that resolves to the current state.\n */\nexport async function getHealth(): Promise<ObservabilityHealth> {\n const runtime = requireRuntime();\n trimLoggerCache();\n return {\n ...(await runtime.health()),\n loggerCache: { ...runtime.config.loggerCache, size: loggers.size },\n };\n}\n\n/**\n * Removes the least recently used loggers until the cache meets its limit.\n * @returns Cache limit, or null for no limit.\n */\nfunction trimLoggerCache(): number | null {\n const limit = (ObservabilityRuntime.current() ?? ObservabilityRuntime.stopped())?.config\n .loggerCache.maxEntries;\n const max = limit === undefined ? 256 : limit;\n if (max !== null) {\n // A Map keeps insertion order. The first keys are the least recently used loggers.\n for (const key of loggers.keys()) {\n if (loggers.size <= max) {\n break;\n }\n loggers.delete(key);\n }\n }\n return max;\n}\n\n/**\n * Gives a namespace logger from the cache, or a new scoped logger.\n * @param namespace Application subsystem or module namespace.\n * @param options Context attributes for this logger only.\n * @returns Logger for the namespace. Options or a disabled cache give a new logger.\n */\nexport function getLogger(namespace: string, options?: OneLoggerOptions): OneLogger {\n const max = trimLoggerCache();\n if (options || max === 0) return new OneLogger(requireRuntime, namespace, options);\n\n let logger = loggers.get(namespace);\n\n logger ??= new OneLogger(requireRuntime, namespace);\n\n // Move a cached logger to the end. The first entry is then the least recently used logger.\n loggers.delete(namespace);\n loggers.set(namespace, logger);\n trimLoggerCache();\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 return makeCounter(name, options, (def, value, attributes) => {\n requireRuntime().recordMetric(def, value, attributes);\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 return makeHistogram(name, options, (def, value, attributes) => {\n requireRuntime().recordMetric(def, value, attributes);\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 * Adds a breadcrumb to the trail. The next error record carries the trail.\n * @param message Description of the event.\n * @param data Optional metadata. The library copies it now.\n */\nexport function addBreadcrumb(message: string, data?: Record<string, unknown>): void {\n requireRuntime().addBreadcrumb(message, data);\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 `parent` links the active journey as the parent. `id` sets the journey id, a\n * string of 1 to 64 letters, digits, \"_\", \".\", \":\" or \"-\". Without it, the library makes an id.\n * @returns Started Journey instance.\n */\nexport function startJourney(name: string, options?: { parent?: boolean; id?: string }): 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 * @param options Permissions of the worker. The default permission is \"records\".\n * @returns Function that removes this registration.\n */\nexport function registerWorker(worker: WorkerLike, options?: SourceOptions): () => void {\n return requireRuntime().registerWorker(worker, options);\n}\n\n/**\n * Registers one frame or window at an exact origin.\n * @param frame Child frame or window to register.\n * @param options Expected origin and source permissions.\n * @returns Function that removes this registration.\n */\nexport function registerFrame(\n frame: HTMLIFrameElement | Window,\n options: FrameOptions,\n): () => void {\n return requireRuntime().registerFrame(frame, options);\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 * Reads the delivery state of this context.\n * @returns Promise that resolves to the records that wait, the records in requests, the batches\n * in storage and the time of the last accepted send. A forwarder reports only its own buffers.\n */\nexport function getStats(): Promise<DeliveryStats> {\n return requireRuntime().stats();\n}\n\n/**\n * Starts new correlation in this tab. It ends the active journey and starts a new trace. Other\n * tabs read the new id at their next startup. Use rotateSecurityContext() at logout or at a\n * tenant change.\n */\nexport function newSession(): void {\n requireRuntime().newSession();\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,SAAS6F,EAAQ,GAA2B;CAC1C,OAAO,KAAK,OAAO,YAAY,IAAI,IAAIC,KAAaxE,CAAkB,IAAIA;AAC5E;AAUA,SAASyE,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,GAA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