@utk09/ui-observability 0.8.0 → 0.9.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (177) hide show
  1. package/CHANGELOG.md +59 -0
  2. package/README.md +52 -45
  3. package/dist/bus/bus.d.ts +46 -12
  4. package/dist/bus/links.d.ts +6 -3
  5. package/dist/bus-CtJWf9QN.cjs +2 -0
  6. package/dist/bus-CtJWf9QN.cjs.map +1 -0
  7. package/dist/{bus-DPDrlUBY.js → bus-D8kH58tb.js} +128 -71
  8. package/dist/bus-D8kH58tb.js.map +1 -0
  9. package/dist/capture/interactions.d.ts +7 -6
  10. package/dist/capture/network.d.ts +23 -9
  11. package/dist/capture/types.d.ts +3 -3
  12. package/dist/console-BpHfWstv.cjs +2 -0
  13. package/dist/console-BpHfWstv.cjs.map +1 -0
  14. package/dist/console-DjLbryED.js +82 -0
  15. package/dist/console-DjLbryED.js.map +1 -0
  16. package/dist/constants-Br3b89Wg.cjs +2 -0
  17. package/dist/constants-Br3b89Wg.cjs.map +1 -0
  18. package/dist/constants-DM94FjVX.js +96 -0
  19. package/dist/constants-DM94FjVX.js.map +1 -0
  20. package/dist/constants.d.ts +20 -9
  21. package/dist/core/diagnostics.d.ts +2 -2
  22. package/dist/core/journey.d.ts +16 -4
  23. package/dist/core/logger.d.ts +6 -2
  24. package/dist/core/pipeline.d.ts +18 -9
  25. package/dist/core/record.d.ts +11 -6
  26. package/dist/core/remote-sampling.d.ts +1 -1
  27. package/dist/core/runtime.d.ts +43 -15
  28. package/dist/core/sender.d.ts +15 -10
  29. package/dist/deadline-B5DINjD5.js +111 -0
  30. package/dist/deadline-B5DINjD5.js.map +1 -0
  31. package/dist/deadline-Cbg2cbUw.cjs +2 -0
  32. package/dist/deadline-Cbg2cbUw.cjs.map +1 -0
  33. package/dist/error-like-Ywo5uRHo.js +19 -0
  34. package/dist/error-like-Ywo5uRHo.js.map +1 -0
  35. package/dist/error-like-gGRx2s36.cjs +2 -0
  36. package/dist/error-like-gGRx2s36.cjs.map +1 -0
  37. package/dist/errors-CpGRhhIf.cjs +3 -0
  38. package/dist/errors-CpGRhhIf.cjs.map +1 -0
  39. package/dist/{errors-Dnc-X4Ec.js → errors-DH4QJS0u.js} +39 -20
  40. package/dist/errors-DH4QJS0u.js.map +1 -0
  41. package/dist/global-scope-BN-Io_yv.cjs.map +1 -1
  42. package/dist/global-scope-dp2jADRl.js.map +1 -1
  43. package/dist/index.cjs +1 -1
  44. package/dist/index.cjs.map +1 -1
  45. package/dist/index.d.ts +11 -4
  46. package/dist/index.js +561 -436
  47. package/dist/index.js.map +1 -1
  48. package/dist/indexeddb-storage-DNdf1fmL.cjs +2 -0
  49. package/dist/indexeddb-storage-DNdf1fmL.cjs.map +1 -0
  50. package/dist/{indexeddb-storage-uD4oaRMc.js → indexeddb-storage-n1qkFBGA.js} +17 -17
  51. package/dist/indexeddb-storage-n1qkFBGA.js.map +1 -0
  52. package/dist/interactions-31eHGwEQ.cjs +2 -0
  53. package/dist/interactions-31eHGwEQ.cjs.map +1 -0
  54. package/dist/{interactions-igKTAJvj.js → interactions-OU94MPXs.js} +22 -19
  55. package/dist/interactions-OU94MPXs.js.map +1 -0
  56. package/dist/journey-CE2EcwHW.cjs +2 -0
  57. package/dist/journey-CE2EcwHW.cjs.map +1 -0
  58. package/dist/journey-CeJ1QoT2.js +162 -0
  59. package/dist/journey-CeJ1QoT2.js.map +1 -0
  60. package/dist/{library-request-Br_T09Bn.cjs → library-request-C9uJFlbq.cjs} +2 -2
  61. package/dist/{library-request-Br_T09Bn.cjs.map → library-request-C9uJFlbq.cjs.map} +1 -1
  62. package/dist/{library-request-Dt0fXhcn.js → library-request-DvhuplAB.js} +2 -2
  63. package/dist/{library-request-Dt0fXhcn.js.map → library-request-DvhuplAB.js.map} +1 -1
  64. package/dist/{long-frames-DahhqM6u.cjs → long-frames-B8VdA_ny.cjs} +2 -2
  65. package/dist/{long-frames-DahhqM6u.cjs.map → long-frames-B8VdA_ny.cjs.map} +1 -1
  66. package/dist/{long-frames-6pnjWSSR.js → long-frames-C_7OutLs.js} +3 -3
  67. package/dist/{long-frames-6pnjWSSR.js.map → long-frames-C_7OutLs.js.map} +1 -1
  68. package/dist/models/batch.d.ts +1 -1
  69. package/dist/models/bus.d.ts +7 -4
  70. package/dist/models/config.d.ts +43 -12
  71. package/dist/models/log-record.d.ts +12 -6
  72. package/dist/network-BAV7ipyn.cjs +2 -0
  73. package/dist/network-BAV7ipyn.cjs.map +1 -0
  74. package/dist/network-D_lloS5t.js +174 -0
  75. package/dist/network-D_lloS5t.js.map +1 -0
  76. package/dist/patch-BX8KrPCT.cjs +2 -0
  77. package/dist/patch-BX8KrPCT.cjs.map +1 -0
  78. package/dist/patch-CCWfuEY7.js +9 -0
  79. package/dist/patch-CCWfuEY7.js.map +1 -0
  80. package/dist/{platform-D_XkVIF6.cjs → platform-D4wu1eIF.cjs} +2 -2
  81. package/dist/platform-D4wu1eIF.cjs.map +1 -0
  82. package/dist/platform-IHBZGqUe.js +48 -0
  83. package/dist/platform-IHBZGqUe.js.map +1 -0
  84. package/dist/{remote-rules-5UA23alm.js → remote-rules-Bt1XsdEQ.js} +14 -14
  85. package/dist/remote-rules-Bt1XsdEQ.js.map +1 -0
  86. package/dist/{remote-rules-rJJZKVG8.cjs → remote-rules-kuDf5gbe.cjs} +2 -2
  87. package/dist/remote-rules-kuDf5gbe.cjs.map +1 -0
  88. package/dist/sampling-BI15ds9D.cjs +2 -0
  89. package/dist/sampling-BI15ds9D.cjs.map +1 -0
  90. package/dist/sampling-o0VY1mqQ.js +63 -0
  91. package/dist/sampling-o0VY1mqQ.js.map +1 -0
  92. package/dist/sanitize-B9UheVKc.js +123 -0
  93. package/dist/sanitize-B9UheVKc.js.map +1 -0
  94. package/dist/sanitize-DSIP7amZ.cjs +2 -0
  95. package/dist/sanitize-DSIP7amZ.cjs.map +1 -0
  96. package/dist/{sender-G6v4Uqi4.js → sender-BnNj9bOX.js} +234 -176
  97. package/dist/sender-BnNj9bOX.js.map +1 -0
  98. package/dist/sender-D0OsyB1c.cjs +3 -0
  99. package/dist/sender-D0OsyB1c.cjs.map +1 -0
  100. package/dist/storage/emergency-queue.d.ts +1 -1
  101. package/dist/storage/factory.d.ts +1 -1
  102. package/dist/storage/idb-driver.d.ts +1 -1
  103. package/dist/storage/local-storage.d.ts +3 -3
  104. package/dist/storage/memory-storage.d.ts +3 -3
  105. package/dist/{storm-DJkEZP_8.js → storm-BTw0J6eE.js} +2 -2
  106. package/dist/{storm-DJkEZP_8.js.map → storm-BTw0J6eE.js.map} +1 -1
  107. package/dist/{storm-BtzgLOCX.cjs → storm-Y-yuBhvv.cjs} +2 -2
  108. package/dist/{storm-BtzgLOCX.cjs.map → storm-Y-yuBhvv.cjs.map} +1 -1
  109. package/dist/transport/compression.d.ts +1 -1
  110. package/dist/transport/exit-flush.d.ts +21 -17
  111. package/dist/transport/http-transport.d.ts +61 -7
  112. package/dist/transport/retry-engine.d.ts +5 -5
  113. package/dist/transport/status-transport.d.ts +4 -2
  114. package/dist/utils/console.d.ts +1 -1
  115. package/dist/utils/error-like.d.ts +25 -0
  116. package/dist/utils/global-scope.d.ts +1 -1
  117. package/dist/utils/identity.d.ts +1 -1
  118. package/dist/utils/library-console.d.ts +1 -1
  119. package/dist/utils/library-request.d.ts +1 -1
  120. package/dist/utils/patch.d.ts +9 -0
  121. package/dist/utils/platform.d.ts +3 -3
  122. package/dist/utils/sequence.d.ts +0 -5
  123. package/dist/utils/timer.d.ts +1 -1
  124. package/dist/utils/tracing.d.ts +3 -3
  125. package/dist/utils/unref.d.ts +2 -2
  126. package/dist/{web-vitals-DHZ0yA_H.js → web-vitals-Bflr5jSA.js} +4 -2
  127. package/dist/web-vitals-Bflr5jSA.js.map +1 -0
  128. package/dist/web-vitals-DFuoTQbZ.cjs +2 -0
  129. package/dist/web-vitals-DFuoTQbZ.cjs.map +1 -0
  130. package/package.json +2 -2
  131. package/dist/bus-CUXRY0JR.cjs +0 -2
  132. package/dist/bus-CUXRY0JR.cjs.map +0 -1
  133. package/dist/bus-DPDrlUBY.js.map +0 -1
  134. package/dist/console-CNljJict.js +0 -81
  135. package/dist/console-CNljJict.js.map +0 -1
  136. package/dist/console-PKzc-FmR.cjs +0 -2
  137. package/dist/console-PKzc-FmR.cjs.map +0 -1
  138. package/dist/constants-B28fDv2F.cjs +0 -2
  139. package/dist/constants-B28fDv2F.cjs.map +0 -1
  140. package/dist/constants-Bu49bm39.js +0 -93
  141. package/dist/constants-Bu49bm39.js.map +0 -1
  142. package/dist/errors-C78ZTjet.cjs +0 -3
  143. package/dist/errors-C78ZTjet.cjs.map +0 -1
  144. package/dist/errors-Dnc-X4Ec.js.map +0 -1
  145. package/dist/indexeddb-storage-D0p3iMD0.cjs +0 -2
  146. package/dist/indexeddb-storage-D0p3iMD0.cjs.map +0 -1
  147. package/dist/indexeddb-storage-uD4oaRMc.js.map +0 -1
  148. package/dist/interactions-CsE2y_fQ.cjs +0 -2
  149. package/dist/interactions-CsE2y_fQ.cjs.map +0 -1
  150. package/dist/interactions-igKTAJvj.js.map +0 -1
  151. package/dist/network-CZ0aFUsy.cjs +0 -2
  152. package/dist/network-CZ0aFUsy.cjs.map +0 -1
  153. package/dist/network-aSNbwpue.js +0 -112
  154. package/dist/network-aSNbwpue.js.map +0 -1
  155. package/dist/platform-BwbMRwHm.js +0 -48
  156. package/dist/platform-BwbMRwHm.js.map +0 -1
  157. package/dist/platform-D_XkVIF6.cjs.map +0 -1
  158. package/dist/remote-rules-5UA23alm.js.map +0 -1
  159. package/dist/remote-rules-rJJZKVG8.cjs.map +0 -1
  160. package/dist/sampling-E4x92Nn2.cjs +0 -2
  161. package/dist/sampling-E4x92Nn2.cjs.map +0 -1
  162. package/dist/sampling-J1eahbfT.js +0 -160
  163. package/dist/sampling-J1eahbfT.js.map +0 -1
  164. package/dist/sanitize-BMhh8ghJ.cjs +0 -2
  165. package/dist/sanitize-BMhh8ghJ.cjs.map +0 -1
  166. package/dist/sanitize-UJ-4Lb0n.js +0 -114
  167. package/dist/sanitize-UJ-4Lb0n.js.map +0 -1
  168. package/dist/sender-B6ufz26f.cjs +0 -3
  169. package/dist/sender-B6ufz26f.cjs.map +0 -1
  170. package/dist/sender-G6v4Uqi4.js.map +0 -1
  171. package/dist/unref-16maCyKA.js +0 -8
  172. package/dist/unref-16maCyKA.js.map +0 -1
  173. package/dist/unref-CU9Nyz_9.cjs +0 -2
  174. package/dist/unref-CU9Nyz_9.cjs.map +0 -1
  175. package/dist/web-vitals-B2FYsEAU.cjs +0 -2
  176. package/dist/web-vitals-B2FYsEAU.cjs.map +0 -1
  177. package/dist/web-vitals-DHZ0yA_H.js.map +0 -1
@@ -1 +0,0 @@
1
- {"version":3,"file":"sender-G6v4Uqi4.js","names":["keyFor","items","nested","STORAGE_DEADLINE_MS","CONTENT_TYPE_TEXT_PLAIN","RESOURCE_DEPLOYMENT_ENVIRONMENT","REQUEST_TIMEOUT_MS","RESOURCE_SERVICE_VERSION","HEADER_ATTEMPT","RETRY_IDLE_DELAY_MS","ECS_LEVEL_NAMES","HEADER_CONTENT_TYPE","HEADER_BATCH_ID","CONTENT_TYPE_JSON","RESOURCE_BROWSER_USER_AGENT","RESOURCE_SERVICE_NAME","STORAGE_DB_NAME","EMERGENCY_STORAGE_KEY_PREFIX","RETRY_MAX_DELAY_MS","RETRY_BASE_DELAY_MS","HEADER_SAMPLING","HEADER_RETRY_AFTER","STORAGE_NAME_NONE","QUERY_PARAM_BATCH_ID","STORAGE_LIMITS","METRIC_FLUSH_INTERVAL_MS","NANOS_PER_MILLI","NANOS_PATTERN","STORAGE_NAME_MEMORY","CONTENT_TYPE_NDJSON","ATTR_LOG_TYPE","TELEMETRY_SDK_NAME","LOG_FLUSH_INTERVAL_MS","STORAGE_PROBE_KEY","MILLIS_PER_SECOND","HEADER_CONTENT_ENCODING","SERIALIZER_NAME_OTLP","STORAGE_NAME_LOCAL","TELEMETRY_SDK_VERSION","LOG_TYPE_METRIC","BATCH_STORAGE_KEY_PREFIX","QUERY_PARAM_EXIT_REASON","ENCODING_GZIP","withDeadline","DeadlineError","newId","nowUnixNano","ErrorCeiling","runAsLibraryConsole","estimateBytes","unrefTimer","parseRemoteRules","applyRemote","runAsLibraryRequest","isLogBatch","value","id","createdAt","attempts","records","splitBatch","batch","middle","halve","diagnostics","withDrainLock","locks","name","skipIfBusy","lock","fn","keysWithPrefix","out","i","key","prefix","keyFor$1","at","readBatch","parsed","raw","importAll","moved","storage","error","saveToEmergencyQueue","context","keys","old","drainEmergencyQueue","keyFor","createdAtOf","start","LocalStorageStorage","limits","onGap","limit","cutoff","result","drop","alive","excess","stored","countRecords","batches","total","MemoryStorage","found","expired","evicted","noop","hasIndexedDb","hasLocalStorage","createStorage","strategy","adapter","IndexedDbStorage","dbName","TransportError","message","cause","kind","status","retryAfterMs","maxBytes","parseRetryAfter","header","seconds","date","toMillis","timeUnixNano","toLabelValue","pushLabel","existing","labels","flattenLabel","scalar","seen","item","entry","toLabels","source","ecsSerializer","millis","record","toAnyValue","toKeyValues","resourceKeys","resourceKey","cached","resource","otlpSerializer","groups","group","resourceLogs","serializerFor","choice","serializeBatch","StatusTransport","config","onSampling","sampling","code","advice","hints","throttled","toTransportRequest","serialized","isResponse","finiteHint","CustomTransport","transport","request","response","deadline","ExitFlush","deps","me","reason","url","target","outcome","onExit","endpoint","nav","body","gzip","CS","stream","text","buffer","CREDENTIAL_ADVICE","HttpTransport","headers","controller","timer","online","RetryEngine","batchesPerDrain","parts","part","delayMs","work","exponential","failure","halves","isMetric","STREAM_OPTIONS","RecordStream","options","onFlush","LogPipeline","retry","flush","streamOptions","inFlight","throttledMs","Sender","pipeline","exitFlush","update","started"],"sources":["../src/models/batch.ts","../src/utils/lock.ts","../src/storage/keys.ts","../src/storage/emergency-queue.ts","../src/storage/local-storage.ts","../src/storage/memory-storage.ts","../src/storage/factory.ts","../src/transport/errors.ts","../src/transport/serializers/ecs.ts","../src/transport/serializers/otlp.ts","../src/transport/serializers/select.ts","../src/transport/status-transport.ts","../src/transport/custom-transport.ts","../src/transport/exit-flush.ts","../src/transport/compression.ts","../src/transport/http-transport.ts","../src/transport/retry-engine.ts","../src/core/pipeline.ts","../src/core/sender.ts"],"sourcesContent":["// src/models/batch.ts\n//\n// A batch of log records for delivery to the ingest endpoint.\n\nimport type { Diagnostics } from \"../core/diagnostics\";\nimport { newId } from \"../utils/identity\";\nimport type { LogRecord } from \"./log-record\";\n\n/**\n * A batch of records with a stable id used for server-side deduplication across retries.\n * @see {@link splitBatch}\n */\nexport interface LogBatch {\n /** Deduplication key. It stays the same across retries and reloads. */\n id: string;\n /** Records to deliver, in log order. */\n records: LogRecord[];\n /** Batch creation time, in epoch milliseconds. */\n createdAt: number;\n /** Delivery attempts so far. */\n attempts: number;\n}\n\n/**\n * Tells whether a value from storage has all fields of a batch. `keyOf` cannot match\n * an entry without `id` after delivery. The library then retries that entry with no\n * end, and the entry blocks each batch behind it. An entry without `attempts` counts\n * as NaN. That count never reaches `maxAttempts`. Thus the library never drops the\n * entry as a dead letter.\n * @param value Parsed storage entry.\n * @returns True when each required field is present and has the correct type.\n */\nexport function isLogBatch(value: unknown): value is LogBatch {\n if (typeof value !== \"object\" || value === null) {\n return false;\n }\n\n const id: unknown = Reflect.get(value, \"id\");\n const createdAt: unknown = Reflect.get(value, \"createdAt\");\n const attempts: unknown = Reflect.get(value, \"attempts\");\n const records: unknown = Reflect.get(value, \"records\");\n\n return (\n typeof id === \"string\" &&\n typeof createdAt === \"number\" &&\n typeof attempts === \"number\" &&\n Array.isArray(records)\n );\n}\n\n/**\n * Splits a batch that the server rejected as too large into two halves.\n * Each half gets a new id. Each half keeps the age and attempts of the original batch.\n * @param batch The rejected batch.\n * @param diagnostics Diagnostics reporter for the new batch ids.\n * @returns Two batches, or `null` if a single record is already over the limit.\n */\nexport function splitBatch(batch: LogBatch, diagnostics: Diagnostics): [LogBatch, LogBatch] | null {\n if (batch.records.length < 2) {\n return null;\n }\n\n const middle = Math.floor(batch.records.length / 2);\n const halve = (records: LogRecord[]): LogBatch => ({\n id: newId(diagnostics),\n records,\n createdAt: batch.createdAt,\n attempts: batch.attempts,\n });\n\n return [halve(batch.records.slice(0, middle)), halve(batch.records.slice(middle))];\n}\n","// src/utils/lock.ts\n//\n// Coordinates origin-wide batch draining operations using the Web Locks API.\n// Without the lock, every window on the origin drains and sends the same batches.\n\nimport type { Diagnostics } from \"../core/diagnostics\";\n\n/** Lock grant object, or null when the lock is not available. */\ntype LockGrant = { name: string } | null;\n\n/** Structural interface for navigator.locks operations. */\ninterface LockManagerLike {\n /**\n * Requests a lock and executes a callback under the acquired lock grant.\n * @param name Lock name.\n * @param options Lock request options.\n * @param callback Callback that runs with the lock grant.\n */\n request<T>(\n name: string,\n options: { ifAvailable?: boolean },\n callback: (lock: LockGrant) => Promise<T>,\n ): Promise<T>;\n}\n\n/**\n * Executes an asynchronous function under a Web Locks API origin-wide lock.\n * It runs the task directly when the Web Locks API is not available.\n * @param name Origin-scoped lock identifier.\n * @param diagnostics Diagnostics reporter.\n * @param fn Asynchronous task to execute while holding the lock.\n * @param options Lock acquisition options.\n * @param options.skipIfBusy When true, the task does not run if another context holds the lock.\n * @returns Promise of the task result. It resolves to undefined when another context holds the\n * lock. A caller that reads undefined as a task result stops rescheduling.\n */\nexport function withDrainLock<T>(\n name: string,\n diagnostics: Diagnostics,\n fn: () => Promise<T>,\n { skipIfBusy = true }: { skipIfBusy?: boolean } = {},\n): Promise<T | undefined> {\n const locks = (globalThis as { navigator?: { locks?: LockManagerLike } }).navigator?.locks;\n\n // Run the task without a lock when the Web Locks API is not available.\n if (!locks?.request) {\n return fn();\n }\n\n return diagnostics.guardAsync(\n \"storage.degraded\",\n `The library could not get the lock ${name}.`,\n () =>\n locks.request(name, { ifAvailable: skipIfBusy }, (lock) =>\n lock ? fn() : Promise.resolve(undefined),\n ),\n );\n}\n","// src/storage/keys.ts\n//\n// This module returns the sorted localStorage keys that start with a prefix. A sandboxed\n// frame and private mode throw on first access. They do not return null.\n\nimport type { Diagnostics } from \"../core/diagnostics\";\n\n/**\n * Returns all localStorage keys that start with the prefix, in sorted order.\n * @param prefix Storage key prefix to filter by.\n * @param diagnostics Diagnostics reporter.\n * @returns Sorted array of matching storage keys.\n */\nexport function keysWithPrefix(prefix: string, diagnostics: Diagnostics): string[] {\n const out: string[] = [];\n\n diagnostics.guard(\n \"storage.unavailable\",\n \"The library could not list the localStorage keys.\",\n () => {\n for (let i = 0; i < localStorage.length; i++) {\n // localStorage.key(i) has the type string | null. It cannot be null below length. A\n // null check here adds a branch that no test can reach.\n const key = String(localStorage.key(i));\n if (key.startsWith(prefix)) {\n out.push(key);\n }\n }\n },\n );\n\n return out.sort();\n}\n","// src/storage/emergency-queue.ts\n//\n// This module keeps a synchronous localStorage queue. It holds oversized batches during unload.\n// Startup recovers them. The code is synchronous and never throws. It runs while the browser\n// destroys the document. No promise settles at that time.\n\nimport {\n BATCH_KEY_TIME_WIDTH,\n EMERGENCY_LOCK_NAME,\n EMERGENCY_MAX_ENTRIES,\n EMERGENCY_STORAGE_KEY_PREFIX,\n STORAGE_DEADLINE_MS,\n} from \"../constants\";\nimport type { Diagnostics } from \"../core/diagnostics\";\nimport { isLogBatch, type LogBatch } from \"../models/batch\";\nimport type { StorageAdapter } from \"../models/storage\";\nimport { withDeadline } from \"../utils/deadline\";\nimport { withDrainLock } from \"../utils/lock\";\nimport { keysWithPrefix } from \"./keys\";\n\n/**\n * Formats a storage key with a zero-padded creation time. The keys sort in FIFO\n * order.\n * @param batch Target log batch.\n * @returns Prefixed, timestamp-ordered storage key.\n */\nfunction keyFor(batch: LogBatch): string {\n const at = String(batch.createdAt).padStart(BATCH_KEY_TIME_WIDTH, \"0\");\n return `${EMERGENCY_STORAGE_KEY_PREFIX}${at}.${batch.id}`;\n}\n\n/**\n * Parses a raw storage string and validates it as a LogBatch.\n * @param raw Raw serialized storage string.\n * @param diagnostics Diagnostics reporter.\n * @returns Validated LogBatch or null if unparseable or malformed.\n */\nfunction readBatch(raw: string, diagnostics: Diagnostics): LogBatch | null {\n const parsed = diagnostics.guard(\n \"storage.degraded\",\n \"An emergency entry is not valid JSON. The library dropped it.\",\n () => JSON.parse(raw) as unknown,\n );\n\n // The guard above already reported a parse failure.\n if (parsed === undefined) {\n return null;\n }\n\n if (!isLogBatch(parsed)) {\n diagnostics.report(\n \"storage.degraded\",\n \"An emergency entry is not a batch. The library dropped it.\",\n );\n return null;\n }\n\n return parsed;\n}\n\n/**\n * Imports all emergency queue entries into the target adapter in FIFO order.\n * @param storage Destination storage adapter.\n * @param diagnostics Diagnostics reporter.\n * @returns Total number of recovered batches.\n */\nasync function importAll(storage: StorageAdapter, diagnostics: Diagnostics): Promise<number> {\n let moved = 0;\n\n for (const key of keysWithPrefix(EMERGENCY_STORAGE_KEY_PREFIX, diagnostics)) {\n // Read and remove the key in one synchronous step, before the async save. A second window\n // that imports at the same time cannot take the same batch.\n const raw = diagnostics.guard(\n \"storage.unavailable\",\n \"The library could not read the emergency queue.\",\n () => {\n const value = localStorage.getItem(key);\n localStorage.removeItem(key);\n return value;\n },\n );\n\n if (!raw) {\n continue;\n }\n\n const batch = readBatch(raw, diagnostics);\n if (batch === null) {\n continue;\n }\n\n try {\n // Set a deadline. This code runs during startup. A save that does not settle keeps the\n // runtime not ready. Each record then goes to the boot buffer.\n await withDeadline(storage.save(batch), STORAGE_DEADLINE_MS);\n moved++;\n } catch (error) {\n diagnostics.report(\n \"storage.degraded\",\n \"The library could not recover an emergency batch.\",\n { key },\n error,\n );\n }\n }\n\n return moved;\n}\n\n/**\n * Writes an unsent batch to the emergency queue synchronously during unload.\n * @param batch Oversized log batch.\n * @param diagnostics Diagnostics reporter.\n */\nexport function saveToEmergencyQueue(batch: LogBatch, diagnostics: Diagnostics): void {\n // Name the record count. A full localStorage drops this batch permanently. Removal of\n // emergency keys cannot free quota that the keys of other applications use.\n const context = `writing the emergency queue, ${String(batch.records.length)} records`;\n\n diagnostics.guard(\"storage.quota_exceeded\", context, () => {\n const keys = keysWithPrefix(EMERGENCY_STORAGE_KEY_PREFIX, diagnostics);\n\n // Remove the oldest entries to keep the queue within its capacity.\n for (const old of keys.slice(0, Math.max(0, keys.length - EMERGENCY_MAX_ENTRIES + 1))) {\n localStorage.removeItem(old);\n }\n\n localStorage.setItem(keyFor(batch), JSON.stringify(batch));\n });\n}\n\n/**\n * Recovers the batches that earlier shutdowns saved to emergency storage.\n * @param storage Destination storage adapter.\n * @param diagnostics Diagnostics reporter.\n * @returns Promise resolving to the number of recovered batches.\n */\nexport async function drainEmergencyQueue(\n storage: StorageAdapter,\n diagnostics: Diagnostics,\n): Promise<number> {\n const moved = await withDrainLock(\n EMERGENCY_LOCK_NAME,\n diagnostics,\n () => importAll(storage, diagnostics),\n { skipIfBusy: false },\n );\n\n return moved ?? 0;\n}\n","// src/storage/local-storage.ts\n//\n// This module stores batches in localStorage with time-ordered keys. The padding makes\n// keys().sort() a sort by creation time. Without padding, the sort uses hex order. take()\n// then does not return the oldest batch first.\n\nimport {\n BATCH_KEY_TIME_WIDTH,\n BATCH_STORAGE_KEY_PREFIX,\n QUOTA_EVICTION_DIVISOR,\n STORAGE_NAME_LOCAL,\n} from \"../constants\";\nimport type { Diagnostics } from \"../core/diagnostics\";\nimport { isLogBatch, type LogBatch } from \"../models/batch\";\nimport type { GapReporter, PruneResult, StorageAdapter, StorageLimits } from \"../models/storage\";\nimport { keysWithPrefix } from \"./keys\";\n\n/**\n * Formats a storage key with a zero-padded creation time. The keys sort in FIFO\n * order. Always use batch.createdAt, never Date.now(). A key from Date.now() does not match\n * the written key.\n * @param batch Target log batch.\n * @returns Prefixed, timestamp-ordered storage key.\n */\nfunction keyFor(batch: LogBatch): string {\n const at = String(batch.createdAt).padStart(BATCH_KEY_TIME_WIDTH, \"0\");\n return `${BATCH_STORAGE_KEY_PREFIX}${at}.${batch.id}`;\n}\n\n/**\n * Reads the creation time from a storage key. prune() runs after each save. A\n * read from the batch parses the full store for each save.\n * @param key Prefixed storage key.\n * @returns Creation time in epoch milliseconds, or null if the key is malformed.\n */\nfunction createdAtOf(key: string): number | null {\n const start = BATCH_STORAGE_KEY_PREFIX.length;\n const at = Number(key.slice(start, start + BATCH_KEY_TIME_WIDTH));\n\n return Number.isFinite(at) ? at : null;\n}\n\n/** This StorageAdapter keeps batches in localStorage. */\nexport class LocalStorageStorage implements StorageAdapter {\n /** This field holds the storage strategy name. */\n readonly name = STORAGE_NAME_LOCAL;\n\n /**\n * @param limits Storage capacity and retention thresholds.\n * @param diagnostics Diagnostics reporter.\n * @param onGap Optional callback for dropped record reporting.\n */\n constructor(\n private readonly limits: StorageLimits,\n private readonly diagnostics: Diagnostics,\n private readonly onGap?: GapReporter,\n ) {}\n\n /**\n * Writes a batch to localStorage. It removes the oldest entries on a quota error.\n * @param batch Batch to store.\n */\n async save(batch: LogBatch): Promise<void> {\n if (this.write(batch, \"localStorage refused a batch, evicting the oldest\")) {\n await this.prune();\n return;\n }\n\n this.evictForQuota();\n\n // The eviction makes room for this batch. Without a second write, save() resolves but the\n // batch is lost and not counted.\n if (!this.write(batch, \"localStorage refused a batch even after evicting\")) {\n this.reportGap({ batches: 1, records: batch.records.length, reason: \"quota\" });\n }\n }\n\n /**\n * Returns up to `limit` batches in FIFO order. It does not delete them.\n * @param limit Maximum number of batches to retrieve.\n * @returns Promise resolving to an array of valid batches.\n */\n take(limit: number): Promise<LogBatch[]> {\n const out: LogBatch[] = [];\n\n for (const key of this.keys().slice(0, limit)) {\n const batch = this.read(key);\n // The entry is corrupt and cannot be recovered. Remove it without a gap count. It has\n // no readable record count.\n if (batch === null) {\n this.removeKey(key);\n continue;\n }\n out.push(batch);\n }\n\n return Promise.resolve(out);\n }\n\n /**\n * Deletes the batch with the given ID from localStorage.\n * @param id Batch identifier.\n */\n remove(id: string): Promise<void> {\n const key = this.keyOf(id);\n if (key !== null) {\n this.removeKey(key);\n }\n return Promise.resolve();\n }\n\n /**\n * Sets the delivery attempt count of a stored batch. It does not change the key.\n * @param id Batch identifier.\n * @param attempts New absolute attempt count.\n */\n bumpAttempts(id: string, attempts: number): Promise<void> {\n const key = this.keyOf(id);\n if (key === null) {\n return Promise.resolve();\n }\n\n const batch = this.read(key);\n if (batch === null) {\n return Promise.resolve();\n }\n\n batch.attempts = attempts;\n this.diagnostics.guard(\n \"storage.degraded\",\n \"The library could not update the attempt count.\",\n () => {\n localStorage.setItem(key, JSON.stringify(batch));\n },\n );\n\n return Promise.resolve();\n }\n\n /**\n * Deletes expired batches. It then removes the oldest batches above the\n * capacity limit.\n * @returns Promise resolving to prune summary metrics.\n */\n prune(): Promise<PruneResult> {\n const cutoff = Date.now() - this.limits.maxAgeMs;\n const result: PruneResult = { batches: 0, records: 0, reason: \"expired\" };\n\n // Parse only the deleted batches. The record count is the one field that the key does\n // not contain.\n const drop = (key: string): void => {\n const batch = this.read(key);\n this.removeKey(key);\n result.batches++;\n result.records += batch?.records.length ?? 0;\n };\n\n const alive: string[] = [];\n\n for (const key of this.keys()) {\n const createdAt = createdAtOf(key);\n // A key with no readable time also has no position in the sort order.\n if (createdAt === null || createdAt < cutoff) {\n drop(key);\n continue;\n }\n alive.push(key);\n }\n\n const excess = alive.length - this.limits.maxBatches;\n if (excess > 0) {\n result.reason = \"over_capacity\";\n for (const key of alive.slice(0, excess)) {\n drop(key);\n }\n }\n\n this.reportGap(result);\n\n return Promise.resolve(result);\n }\n\n /**\n * Returns the number of stored batch keys. It does not deserialize the batches.\n * @returns Promise resolving to batch count.\n */\n count(): Promise<number> {\n return Promise.resolve(this.keys().length);\n }\n\n /** This method deletes all batch keys from localStorage. */\n clear(): Promise<void> {\n this.evict(this.keys());\n return Promise.resolve();\n }\n\n /** This method does nothing. localStorage has no connection to close. */\n close(): Promise<void> {\n return Promise.resolve();\n }\n\n /**\n * Writes a batch to localStorage.\n * @param batch Batch to store.\n * @param context Text that diagnostics reports when the write fails.\n * @returns True if the write succeeded.\n */\n private write(batch: LogBatch, context: string): boolean {\n const written = this.diagnostics.guard(\"storage.quota_exceeded\", context, () => {\n localStorage.setItem(keyFor(batch), JSON.stringify(batch));\n return true;\n });\n\n return written === true;\n }\n\n /** This method removes the oldest quarter of the store to free quota. It counts the loss. */\n private evictForQuota(): void {\n const keys = this.keys();\n const result: PruneResult = { batches: 0, records: 0, reason: \"quota\" };\n\n for (const key of keys.slice(0, Math.ceil(keys.length / QUOTA_EVICTION_DIVISOR))) {\n const stored = this.read(key);\n this.removeKey(key);\n result.batches++;\n result.records += stored?.records.length ?? 0;\n }\n\n this.reportGap(result);\n }\n\n /**\n * Reports dropped records to diagnostics and to the gap handler.\n * @param result Eviction metrics.\n */\n private reportGap(result: PruneResult): void {\n if (result.batches === 0) {\n return;\n }\n\n this.diagnostics.report(\n \"storage.evicted\",\n `The library dropped ${String(result.batches)} stored batches (${String(result.records)} records).`,\n { ...result },\n );\n this.onGap?.(result);\n }\n\n /**\n * Reads and validates the stored batch at a key.\n * @param key Storage key to read.\n * @returns Validated LogBatch or null if missing or malformed.\n */\n private read(key: string): LogBatch | null {\n const raw = this.diagnostics.guard(\n \"storage.unavailable\",\n \"The library could not read a stored batch.\",\n () => localStorage.getItem(key),\n );\n if (!raw) {\n return null;\n }\n\n const parsed = this.diagnostics.guard(\n \"storage.degraded\",\n \"A stored batch is corrupt. The library removed it.\",\n () => JSON.parse(raw) as unknown,\n );\n // The guard above already reported a parse failure. A second report counts one corrupt\n // entry twice.\n if (parsed === undefined) {\n return null;\n }\n\n if (!isLogBatch(parsed)) {\n this.diagnostics.report(\n \"storage.degraded\",\n \"A stored entry is not a batch. The library dropped it.\",\n );\n return null;\n }\n\n return parsed;\n }\n\n /**\n * Finds the storage key that ends with the batch ID.\n * @param id Batch identifier.\n * @returns Matching storage key string or null.\n */\n private keyOf(id: string): string | null {\n return this.keys().find((key) => key.endsWith(`.${id}`)) ?? null;\n }\n\n /**\n * Deletes a list of storage keys.\n * @param keys Keys to delete.\n */\n private evict(keys: string[]): void {\n for (const key of keys) {\n this.removeKey(key);\n }\n }\n\n /**\n * Deletes one storage key inside a guard.\n * @param key Storage key to remove.\n */\n private removeKey(key: string): void {\n this.diagnostics.guard(\n \"storage.degraded\",\n \"The library could not remove a stored batch.\",\n () => {\n localStorage.removeItem(key);\n },\n );\n }\n\n /**\n * Returns all batch storage keys in sorted order.\n * @returns Sorted array of storage keys.\n */\n private keys(): string[] {\n return keysWithPrefix(BATCH_STORAGE_KEY_PREFIX, this.diagnostics);\n }\n}\n","// src/storage/memory-storage.ts\n//\n// This module keeps batches in volatile memory during offline periods. A reload loses all of\n// them. This adapter is the last fallback.\n\nimport { STORAGE_NAME_MEMORY } from \"../constants\";\nimport type { LogBatch } from \"../models/batch\";\nimport type { GapReporter, PruneResult, StorageAdapter, StorageLimits } from \"../models/storage\";\n\n/**\n * Returns the total record count of the batches.\n * @param batches Batches to measure.\n * @returns Total record count.\n */\nfunction countRecords(batches: LogBatch[]): number {\n return batches.reduce((total, batch) => total + batch.records.length, 0);\n}\n\n/** This StorageAdapter keeps batches in volatile memory. */\nexport class MemoryStorage implements StorageAdapter {\n /** This field holds the storage strategy name. */\n readonly name = STORAGE_NAME_MEMORY;\n\n /** This array holds the batches in FIFO order. */\n private batches: LogBatch[] = [];\n\n /**\n * @param limits Storage capacity and retention thresholds.\n * @param onGap Optional callback for dropped record reporting.\n */\n constructor(\n private readonly limits: StorageLimits,\n private readonly onGap?: GapReporter,\n ) {}\n\n /**\n * Appends a batch and applies retention pruning.\n * @param batch Batch to store.\n */\n async save(batch: LogBatch): Promise<void> {\n this.batches.push(batch);\n await this.prune();\n }\n\n /**\n * Returns up to `limit` batches in FIFO order. It does not delete them.\n * @param limit Maximum number of batches to retrieve.\n * @returns Promise resolving to an array of batches.\n */\n take(limit: number): Promise<LogBatch[]> {\n return Promise.resolve(this.batches.slice(0, limit));\n }\n\n /**\n * Deletes the batch with the given ID.\n * @param id Batch identifier.\n */\n remove(id: string): Promise<void> {\n this.batches = this.batches.filter((batch) => batch.id !== id);\n return Promise.resolve();\n }\n\n /**\n * Sets the delivery attempt count of a stored batch.\n * @param id Batch identifier.\n * @param attempts New absolute attempt count.\n */\n bumpAttempts(id: string, attempts: number): Promise<void> {\n const found = this.batches.find((batch) => batch.id === id);\n if (found) {\n found.attempts = attempts;\n }\n return Promise.resolve();\n }\n\n /**\n * Removes expired batches. It then removes the oldest batches above the\n * capacity limit.\n * @returns Promise resolving to prune summary metrics.\n */\n prune(): Promise<PruneResult> {\n const cutoff = Date.now() - this.limits.maxAgeMs;\n const result: PruneResult = { batches: 0, records: 0, reason: \"expired\" };\n\n const expired = this.batches.filter((batch) => batch.createdAt < cutoff);\n this.batches = this.batches.filter((batch) => batch.createdAt >= cutoff);\n result.batches += expired.length;\n result.records += countRecords(expired);\n\n const excess = this.batches.length - this.limits.maxBatches;\n if (excess > 0) {\n result.reason = \"over_capacity\";\n const evicted = this.batches.slice(0, excess);\n this.batches = this.batches.slice(excess);\n result.batches += evicted.length;\n result.records += countRecords(evicted);\n }\n\n if (result.batches > 0) {\n this.onGap?.(result);\n }\n\n return Promise.resolve(result);\n }\n\n /**\n * Returns the number of stored batches.\n * @returns Promise resolving to batch count.\n */\n count(): Promise<number> {\n return Promise.resolve(this.batches.length);\n }\n\n /** This method deletes all stored batches. */\n clear(): Promise<void> {\n this.batches = [];\n return Promise.resolve();\n }\n\n /** This method deletes all stored batches when the storage closes. */\n close(): Promise<void> {\n this.batches = [];\n return Promise.resolve();\n }\n}\n","// src/storage/factory.ts\n//\n// This module selects a storage adapter. It falls back from IndexedDB to localStorage to memory.\n// It falls back and does not throw. IndexedDB is unavailable in private mode and sandboxed\n// frames.\n\nimport {\n STORAGE_NAME_INDEXEDDB,\n STORAGE_NAME_MEMORY,\n STORAGE_NAME_NONE,\n STORAGE_PROBE_KEY,\n} from \"../constants\";\nimport type { Diagnostics } from \"../core/diagnostics\";\nimport type { StorageStrategy } from \"../models/config\";\nimport type { GapReporter, StorageAdapter, StorageLimits } from \"../models/storage\";\nimport { LocalStorageStorage } from \"./local-storage\";\nimport { MemoryStorage } from \"./memory-storage\";\n\n/**\n * This adapter does nothing. The factory returns it for the \"none\" strategy. Each method\n * resolves. A sender that calls close() on shutdown must not crash.\n */\nconst noop: StorageAdapter = {\n name: STORAGE_NAME_NONE,\n save: () => Promise.resolve(),\n take: () => Promise.resolve([]),\n remove: () => Promise.resolve(),\n bumpAttempts: () => Promise.resolve(),\n prune: () => Promise.resolve({ batches: 0, records: 0, reason: \"expired\" as const }),\n count: () => Promise.resolve(0),\n clear: () => Promise.resolve(),\n close: () => Promise.resolve(),\n};\n\n/**\n * Checks whether IndexedDB is available in the current context.\n * @param diagnostics Diagnostics reporter.\n * @returns True if IDBFactory is available.\n */\nfunction hasIndexedDb(diagnostics: Diagnostics): boolean {\n const available = diagnostics.guard(\n \"storage.unavailable\",\n \"The library could not read indexedDB.\",\n () => {\n const factory = (globalThis as { indexedDB?: IDBFactory | null }).indexedDB;\n return factory !== undefined && factory !== null;\n },\n );\n\n return available === true;\n}\n\n/**\n * Checks whether localStorage is available and accepts writes.\n * @param diagnostics Diagnostics reporter.\n * @returns True if localStorage probe write succeeds.\n */\nfunction hasLocalStorage(diagnostics: Diagnostics): boolean {\n const usable = diagnostics.guard(\n \"storage.unavailable\",\n \"The library could not write a test key to localStorage.\",\n () => {\n localStorage.setItem(STORAGE_PROBE_KEY, \"1\");\n localStorage.removeItem(STORAGE_PROBE_KEY);\n return true;\n },\n );\n\n return usable === true;\n}\n\n/**\n * Creates the requested storage adapter. It falls back to the next adapter when\n * a dependency is unavailable.\n * @param strategy Configured persistence strategy.\n * @param dbName IndexedDB database name.\n * @param limits Storage retention and capacity thresholds.\n * @param diagnostics Diagnostics reporter.\n * @param onGap Optional callback for telemetry gap reporting.\n * @returns Promise resolving to the selected StorageAdapter instance.\n */\nexport async function createStorage(\n strategy: StorageStrategy,\n dbName: string,\n limits: StorageLimits,\n diagnostics: Diagnostics,\n onGap?: GapReporter,\n): Promise<StorageAdapter> {\n if (strategy === STORAGE_NAME_NONE) {\n return noop;\n }\n if (strategy === STORAGE_NAME_MEMORY) {\n return new MemoryStorage(limits, onGap);\n }\n\n if (strategy === STORAGE_NAME_INDEXEDDB || strategy === \"auto\") {\n if (hasIndexedDb(diagnostics)) {\n // Import IndexedDbStorage dynamically. This keeps the driver out of the main bundle. A\n // chunk that does not load falls back to the next adapter.\n const adapter = await diagnostics.guardAsync(\n \"storage.unavailable\",\n \"The library could not open IndexedDB.\",\n async () => {\n const { IndexedDbStorage } = await import(\"./indexeddb-storage\");\n const storage = new IndexedDbStorage(dbName, limits, diagnostics, onGap);\n // Open the database here, not on first use. Private mode, a corrupt profile and\n // some WebViews define indexedDB but reject open(). Only a rejection in this\n // block selects the next adapter.\n await storage.open();\n return storage;\n },\n );\n if (adapter) {\n return adapter;\n }\n }\n\n if (strategy === STORAGE_NAME_INDEXEDDB) {\n diagnostics.report(\n \"storage.degraded\",\n \"IndexedDB is not available. The library uses memory storage instead.\",\n );\n return new MemoryStorage(limits, onGap);\n }\n }\n\n if (hasLocalStorage(diagnostics)) {\n return new LocalStorageStorage(limits, diagnostics, onGap);\n }\n\n diagnostics.report(\n \"storage.degraded\",\n \"No persistent storage is available. The library keeps undelivered records in memory only.\",\n );\n return new MemoryStorage(limits, onGap);\n}\n","// src/transport/errors.ts\n//\n// This module classifies HTTP transport failures. It also parses the Retry-After header.\n\nimport { MILLIS_PER_SECOND } from \"../constants\";\n\n/**\n * The failure kind sets the retry, backoff or drop behavior. The engine retries transient,\n * offline and timeout failures with backoff. A throttled failure waits for the server delay.\n * A too_large failure splits the batch. The engine drops a permanent failure. The server\n * never accepts that batch.\n */\nexport type TransportFailureKind =\n \"transient\" | \"throttled\" | \"too_large\" | \"permanent\" | \"timeout\" | \"offline\";\n\n/** This error records a failed transport attempt, its failure kind and its metadata. */\nexport class TransportError extends Error {\n /**\n * @param kind Failure classification.\n * @param message Error description.\n * @param status Optional HTTP response status code.\n * @param retryAfterMs Delay requested by the server in milliseconds.\n * @param maxBytes Maximum payload bytes suggested by a 413 response.\n * @param cause Error that caused this failure.\n */\n constructor(\n public readonly kind: TransportFailureKind,\n message: string,\n public readonly status?: number,\n public readonly retryAfterMs?: number,\n public readonly maxBytes?: number,\n cause?: unknown,\n ) {\n super(message, cause === undefined ? undefined : { cause });\n this.name = \"TransportError\";\n }\n}\n\n/**\n * Parses an HTTP Retry-After value into a delay in milliseconds. The value\n * can be a number of seconds or an HTTP date. The function clamps a negative delay to zero.\n * A date in the past gives a negative delay.\n * @param header Raw Retry-After header string or null.\n * @returns Non-negative delay in milliseconds, or undefined if invalid or missing.\n */\nexport function parseRetryAfter(header: string | null): number | undefined {\n if (!header) {\n return undefined;\n }\n\n const seconds = Number(header);\n if (Number.isFinite(seconds)) {\n return Math.max(0, seconds * MILLIS_PER_SECOND);\n }\n\n const date = Date.parse(header);\n return Number.isNaN(date) ? undefined : Math.max(0, date - Date.now());\n}\n","// src/transport/serializers/ecs.ts\n//\n// This module serializes log batches as Elastic Common Schema (ECS) newline-delimited JSON.\n\nimport {\n ATTR_PAGE_URL,\n ATTR_URL_FULL,\n CONTENT_TYPE_NDJSON,\n ECS_LEVEL_NAMES,\n NANOS_PATTERN,\n NANOS_PER_MILLI,\n RESOURCE_BROWSER_USER_AGENT,\n RESOURCE_DEPLOYMENT_ENVIRONMENT,\n RESOURCE_SERVICE_NAME,\n RESOURCE_SERVICE_VERSION,\n SERIALIZER_NAME_ECS,\n} from \"../../constants\";\nimport type { LogRecord } from \"../../models/log-record\";\nimport type { LogSerializer, SerializedBatch } from \"../../models/serializer\";\n\n/**\n * Converts a nanosecond epoch string to epoch milliseconds. A record from the\n * bus has passed only a shape check. BigInt throws a SyntaxError on a non-numeric string.\n * That error loses the whole batch, not one record.\n * @param timeUnixNano Nanosecond epoch as decimal digits.\n * @returns Epoch milliseconds, or the current time when the input is not numeric.\n */\nfunction toMillis(timeUnixNano: string): number {\n if (!NANOS_PATTERN.test(timeUnixNano)) {\n return Date.now();\n }\n\n return Number(BigInt(timeUnixNano) / NANOS_PER_MILLI);\n}\n\n/** Elasticsearch maps these value types under `labels` without a dynamic mapping conflict. */\ntype LabelValue = string | number | boolean;\n\n/**\n * Converts a value to its label form.\n * @param value Raw attribute or resource value.\n * @returns Scalar label value, or null when the value has no scalar form.\n */\nfunction toLabelValue(value: unknown): LabelValue | null {\n if (typeof value === \"string\" || typeof value === \"number\" || typeof value === \"boolean\") {\n return value;\n }\n\n // JSON.stringify throws on a BigInt. That error loses the whole batch.\n if (typeof value === \"bigint\") {\n return value.toString();\n }\n\n return null;\n}\n\n/**\n * Writes one label. It folds a repeated key into an array. Elasticsearch reads\n * a repeated leaf as one multi-valued field. An array of objects maps the same way.\n * @param labels Label map being built.\n * @param key Dotted label key.\n * @param value Scalar label value.\n */\nfunction pushLabel(labels: Record<string, unknown>, key: string, value: LabelValue): void {\n const existing = labels[key];\n\n if (existing === undefined) {\n labels[key] = value;\n return;\n }\n\n if (Array.isArray(existing)) {\n (existing as LabelValue[]).push(value);\n return;\n }\n\n labels[key] = [existing, value];\n}\n\n/**\n * Flattens one value into dotted label keys. ECS `labels` is a flat map. A\n * nested object under it causes an Elasticsearch dynamic mapping conflict.\n * @param labels Label map being built.\n * @param key Dotted key for this value.\n * @param value Value to flatten.\n * @param seen Active ancestor objects. This set stops infinite recursion on a cycle.\n */\nfunction flattenLabel(\n labels: Record<string, unknown>,\n key: string,\n value: unknown,\n seen: WeakSet<object>,\n): void {\n const scalar = toLabelValue(value);\n\n if (scalar !== null) {\n pushLabel(labels, key, scalar);\n return;\n }\n\n // A forwarded record has passed only a shape check. Its attributes can contain a cycle.\n if (typeof value !== \"object\" || value === null || seen.has(value)) {\n return;\n }\n\n seen.add(value);\n\n if (Array.isArray(value)) {\n for (const item of value as unknown[]) {\n flattenLabel(labels, key, item, seen);\n }\n } else {\n for (const [name, entry] of Object.entries(value)) {\n flattenLabel(labels, `${key}.${name}`, entry, seen);\n }\n }\n\n // Remove the object on unwind. Otherwise a repeated sibling reads as a cycle.\n seen.delete(value);\n}\n\n/**\n * Flattens an attribute or resource map into ECS labels.\n * @param source Attribute or resource map.\n * @returns Flat label map keyed by dotted path.\n */\nfunction toLabels(source: Record<string, unknown>): Record<string, unknown> {\n // Use a null prototype. An attribute named `__proto__` must become a key, not a prototype.\n const labels: Record<string, unknown> = Object.create(null) as Record<string, unknown>;\n const seen = new WeakSet();\n\n for (const [key, value] of Object.entries(source)) {\n flattenLabel(labels, key, value, seen);\n }\n\n return labels;\n}\n\n/** This serializer writes log records as Elastic Common Schema (ECS) NDJSON documents. */\nexport const ecsSerializer: LogSerializer = {\n /** This field holds the format name. */\n name: SERIALIZER_NAME_ECS,\n\n /**\n * Serializes log records into newline-delimited ECS JSON documents.\n * @param records Records to serialize.\n * @returns Serialized NDJSON batch payload.\n */\n serialize(records: LogRecord[]): SerializedBatch {\n const lines = records.map((record) => {\n const millis = toMillis(record.timeUnixNano);\n\n return JSON.stringify({\n \"@timestamp\": new Date(millis).toISOString(),\n message: record.body,\n log: { level: ECS_LEVEL_NAMES[record.severityText] ?? record.severityText.toLowerCase() },\n trace: { id: record.traceId },\n span: { id: record.spanId },\n service: {\n name: record.resource[RESOURCE_SERVICE_NAME],\n version: record.resource[RESOURCE_SERVICE_VERSION],\n environment: record.resource[RESOURCE_DEPLOYMENT_ENVIRONMENT],\n },\n user_agent: { original: record.resource[RESOURCE_BROWSER_USER_AGENT] },\n // Use the request URL of a captured network event before the page URL.\n url: {\n full: record.attributes[ATTR_URL_FULL] ?? record.attributes[ATTR_PAGE_URL],\n },\n // Spread the attributes last. A record attribute overrides a resource key with the same\n // name.\n labels: { ...toLabels(record.resource), ...toLabels(record.attributes) },\n });\n });\n\n return { body: `${lines.join(\"\\n\")}\\n`, contentType: CONTENT_TYPE_NDJSON };\n },\n};\n","// src/transport/serializers/otlp.ts\n//\n// This module serializes log batches as OTLP/JSON log records. It groups the records by resource.\n\nimport {\n CONTENT_TYPE_JSON,\n SERIALIZER_NAME_OTLP,\n TELEMETRY_SDK_NAME,\n TELEMETRY_SDK_VERSION,\n} from \"../../constants\";\nimport type { LogRecord } from \"../../models/log-record\";\nimport type { LogSerializer, SerializedBatch } from \"../../models/serializer\";\n\n/** This type holds an OTLP AnyValue with typed value wrappers. */\ntype AnyValue = Record<string, unknown>;\n\n/** This interface holds an OTLP KeyValue pair. */\ninterface KeyValue {\n /** This field holds the attribute key. */\n key: string;\n /** This field holds the typed AnyValue. */\n value: AnyValue;\n}\n\n/** This interface holds the records that share resource attributes. */\ninterface ResourceGroup {\n /** This field holds the resource attribute map. */\n resource: Record<string, unknown>;\n /** This field holds the log records of the resource. */\n records: LogRecord[];\n}\n\n/**\n * Wraps a JavaScript value in an OTLP AnyValue.\n * @param value Raw attribute or resource value.\n * @returns Typed AnyValue object or null if unsupported.\n */\nfunction toAnyValue(value: unknown): AnyValue | null {\n if (value === null || value === undefined) {\n return null;\n }\n\n if (typeof value === \"string\") {\n return { stringValue: value };\n }\n\n if (typeof value === \"boolean\") {\n return { boolValue: value };\n }\n\n // Encode int64 as a decimal string. The OTLP protobuf JSON mapping requires it. A conforming\n // collector returns a 400 status for a number. The response does not give the cause.\n if (typeof value === \"number\") {\n return Number.isInteger(value) ? { intValue: String(value) } : { doubleValue: value };\n }\n\n // Convert a BigInt to a decimal string. JSON.stringify throws on a BigInt and loses the\n // batch.\n if (typeof value === \"bigint\") {\n return { intValue: value.toString() };\n }\n\n if (Array.isArray(value)) {\n const items: readonly unknown[] = value;\n const values = items.map(toAnyValue).filter((item): item is AnyValue => item !== null);\n\n return { arrayValue: { values } };\n }\n\n if (typeof value === \"object\") {\n const nested = value as Record<string, unknown>;\n return { kvlistValue: { values: toKeyValues(nested) } };\n }\n\n return null;\n}\n\n/**\n * Converts a plain object to an array of OTLP KeyValue pairs.\n * @param source Key-value attribute object.\n * @returns Array of valid KeyValue pairs.\n */\nfunction toKeyValues(source: Record<string, unknown>): KeyValue[] {\n const out: KeyValue[] = [];\n\n for (const [key, raw] of Object.entries(source)) {\n const value = toAnyValue(raw);\n if (value) {\n out.push({ key, value });\n }\n }\n\n return out;\n}\n\n/** This map caches the JSON key of each resource object. It prevents a repeated stringify. */\nconst resourceKeys = new WeakMap<object, string>();\n\n/**\n * Returns the stable JSON key of a resource object. It caches the key.\n * @param resource Resource attribute object.\n * @returns JSON key string.\n */\nfunction resourceKey(resource: Record<string, unknown>): string {\n const cached = resourceKeys.get(resource);\n if (cached !== undefined) {\n return cached;\n }\n\n const key = JSON.stringify(resource);\n resourceKeys.set(resource, key);\n\n return key;\n}\n\n/** This serializer writes log records as OTLP/JSON payloads. */\nexport const otlpSerializer: LogSerializer = {\n /** This field holds the format name. */\n name: SERIALIZER_NAME_OTLP,\n\n /**\n * Groups records by resource. It encodes them as an OTLP\n * ExportLogsServiceRequest JSON payload.\n * @param records Array of log records to serialize.\n * @returns Serialized JSON batch payload.\n */\n serialize(records: LogRecord[]): SerializedBatch {\n const groups = new Map<string, ResourceGroup>();\n\n for (const record of records) {\n const key = resourceKey(record.resource);\n const group = groups.get(key);\n\n if (group) {\n group.records.push(record);\n continue;\n }\n\n groups.set(key, { resource: record.resource, records: [record] });\n }\n\n const resourceLogs = [...groups.values()].map((group) => ({\n resource: { attributes: toKeyValues(group.resource) },\n scopeLogs: [\n {\n scope: { name: TELEMETRY_SDK_NAME, version: TELEMETRY_SDK_VERSION },\n logRecords: group.records.map((record) => ({\n timeUnixNano: record.timeUnixNano,\n // Use timeUnixNano when observedTimeUnixNano is not set.\n observedTimeUnixNano: record.observedTimeUnixNano ?? record.timeUnixNano,\n severityNumber: record.severityNumber,\n severityText: record.severityText,\n body: { stringValue: record.body },\n traceId: record.traceId,\n spanId: record.spanId,\n flags: record.traceFlags,\n attributes: toKeyValues(record.attributes),\n })),\n },\n ],\n }));\n\n return {\n body: JSON.stringify({ resourceLogs }),\n contentType: CONTENT_TYPE_JSON,\n };\n },\n};\n","// src/transport/serializers/select.ts\n//\n// This module maps the serializer option to an implementation. Only transport code imports\n// this module. config.ts keeps only the name. The main chunk then contains no serializer.\n\nimport type { Diagnostics } from \"../../core/diagnostics\";\nimport type { LogBatch } from \"../../models/batch\";\nimport type { SerializerChoice } from \"../../models/config\";\nimport type { LogSerializer, SerializedBatch } from \"../../models/serializer\";\nimport { ecsSerializer } from \"./ecs\";\nimport { otlpSerializer } from \"./otlp\";\n\n/**\n * Returns the implementation for a resolved serializer option.\n * @param choice Serializer name, or a custom implementation.\n * @returns Serializer implementation.\n */\nexport function serializerFor(choice: SerializerChoice): LogSerializer {\n if (choice === \"otlp\") {\n return otlpSerializer;\n }\n\n if (choice === \"ecs\") {\n return ecsSerializer;\n }\n\n return choice;\n}\n\n/**\n * Serializes a batch. It reports a serializer that throws, and the caller drops the batch.\n * @param choice Serializer name, or a custom implementation.\n * @param batch Batch to serialize.\n * @param diagnostics Diagnostics reporter.\n * @param message ASD-STE100 sentence for the report.\n * @returns The serialized batch, or undefined if the serializer threw.\n */\nexport function serializeBatch(\n choice: SerializerChoice,\n batch: LogBatch,\n diagnostics: Diagnostics,\n message: string,\n): SerializedBatch | undefined {\n try {\n return serializerFor(choice).serialize(batch.records);\n } catch (error) {\n diagnostics.report(\"transport.serialize_failed\", message, { batchId: batch.id }, error);\n return undefined;\n }\n}\n","// src/transport/status-transport.ts\n//\n// Holds the parts that the HTTP transport and the custom transport share. A status code then\n// has the same meaning on both paths. 2xx accepts the batch. 413 splits it. 429 and 503 throttle.\n// 408 and 5xx retry. Each other code drops the batch.\n\nimport {\n HTTP_FORBIDDEN,\n HTTP_PAYLOAD_TOO_LARGE,\n HTTP_REQUEST_TIMEOUT,\n HTTP_SERVER_ERROR_MIN,\n HTTP_SERVICE_UNAVAILABLE,\n HTTP_TOO_MANY_REQUESTS,\n HTTP_UNAUTHORIZED,\n RETRY_BASE_DELAY_MS,\n} from \"../constants\";\nimport type { Diagnostics } from \"../core/diagnostics\";\nimport type { LogBatch } from \"../models/batch\";\nimport type { ResolvedConfig } from \"../models/config\";\nimport type { SerializedBatch } from \"../models/serializer\";\nimport { TransportError } from \"./errors\";\nimport { serializeBatch } from \"./serializers/select\";\n\n/** The two operations that the pipeline and the retry engine use. */\nexport interface BatchTransport {\n /**\n * Sends one batch.\n * @param batch Batch to send.\n * @throws TransportError when the batch is not accepted.\n */\n send(batch: LogBatch): Promise<void>;\n /**\n * Returns the remaining throttle delay.\n * @returns Milliseconds until the throttle ends, or 0.\n */\n throttledForMs(): number;\n}\n\n/** Hints that come with a rejected batch. */\nexport interface RejectHints {\n /** Delay that the server asks for, in milliseconds. */\n retryAfterMs?: number;\n /** Largest payload that the server accepts, from a 413 answer. */\n maxBytes?: number;\n /** Extra advice for a 401 or a 403 answer. */\n advice?: string;\n}\n\n/** Base class of the HTTP transport and the custom transport. */\nexport abstract class StatusTransport implements BatchTransport {\n /** Epoch time in milliseconds when the server throttle ends. */\n private throttledUntil = 0;\n\n /**\n * @param config Active configuration instance.\n * @param diagnostics Diagnostics reporter.\n * @param onSampling Receives the sampling rules of an accepted batch, before validation.\n */\n constructor(\n protected readonly config: ResolvedConfig,\n protected readonly diagnostics: Diagnostics,\n private readonly onSampling: (raw: unknown) => void = () => undefined,\n ) {}\n\n /**\n * Sends one batch.\n * @param batch Batch to send.\n * @throws TransportError when the batch is not accepted.\n */\n abstract send(batch: LogBatch): Promise<void>;\n\n /**\n * Returns the remaining throttle delay in milliseconds.\n * @returns Milliseconds remaining in throttle window, or 0 if unthrottled.\n */\n throttledForMs(): number {\n return Math.max(0, this.throttledUntil - Date.now());\n }\n\n /**\n * Serializes a batch with the configured serializer. It reports a serializer that throws.\n * @param batch Batch to serialize.\n * @returns The serialized batch, or undefined if the serializer threw.\n */\n protected serialize(batch: LogBatch): SerializedBatch | undefined {\n return serializeBatch(\n this.config.serializer,\n batch,\n this.diagnostics,\n \"The serializer threw an error. The library dropped the batch.\",\n );\n }\n\n /**\n * Records an accepted batch. It ends a server throttle.\n * @param sampling Sampling rules of the answer, as text or as an object.\n */\n protected accept(sampling: unknown): void {\n this.throttledUntil = 0;\n\n // Trust only the answer to a batch that the library sent. A null header means no rules.\n if (this.config.sampling.remote && sampling !== undefined && sampling !== null) {\n this.onSampling(sampling);\n }\n }\n\n /**\n * Converts a status code that is not 2xx into a classified TransportError.\n * @param status Status code of the answer.\n * @param batchId Identifier of the rejected batch.\n * @param hints Delay, size limit and advice that come with the answer.\n * @returns Classified TransportError instance.\n */\n protected reject(status: number, batchId: string, hints: RejectHints): TransportError {\n const code = String(status);\n\n if (status === HTTP_UNAUTHORIZED || status === HTTP_FORBIDDEN) {\n const advice = hints.advice === undefined ? \"\" : ` ${hints.advice}`;\n\n this.diagnostics.report(\n \"transport.rejected_credentials\",\n `The server returned ${code}.${advice}`,\n { status, endpoint: this.config.endpoint },\n );\n // Classify as permanent. A retry loop on a rejected credential blocks each batch after it.\n return new TransportError(\"permanent\", `The server rejected the batch with ${code}.`, status);\n }\n\n if (status === HTTP_PAYLOAD_TOO_LARGE) {\n return new TransportError(\n \"too_large\",\n \"The payload is too large.\",\n status,\n undefined,\n hints.maxBytes,\n );\n }\n\n if (status === HTTP_TOO_MANY_REQUESTS || status === HTTP_SERVICE_UNAVAILABLE) {\n const throttled = status === HTTP_TOO_MANY_REQUESTS;\n this.throttledUntil = Date.now() + (hints.retryAfterMs ?? RETRY_BASE_DELAY_MS);\n\n if (throttled) {\n this.diagnostics.report(\"transport.throttled\", \"The server throttles the requests.\", {\n retryAfterMs: hints.retryAfterMs,\n });\n }\n\n return new TransportError(\n \"throttled\",\n throttled ? \"The server throttles the requests.\" : \"The service is not available.\",\n status,\n hints.retryAfterMs,\n );\n }\n\n if (status === HTTP_REQUEST_TIMEOUT || status >= HTTP_SERVER_ERROR_MIN) {\n return new TransportError(\"transient\", `The server returned the error ${code}.`, status);\n }\n\n this.diagnostics.report(\n \"transport.dropped_permanent\",\n `The server rejected the batch with ${code}. The library dropped it.`,\n { batchId, status },\n );\n return new TransportError(\"permanent\", `The server rejected the batch with ${code}.`, status);\n }\n}\n","// src/transport/custom-transport.ts\n//\n// Sends batches through the transport function that the consumer supplies. The status codes\n// have the same meaning as on the HTTP path. Retry, storage and the exit flush do not change.\n\nimport {\n HTTP_STATUS_MAX,\n HTTP_STATUS_MIN,\n HTTP_SUCCESS_END,\n HTTP_SUCCESS_MIN,\n REQUEST_TIMEOUT_MS,\n} from \"../constants\";\nimport type { LogBatch } from \"../models/batch\";\nimport type { TransportRequest, TransportResponse } from \"../models/config\";\nimport type { SerializedBatch } from \"../models/serializer\";\nimport { DeadlineError, withDeadline } from \"../utils/deadline\";\nimport { runAsLibraryConsole } from \"../utils/library-console\";\nimport { runAsLibraryRequest } from \"../utils/library-request\";\nimport { TransportError } from \"./errors\";\nimport { StatusTransport } from \"./status-transport\";\n\n/**\n * Builds the request that a custom transport and its exit hook receive.\n * @param batch Batch to send.\n * @param serialized Serialized form of the batch.\n * @returns The transport request.\n */\nexport function toTransportRequest(batch: LogBatch, serialized: SerializedBatch): TransportRequest {\n return {\n body: serialized.body,\n contentType: serialized.contentType,\n batchId: batch.id,\n attempt: batch.attempts,\n records: batch.records,\n };\n}\n\n/**\n * Tests whether a value is a usable transport response.\n * @param value Value that the transport resolved to.\n * @returns True if the value has an integer status from 100 to 599.\n */\nfunction isResponse(value: unknown): value is TransportResponse {\n if (typeof value !== \"object\" || value === null) {\n return false;\n }\n\n const status: unknown = Reflect.get(value, \"status\");\n return (\n typeof status === \"number\" &&\n Number.isInteger(status) &&\n status >= HTTP_STATUS_MIN &&\n status <= HTTP_STATUS_MAX\n );\n}\n\n/**\n * Gives a number hint that the server can use. A string, NaN or Infinity breaks the throttle.\n * @param value Hint that the transport returned.\n * @returns The value, 0 or more, or undefined if it is not a finite number.\n */\nfunction finiteHint(value: unknown): number | undefined {\n return typeof value === \"number\" && Number.isFinite(value) ? Math.max(0, value) : undefined;\n}\n\n/** Sends batches through the consumer's transport function. */\nexport class CustomTransport extends StatusTransport {\n /**\n * Sends one batch through the configured transport function.\n * @param batch Batch to send.\n * @throws TransportError when the batch is not accepted.\n */\n async send(batch: LogBatch): Promise<void> {\n const { transport } = this.config;\n\n if (!transport || batch.records.length === 0) {\n return;\n }\n\n const serialized = this.serialize(batch);\n\n if (!serialized) {\n return;\n }\n\n const request = toTransportRequest(batch, serialized);\n\n let response: unknown;\n\n try {\n // A transport that never settles holds a dispatch slot. The deadline frees the slot.\n response = await withDeadline(\n // The capture modules skip a request or a console line inside these scopes.\n runAsLibraryRequest(() => runAsLibraryConsole(() => transport(request))),\n REQUEST_TIMEOUT_MS,\n );\n } catch (error) {\n // The pipeline reports the thrown error. Classify it here.\n const deadline = error instanceof DeadlineError ? error : undefined;\n const kind = deadline ? \"timeout\" : \"transient\";\n const message = deadline?.message ?? \"The custom transport failed.\";\n\n throw new TransportError(kind, message, undefined, undefined, undefined, error);\n }\n\n if (!isResponse(response)) {\n this.diagnostics.report(\n \"transport.http_error\",\n \"The custom transport returned no valid status. The library sends the batch again later.\",\n { batchId: batch.id },\n );\n throw new TransportError(\"transient\", \"The custom transport returned no valid status.\");\n }\n\n const { status } = response;\n\n if (status >= HTTP_SUCCESS_MIN && status < HTTP_SUCCESS_END) {\n this.accept(response.sampling);\n return;\n }\n\n throw this.reject(status, batch.id, {\n retryAfterMs: finiteHint(response.retryAfterMs),\n maxBytes: finiteHint(response.maxBytes),\n });\n }\n}\n","// src/transport/exit-flush.ts\n//\n// This module flushes buffered batches on exit. It uses sendBeacon, a keepalive fetch or\n// emergency storage. It runs during unload. No code in it awaits.\n\nimport {\n BEACON_LIMIT_BYTES,\n CONTENT_TYPE_TEXT_PLAIN,\n HEADER_CONTENT_TYPE,\n QUERY_PARAM_BATCH_ID,\n QUERY_PARAM_EXIT_REASON,\n} from \"../constants\";\nimport type { Diagnostics } from \"../core/diagnostics\";\nimport type { LogBatch } from \"../models/batch\";\nimport type { ExitTransport, ResolvedConfig } from \"../models/config\";\nimport type { SerializedBatch } from \"../models/serializer\";\nimport { saveToEmergencyQueue } from \"../storage/emergency-queue\";\nimport { runAsLibraryRequest } from \"../utils/library-request\";\nimport { estimateBytes } from \"../utils/sanitize\";\nimport { toTransportRequest } from \"./custom-transport\";\nimport { serializeBatch } from \"./serializers/select\";\n\n/** This type names the lifecycle event or manual action that starts an exit flush. */\nexport type ExitReason = \"hidden\" | \"pagehide\" | \"freeze\" | \"openfin-close\" | \"shutdown\";\n\n/**\n * This type holds the answer of the browser to a beacon. `refused` means that the in-flight\n * budget is full. `unavailable` means that the host has no usable sendBeacon.\n */\ntype BeaconOutcome = \"sent\" | \"refused\" | \"unavailable\";\n\n/** This interface describes the OpenFin window event API that the flush uses. */\ninterface FinMeLike {\n on?: (event: string, listener: () => void) => void;\n removeListener?: (event: string, listener: () => void) => void;\n}\n\n/** This type adds the optional OpenFin runtime API to globalThis. */\ntype OpenFinGlobal = typeof globalThis & { fin?: { me?: FinMeLike } };\n\n/** This type reads navigator.sendBeacon without global DOM type assertions. */\ninterface BeaconGlobal {\n navigator?: { sendBeacon?: (url: string, data: Blob) => boolean };\n}\n\n/** This interface lists the dependencies of ExitFlush. */\nexport interface ExitFlushDeps {\n /** This field holds the active configuration. */\n config: ResolvedConfig;\n /** This field holds the diagnostics reporter. */\n diagnostics: Diagnostics;\n /** This callback drains all buffered and unconfirmed batches into one LogBatch. */\n drainForExit: () => LogBatch | null;\n /** This callback drains only the buffered records. It does not touch an in-flight batch. */\n drainPending: () => LogBatch | null;\n}\n\n/**\n * This class flushes pending telemetry on document unload. It uses sendBeacon, a keepalive\n * fetch or emergency storage.\n */\nexport class ExitFlush {\n /** This flag is true while the unload listeners are attached. */\n private installed = false;\n\n /** This listener flushes on visibilitychange when the document becomes hidden. */\n private readonly onVisibility = (): void => {\n if (document.visibilityState === \"hidden\") {\n this.flush(\"hidden\");\n }\n };\n\n /** This listener flushes on the window pagehide event. */\n private readonly onPageHide = (): void => {\n this.flush(\"pagehide\");\n };\n\n /** This listener flushes on the document freeze event. */\n private readonly onFreeze = (): void => {\n this.flush(\"freeze\");\n };\n\n /** This listener flushes on the OpenFin close-requested event. */\n private readonly onOpenFinClose = (): void => {\n this.flush(\"openfin-close\");\n };\n\n /**\n * @param deps Injected configuration, diagnostics, and drain callback.\n */\n constructor(private readonly deps: ExitFlushDeps) {}\n\n /** This method attaches the unload listeners to the document, the window and OpenFin. */\n install(): void {\n if (this.installed || typeof addEventListener === \"undefined\") {\n return;\n }\n this.installed = true;\n\n if (typeof document !== \"undefined\") {\n // visibilitychange and freeze fire on the document. pagehide fires on the window.\n document.addEventListener(\"visibilitychange\", this.onVisibility);\n document.addEventListener(\"freeze\", this.onFreeze);\n }\n\n addEventListener(\"pagehide\", this.onPageHide);\n\n const me = (globalThis as OpenFinGlobal).fin?.me;\n this.deps.diagnostics.guard(\n \"openfin.unavailable\",\n \"The library could not subscribe to close-requested.\",\n () => {\n me?.on?.(\"close-requested\", this.onOpenFinClose);\n },\n );\n }\n\n /** This method removes all unload listeners and subscriptions. */\n uninstall(): void {\n if (!this.installed) {\n return;\n }\n this.installed = false;\n\n if (typeof document !== \"undefined\") {\n document.removeEventListener(\"visibilitychange\", this.onVisibility);\n document.removeEventListener(\"freeze\", this.onFreeze);\n }\n\n removeEventListener(\"pagehide\", this.onPageHide);\n\n const me = (globalThis as OpenFinGlobal).fin?.me;\n this.deps.diagnostics.guard(\n \"openfin.unavailable\",\n \"The library could not unsubscribe from close-requested.\",\n () => {\n me?.removeListener?.(\"close-requested\", this.onOpenFinClose);\n },\n );\n }\n\n /**\n * Drains pending records synchronously. It sends them with a beacon, a\n * keepalive fetch or emergency storage. It never awaits and never throws. The caller is an\n * unload listener.\n * @param reason Trigger reason code.\n */\n flush(reason: ExitReason): void {\n const { config, diagnostics } = this.deps;\n\n if (config.transport) {\n this.flushCustom(reason, config.transportOnExit);\n return;\n }\n\n const url = this.endpointUrl();\n if (url === null) {\n return;\n }\n\n const batch = this.drain(reason);\n if (!batch || batch.records.length === 0) {\n return;\n }\n\n const serialized = this.serialize(batch, reason);\n if (!serialized) {\n return;\n }\n\n // Save an oversized payload to the synchronous localStorage queue. localStorage is the\n // only storage that accepts a write without await.\n if (estimateBytes(serialized.body) > BEACON_LIMIT_BYTES) {\n saveToEmergencyQueue(batch, diagnostics);\n return;\n }\n\n // Send the batch ID and the reason as query parameters. sendBeacon cannot set headers.\n url.searchParams.set(QUERY_PARAM_BATCH_ID, batch.id);\n url.searchParams.set(QUERY_PARAM_EXIT_REASON, reason);\n\n const target = url.toString();\n const outcome = this.beacon(target, serialized.body);\n if (outcome === \"sent\") {\n return;\n }\n\n // A refusal means the in-flight budget is full. A keepalive fetch uses the\n // same budget and fails the same way. The document closes. No code retries the send.\n if (outcome === \"refused\") {\n saveToEmergencyQueue(batch, diagnostics);\n return;\n }\n\n this.keepaliveFetch(target, serialized.body, reason);\n }\n\n /**\n * Gives the pending records to the exit hook of a custom transport. A page that closes cannot\n * wait for the async transport. Without a hook, or when the hook refuses the batch, the batch\n * goes to the emergency queue. The next page load sends it.\n * @param reason Trigger reason code.\n * @param onExit Synchronous exit hook of the custom transport.\n */\n private flushCustom(reason: ExitReason, onExit: ExitTransport | undefined): void {\n const { diagnostics } = this.deps;\n\n // The page keeps running after a tab switch. The pipeline sends the records later.\n if (reason === \"hidden\" && !onExit) {\n return;\n }\n\n const batch = this.drain(reason);\n if (!batch || batch.records.length === 0) {\n return;\n }\n\n const serialized = this.serialize(batch, reason);\n if (!serialized) {\n return;\n }\n\n const accepted =\n onExit !== undefined &&\n diagnostics.guard(\"transport.http_error\", \"The transportOnExit hook threw an error.\", () =>\n runAsLibraryRequest(() => onExit(toTransportRequest(batch, serialized))),\n ) === true;\n\n if (!accepted) {\n saveToEmergencyQueue(batch, diagnostics);\n }\n }\n\n /**\n * Serializes the exit batch. It reports a serializer that throws.\n * @param batch Batch to serialize.\n * @param reason Trigger reason code.\n * @returns The serialized batch, or undefined if the serializer threw.\n */\n private serialize(batch: LogBatch, reason: ExitReason): SerializedBatch | undefined {\n return serializeBatch(\n this.deps.config.serializer,\n batch,\n this.deps.diagnostics,\n `The ${reason} exit flush could not serialize its batch.`,\n );\n }\n\n /**\n * Selects the drain for the reason. `hidden` occurs at each tab switch. The\n * document continues to run after it. A drain of the in-flight batch here sends it again\n * with a new id. The server cannot deduplicate that second send.\n * @param reason Trigger reason code.\n * @returns Combined LogBatch, or null if no records are pending.\n */\n private drain(reason: ExitReason): LogBatch | null {\n return reason === \"hidden\" ? this.deps.drainPending() : this.deps.drainForExit();\n }\n\n /**\n * Parses the configured endpoint URL.\n * @returns URL instance or null if missing or invalid.\n */\n private endpointUrl(): URL | null {\n const { endpoint } = this.deps.config;\n if (!endpoint) {\n return null;\n }\n\n const url = this.deps.diagnostics.guard(\n \"config.invalid\",\n `The exit flush cannot use the endpoint ${endpoint}.`,\n () => new URL(endpoint),\n );\n\n return url ?? null;\n }\n\n /**\n * Sends the payload as text/plain with navigator.sendBeacon.\n * @param url Target endpoint URL with query parameters.\n * @param body Serialized payload string.\n * @returns The answer of the browser.\n */\n private beacon(url: string, body: string): BeaconOutcome {\n const outcome = this.deps.diagnostics.guard<BeaconOutcome>(\n \"transport.http_error\",\n \"The sendBeacon call failed.\",\n () => {\n // Call sendBeacon on navigator to keep its receiver. A detached sendBeacon throws when\n // called.\n const nav = (globalThis as BeaconGlobal).navigator;\n if (!nav?.sendBeacon) {\n return \"unavailable\";\n }\n\n // Use text/plain to prevent a CORS preflight during unload. A preflight during unload\n // usually does not complete. The browser then drops the beacon without an error.\n const accepted = nav.sendBeacon(url, new Blob([body], { type: CONTENT_TYPE_TEXT_PLAIN }));\n return accepted ? \"sent\" : \"refused\";\n },\n );\n\n // A throw is not a refusal. The method is present but unusable. The keepalive fetch can\n // still succeed.\n return outcome ?? \"unavailable\";\n }\n\n /**\n * Sends a fallback POST with fetch and `keepalive: true`. A keepalive request\n * continues after the document closes. The browser cancels a plain fetch at page close.\n * @param url Target endpoint URL.\n * @param body Serialized payload string.\n * @param reason Trigger reason code.\n */\n private keepaliveFetch(url: string, body: string, reason: ExitReason): void {\n const { config, diagnostics } = this.deps;\n\n diagnostics.guard(\"transport.http_error\", \"The keepalive fetch fallback failed.\", () => {\n void fetch(url, {\n method: \"POST\",\n body,\n headers: { [HEADER_CONTENT_TYPE]: CONTENT_TYPE_TEXT_PLAIN },\n credentials: config.credentials,\n keepalive: true,\n }).catch((error: unknown) => {\n diagnostics.report(\"transport.http_error\", \"The exit flush failed.\", { reason }, error);\n });\n });\n }\n}\n","// src/transport/compression.ts\n//\n// This module compresses payloads with the native CompressionStream API. It returns null\n// when the API is absent. It does not return raw text. The server rejects a non-gzip body\n// that has a \"Content-Encoding: gzip\" header with a 400 status.\n\nimport { ENCODING_GZIP } from \"../constants\";\n\n/**\n * Compresses a string to gzip bytes with CompressionStream. The result is a\n * Uint8Array on a non-shared ArrayBuffer. fetch accepts this result as BodyInit.\n * @param text Raw serialized payload to compress.\n * @returns Promise resolving to compressed Uint8Array, or null if CompressionStream is unsupported.\n */\nexport async function gzip(text: string): Promise<Uint8Array<ArrayBuffer> | null> {\n const CS = (globalThis as { CompressionStream?: typeof CompressionStream }).CompressionStream;\n if (CS === undefined) {\n return null;\n }\n\n const stream = new Blob([text]).stream().pipeThrough(new CS(ENCODING_GZIP));\n const buffer = await new Response(stream).arrayBuffer();\n\n return new Uint8Array(buffer);\n}\n","// src/transport/http-transport.ts\n//\n// This module serializes, compresses and sends log batches over HTTP. It classifies each\n// failure, reports it and throws it. The caller that owns storage decides what happens to a\n// rejected batch.\n\nimport {\n COMPRESSION_THRESHOLD_BYTES,\n ENCODING_GZIP,\n HEADER_ATTEMPT,\n HEADER_BATCH_ID,\n HEADER_CONTENT_ENCODING,\n HEADER_CONTENT_TYPE,\n HEADER_RETRY_AFTER,\n HEADER_SAMPLING,\n HTTP_PAYLOAD_TOO_LARGE,\n REQUEST_TIMEOUT_MS,\n} from \"../constants\";\nimport type { LogBatch } from \"../models/batch\";\nimport { runAsLibraryRequest } from \"../utils/library-request\";\nimport { estimateBytes } from \"../utils/sanitize\";\nimport { unrefTimer } from \"../utils/unref\";\nimport { gzip } from \"./compression\";\nimport { parseRetryAfter, TransportError } from \"./errors\";\nimport { StatusTransport } from \"./status-transport\";\n\n/** Advice for a 401 or a 403 answer on the HTTP path. */\nconst CREDENTIAL_ADVICE =\n \"In a cross-origin iframe, the session cookie is a third-party cookie. The browser \" +\n \"often blocks it. Forward the records to the platform document. As an alternative, \" +\n \"issue the cookie with the Partitioned attribute.\";\n\n/**\n * This class sends serialized log batches over HTTP. It resolves headers, applies gzip\n * compression and classifies errors.\n */\nexport class HttpTransport extends StatusTransport {\n /**\n * Sends one log batch over HTTP.\n * @param batch Batch to send.\n * @throws TransportError on transient, throttled, 413, or permanent network failures.\n */\n async send(batch: LogBatch): Promise<void> {\n const { endpoint } = this.config;\n\n if (!endpoint || batch.records.length === 0) {\n return;\n }\n\n await this.post(batch, endpoint);\n }\n\n /**\n * Serializes, encodes and sends a batch. It throws a classified TransportError\n * on failure.\n * @param batch Batch to deliver.\n * @param endpoint Ingest URL. The caller reads it one time. A reconfigure during the send\n * cannot change it.\n */\n private async post(batch: LogBatch, endpoint: string): Promise<void> {\n const serialized = this.serialize(batch);\n\n if (!serialized) {\n return;\n }\n\n // Headers ignores the case of header names. A config header cannot duplicate a header below.\n const headers = new Headers(await this.resolveHeaders());\n headers.set(HEADER_CONTENT_TYPE, serialized.contentType);\n headers.set(HEADER_BATCH_ID, batch.id);\n headers.set(HEADER_ATTEMPT, String(batch.attempts));\n\n const body = await this.encodeBody(serialized.body);\n if (typeof body !== \"string\") {\n headers.set(HEADER_CONTENT_ENCODING, ENCODING_GZIP);\n }\n\n const response = await this.dispatch(endpoint, headers, body);\n if (response.ok) {\n // The server must list the header in Access-Control-Expose-Headers. Else the value is null.\n this.accept(response.headers.get(HEADER_SAMPLING));\n return;\n }\n\n const status = response.status;\n const retryAfterMs = parseRetryAfter(response.headers.get(HEADER_RETRY_AFTER));\n const maxBytes =\n status === HTTP_PAYLOAD_TOO_LARGE ? await this.readMaxBytes(response) : undefined;\n\n throw this.reject(status, batch.id, { retryAfterMs, maxBytes, advice: CREDENTIAL_ADVICE });\n }\n\n /**\n * Compresses the serialized payload when gzip is enabled. The payload size must\n * be at or above the threshold.\n * @param text Serialized payload string.\n * @returns Promise resolving to original string or compressed byte array.\n */\n private async encodeBody(text: string): Promise<string | Uint8Array<ArrayBuffer>> {\n const { config } = this;\n if (config.compression !== ENCODING_GZIP || estimateBytes(text) < COMPRESSION_THRESHOLD_BYTES) {\n return text;\n }\n\n const compressed = await this.diagnostics.guardAsync(\n \"transport.http_error\",\n \"The library could not compress the payload.\",\n () => gzip(text),\n );\n\n return compressed ?? text;\n }\n\n /**\n * Sends the HTTP POST request with a timeout. It maps network errors to\n * TransportError.\n * @param endpoint Ingest URL.\n * @param headers HTTP request headers.\n * @param body Request body string or byte array.\n * @returns Promise resolving to the HTTP Response.\n * @throws TransportError on network failure, timeout, or offline status.\n */\n private async dispatch(\n endpoint: string,\n headers: Headers,\n body: string | Uint8Array<ArrayBuffer>,\n ): Promise<Response> {\n const { config } = this;\n const controller = new AbortController();\n const timer = setTimeout(() => {\n controller.abort();\n }, REQUEST_TIMEOUT_MS);\n unrefTimer(timer);\n\n try {\n return await runAsLibraryRequest(() =>\n fetch(endpoint, {\n method: \"POST\",\n headers,\n body,\n credentials: config.credentials,\n signal: controller.signal,\n cache: \"no-store\",\n }),\n );\n } catch {\n if (controller.signal.aborted) {\n const waited = String(REQUEST_TIMEOUT_MS);\n throw new TransportError(\"timeout\", `The request took longer than ${waited} ms.`);\n }\n const online = (globalThis as { navigator?: { onLine?: boolean } }).navigator?.onLine;\n throw new TransportError(\n online === false ? \"offline\" : \"transient\",\n \"A network error occurred.\",\n );\n } finally {\n clearTimeout(timer);\n }\n }\n\n /**\n * Reads the optional maxBytes limit from a 413 response body.\n * @param response HTTP 413 Response instance.\n * @returns Promise resolving to maximum byte limit or undefined.\n */\n private async readMaxBytes(response: Response): Promise<number | undefined> {\n return this.diagnostics.guardAsync(\n \"transport.http_error\",\n \"The library could not read the body of the 413 response.\",\n async () => {\n const parsed = JSON.parse(await response.text()) as {\n maxBytes?: unknown;\n };\n return typeof parsed.maxBytes === \"number\" ? parsed.maxBytes : undefined;\n },\n );\n }\n\n /**\n * Resolves the configured static or dynamic request headers.\n * @returns Promise resolving to resolved header map.\n */\n private async resolveHeaders(): Promise<Record<string, string>> {\n const { headers } = this.config;\n if (!headers) {\n return {};\n }\n if (typeof headers !== \"function\") {\n return headers;\n }\n\n const resolved = await this.diagnostics.guardAsync(\n \"transport.http_error\",\n \"The headers() function threw an error.\",\n () => Promise.resolve(headers()),\n );\n return resolved ?? {};\n }\n}\n","// src/transport/retry-engine.ts\n//\n// This module sends stored log batches again in the background. It uses exponential\n// backoff with jitter. It keeps one timer, never a chain of timers. Each scheduling path\n// clears the pending timer first.\n\nimport {\n BATCHES_PER_DRAIN,\n DRAIN_LOCK_NAME,\n RETRY_BASE_DELAY_MS,\n RETRY_IDLE_DELAY_MS,\n RETRY_MAX_DELAY_MS,\n STORAGE_DEADLINE_MS,\n STORAGE_LIMITS,\n} from \"../constants\";\nimport type { Diagnostics } from \"../core/diagnostics\";\nimport { type LogBatch, splitBatch } from \"../models/batch\";\nimport type { ResolvedConfig } from \"../models/config\";\nimport type { StorageAdapter } from \"../models/storage\";\nimport { withDeadline } from \"../utils/deadline\";\nimport { withDrainLock } from \"../utils/lock\";\nimport { unrefTimer } from \"../utils/unref\";\nimport { TransportError } from \"./errors\";\nimport type { BatchTransport } from \"./status-transport\";\n\n/**\n * This class sends persisted offline batches again on a timer. It uses backoff, a cross-tab\n * drain lock and batch splitting.\n */\nexport class RetryEngine {\n /** This field holds the active retry timer handle. It is null when no timer is armed. */\n private timer: ReturnType<typeof setTimeout> | null = null;\n\n /** This field counts consecutive failed deliveries. The backoff calculation uses it. */\n private attempt = 0;\n\n /** This flag is true while a storage drain runs. */\n private draining = false;\n\n /** This flag is true when the engine is stopped. */\n private stopped = false;\n\n /** This listener runs on the online event. It resets the attempt count and starts a drain. */\n private readonly onOnline = (): void => {\n this.attempt = 0;\n this.schedule(0);\n };\n\n /**\n * @param storage Storage adapter holding undelivered batches.\n * @param transport HTTP transport for batch delivery.\n * @param diagnostics Diagnostics reporter.\n * @param config Active configuration instance.\n * @param batchesPerDrain Maximum batches processed per drain tick.\n */\n constructor(\n private readonly storage: StorageAdapter,\n private readonly transport: BatchTransport,\n private readonly diagnostics: Diagnostics,\n private readonly config: ResolvedConfig,\n private readonly batchesPerDrain = BATCHES_PER_DRAIN,\n ) {}\n\n /** This method starts the engine. It listens for online events and arms the first timer. */\n start(): void {\n this.stopped = false;\n\n if (typeof addEventListener !== \"undefined\") {\n addEventListener(\"online\", this.onOnline);\n }\n\n this.schedule(RETRY_IDLE_DELAY_MS);\n }\n\n /** This method schedules an earlier retry when storage receives a new offline batch. */\n nudge(): void {\n if (!this.draining) {\n this.schedule(RETRY_BASE_DELAY_MS);\n }\n }\n\n /**\n * Stores a batch that failed outside the drain loop. It applies the same rules\n * as the drain. It does not store a refused batch whole. A whole batch causes another request\n * with a payload that the server refused.\n * @param batch Rejected batch, with its attempt already counted.\n * @param error Failure thrown by the transport.\n */\n async storeFailed(batch: LogBatch, error: unknown): Promise<void> {\n const parts = this.toStorable(batch, error);\n\n for (const part of parts) {\n await this.bounded(this.storage.save(part));\n }\n\n if (parts.length > 0) {\n this.nudge();\n }\n }\n\n /** This method stops the engine. It removes the listener and clears the pending timer. */\n stop(): void {\n this.stopped = true;\n\n if (typeof removeEventListener !== \"undefined\") {\n removeEventListener(\"online\", this.onOnline);\n }\n\n this.clearTimer();\n }\n\n /**\n * Clears the pending timer. It then schedules a drain after the delay.\n * @param delayMs Delay duration in milliseconds.\n */\n private schedule(delayMs: number): void {\n if (this.stopped) {\n return;\n }\n\n this.clearTimer();\n\n const timer = setTimeout(() => {\n void this.drain();\n }, delayMs);\n\n this.timer = timer;\n unrefTimer(timer);\n }\n\n /**\n * Sets a deadline on a storage call. A call that does not settle keeps\n * `draining` true. This window then runs no more drains.\n * @param work Storage promise to bound.\n * @returns The value of the promise, or a rejection after the deadline.\n */\n private bounded<T>(work: Promise<T>): Promise<T> {\n return withDeadline(work, STORAGE_DEADLINE_MS);\n }\n\n /** This method clears the pending timer when a timer is active. */\n private clearTimer(): void {\n if (this.timer !== null) {\n clearTimeout(this.timer);\n this.timer = null;\n }\n }\n\n /**\n * Calculates the exponential backoff delay from consecutive failures. It applies\n * full jitter, not a fixed offset. With a fixed offset, tabs that reconnect together send\n * their requests at the same time.\n * @returns Backoff duration in milliseconds.\n */\n private backoffMs(): number {\n const exponential = Math.min(RETRY_BASE_DELAY_MS * 2 ** this.attempt, RETRY_MAX_DELAY_MS);\n\n return Math.random() * exponential;\n }\n\n /** This method runs a drain under the origin-wide Web Lock. */\n private async drain(): Promise<void> {\n if (this.draining) {\n return;\n }\n this.draining = true;\n\n try {\n const ran = await withDrainLock(DRAIN_LOCK_NAME, this.diagnostics, () => this.drainLocked());\n\n // The value is undefined when another window holds the lock. Without this reschedule,\n // one lost lock race stops all drains in this window.\n if (ran !== true) {\n this.schedule(RETRY_IDLE_DELAY_MS);\n }\n } finally {\n this.draining = false;\n }\n }\n\n /**\n * Processes batches while it holds the Web Lock. It schedules the next tick.\n * It always resolves. A throw leaves the engine idle with no armed timer.\n * @returns Promise resolving to true on completion.\n */\n private async drainLocked(): Promise<true> {\n try {\n const online = (globalThis as { navigator?: { onLine?: boolean } }).navigator?.onLine;\n if (online === false) {\n this.schedule(RETRY_IDLE_DELAY_MS);\n return true;\n }\n\n const batches = await this.bounded(this.storage.take(this.batchesPerDrain));\n\n if (batches.length === 0) {\n this.schedule(RETRY_IDLE_DELAY_MS);\n return true;\n }\n\n for (const batch of batches) {\n if (this.stopped) {\n return true;\n }\n\n const done = await this.deliver(batch);\n if (!done) {\n return true;\n }\n }\n\n this.schedule(batches.length === this.batchesPerDrain ? 0 : RETRY_IDLE_DELAY_MS);\n return true;\n } catch (error) {\n this.diagnostics.report(\n \"storage.degraded\",\n \"The drain loop threw an error.\",\n undefined,\n error,\n );\n this.attempt++;\n this.schedule(this.backoffMs());\n return true;\n }\n }\n\n /**\n * Tries to deliver one batch. It removes the batch on success. It handles each\n * failure kind on failure.\n * @param batch Log batch to deliver.\n * @returns True to continue with the next batch. False to stop the current drain.\n */\n private async deliver(batch: LogBatch): Promise<boolean> {\n if (batch.attempts >= STORAGE_LIMITS.maxAttempts) {\n this.diagnostics.report(\n \"storage.dead_lettered\",\n `The library dropped a batch after ${batch.attempts.toString()} attempts.`,\n { batchId: batch.id, records: batch.records.length },\n );\n await this.bounded(this.storage.remove(batch.id));\n return true;\n }\n\n try {\n await this.transport.send(batch);\n await this.bounded(this.storage.remove(batch.id));\n this.attempt = 0;\n return true;\n } catch (error) {\n const failure = error instanceof TransportError ? error : undefined;\n\n if (failure?.kind === \"permanent\" || failure?.kind === \"too_large\") {\n await this.replaceStored(batch, error);\n return true;\n }\n\n if (failure?.kind === \"offline\") {\n this.schedule(RETRY_IDLE_DELAY_MS);\n return false;\n }\n\n // A throttle rejects no records. The server asks for the batch later. Do not bump the\n // stored attempts here. A bump dead-letters the batch after five throttled responses.\n if (failure?.kind === \"throttled\") {\n this.attempt++;\n this.schedule(failure.retryAfterMs ?? this.backoffMs());\n return false;\n }\n\n await this.bounded(this.storage.bumpAttempts(batch.id, batch.attempts + 1));\n this.attempt++;\n this.schedule(failure?.retryAfterMs ?? this.backoffMs());\n return false;\n }\n }\n\n /**\n * Replaces a stored batch with the parts that survive its failure. The parts\n * are the split halves, or nothing after a permanent refusal.\n * @param batch Rejected log batch, already held in storage.\n * @param error Failure thrown by the transport.\n */\n private async replaceStored(batch: LogBatch, error: unknown): Promise<void> {\n const parts = this.toStorable(batch, error);\n await this.bounded(this.storage.remove(batch.id));\n\n for (const part of parts) {\n await this.bounded(this.storage.save(part));\n }\n }\n\n /**\n * Selects the batches to keep after a failure. A 413 response splits the batch\n * in two. A permanent refusal keeps nothing. Each other failure keeps the batch whole.\n * @param batch Rejected log batch.\n * @param error Failure thrown by the transport.\n * @returns Batches to persist. The array is empty when the engine drops the records.\n */\n private toStorable(batch: LogBatch, error: unknown): LogBatch[] {\n const failure = error instanceof TransportError ? error : undefined;\n\n if (failure?.kind === \"permanent\") {\n return [];\n }\n\n if (failure?.kind !== \"too_large\") {\n return [batch];\n }\n\n const halves = splitBatch(batch, this.diagnostics);\n\n if (!halves) {\n this.diagnostics.report(\n \"transport.dropped_permanent\",\n \"One record is larger than the server limit. The library dropped it.\",\n {\n batchId: batch.id,\n bodies: batch.records.map((record) => record.body),\n },\n );\n return [];\n }\n\n this.diagnostics.report(\n \"transport.batch_split\",\n \"The server refused the batch because it is too large.\",\n {\n from: batch.records.length,\n to: halves[0].records.length,\n serverMaxBytes: failure.maxBytes,\n },\n );\n\n return halves;\n }\n}\n","// src/core/pipeline.ts\n//\n// This module buffers log and metric streams, makes batches and delivers them.\n//\n// Each stream has its own buffer and flush timer. Thus the exit flush can take each\n// record that is not yet at the transport.\n\nimport {\n ATTR_LOG_TYPE,\n LOG_BATCH_SIZE,\n LOG_FLUSH_INTERVAL_MS,\n LOG_TYPE_METRIC,\n MAX_CONCURRENT_REQUESTS,\n METRIC_BATCH_SIZE,\n METRIC_FLUSH_INTERVAL_MS,\n STORAGE_DEADLINE_MS,\n} from \"../constants\";\nimport type { LogBatch } from \"../models/batch\";\nimport { type LogRecord, nowUnixNano } from \"../models/log-record\";\nimport type { StorageAdapter } from \"../models/storage\";\nimport type { BatchTransport } from \"../transport/status-transport\";\nimport type { RetryEngine } from \"../transport/retry-engine\";\nimport { withDeadline } from \"../utils/deadline\";\nimport { newId } from \"../utils/identity\";\nimport { unrefTimer } from \"../utils/unref\";\nimport type { Diagnostics } from \"./diagnostics\";\nimport { ErrorCeiling } from \"./sampling\";\n\n/** Name of a pipeline stream. */\nexport type StreamName = \"logs\" | \"metrics\";\n\n/**\n * Checks if a log record is a metric.\n * @param record Record to evaluate.\n * @returns True if the record log type attribute equals metric.\n */\nfunction isMetric(record: LogRecord): boolean {\n return record.attributes[ATTR_LOG_TYPE] === LOG_TYPE_METRIC;\n}\n\n/** Batching policy for one record stream. */\nexport interface StreamOptions {\n /** Maximum time in milliseconds that a partial batch waits before the pipeline sends it. */\n flushIntervalMs: number;\n /** Maximum records in a batch. At this count, the pipeline sends the batch early. */\n batchSize: number;\n}\n\n/**\n * Batching policy per stream. Metrics use larger batches and a longer interval.\n * Metrics have a higher volume, and no process waits for them.\n */\nexport const STREAM_OPTIONS: Record<StreamName, StreamOptions> = {\n logs: { flushIntervalMs: LOG_FLUSH_INTERVAL_MS, batchSize: LOG_BATCH_SIZE },\n metrics: { flushIntervalMs: METRIC_FLUSH_INTERVAL_MS, batchSize: METRIC_BATCH_SIZE },\n};\n\n/** One stream's pending records and the timer that closes a partial batch. */\nclass RecordStream {\n /** Pending records in time order. */\n private pending: LogRecord[] = [];\n\n /** Handle of the armed flush timer, or null when none is pending. */\n private timer: ReturnType<typeof setTimeout> | null = null;\n\n /**\n * @param options Batching policy for this stream.\n * @param onFlush Called with this stream when a batch is ready to close.\n */\n constructor(\n readonly options: StreamOptions,\n private readonly onFlush: (stream: RecordStream) => void,\n ) {}\n\n /**\n * Adds a record to the buffer. At batchSize records, it closes the batch.\n * Below batchSize, it starts the interval timer. Without the timer, a small batch\n * waits for the next record. On a quiet page, the next record does not come.\n * @param record Record to enqueue.\n */\n add(record: LogRecord): void {\n this.pending.push(record);\n\n if (this.pending.length >= this.options.batchSize) {\n this.onFlush(this);\n return;\n }\n\n this.arm();\n }\n\n /**\n * Removes and returns all buffered records. It also stops the flush timer.\n * @returns Array of buffered records.\n */\n take(): LogRecord[] {\n this.clearTimer();\n\n const records = this.pending;\n this.pending = [];\n\n return records;\n }\n\n /** Stops the flush timer. The buffered records stay in place. */\n stop(): void {\n this.clearTimer();\n }\n\n /** Arms the flush timer unless one is already pending. */\n private arm(): void {\n if (this.timer !== null) {\n return;\n }\n\n const timer = setTimeout(() => {\n this.timer = null;\n this.onFlush(this);\n }, this.options.flushIntervalMs);\n\n this.timer = timer;\n unrefTimer(timer);\n }\n\n /** Clears the pending timer handle if armed. */\n private clearTimer(): void {\n if (this.timer !== null) {\n clearTimeout(this.timer);\n this.timer = null;\n }\n }\n}\n\n/** Buffers log and metric streams, makes batches and sends them over HTTP. */\nexport class LogPipeline {\n /** Buffer instances for logs and metrics streams. */\n private readonly streams: Record<StreamName, RecordStream>;\n\n /** In-flight batches without delivery confirmation. The exit flush sends them again. */\n private readonly unconfirmed = new Map<string, LogBatch>();\n\n /** Closed batches waiting for a free dispatch slot. */\n private readonly queue: LogBatch[] = [];\n\n /** Ceiling on the ERROR and FATAL records that bypass sampling. */\n private readonly ceiling = new ErrorCeiling();\n\n /** Dispatches currently in flight, capped at MAX_CONCURRENT_REQUESTS. */\n private inFlight = 0;\n\n /** It is true when a pump is in the queue. One microtask then drains a burst. */\n private pumpScheduled = false;\n\n /** Indicates whether the pipeline has been destroyed. */\n private stopped = false;\n\n /**\n * @param transport HTTP transport for live batch delivery.\n * @param storage Storage adapter for offline batch persistence.\n * @param retry Retry engine for redelivering persisted batches.\n * @param diagnostics Diagnostics reporter.\n * @param streamOptions Batching policy per stream.\n */\n constructor(\n private readonly transport: BatchTransport,\n private readonly storage: StorageAdapter,\n private readonly retry: RetryEngine,\n private readonly diagnostics: Diagnostics,\n streamOptions: Record<StreamName, StreamOptions> = STREAM_OPTIONS,\n ) {\n const flush = (stream: RecordStream): void => {\n this.claim(stream);\n };\n\n this.streams = {\n logs: new RecordStream(streamOptions.logs, flush),\n metrics: new RecordStream(streamOptions.metrics, flush),\n };\n }\n\n /**\n * Sets the observed timestamp and adds a record to the pipeline.\n * @param record Record to push.\n */\n push(record: LogRecord): void {\n if (this.stopped) {\n return;\n }\n\n record.observedTimeUnixNano = nowUnixNano();\n this.route(record);\n }\n\n /**\n * Drains the stream buffers into one batch. It does not take in-flight batches.\n * An in-flight batch has its own ID and its send is not complete. If this method\n * takes it, the pipeline sends each record again under a new ID. The server cannot\n * deduplicate that ID.\n * @returns Combined LogBatch or null if no records are buffered.\n */\n drainPending(): LogBatch | null {\n return this.toBatch([...this.streams.metrics.take(), ...this.streams.logs.take()]);\n }\n\n /**\n * Drains all buffered and unconfirmed in-flight records into one exit batch in one step.\n * Records already given to fetch go again under a new batch ID. The server cannot\n * deduplicate them. Thus the exit flush can deliver duplicates. This is intentional.\n * A closing document cannot confirm delivery.\n * @returns Combined LogBatch or null if no records are pending.\n */\n drainForExit(): LogBatch | null {\n const inFlight = [...this.unconfirmed.values()].flatMap((batch) => batch.records);\n this.unconfirmed.clear();\n\n return this.toBatch([...inFlight, ...this.streams.metrics.take(), ...this.streams.logs.take()]);\n }\n\n /** Stops the flush timers and refuses further records. */\n destroy(): void {\n this.stopped = true;\n this.streams.logs.stop();\n this.streams.metrics.stop();\n this.queue.length = 0;\n }\n\n /**\n * Wraps drained records in a batch.\n * @param records Records taken from the buffers, in delivery order.\n * @returns New LogBatch, or null when nothing was drained.\n */\n private toBatch(records: LogRecord[]): LogBatch | null {\n if (records.length === 0) {\n return null;\n }\n\n return { id: newId(this.diagnostics), records, createdAt: Date.now(), attempts: 0 };\n }\n\n /**\n * Sorts a record into its stream. Sampling already ran. RecordBuilder samples a local\n * record. The runtime samples a forwarded record. This method catches each fault.\n * A record without `attributes` makes isMetric throw. An uncaught throw goes into the\n * log call of the caller.\n * @param record Record to sort.\n */\n private route(record: LogRecord): void {\n try {\n const stream = isMetric(record) ? this.streams.metrics : this.streams.logs;\n\n // ERROR and FATAL records bypass sampling upstream. This ceiling is their only\n // limit.\n if (!this.ceiling.allow(record)) {\n this.diagnostics.count(\"record.dropped_by_ceiling\");\n return;\n }\n\n stream.add(record);\n } catch (error) {\n this.diagnostics.report(\n \"pipeline.crashed\",\n \"The pipeline dropped a record before it reached a stream.\",\n undefined,\n error,\n );\n }\n }\n\n /**\n * Drains a stream buffer into a new batch and queues the batch for dispatch.\n * The buffer always has one or more records here. Only a push starts a timer.\n * Each `take` stops the timer that calls this method.\n * @param stream Stream buffer to drain.\n */\n private claim(stream: RecordStream): void {\n const records = stream.take();\n\n const batch: LogBatch = {\n id: newId(this.diagnostics),\n records,\n createdAt: Date.now(),\n attempts: 0,\n };\n this.unconfirmed.set(batch.id, batch);\n this.enqueue(batch);\n }\n\n /**\n * Queues a batch and schedules the pump on a microtask. An inline dispatch starts\n * a fetch inside the log call of the application.\n * @param batch Batch ready for delivery.\n */\n private enqueue(batch: LogBatch): void {\n this.queue.push(batch);\n\n if (this.pumpScheduled) {\n return;\n }\n\n this.pumpScheduled = true;\n queueMicrotask(() => {\n this.pumpScheduled = false;\n this.pump();\n });\n }\n\n /** Starts queued dispatches up to the concurrency limit. */\n private pump(): void {\n while (this.inFlight < MAX_CONCURRENT_REQUESTS) {\n const batch = this.queue.shift();\n if (!batch) {\n return;\n }\n\n this.inFlight++;\n void this.run(batch);\n }\n }\n\n /**\n * Delivers one batch and frees its concurrency slot.\n * @param batch Batch to deliver.\n */\n private async run(batch: LogBatch): Promise<void> {\n try {\n await this.dispatch(batch);\n } catch (error) {\n this.diagnostics.report(\n \"pipeline.crashed\",\n \"A dispatch rejected its promise. This must not occur.\",\n { batchId: batch.id },\n error,\n );\n } finally {\n this.inFlight--;\n this.pump();\n }\n }\n\n /**\n * Sends a batch over the HTTP transport. If the transport throttles or fails, it stores\n * the batch.\n * @param batch Batch to deliver.\n */\n private async dispatch(batch: LogBatch): Promise<void> {\n try {\n // Store the batch while the transport throttles. A send here posts a batch each\n // flush interval through the throttle. Do not change the attempt count.\n // The pipeline sent nothing.\n const throttledMs = this.transport.throttledForMs();\n if (throttledMs > 0) {\n await this.store(batch);\n this.diagnostics.report(\n \"transport.throttled\",\n \"The server throttles requests. The pipeline stored the batch and did not send it.\",\n {\n batchId: batch.id,\n records: batch.records.length,\n throttledMs,\n },\n );\n return;\n }\n\n try {\n await this.transport.send(batch);\n } catch (error) {\n // Increment the attempt count before the store. At 0, the batch exceeds\n // STORAGE_LIMITS.maxAttempts by one. The attempt headers then report one too few.\n await this.storeFailed({ ...batch, attempts: batch.attempts + 1 }, error);\n this.diagnostics.report(\n \"transport.http_error\",\n \"The send failed. The pipeline stored the batch for a retry.\",\n { batchId: batch.id, records: batch.records.length },\n error,\n );\n }\n } finally {\n this.unconfirmed.delete(batch.id);\n }\n }\n\n /**\n * Stores a batch that the transport refused. The retry engine splits a 413 and\n * drops a batch that the server does not accept.\n * @param batch Batch to persist, with its attempt already counted.\n * @param error Failure thrown by the transport.\n */\n private async storeFailed(batch: LogBatch, error: unknown): Promise<void> {\n await this.diagnostics.guardAsync(\n \"storage.degraded\",\n \"The library could not store an undelivered batch.\",\n async () => {\n await this.retry.storeFailed(batch, error);\n },\n );\n }\n\n /**\n * Stores an undelivered batch and triggers the retry engine. A deadline limits the\n * wait. A storage call that does not settle holds this dispatch slot. Two such calls\n * stop the pipeline.\n * @param batch Batch to persist.\n */\n private async store(batch: LogBatch): Promise<void> {\n await this.diagnostics.guardAsync(\n \"storage.degraded\",\n \"The library could not store an undelivered batch.\",\n async () => {\n await withDeadline(this.storage.save(batch), STORAGE_DEADLINE_MS);\n this.retry.nudge();\n },\n );\n }\n}\n","// src/core/sender.ts\n//\n// This module builds the delivery stack of the sender role.\n// The stack has storage, transport, retry, pipeline and exit flush.\n// The runtime imports this module dynamically only when the config sets an endpoint.\n// Console-only mode does not download this module.\n\nimport { STORAGE_DB_NAME, STORAGE_LIMITS } from \"../constants\";\nimport type { ResolvedConfig } from \"../models/config\";\nimport type { LogRecord } from \"../models/log-record\";\nimport type { GapReporter, StorageAdapter } from \"../models/storage\";\nimport { drainEmergencyQueue } from \"../storage/emergency-queue\";\nimport { createStorage } from \"../storage/factory\";\nimport { ExitFlush } from \"../transport/exit-flush\";\nimport { CustomTransport } from \"../transport/custom-transport\";\nimport { HttpTransport } from \"../transport/http-transport\";\nimport { RetryEngine } from \"../transport/retry-engine\";\nimport type { BatchTransport } from \"../transport/status-transport\";\nimport type { Diagnostics } from \"./diagnostics\";\nimport { LogPipeline } from \"./pipeline\";\nimport { applyRemote, parseRemoteRules } from \"./remote-rules\";\nimport type { RemoteSlot } from \"./remote-sampling\";\n\n/** Inputs to build the delivery stack. */\nexport interface SenderDeps {\n /** Active configuration instance. */\n config: ResolvedConfig;\n /** Diagnostics reporter. */\n diagnostics: Diagnostics;\n /** Receives a report when storage drops batches before delivery. */\n onGap: GapReporter;\n /** Slot of the runtime for the sampling rules from the ingest server. */\n remote: RemoteSlot;\n}\n\n/** Delivery stack for one sender runtime. */\nexport class Sender {\n /**\n * @param storage Storage adapter for undelivered batches.\n * @param transport HTTP transport for live delivery.\n * @param retry Retry engine for stored batches.\n * @param pipeline Pipeline that batches records.\n * @param exitFlush Handler that sends pending records on unload.\n * @param diagnostics Diagnostics reporter.\n */\n private constructor(\n private readonly storage: StorageAdapter,\n private readonly transport: BatchTransport,\n private readonly retry: RetryEngine,\n private readonly pipeline: LogPipeline,\n private readonly exitFlush: ExitFlush,\n private readonly diagnostics: Diagnostics,\n ) {}\n\n /**\n * Builds the delivery stack, drains the emergency queue and starts the retry loop.\n * @param deps Configuration, diagnostics and gap reporter.\n * @returns Promise resolving to the started sender.\n */\n static async create(deps: SenderDeps): Promise<Sender> {\n const { config, diagnostics } = deps;\n\n const storage = await createStorage(\n config.storage,\n STORAGE_DB_NAME,\n STORAGE_LIMITS,\n diagnostics,\n deps.onGap,\n );\n const onSampling = (raw: unknown): void => {\n const update = parseRemoteRules(raw, diagnostics);\n\n if (update) {\n applyRemote(deps.remote, config, update);\n }\n };\n\n // The stack keeps one transport for its life. The runtime refuses a later change.\n const transport: BatchTransport = config.transport\n ? new CustomTransport(config, diagnostics, onSampling)\n : new HttpTransport(config, diagnostics, onSampling);\n const retry = new RetryEngine(storage, transport, diagnostics, config);\n const pipeline = new LogPipeline(transport, storage, retry, diagnostics);\n\n const exitFlush = new ExitFlush({\n config,\n diagnostics,\n drainForExit: () => pipeline.drainForExit(),\n drainPending: () => pipeline.drainPending(),\n });\n\n await drainEmergencyQueue(storage, diagnostics);\n\n // If one step fails, stop both. A retry loop with no owner sends after load reports failure.\n let started = false;\n\n try {\n exitFlush.install();\n retry.start();\n started = true;\n } finally {\n if (!started) {\n exitFlush.uninstall();\n retry.stop();\n }\n }\n\n return new Sender(storage, transport, retry, pipeline, exitFlush, diagnostics);\n }\n\n /**\n * Adds a record to the pipeline.\n * @param record Record to deliver.\n */\n push(record: LogRecord): void {\n this.pipeline.push(record);\n }\n\n /**\n * Sends the records held in the stream buffers.\n * @returns Promise resolving when the batch is sent or stored for retry.\n */\n async flush(): Promise<void> {\n const batch = this.pipeline.drainPending();\n\n if (!batch) {\n return;\n }\n\n try {\n await this.transport.send(batch);\n } catch (error) {\n await this.diagnostics.guardAsync(\n \"storage.degraded\",\n \"The library could not store the batch that flush() drained.\",\n // The retry engine classifies the failure. It splits the batch on a 413, as the drain does.\n async () => {\n await this.retry.storeFailed({ ...batch, attempts: batch.attempts + 1 }, error);\n },\n );\n this.diagnostics.report(\n \"transport.http_error\",\n \"The send from flush() failed. The library stored the batch for a retry.\",\n { batchId: batch.id, records: batch.records.length },\n error,\n );\n }\n }\n\n /**\n * Counts the batches held in storage.\n * @returns Promise resolving to the batch count, or 0 if storage fails.\n */\n async queueDepth(): Promise<number> {\n const count = await this.diagnostics.guardAsync(\n \"storage.degraded\",\n \"The library could not count the batches in storage.\",\n () => this.storage.count(),\n );\n\n return count ?? 0;\n }\n\n /**\n * Sends pending records and stops all timers and listeners. Then it closes storage.\n * The synchronous steps run before the first await. The runtime relies on this order.\n * @returns Promise resolving when storage is closed.\n */\n async destroy(): Promise<void> {\n this.exitFlush.flush(\"shutdown\");\n this.exitFlush.uninstall();\n this.retry.stop();\n this.pipeline.destroy();\n\n await this.storage.close();\n }\n}\n"],"mappings":";;;;;;;AAgCA,SAAgBsD,EAAW,GAAmC;CAC5D,IAAI,OAAOC,KAAU,aAAYA,GAC/B,OAAO;CAGT,IAAMC,IAAc,QAAQ,IAAID,GAAO,IAAI,GACrCE,IAAqB,QAAQ,IAAIF,GAAO,WAAW,GACnDG,IAAoB,QAAQ,IAAIH,GAAO,UAAU,GACjDI,IAAmB,QAAQ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KAAK,UAAU,MAAM,UAAU,GAC/B,KAAK,UAAU,UAAU,GACzB,KAAK,MAAM,KAAK,GAChB,KAAK,SAAS,QAAQ,GAEtB,MAAM,KAAK,QAAQ,MAAM;CAC3B;AACF"}
@@ -1,8 +0,0 @@
1
- //#region src/utils/unref.ts
2
- function e(e) {
3
- typeof e != "number" && e.unref?.();
4
- }
5
- //#endregion
6
- export { e as t };
7
-
8
- //# sourceMappingURL=unref-16maCyKA.js.map
@@ -1 +0,0 @@
1
- {"version":3,"file":"unref-16maCyKA.js","names":["unrefTimer","timer"],"sources":["../src/utils/unref.ts"],"sourcesContent":["// src/utils/unref.ts\n//\n// Unreferences timer handles in Node and browser environments. A pending timer\n// keeps a Node process alive under SSR and in tests.\n\n/** Cross-platform timer handle representing browser numeric IDs or Node Timeout objects. */\nexport type TimerHandle = number | { unref?: () => void };\n\n/**\n * Unreferences a timer handle to prevent it from keeping a Node.js process alive.\n * @param timer Timer handle returned by setTimeout.\n */\nexport function unrefTimer(timer: TimerHandle): void {\n if (typeof timer !== \"number\") {\n timer.unref?.();\n }\n}\n"],"mappings":";AAYA,SAAgBA,EAAW,GAA0B;CACnD,AAAI,OAAOC,KAAU,YACnBA,EAAM,QAAQ;AAElB"}
@@ -1,2 +0,0 @@
1
- function e(e){typeof e!=`number`&&e.unref?.()}Object.defineProperty(exports,"t",{enumerable:!0,get:function(){return e}});
2
- //# sourceMappingURL=unref-CU9Nyz_9.cjs.map
@@ -1 +0,0 @@
1
- {"version":3,"file":"unref-CU9Nyz_9.cjs","names":["unrefTimer","timer"],"sources":["../src/utils/unref.ts"],"sourcesContent":["// src/utils/unref.ts\n//\n// Unreferences timer handles in Node and browser environments. A pending timer\n// keeps a Node process alive under SSR and in tests.\n\n/** Cross-platform timer handle representing browser numeric IDs or Node Timeout objects. */\nexport type TimerHandle = number | { unref?: () => void };\n\n/**\n * Unreferences a timer handle to prevent it from keeping a Node.js process alive.\n * @param timer Timer handle returned by setTimeout.\n */\nexport function unrefTimer(timer: TimerHandle): void {\n if (typeof timer !== \"number\") {\n timer.unref?.();\n }\n}\n"],"mappings":"AAYA,SAAgBA,EAAW,EAA0B,CAC/C,OAAOC,GAAU,UACnBA,EAAM,QAAQ,CAElB"}
@@ -1,2 +0,0 @@
1
- var e=class{ctx;name=`web-vitals`;installed=!1;constructor(e){this.ctx=e}install(){if(this.installed||(this.installed=!0,this.reportNavigationTiming(),this.ctx.once.webVitals))return;let e=this.ctx.config.capture.webVitalsLoader;e?(this.ctx.once.webVitals=!0,this.loadWebVitals(e)):this.ctx.diagnostics.report(`config.invalid`,`capture.webVitals needs capture.webVitalsLoader. LCP, CLS and INP are off. Navigation timing continues.`)}uninstall(){this.installed=!1}async loadWebVitals(e){let t=await this.ctx.diagnostics.guardAsync(`capture.install_failed`,`The library could not load web-vitals.`,e);if(!t){this.ctx.diagnostics.report(`capture.install_failed`,`The web-vitals module is not available. LCP, CLS and INP are off. Navigation timing continues.`);return}let n=(e,t)=>n=>{this.ctx.logger.logMetric(`web_vitals.${e}`,Math.round(n.value*1e3)/1e3,t,`gauge`,{"metric.rating":n.rating,"metric.id":n.id})};t.onLCP(n(`lcp`,`ms`)),t.onCLS(n(`cls`,`1`)),t.onINP(n(`inp`,`ms`)),t.onFCP(n(`fcp`,`ms`)),t.onTTFB(n(`ttfb`,`ms`))}reportNavigationTiming(){this.ctx.once.navigationTiming||(this.ctx.once.navigationTiming=!0,this.ctx.diagnostics.guard(`capture.install_failed`,`The library could not read the navigation timing.`,()=>{let e=performance.getEntriesByType(`navigation`)[0];if(!e)return;let t={"navigation.dns_ms":e.domainLookupEnd-e.domainLookupStart,"navigation.tcp_ms":e.connectEnd-e.connectStart,"navigation.ttfb_ms":e.responseStart-e.requestStart,"navigation.response_ms":e.responseEnd-e.responseStart,"navigation.dom_interactive_ms":e.domInteractive,"navigation.dom_complete_ms":e.domComplete,"navigation.load_ms":e.loadEventEnd};for(let[n,r]of Object.entries(t))Number.isFinite(r)&&r>=0&&this.ctx.logger.logMetric(n,Math.round(r),`ms`,`gauge`,{"navigation.type":e.type})}))}};exports.WebVitalsCapture=e;
2
- //# sourceMappingURL=web-vitals-B2FYsEAU.cjs.map
@@ -1 +0,0 @@
1
- {"version":3,"file":"web-vitals-B2FYsEAU.cjs","names":["WebVitalsCapture","ctx","loader","module","send","name","metric","unit","nav","metrics","value"],"sources":["../src/capture/web-vitals.ts"],"sourcesContent":["// src/capture/web-vitals.ts\n//\n// Captures browser navigation timing and Core Web Vitals metrics through an optional peer.\n\nimport type { WebVitalsMetric, WebVitalsModule, WebVitalsReporter } from \"../models/config\";\nimport type { Capture, CaptureContext } from \"./types\";\n\n/** Captures browser navigation timing benchmarks and Core Web Vitals. */\nexport class WebVitalsCapture implements Capture {\n /** Capture module identifier. */\n readonly name = \"web-vitals\";\n\n /** Prevents duplicate listener registration. */\n private installed = false;\n\n /**\n * @param ctx Capture context containing configuration, diagnostics, and logger.\n */\n constructor(private readonly ctx: CaptureContext) {}\n\n /** Reports navigation timing and starts to load web-vitals. */\n install(): void {\n if (this.installed) {\n return;\n }\n this.installed = true;\n\n this.reportNavigationTiming();\n\n if (this.ctx.once.webVitals) {\n return;\n }\n\n // Do not import the peer by name. The Vite dev server fails if the peer is not installed.\n // Do not set once here. A later configure() call with a loader must subscribe.\n const loader = this.ctx.config.capture.webVitalsLoader;\n if (!loader) {\n this.ctx.diagnostics.report(\n \"config.invalid\",\n \"capture.webVitals needs capture.webVitalsLoader. LCP, CLS and INP are off. Navigation timing continues.\",\n );\n return;\n }\n\n // Set the flag before the load, not after. Without this order, two configure() calls\n // in one turn both pass this check and subscribe two times.\n this.ctx.once.webVitals = true;\n\n void this.loadWebVitals(loader);\n }\n\n /**\n * Marks the module as uninstalled. The web-vitals reporters stay subscribed\n * because the package has no unsubscribe. `ctx.once` prevents a second set.\n */\n uninstall(): void {\n this.installed = false;\n }\n\n /**\n * Loads the web-vitals module and registers metric reporters.\n * @param loader Loader that the consumer supplies.\n */\n private async loadWebVitals(loader: () => Promise<WebVitalsModule>): Promise<void> {\n const module = await this.ctx.diagnostics.guardAsync(\n \"capture.install_failed\",\n \"The library could not load web-vitals.\",\n loader,\n );\n\n if (!module) {\n this.ctx.diagnostics.report(\n \"capture.install_failed\",\n \"The web-vitals module is not available. LCP, CLS and INP are off. Navigation timing continues.\",\n );\n return;\n }\n\n const send =\n (name: string, unit: string): WebVitalsReporter =>\n (metric: WebVitalsMetric): void => {\n this.ctx.logger.logMetric(\n `web_vitals.${name}`,\n // Keep three decimals. CLS is a small fraction. An integer value\n // reports each layout shift as zero.\n Math.round(metric.value * 1000) / 1000,\n unit,\n \"gauge\",\n { \"metric.rating\": metric.rating, \"metric.id\": metric.id },\n );\n };\n\n module.onLCP(send(\"lcp\", \"ms\"));\n module.onCLS(send(\"cls\", \"1\"));\n module.onINP(send(\"inp\", \"ms\"));\n module.onFCP(send(\"fcp\", \"ms\"));\n module.onTTFB(send(\"ttfb\", \"ms\"));\n }\n\n /** Extracts and logs PerformanceNavigationTiming benchmarks one time for each document. */\n private reportNavigationTiming(): void {\n // The entry describes the one navigation of this document. A second report after a\n // reconfigure duplicates the seven metrics.\n if (this.ctx.once.navigationTiming) {\n return;\n }\n this.ctx.once.navigationTiming = true;\n\n this.ctx.diagnostics.guard(\n \"capture.install_failed\",\n \"The library could not read the navigation timing.\",\n () => {\n const nav = performance.getEntriesByType(\"navigation\")[0] as\n PerformanceNavigationTiming | undefined;\n if (!nav) {\n return;\n }\n\n const metrics: Record<string, number> = {\n \"navigation.dns_ms\": nav.domainLookupEnd - nav.domainLookupStart,\n \"navigation.tcp_ms\": nav.connectEnd - nav.connectStart,\n \"navigation.ttfb_ms\": nav.responseStart - nav.requestStart,\n \"navigation.response_ms\": nav.responseEnd - nav.responseStart,\n \"navigation.dom_interactive_ms\": nav.domInteractive,\n \"navigation.dom_complete_ms\": nav.domComplete,\n \"navigation.load_ms\": nav.loadEventEnd,\n };\n\n for (const [name, value] of Object.entries(metrics)) {\n // Filters unrecorded or negative timings to avoid false zero readings.\n if (Number.isFinite(value) && value >= 0) {\n this.ctx.logger.logMetric(name, Math.round(value), \"ms\", \"gauge\", {\n \"navigation.type\": nav.type,\n });\n }\n }\n },\n );\n }\n}\n"],"mappings":"AAQA,IAAaA,EAAb,KAAiD,CAUlB,IAR7B,KAAgB,aAGhB,UAAoB,GAKpB,YAAY,EAAsC,CAArB,KAAA,IAAAC,CAAsB,CAGnD,SAAgB,CAQd,GAPI,KAAK,YAGT,KAAK,UAAY,GAEjB,KAAK,uBAAuB,EAExB,KAAK,IAAI,KAAK,WAChB,OAKF,IAAMC,EAAS,KAAK,IAAI,OAAO,QAAQ,gBAClCA,GAUL,KAAK,IAAI,KAAK,UAAY,GAE1B,KAAU,cAAcA,CAAM,GAX5B,KAAK,IAAI,YAAY,OACnB,iBACA,yGACF,CASJ,CAMA,WAAkB,CAChB,KAAK,UAAY,EACnB,CAMA,MAAc,cAAc,EAAuD,CACjF,IAAMC,EAAS,MAAM,KAAK,IAAI,YAAY,WACxC,yBACA,yCACAD,CACF,EAEA,GAAI,CAACC,EAAQ,CACX,KAAK,IAAI,YAAY,OACnB,yBACA,gGACF,EACA,MACF,CAEA,IAAMC,GACH,EAAc,IACd,GAAkC,CACjC,KAAK,IAAI,OAAO,UACd,cAAcC,IAGd,KAAK,MAAMC,EAAO,MAAQ,GAAI,EAAI,IAClCC,EACA,QACA,CAAE,gBAAiBD,EAAO,OAAQ,YAAaA,EAAO,EAAG,CAC3D,CACF,EAEFH,EAAO,MAAMC,EAAK,MAAO,IAAI,CAAC,EAC9BD,EAAO,MAAMC,EAAK,MAAO,GAAG,CAAC,EAC7BD,EAAO,MAAMC,EAAK,MAAO,IAAI,CAAC,EAC9BD,EAAO,MAAMC,EAAK,MAAO,IAAI,CAAC,EAC9BD,EAAO,OAAOC,EAAK,OAAQ,IAAI,CAAC,CAClC,CAGA,wBAAuC,CAGjC,KAAK,IAAI,KAAK,mBAGlB,KAAK,IAAI,KAAK,iBAAmB,GAEjC,KAAK,IAAI,YAAY,MACnB,yBACA,wDACM,CACJ,IAAMI,EAAM,YAAY,iBAAiB,YAAY,CAAC,CAAC,GAEvD,GAAI,CAACA,EACH,OAGF,IAAMC,EAAkC,CACtC,oBAAqBD,EAAI,gBAAkBA,EAAI,kBAC/C,oBAAqBA,EAAI,WAAaA,EAAI,aAC1C,qBAAsBA,EAAI,cAAgBA,EAAI,aAC9C,yBAA0BA,EAAI,YAAcA,EAAI,cAChD,gCAAiCA,EAAI,eACrC,6BAA8BA,EAAI,YAClC,qBAAsBA,EAAI,YAC5B,EAEA,IAAK,GAAM,CAACH,EAAMK,KAAU,OAAO,QAAQD,CAAO,EAE5C,OAAO,SAASC,CAAK,GAAKA,GAAS,GACrC,KAAK,IAAI,OAAO,UAAUL,EAAM,KAAK,MAAMK,CAAK,EAAG,KAAM,QAAS,CAChE,kBAAmBF,EAAI,IACzB,CAAC,CAGP,CACF,EACF,CACF"}
@@ -1 +0,0 @@
1
- {"version":3,"file":"web-vitals-DHZ0yA_H.js","names":["WebVitalsCapture","ctx","loader","module","send","name","metric","unit","nav","metrics","value"],"sources":["../src/capture/web-vitals.ts"],"sourcesContent":["// src/capture/web-vitals.ts\n//\n// Captures browser navigation timing and Core Web Vitals metrics through an optional peer.\n\nimport type { WebVitalsMetric, WebVitalsModule, WebVitalsReporter } from \"../models/config\";\nimport type { Capture, CaptureContext } from \"./types\";\n\n/** Captures browser navigation timing benchmarks and Core Web Vitals. */\nexport class WebVitalsCapture implements Capture {\n /** Capture module identifier. */\n readonly name = \"web-vitals\";\n\n /** Prevents duplicate listener registration. */\n private installed = false;\n\n /**\n * @param ctx Capture context containing configuration, diagnostics, and logger.\n */\n constructor(private readonly ctx: CaptureContext) {}\n\n /** Reports navigation timing and starts to load web-vitals. */\n install(): void {\n if (this.installed) {\n return;\n }\n this.installed = true;\n\n this.reportNavigationTiming();\n\n if (this.ctx.once.webVitals) {\n return;\n }\n\n // Do not import the peer by name. The Vite dev server fails if the peer is not installed.\n // Do not set once here. A later configure() call with a loader must subscribe.\n const loader = this.ctx.config.capture.webVitalsLoader;\n if (!loader) {\n this.ctx.diagnostics.report(\n \"config.invalid\",\n \"capture.webVitals needs capture.webVitalsLoader. LCP, CLS and INP are off. Navigation timing continues.\",\n );\n return;\n }\n\n // Set the flag before the load, not after. Without this order, two configure() calls\n // in one turn both pass this check and subscribe two times.\n this.ctx.once.webVitals = true;\n\n void this.loadWebVitals(loader);\n }\n\n /**\n * Marks the module as uninstalled. The web-vitals reporters stay subscribed\n * because the package has no unsubscribe. `ctx.once` prevents a second set.\n */\n uninstall(): void {\n this.installed = false;\n }\n\n /**\n * Loads the web-vitals module and registers metric reporters.\n * @param loader Loader that the consumer supplies.\n */\n private async loadWebVitals(loader: () => Promise<WebVitalsModule>): Promise<void> {\n const module = await this.ctx.diagnostics.guardAsync(\n \"capture.install_failed\",\n \"The library could not load web-vitals.\",\n loader,\n );\n\n if (!module) {\n this.ctx.diagnostics.report(\n \"capture.install_failed\",\n \"The web-vitals module is not available. LCP, CLS and INP are off. Navigation timing continues.\",\n );\n return;\n }\n\n const send =\n (name: string, unit: string): WebVitalsReporter =>\n (metric: WebVitalsMetric): void => {\n this.ctx.logger.logMetric(\n `web_vitals.${name}`,\n // Keep three decimals. CLS is a small fraction. An integer value\n // reports each layout shift as zero.\n Math.round(metric.value * 1000) / 1000,\n unit,\n \"gauge\",\n { \"metric.rating\": metric.rating, \"metric.id\": metric.id },\n );\n };\n\n module.onLCP(send(\"lcp\", \"ms\"));\n module.onCLS(send(\"cls\", \"1\"));\n module.onINP(send(\"inp\", \"ms\"));\n module.onFCP(send(\"fcp\", \"ms\"));\n module.onTTFB(send(\"ttfb\", \"ms\"));\n }\n\n /** Extracts and logs PerformanceNavigationTiming benchmarks one time for each document. */\n private reportNavigationTiming(): void {\n // The entry describes the one navigation of this document. A second report after a\n // reconfigure duplicates the seven metrics.\n if (this.ctx.once.navigationTiming) {\n return;\n }\n this.ctx.once.navigationTiming = true;\n\n this.ctx.diagnostics.guard(\n \"capture.install_failed\",\n \"The library could not read the navigation timing.\",\n () => {\n const nav = performance.getEntriesByType(\"navigation\")[0] as\n PerformanceNavigationTiming | undefined;\n if (!nav) {\n return;\n }\n\n const metrics: Record<string, number> = {\n \"navigation.dns_ms\": nav.domainLookupEnd - nav.domainLookupStart,\n \"navigation.tcp_ms\": nav.connectEnd - nav.connectStart,\n \"navigation.ttfb_ms\": nav.responseStart - nav.requestStart,\n \"navigation.response_ms\": nav.responseEnd - nav.responseStart,\n \"navigation.dom_interactive_ms\": nav.domInteractive,\n \"navigation.dom_complete_ms\": nav.domComplete,\n \"navigation.load_ms\": nav.loadEventEnd,\n };\n\n for (const [name, value] of Object.entries(metrics)) {\n // Filters unrecorded or negative timings to avoid false zero readings.\n if (Number.isFinite(value) && value >= 0) {\n this.ctx.logger.logMetric(name, Math.round(value), \"ms\", \"gauge\", {\n \"navigation.type\": nav.type,\n });\n }\n }\n },\n );\n }\n}\n"],"mappings":";AAQA,IAAaA,IAAb,MAAiD;CAUlB;CAR7B,OAAgB;CAGhB,YAAoB;CAKpB,YAAY,GAAsC;EAArB,KAAA,MAAAC;CAAsB;CAGnD,UAAgB;EAQd,IAPI,KAAK,cAGT,KAAK,YAAY,IAEjB,KAAK,uBAAuB,GAExB,KAAK,IAAI,KAAK,YAChB;EAKF,IAAMC,IAAS,KAAK,IAAI,OAAO,QAAQ;EACvC,AAAKA,KAUL,KAAK,IAAI,KAAK,YAAY,IAE1B,KAAU,cAAcA,CAAM,KAX5B,KAAK,IAAI,YAAY,OACnB,kBACA,yGACF;CASJ;CAMA,YAAkB;EAChB,KAAK,YAAY;CACnB;CAMA,MAAc,cAAc,GAAuD;EACjF,IAAMC,IAAS,MAAM,KAAK,IAAI,YAAY,WACxC,0BACA,0CACAD,CACF;EAEA,IAAI,CAACC,GAAQ;GACX,KAAK,IAAI,YAAY,OACnB,0BACA,gGACF;GACA;EACF;EAEA,IAAMC,KACH,GAAc,OACd,MAAkC;GACjC,KAAK,IA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