@utk09/ui-observability 0.10.0 → 0.12.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 (406) hide show
  1. package/CHANGELOG.md +77 -1
  2. package/README.md +323 -113
  3. package/bin/uiobs.mjs +1 -1
  4. package/dist/{batch-BMdT9mKm.js → batch-BjQUwjA6.js} +5 -6
  5. package/dist/batch-BjQUwjA6.js.map +1 -0
  6. package/dist/{batch-BHXypM1j.cjs → batch-D5LlU4Q9.cjs} +2 -2
  7. package/dist/batch-D5LlU4Q9.cjs.map +1 -0
  8. package/dist/bus/bus.d.ts +48 -47
  9. package/dist/bus/links.d.ts +4 -4
  10. package/dist/bus/validation.d.ts +1 -1
  11. package/dist/bus-D_7pd7RN.cjs +2 -0
  12. package/dist/bus-D_7pd7RN.cjs.map +1 -0
  13. package/dist/{bus-DKfBaica.js → bus-ecxUNTja.js} +105 -109
  14. package/dist/bus-ecxUNTja.js.map +1 -0
  15. package/dist/capture/console.d.ts +10 -10
  16. package/dist/capture/errors.d.ts +6 -6
  17. package/dist/capture/interactions.d.ts +14 -14
  18. package/dist/capture/lifecycle.d.ts +3 -3
  19. package/dist/capture/long-frames.d.ts +6 -6
  20. package/dist/capture/network.d.ts +17 -17
  21. package/dist/capture/profiler-frames.d.ts +44 -0
  22. package/dist/capture/replay-buffer.d.ts +46 -0
  23. package/dist/capture/replay-upload.d.ts +74 -0
  24. package/dist/capture/replay.d.ts +114 -0
  25. package/dist/capture/reports.d.ts +2 -2
  26. package/dist/capture/resource-timing.d.ts +1 -1
  27. package/dist/capture/server-timing.d.ts +3 -3
  28. package/dist/capture/storm.d.ts +3 -3
  29. package/dist/capture/types.d.ts +45 -33
  30. package/dist/capture/unclean-exit.d.ts +8 -8
  31. package/dist/capture/user-timing.d.ts +3 -3
  32. package/dist/capture/web-socket.d.ts +11 -11
  33. package/dist/capture/web-vitals.d.ts +20 -7
  34. package/dist/compression-AJJCMBOa.js +11 -0
  35. package/dist/compression-AJJCMBOa.js.map +1 -0
  36. package/dist/compression-lD9abCcO.cjs +2 -0
  37. package/dist/compression-lD9abCcO.cjs.map +1 -0
  38. package/dist/console-CLz_PvFn.cjs +2 -0
  39. package/dist/console-CLz_PvFn.cjs.map +1 -0
  40. package/dist/{console-BX_0UCV7.js → console-cwgHKXvM.js} +14 -15
  41. package/dist/console-cwgHKXvM.js.map +1 -0
  42. package/dist/constants-Bwl_YtQi.js +349 -0
  43. package/dist/constants-Bwl_YtQi.js.map +1 -0
  44. package/dist/constants-DakMxVB2.cjs +2 -0
  45. package/dist/constants-DakMxVB2.cjs.map +1 -0
  46. package/dist/constants.d.ts +150 -103
  47. package/dist/context-storage-BjzeBSxH.cjs.map +1 -1
  48. package/dist/{context-storage-DxZf4Gfh.js → context-storage-BzkoHzkQ.js} +2 -3
  49. package/dist/context-storage-BzkoHzkQ.js.map +1 -0
  50. package/dist/core/breadcrumbs.d.ts +16 -15
  51. package/dist/core/config.d.ts +3 -3
  52. package/dist/core/context.d.ts +7 -7
  53. package/dist/core/debug-buffer.d.ts +10 -10
  54. package/dist/core/debug-bundle.d.ts +3 -3
  55. package/dist/core/deferred.d.ts +2 -2
  56. package/dist/core/diagnostics.d.ts +24 -21
  57. package/dist/core/drops.d.ts +7 -7
  58. package/dist/core/hold-buffer.d.ts +1 -1
  59. package/dist/core/journey.d.ts +22 -23
  60. package/dist/core/logger.d.ts +22 -21
  61. package/dist/core/measure.d.ts +7 -7
  62. package/dist/core/meter.d.ts +25 -21
  63. package/dist/core/pipeline.d.ts +42 -41
  64. package/dist/core/profile-buckets.d.ts +31 -0
  65. package/dist/core/profiler.d.ts +218 -0
  66. package/dist/core/record.d.ts +23 -23
  67. package/dist/core/remote-rules.d.ts +4 -4
  68. package/dist/core/remote-sampling.d.ts +21 -20
  69. package/dist/core/runtime.d.ts +206 -137
  70. package/dist/core/sampling.d.ts +18 -18
  71. package/dist/core/sender.d.ts +22 -20
  72. package/dist/core/spans.d.ts +5 -5
  73. package/dist/{deadline-5_PecIl5.js → deadline-C4ccAuk5.js} +4 -9
  74. package/dist/deadline-C4ccAuk5.js.map +1 -0
  75. package/dist/deadline-CUGbto-y.cjs +2 -0
  76. package/dist/deadline-CUGbto-y.cjs.map +1 -0
  77. package/dist/{debug-bundle-CZZ6SQQh.js → debug-bundle-BOdYmCeV.js} +12 -6
  78. package/dist/debug-bundle-BOdYmCeV.js.map +1 -0
  79. package/dist/debug-bundle-Ex4L_LSP.cjs +2 -0
  80. package/dist/debug-bundle-Ex4L_LSP.cjs.map +1 -0
  81. package/dist/doctor.cjs +1 -1
  82. package/dist/doctor.cjs.map +1 -1
  83. package/dist/doctor.d.ts +16 -6
  84. package/dist/doctor.js +148 -54
  85. package/dist/doctor.js.map +1 -1
  86. package/dist/{emergency-queue-Cs8-i2xw.js → emergency-queue-B9WZxanZ.js} +15 -17
  87. package/dist/emergency-queue-B9WZxanZ.js.map +1 -0
  88. package/dist/{emergency-queue-CQ-9acZf.cjs → emergency-queue-HBpL5r3V.cjs} +2 -2
  89. package/dist/emergency-queue-HBpL5r3V.cjs.map +1 -0
  90. package/dist/{error-like-Ywo5uRHo.js → error-like-B11pB4aL.js} +2 -3
  91. package/dist/error-like-B11pB4aL.js.map +1 -0
  92. package/dist/error-like-gGRx2s36.cjs.map +1 -1
  93. package/dist/{errors-oyxrpHjY.js → errors-D6bwgJtO.js} +5 -6
  94. package/dist/errors-D6bwgJtO.js.map +1 -0
  95. package/dist/{errors-CigX45pL.cjs → errors-DCOCRdSi.cjs} +2 -2
  96. package/dist/errors-DCOCRdSi.cjs.map +1 -0
  97. package/dist/{factory-BkjNzPYL.cjs → factory-DLFDjdLv.cjs} +2 -2
  98. package/dist/factory-DLFDjdLv.cjs.map +1 -0
  99. package/dist/{factory-Bgsky_e0.js → factory-e9Qo3K0z.js} +18 -22
  100. package/dist/factory-e9Qo3K0z.js.map +1 -0
  101. package/dist/fixed-window-CvESpFYV.cjs.map +1 -1
  102. package/dist/{fixed-window-CtaFHanJ.js → fixed-window-Dq3MLUUv.js} +2 -3
  103. package/dist/fixed-window-Dq3MLUUv.js.map +1 -0
  104. package/dist/global-scope-BN-Io_yv.cjs.map +1 -1
  105. package/dist/{global-scope-dp2jADRl.js → global-scope-D9I8s-oN.js} +2 -3
  106. package/dist/global-scope-D9I8s-oN.js.map +1 -0
  107. package/dist/{guards-CpvOpJL6.js → guards-Cidk71ME.js} +2 -3
  108. package/dist/guards-Cidk71ME.js.map +1 -0
  109. package/dist/guards-nJ70syPt.cjs.map +1 -1
  110. package/dist/{identity-BMlKGHUM.cjs → identity-BlvlgjrU.cjs} +2 -2
  111. package/dist/identity-BlvlgjrU.cjs.map +1 -0
  112. package/dist/{identity-DOaHdfhT.js → identity-BrQp_5J5.js} +20 -21
  113. package/dist/identity-BrQp_5J5.js.map +1 -0
  114. package/dist/index.cjs +1 -1
  115. package/dist/index.cjs.map +1 -1
  116. package/dist/index.d.ts +112 -79
  117. package/dist/index.js +797 -659
  118. package/dist/index.js.map +1 -1
  119. package/dist/{indexeddb-storage-CaXGJqDD.cjs → indexeddb-storage-CtLvZH1r.cjs} +2 -2
  120. package/dist/indexeddb-storage-CtLvZH1r.cjs.map +1 -0
  121. package/dist/{indexeddb-storage-D-lUW_5P.js → indexeddb-storage-DLXQzAGh.js} +5 -6
  122. package/dist/indexeddb-storage-DLXQzAGh.js.map +1 -0
  123. package/dist/{interactions-CqDNrtIR.js → interactions-B6z2I4tU.js} +10 -11
  124. package/dist/interactions-B6z2I4tU.js.map +1 -0
  125. package/dist/{interactions-8DgxtmgO.cjs → interactions-P6pz08Jn.cjs} +2 -2
  126. package/dist/interactions-P6pz08Jn.cjs.map +1 -0
  127. package/dist/{journey-DgIjhrIc.js → journey-35yCMNFo.js} +21 -21
  128. package/dist/journey-35yCMNFo.js.map +1 -0
  129. package/dist/journey-DAGh5h9k.cjs +2 -0
  130. package/dist/journey-DAGh5h9k.cjs.map +1 -0
  131. package/dist/keys-BHhw_0Wh.cjs.map +1 -1
  132. package/dist/{keys-D5r_GH9q.js → keys-BU9j5YqW.js} +2 -3
  133. package/dist/keys-BU9j5YqW.js.map +1 -0
  134. package/dist/{library-console-g_VU-wzP.cjs → library-console-BFWEuQsl.cjs} +2 -2
  135. package/dist/library-console-BFWEuQsl.cjs.map +1 -0
  136. package/dist/library-console-Dl_Ly6DQ.js +13 -0
  137. package/dist/library-console-Dl_Ly6DQ.js.map +1 -0
  138. package/dist/{library-request-FQaiWjCP.cjs → library-request-Da-CHKzT.cjs} +2 -2
  139. package/dist/library-request-Da-CHKzT.cjs.map +1 -0
  140. package/dist/{library-request-CyC-9IOk.js → library-request-nI6pvI6I.js} +4 -5
  141. package/dist/library-request-nI6pvI6I.js.map +1 -0
  142. package/dist/{lifecycle-C2z_d8OX.cjs → lifecycle-BGGOcN4N.cjs} +2 -2
  143. package/dist/lifecycle-BGGOcN4N.cjs.map +1 -0
  144. package/dist/{lifecycle-BLC4VU7c.js → lifecycle-CZ6RRXc6.js} +3 -4
  145. package/dist/lifecycle-CZ6RRXc6.js.map +1 -0
  146. package/dist/{log-record-DKvo-B-d.cjs → log-record-D7bA1RPb.cjs} +2 -2
  147. package/dist/log-record-D7bA1RPb.cjs.map +1 -0
  148. package/dist/{log-record-CndanC-p.js → log-record-DIA6McNr.js} +3 -4
  149. package/dist/log-record-DIA6McNr.js.map +1 -0
  150. package/dist/{long-frames-BQef9rXR.js → long-frames-430_85Da.js} +9 -8
  151. package/dist/long-frames-430_85Da.js.map +1 -0
  152. package/dist/long-frames-Dd8tsi2U.cjs +2 -0
  153. package/dist/long-frames-Dd8tsi2U.cjs.map +1 -0
  154. package/dist/models/batch.d.ts +14 -15
  155. package/dist/models/bus.d.ts +24 -24
  156. package/dist/models/config.d.ts +402 -216
  157. package/dist/models/drop.d.ts +13 -11
  158. package/dist/models/health.d.ts +13 -13
  159. package/dist/models/log-record.d.ts +13 -14
  160. package/dist/models/metric.d.ts +82 -17
  161. package/dist/models/plugin.d.ts +13 -13
  162. package/dist/models/replay.d.ts +60 -0
  163. package/dist/models/serializer.d.ts +2 -3
  164. package/dist/models/stats.d.ts +2 -2
  165. package/dist/models/storage.d.ts +12 -11
  166. package/dist/{network-CvkvYzRU.js → network-C7SkLf4v.js} +30 -32
  167. package/dist/network-C7SkLf4v.js.map +1 -0
  168. package/dist/{network-CqnQOqon.cjs → network-pEX3PAJv.cjs} +2 -2
  169. package/dist/network-pEX3PAJv.cjs.map +1 -0
  170. package/dist/openfin-Bxelt0yg.js +7 -0
  171. package/dist/openfin-Bxelt0yg.js.map +1 -0
  172. package/dist/openfin-DtH2f7zX.cjs.map +1 -1
  173. package/dist/otlp-2MCrC3kd.cjs +2 -0
  174. package/dist/otlp-2MCrC3kd.cjs.map +1 -0
  175. package/dist/{otlp-CYIL7MOE.js → otlp-COq033e3.js} +26 -35
  176. package/dist/otlp-COq033e3.js.map +1 -0
  177. package/dist/patch-BX8KrPCT.cjs.map +1 -1
  178. package/dist/{patch-CCWfuEY7.js → patch-UdPz1ea8.js} +2 -3
  179. package/dist/patch-UdPz1ea8.js.map +1 -0
  180. package/dist/{platform-KMWkoI-v.cjs → platform-12uR7kBQ.cjs} +2 -2
  181. package/dist/platform-12uR7kBQ.cjs.map +1 -0
  182. package/dist/{platform-wcAkkv9F.js → platform-CVewe4wQ.js} +9 -10
  183. package/dist/platform-CVewe4wQ.js.map +1 -0
  184. package/dist/profiler-BVWIOgnq.js +310 -0
  185. package/dist/profiler-BVWIOgnq.js.map +1 -0
  186. package/dist/profiler-eVCknCzS.cjs +2 -0
  187. package/dist/profiler-eVCknCzS.cjs.map +1 -0
  188. package/dist/profiler-frames-CLXlT_xL.js +86 -0
  189. package/dist/profiler-frames-CLXlT_xL.js.map +1 -0
  190. package/dist/profiler-frames-Dg2OebB2.cjs +2 -0
  191. package/dist/profiler-frames-Dg2OebB2.cjs.map +1 -0
  192. package/dist/{remote-rules-CH_7PphT.js → remote-rules-BJGDJGwA.js} +29 -30
  193. package/dist/remote-rules-BJGDJGwA.js.map +1 -0
  194. package/dist/{remote-rules-BL8km4xk.cjs → remote-rules-CJD3ToVk.cjs} +2 -2
  195. package/dist/remote-rules-CJD3ToVk.cjs.map +1 -0
  196. package/dist/replay-0zAJv9T3.js +338 -0
  197. package/dist/replay-0zAJv9T3.js.map +1 -0
  198. package/dist/replay-DomJpXqW.cjs +2 -0
  199. package/dist/replay-DomJpXqW.cjs.map +1 -0
  200. package/dist/{reports-Bh_-KpZ2.cjs → reports-BsbqmP8h.cjs} +2 -2
  201. package/dist/reports-BsbqmP8h.cjs.map +1 -0
  202. package/dist/{reports-BOKyY3_A.js → reports-BuXekPOS.js} +4 -5
  203. package/dist/reports-BuXekPOS.js.map +1 -0
  204. package/dist/{resource-timing-BROnEJ0E.js → resource-timing-CXGHwFRD.js} +6 -7
  205. package/dist/resource-timing-CXGHwFRD.js.map +1 -0
  206. package/dist/{resource-timing-CbgwNpog.cjs → resource-timing-DkycFGDa.cjs} +2 -2
  207. package/dist/resource-timing-DkycFGDa.cjs.map +1 -0
  208. package/dist/{sampling-ECGVYiDD.cjs → sampling-Dd0wllyq.cjs} +2 -2
  209. package/dist/sampling-Dd0wllyq.cjs.map +1 -0
  210. package/dist/{sampling-BLO_pcV4.js → sampling-UUDbi3K0.js} +11 -12
  211. package/dist/sampling-UUDbi3K0.js.map +1 -0
  212. package/dist/{sanitize-DS0G4_ea.js → sanitize-CNmsD9r3.js} +4 -5
  213. package/dist/sanitize-CNmsD9r3.js.map +1 -0
  214. package/dist/{sanitize-Bsn8HQWC.cjs → sanitize-ChLn97Ch.cjs} +2 -2
  215. package/dist/sanitize-ChLn97Ch.cjs.map +1 -0
  216. package/dist/{select-DWO0-w8_.cjs → select-CTk-K5mG.cjs} +3 -3
  217. package/dist/select-CTk-K5mG.cjs.map +1 -0
  218. package/dist/{select-wqt9Wxio.js → select-DPv_j6wq.js} +64 -67
  219. package/dist/select-DPv_j6wq.js.map +1 -0
  220. package/dist/{sender-BkAVt-Rq.js → sender-15zEsZpr.js} +98 -101
  221. package/dist/sender-15zEsZpr.js.map +1 -0
  222. package/dist/sender-Bfpv9tad.cjs +2 -0
  223. package/dist/sender-Bfpv9tad.cjs.map +1 -0
  224. package/dist/storage/context-storage.d.ts +34 -33
  225. package/dist/storage/emergency-queue.d.ts +9 -9
  226. package/dist/storage/eviction.d.ts +12 -12
  227. package/dist/storage/factory.d.ts +8 -7
  228. package/dist/storage/gap.d.ts +6 -6
  229. package/dist/storage/idb-driver.d.ts +31 -32
  230. package/dist/storage/indexeddb-storage.d.ts +26 -27
  231. package/dist/storage/keys.d.ts +7 -7
  232. package/dist/storage/local-storage.d.ts +38 -38
  233. package/dist/storage/memory-storage.d.ts +21 -22
  234. package/dist/storage/persistence.d.ts +1 -1
  235. package/dist/storage-BA9RqRO-.cjs.map +1 -1
  236. package/dist/{storage-w7Tslvlq.js → storage-DZwed89z.js} +2 -3
  237. package/dist/storage-DZwed89z.js.map +1 -0
  238. package/dist/{storm-DD4cUkoL.js → storm-BTSNTIWI.js} +4 -5
  239. package/dist/storm-BTSNTIWI.js.map +1 -0
  240. package/dist/{storm-DCEsqViG.cjs → storm-D0_qZOEg.cjs} +2 -2
  241. package/dist/storm-D0_qZOEg.cjs.map +1 -0
  242. package/dist/transport/compression.d.ts +2 -2
  243. package/dist/transport/errors.d.ts +7 -7
  244. package/dist/transport/exit-flush.d.ts +39 -39
  245. package/dist/transport/headers.d.ts +2 -2
  246. package/dist/transport/http-transport.d.ts +28 -27
  247. package/dist/transport/memory-transport.d.ts +6 -6
  248. package/dist/transport/retry-engine.d.ts +35 -34
  249. package/dist/transport/serializers/ecs.d.ts +1 -1
  250. package/dist/transport/serializers/otlp-metrics.d.ts +1 -1
  251. package/dist/transport/serializers/otlp-traces.d.ts +1 -1
  252. package/dist/transport/serializers/otlp.d.ts +16 -16
  253. package/dist/transport/serializers/select.d.ts +7 -7
  254. package/dist/transport/status-transport.d.ts +20 -20
  255. package/dist/transport/worker-protocol.d.ts +3 -3
  256. package/dist/{types-BR9t_w28.js → types-BAerHgCq.js} +2 -3
  257. package/dist/types-BAerHgCq.js.map +1 -0
  258. package/dist/types-C7WNpnG1.cjs.map +1 -1
  259. package/dist/{unclean-exit-CwdpbUDg.cjs → unclean-exit-ClGzrc2A.cjs} +2 -2
  260. package/dist/unclean-exit-ClGzrc2A.cjs.map +1 -0
  261. package/dist/{unclean-exit-BYZ5yaSI.js → unclean-exit-Cob_jyTv.js} +3 -4
  262. package/dist/unclean-exit-Cob_jyTv.js.map +1 -0
  263. package/dist/unref-CU9Nyz_9.cjs +2 -0
  264. package/dist/unref-CU9Nyz_9.cjs.map +1 -0
  265. package/dist/unref-DgHPQeWv.js +7 -0
  266. package/dist/unref-DgHPQeWv.js.map +1 -0
  267. package/dist/user-timing-CdYqx3PF.cjs +2 -0
  268. package/dist/user-timing-CdYqx3PF.cjs.map +1 -0
  269. package/dist/{user-timing-Di2ra5DB.js → user-timing-DgHubxCI.js} +7 -6
  270. package/dist/user-timing-DgHubxCI.js.map +1 -0
  271. package/dist/utils/console.d.ts +2 -2
  272. package/dist/utils/deadline.d.ts +4 -4
  273. package/dist/utils/error-like.d.ts +7 -7
  274. package/dist/utils/fixed-window.d.ts +9 -8
  275. package/dist/utils/global-scope.d.ts +8 -8
  276. package/dist/utils/guards.d.ts +2 -2
  277. package/dist/utils/identity.d.ts +17 -17
  278. package/dist/utils/library-console.d.ts +4 -4
  279. package/dist/utils/library-request.d.ts +10 -10
  280. package/dist/utils/lock.d.ts +10 -9
  281. package/dist/utils/openfin.d.ts +5 -5
  282. package/dist/utils/patch.d.ts +6 -6
  283. package/dist/utils/platform.d.ts +13 -11
  284. package/dist/utils/sanitize.d.ts +4 -4
  285. package/dist/utils/timer.d.ts +1 -1
  286. package/dist/utils/tracing.d.ts +38 -38
  287. package/dist/utils/unref.d.ts +3 -3
  288. package/dist/{web-socket-DwBNhgre.cjs → web-socket-BTuvYoJI.cjs} +2 -2
  289. package/dist/web-socket-BTuvYoJI.cjs.map +1 -0
  290. package/dist/{web-socket-B-5qqPy7.js → web-socket-DthJuSAg.js} +14 -15
  291. package/dist/web-socket-DthJuSAg.js.map +1 -0
  292. package/dist/web-vitals-Ch5BpDmo.cjs +2 -0
  293. package/dist/web-vitals-Ch5BpDmo.cjs.map +1 -0
  294. package/dist/web-vitals-CsGCWnUr.js +77 -0
  295. package/dist/web-vitals-CsGCWnUr.js.map +1 -0
  296. package/dist/{worker-protocol-0HMf4-kY.js → worker-protocol-B0_8rWy5.js} +6 -7
  297. package/dist/worker-protocol-B0_8rWy5.js.map +1 -0
  298. package/dist/{worker-protocol-DXekoADQ.cjs → worker-protocol-BjzFORfq.cjs} +2 -2
  299. package/dist/worker-protocol-BjzFORfq.cjs.map +1 -0
  300. package/dist/worker-server-4en-Lt-3.cjs +2 -0
  301. package/dist/worker-server-4en-Lt-3.cjs.map +1 -0
  302. package/dist/{worker-server-CKcmX5m5.js → worker-server-Cne9MX9I.js} +25 -26
  303. package/dist/{worker-server-CKcmX5m5.js.map → worker-server-Cne9MX9I.js.map} +1 -1
  304. package/dist/worker-transport-B-GF4Aqn.cjs +2 -0
  305. package/dist/worker-transport-B-GF4Aqn.cjs.map +1 -0
  306. package/dist/{worker-transport-2220ghFZ.js → worker-transport-C3SjJAEC.js} +64 -65
  307. package/dist/worker-transport-C3SjJAEC.js.map +1 -0
  308. package/package.json +33 -41
  309. package/dist/batch-BHXypM1j.cjs.map +0 -1
  310. package/dist/batch-BMdT9mKm.js.map +0 -1
  311. package/dist/bus-DKfBaica.js.map +0 -1
  312. package/dist/bus-Dea9rVhy.cjs +0 -2
  313. package/dist/bus-Dea9rVhy.cjs.map +0 -1
  314. package/dist/console-BX_0UCV7.js.map +0 -1
  315. package/dist/console-DZEcs7FL.cjs +0 -2
  316. package/dist/console-DZEcs7FL.cjs.map +0 -1
  317. package/dist/constants-CL0ZdI2f.cjs +0 -2
  318. package/dist/constants-CL0ZdI2f.cjs.map +0 -1
  319. package/dist/constants-CU60FG4w.js +0 -305
  320. package/dist/constants-CU60FG4w.js.map +0 -1
  321. package/dist/context-storage-DxZf4Gfh.js.map +0 -1
  322. package/dist/deadline-5_PecIl5.js.map +0 -1
  323. package/dist/deadline-XSnm95pg.cjs +0 -2
  324. package/dist/deadline-XSnm95pg.cjs.map +0 -1
  325. package/dist/debug-bundle-CZZ6SQQh.js.map +0 -1
  326. package/dist/debug-bundle-yRkrU1ny.cjs +0 -2
  327. package/dist/debug-bundle-yRkrU1ny.cjs.map +0 -1
  328. package/dist/emergency-queue-CQ-9acZf.cjs.map +0 -1
  329. package/dist/emergency-queue-Cs8-i2xw.js.map +0 -1
  330. package/dist/error-like-Ywo5uRHo.js.map +0 -1
  331. package/dist/errors-CigX45pL.cjs.map +0 -1
  332. package/dist/errors-oyxrpHjY.js.map +0 -1
  333. package/dist/factory-Bgsky_e0.js.map +0 -1
  334. package/dist/factory-BkjNzPYL.cjs.map +0 -1
  335. package/dist/fixed-window-CtaFHanJ.js.map +0 -1
  336. package/dist/global-scope-dp2jADRl.js.map +0 -1
  337. package/dist/guards-CpvOpJL6.js.map +0 -1
  338. package/dist/identity-BMlKGHUM.cjs.map +0 -1
  339. package/dist/identity-DOaHdfhT.js.map +0 -1
  340. package/dist/indexeddb-storage-CaXGJqDD.cjs.map +0 -1
  341. package/dist/indexeddb-storage-D-lUW_5P.js.map +0 -1
  342. package/dist/interactions-8DgxtmgO.cjs.map +0 -1
  343. package/dist/interactions-CqDNrtIR.js.map +0 -1
  344. package/dist/journey-5tcxEbnG.cjs +0 -2
  345. package/dist/journey-5tcxEbnG.cjs.map +0 -1
  346. package/dist/journey-DgIjhrIc.js.map +0 -1
  347. package/dist/keys-D5r_GH9q.js.map +0 -1
  348. package/dist/library-console-CabK2j2-.js +0 -14
  349. package/dist/library-console-CabK2j2-.js.map +0 -1
  350. package/dist/library-console-g_VU-wzP.cjs.map +0 -1
  351. package/dist/library-request-CyC-9IOk.js.map +0 -1
  352. package/dist/library-request-FQaiWjCP.cjs.map +0 -1
  353. package/dist/lifecycle-BLC4VU7c.js.map +0 -1
  354. package/dist/lifecycle-C2z_d8OX.cjs.map +0 -1
  355. package/dist/log-record-CndanC-p.js.map +0 -1
  356. package/dist/log-record-DKvo-B-d.cjs.map +0 -1
  357. package/dist/long-frames-BQef9rXR.js.map +0 -1
  358. package/dist/long-frames-CV5ZG2cx.cjs +0 -2
  359. package/dist/long-frames-CV5ZG2cx.cjs.map +0 -1
  360. package/dist/network-CqnQOqon.cjs.map +0 -1
  361. package/dist/network-CvkvYzRU.js.map +0 -1
  362. package/dist/openfin-BwEN0uj4.js +0 -8
  363. package/dist/openfin-BwEN0uj4.js.map +0 -1
  364. package/dist/otlp-CYIL7MOE.js.map +0 -1
  365. package/dist/otlp-RVbkNQRh.cjs +0 -2
  366. package/dist/otlp-RVbkNQRh.cjs.map +0 -1
  367. package/dist/patch-CCWfuEY7.js.map +0 -1
  368. package/dist/platform-KMWkoI-v.cjs.map +0 -1
  369. package/dist/platform-wcAkkv9F.js.map +0 -1
  370. package/dist/remote-rules-BL8km4xk.cjs.map +0 -1
  371. package/dist/remote-rules-CH_7PphT.js.map +0 -1
  372. package/dist/reports-BOKyY3_A.js.map +0 -1
  373. package/dist/reports-Bh_-KpZ2.cjs.map +0 -1
  374. package/dist/resource-timing-BROnEJ0E.js.map +0 -1
  375. package/dist/resource-timing-CbgwNpog.cjs.map +0 -1
  376. package/dist/sampling-BLO_pcV4.js.map +0 -1
  377. package/dist/sampling-ECGVYiDD.cjs.map +0 -1
  378. package/dist/sanitize-Bsn8HQWC.cjs.map +0 -1
  379. package/dist/sanitize-DS0G4_ea.js.map +0 -1
  380. package/dist/select-DWO0-w8_.cjs.map +0 -1
  381. package/dist/select-wqt9Wxio.js.map +0 -1
  382. package/dist/sender-BkAVt-Rq.js.map +0 -1
  383. package/dist/sender-D82PxlCY.cjs +0 -2
  384. package/dist/sender-D82PxlCY.cjs.map +0 -1
  385. package/dist/storage-w7Tslvlq.js.map +0 -1
  386. package/dist/storm-DCEsqViG.cjs.map +0 -1
  387. package/dist/storm-DD4cUkoL.js.map +0 -1
  388. package/dist/types-BR9t_w28.js.map +0 -1
  389. package/dist/unclean-exit-BYZ5yaSI.js.map +0 -1
  390. package/dist/unclean-exit-CwdpbUDg.cjs.map +0 -1
  391. package/dist/user-timing-C1kB3JEg.cjs +0 -2
  392. package/dist/user-timing-C1kB3JEg.cjs.map +0 -1
  393. package/dist/user-timing-Di2ra5DB.js.map +0 -1
  394. package/dist/web-socket-B-5qqPy7.js.map +0 -1
  395. package/dist/web-socket-DwBNhgre.cjs.map +0 -1
  396. package/dist/web-vitals-Bflr5jSA.js +0 -53
  397. package/dist/web-vitals-Bflr5jSA.js.map +0 -1
  398. package/dist/web-vitals-DFuoTQbZ.cjs +0 -2
  399. package/dist/web-vitals-DFuoTQbZ.cjs.map +0 -1
  400. package/dist/worker-protocol-0HMf4-kY.js.map +0 -1
  401. package/dist/worker-protocol-DXekoADQ.cjs.map +0 -1
  402. package/dist/worker-server-BQK5z2yl.cjs +0 -2
  403. package/dist/worker-server-BQK5z2yl.cjs.map +0 -1
  404. package/dist/worker-transport-2220ghFZ.js.map +0 -1
  405. package/dist/worker-transport-Dj2yCQN5.cjs +0 -2
  406. package/dist/worker-transport-Dj2yCQN5.cjs.map +0 -1
@@ -0,0 +1 @@
1
+ {"version":3,"file":"sender-15zEsZpr.js","names":["CONTENT_TYPE_TEXT_PLAIN","STORAGE_DEADLINE_MS","QUERY_PARAM_EXIT_REASON","DRAIN_LOCK_NAME","QUERY_PARAM_BATCH_ID","HEADER_CONTENT_ENCODING","HEADER_RETRY_AFTER","HEADER_SAMPLING","ATTR_LOG_TYPE","HEADER_CONTENT_TYPE","HEADER_ATTEMPT","HEADER_BATCH_ID","ENCODING_GZIP","HEADER_DATE","withDrainLock","lockName","withDeadline","DeadlineError","trackTransportCall","runAsLibraryRequest","getFin","estimateBytes","runAsLibraryConsole","parseRetryAfter","endpointFor","serializeBatch","TransportError","batchKind","isOnline","unrefTimer","gzip","splitBatch","nowUnixNano","newId","ErrorCeiling","parseRemoteRules","applyRemote","requestPersistence","storage","diagnostics","clockOffset","serverMs","date","StatusTransport","batch","cancel","cancelled","work","config","onSampling","onLoss","onClock","serialized","kind","sampling","offset","code","status","advice","hints","throttled","retryAfterMs","toTransportRequest","isResponse","value","finiteHint","CustomTransport","transport","request","response","error","deadline","message","ExitFlush","deps","me","reason","url","target","custom","headers","outcome","onExit","saveToEmergencyQueue","endpoint","nav","body","park","bytes","caches","lastHeaders","cached","owner","resolveHeaders","resolved","resetHeaders","CREDENTIAL_ADVICE","HttpTransport","onKeepalive","maxBytes","keepalive","text","controller","timer","hidden","parsed","RetryEngine","batchesPerDrain","storageLimits","parts","part","delayMs","exponential","lock","batches","blocked","failure","halves","record","STREAM_ORDER","streamOf","type","RecordStream","options","onFlush","records","LogPipeline","pending","stream","full","maxPendingRecords","maxPendingBytes","fits","overflow","retry","routingContextId","policy","flush","streamOptions","queued","inFlight","name","total","item","items","ATTR_CLOCK_OFFSET_MS","resolve","settle","throttledMs","Sender","pipeline","exitFlush","backing","createStorage","storageName","ContextStorage","update","raw","clockOffsetMs","offsetMs","worker","http","batching","started","sender","scope","clearEmergencyContext","contextId","timeoutMs","drained","buffered","stored","discard","moved","drainEmergencyQueue"],"sources":["../src/storage/persistence.ts","../src/transport/status-transport.ts","../src/transport/custom-transport.ts","../src/transport/exit-flush.ts","../src/transport/headers.ts","../src/transport/http-transport.ts","../src/transport/retry-engine.ts","../src/core/pipeline.ts","../src/core/sender.ts"],"sourcesContent":["// src/storage/persistence.ts\n//\n// Asks the browser to keep the stored batches under storage pressure.\n\nimport type { Diagnostics } from \"../core/diagnostics\";\nimport type { StoragePersistence } from \"../models/storage\";\n\n/** The global that holds the storage manager. Workers, Node and insecure pages can lack it. */\ninterface StorageGlobal {\n navigator?: { storage?: StorageManager };\n}\n\n/**\n * Asks the browser for persistent storage. Firefox can show a permission prompt.\n * @param diagnostics Diagnostics reporter.\n * @returns The browser's answer. Never rejects.\n */\nexport async function requestPersistence(diagnostics: Diagnostics): Promise<StoragePersistence> {\n const storage = (globalThis as StorageGlobal).navigator?.storage;\n // An old browser can have navigator.storage without persist().\n if (typeof storage?.persist !== \"function\") {\n return \"unsupported\";\n }\n\n const granted = await diagnostics.guardAsync(\n \"storage.unavailable\",\n \"The browser rejected the request for persistent storage.\",\n () => storage.persist(),\n );\n\n return granted === true ? \"granted\" : \"denied\";\n}\n","// src/transport/status-transport.ts\n//\n// Holds what the HTTP transport and the custom transport share, so a status code means the\n// same on both paths. 2xx accepts the batch, 413 splits it, 429 and 503 throttle, and 408 and\n// 5xx retry. Any other code drops the batch.\n\nimport {\n DATE_HEADER_HALF_STEP_MS,\n HTTP_FORBIDDEN,\n HTTP_PAYLOAD_TOO_LARGE,\n HTTP_REQUEST_TIMEOUT,\n HTTP_SERVER_ERROR_MIN,\n HTTP_SERVICE_UNAVAILABLE,\n HTTP_TOO_MANY_REQUESTS,\n HTTP_UNAUTHORIZED,\n} from \"../constants\";\nimport type { Diagnostics } from \"../core/diagnostics\";\nimport type { LogBatch } from \"../models/batch\";\nimport type { BatchKind, ResolvedConfig } from \"../models/config\";\nimport type { LossReporter } from \"../models/drop\";\nimport type { SerializedBatch } from \"../models/serializer\";\nimport { TransportError } from \"./errors\";\nimport { batchKind, endpointFor, serializeBatch } from \"./serializers/select\";\n\n/**\n * Computes the clock offset from an answer's Date header.\n * @param date Value of the Date header. It has whole seconds.\n * @returns Server time minus client time in milliseconds, or undefined without a valid date.\n */\nfunction clockOffset(date: unknown): number | undefined {\n const serverMs = typeof date === \"string\" ? Date.parse(date) : Number.NaN;\n\n return Number.isNaN(serverMs)\n ? undefined\n : Math.round(serverMs + DATE_HEADER_HALF_STEP_MS - Date.now());\n}\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 * @param onKeepalive Runs when one of the batch's requests starts with keepalive.\n * @throws TransportError when the batch isn't accepted.\n */\n send(batch: LogBatch, onKeepalive?: () => void): Promise<void>;\n /**\n * Returns the remaining throttle delay for a batch's endpoint.\n * @param batch Batch to send.\n * @returns Milliseconds until the throttle ends, or 0.\n */\n throttledForMs(batch: LogBatch): 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 /** Abort controller shared by the requests of this delivery context. */\n protected readonly cancellation = new AbortController();\n /** Cancels this context's work. A custom transport receives the same abort signal. */\n stop(): void {\n this.cancellation.abort();\n }\n\n /**\n * Checks the batch context after every asynchronous step and before a send.\n * @param batch Batch to check.\n * @throws TransportError if the context stopped or the context id doesn't match.\n */\n protected assertContext(batch: LogBatch): void {\n if (\n this.cancellation.signal.aborted ||\n (this.config.securityContext.isolation &&\n this.config.securityContext.id &&\n batch.routingContextId !== this.config.securityContext.id)\n ) {\n this.diagnostics.count(\"security.context_mismatch\");\n throw new TransportError(\n \"permanent\",\n \"The delivery context is inactive or does not match the batch.\",\n );\n }\n }\n\n /**\n * Ends the wait if this context stops before the work completes.\n * @param work Work to wait for.\n * @returns The result of the work.\n * @throws TransportError if this context stops first.\n */\n protected async untilCancelled<T>(work: Promise<T>): Promise<T> {\n if (this.cancellation.signal.aborted)\n throw new TransportError(\"permanent\", \"The delivery context retired.\");\n let cancel!: () => void;\n const cancelled = new Promise<never>((_resolve, reject) => {\n cancel = () => {\n reject(new TransportError(\"permanent\", \"The delivery context retired.\"));\n };\n this.cancellation.signal.addEventListener(\"abort\", cancel, { once: true });\n });\n try {\n return await Promise.race([work, cancelled]);\n } finally {\n this.cancellation.signal.removeEventListener(\"abort\", cancel);\n }\n }\n /**\n * Epoch time in milliseconds when the server throttle ends, per endpoint, so that a 429 from\n * metricsEndpoint doesn't stop the log batches.\n */\n private readonly throttledUntil: Record<BatchKind, number> = { logs: 0, metrics: 0, traces: 0 };\n\n /** Epoch time in milliseconds when the server last accepted a batch, or null. */\n private acceptedAt: number | null = null;\n\n /**\n * @param config Active configuration instance.\n * @param diagnostics Diagnostics reporter.\n * @param onSampling Receives an accepted batch's sampling rules, before validation.\n * @param onLoss Receives the records of a batch that the serializer can't encode.\n * @param onClock Receives an accepted batch's clock offset, in milliseconds.\n */\n constructor(\n protected readonly config: ResolvedConfig,\n protected readonly diagnostics: Diagnostics,\n private readonly onSampling: (raw: unknown) => void = () => undefined,\n private readonly onLoss: LossReporter = () => undefined,\n private readonly onClock: (offsetMs: number) => void = () => undefined,\n ) {}\n\n /**\n * Sends one batch.\n * @param batch Batch to send.\n * @param onKeepalive Runs when one of the batch's requests starts with keepalive.\n * @throws TransportError when the batch isn't accepted.\n */\n abstract send(batch: LogBatch, onKeepalive?: () => void): Promise<void>;\n\n /**\n * Returns the remaining throttle delay for a batch's endpoint, in milliseconds.\n * @param batch Batch to send.\n * @returns Milliseconds remaining in throttle window, or 0 if unthrottled.\n */\n throttledForMs(batch: LogBatch): number {\n return Math.max(0, this.throttledUntil[batchKind(batch, this.config)] - Date.now());\n }\n\n /**\n * Returns the time when the server last accepted a batch.\n * @returns Epoch time in milliseconds, or null before the first accepted batch.\n */\n lastSendAt(): number | null {\n return this.acceptedAt;\n }\n\n /**\n * Serializes a batch with the configured serializer. A metrics batch gets the OTLP metrics\n * format. 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 const serialized = serializeBatch(\n this.config,\n batch,\n this.diagnostics,\n \"The serializer threw an error. The library dropped the batch.\",\n );\n\n if (!serialized) {\n this.onLoss(\"unserializable\", batch.records, [batch.id]);\n }\n\n return serialized;\n }\n\n /**\n * Records an accepted batch and ends the server throttle for that batch's endpoint.\n * @param kind Kind of the accepted batch.\n * @param sampling The answer's sampling rules, as text or as an object.\n * @param date The answer's Date header. Null when the server doesn't expose it.\n */\n protected accept(kind: BatchKind, sampling: unknown, date: unknown): void {\n this.throttledUntil[kind] = 0;\n this.acceptedAt = Date.now();\n\n // Only trust the answer to a batch that we sent ourselves. A null header means no rules.\n if (this.config.sampling.remote && sampling !== undefined && sampling !== null) {\n this.onSampling(sampling);\n }\n\n const offset = clockOffset(date);\n if (offset !== undefined) {\n this.onClock(offset);\n }\n }\n\n /**\n * Converts a non-2xx status code into a classified TransportError.\n * @param status The answer's status code.\n * @param batchId Identifier of the rejected batch.\n * @param kind Kind of the rejected batch. A throttle applies only to its endpoint.\n * @param hints Delay, size limit and advice that come with the answer.\n * @returns Classified TransportError instance.\n */\n protected reject(\n status: number,\n batchId: string,\n kind: BatchKind,\n hints: RejectHints,\n ): 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: endpointFor(kind, this.config) },\n );\n // Classify as permanent. Retrying a rejected credential would block every batch behind 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 // Cap the server delay, otherwise a large Retry-After could stop delivery for hours.\n const retryAfterMs =\n hints.retryAfterMs === undefined\n ? undefined\n : Math.min(hints.retryAfterMs, this.config.delivery.retryMaxDelayMs);\n this.throttledUntil[kind] =\n Date.now() + (retryAfterMs ?? this.config.delivery.retryBaseDelayMs);\n\n if (throttled) {\n this.diagnostics.report(\"transport.throttled\", \"The server throttles the requests.\", {\n 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 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 consumer's own transport function. Status codes mean the same as\n// on the HTTP path, and retry, storage and the exit flush work unchanged.\n\nimport { HTTP_STATUS_MAX, HTTP_STATUS_MIN, HTTP_SUCCESS_END, HTTP_SUCCESS_MIN } from \"../constants\";\nimport type { LogBatch } from \"../models/batch\";\nimport type { BatchKind, 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, trackTransportCall } from \"../utils/library-request\";\nimport { TransportError } from \"./errors\";\nimport { batchKind } from \"./serializers/select\";\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 * @param kind Kind of the batch.\n * @returns The transport request.\n */\nexport function toTransportRequest(\n batch: LogBatch,\n serialized: SerializedBatch,\n kind: BatchKind,\n): TransportRequest {\n return {\n kind,\n body: serialized.body,\n contentType: serialized.contentType,\n batchId: batch.id,\n attempt: batch.attempts,\n records: batch.records,\n routingContextId: batch.routingContextId,\n };\n}\n\n/**\n * Checks 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 * Cleans a numeric hint from the transport's response before the library's throttle and\n * batch split use it. A string, NaN or Infinity would break the throttle.\n * @param value Hint that the transport returned.\n * @returns The value, 0 or more, or undefined if it isn't 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 this.assertContext(batch);\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 kind = batchKind(batch, this.config);\n const request = toTransportRequest(batch, serialized, kind);\n request.signal = this.cancellation.signal;\n\n let response: unknown;\n\n try {\n // A transport that never settles would hold a dispatch slot forever. The deadline frees it.\n response = await withDeadline(\n // Inside these scopes the capture modules skip requests and console lines. A request\n // made after an await falls outside the scopes, and network capture warns about it.\n this.untilCancelled(\n trackTransportCall(() =>\n runAsLibraryRequest(() => runAsLibraryConsole(() => transport(request))),\n ),\n ),\n this.config.delivery.requestTimeoutMs,\n );\n } catch (error) {\n // The pipeline reports the thrown error. All we do here is classify it.\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 this.assertContext(batch);\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(kind, response.sampling, response.date);\n return;\n }\n\n throw this.reject(status, batch.id, kind, {\n retryAfterMs: finiteHint(response.retryAfterMs),\n maxBytes: finiteHint(response.maxBytes),\n });\n }\n}\n","// src/transport/exit-flush.ts\n//\n// Flushes buffered batches on exit with sendBeacon, a keepalive fetch or emergency storage.\n// It runs during unload, so nothing in here awaits. A hidden document is still running, so it\n// gets a normal flush.\n\nimport {\n BEACON_LIMIT_BYTES,\n CONTENT_TYPE_TEXT_PLAIN,\n HEADER_BATCH_ID,\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 { LossReporter } from \"../models/drop\";\nimport type { SerializedBatch } from \"../models/serializer\";\nimport { saveToEmergencyQueue } from \"../storage/emergency-queue\";\nimport { runAsLibraryRequest } from \"../utils/library-request\";\nimport { getFin } from \"../utils/openfin\";\nimport { estimateBytes } from \"../utils/sanitize\";\nimport { toTransportRequest } from \"./custom-transport\";\nimport { batchKind, endpointFor, serializeBatch } from \"./serializers/select\";\n\n/** The lifecycle event or manual action that starts an exit flush. */\nexport type ExitReason = \"hidden\" | \"pagehide\" | \"freeze\" | \"openfin-close\" | \"shutdown\";\n\n/**\n * The browser's answer to a beacon. `refused` means the in-flight budget is full.\n * `unavailable` means the host has no usable sendBeacon.\n */\ntype BeaconOutcome = \"sent\" | \"refused\" | \"unavailable\";\n\n/** Lets us read navigator.sendBeacon without global DOM type assertions. */\ninterface BeaconGlobal {\n navigator?: { sendBeacon?: (url: string, data: Blob) => boolean };\n}\n\n/** Dependencies of ExitFlush. */\nexport interface ExitFlushDeps {\n /** The active configuration. */\n config: ResolvedConfig;\n /** Diagnostics reporter. */\n diagnostics: Diagnostics;\n /** Drains all buffered and unconfirmed records into one batch per kind. */\n drainForExit: () => LogBatch[];\n /**\n * Runs a normal flush with headers, gzip and retry. Used for a hidden document.\n * It doesn't touch an in-flight batch.\n */\n flushAlive: () => void | Promise<void>;\n /**\n * Returns the headers that the HTTP transport sent last, or undefined. sendBeacon can't set\n * a header, so when there are headers the exit flush uses a keepalive fetch.\n */\n exitHeaders: () => Record<string, string> | undefined;\n /** Receives the records that the exit flush loses. */\n onLoss?: LossReporter;\n /** Pushes the open metric interval's points into the buffers. */\n beforeExit?: () => void;\n}\n\n/**\n * Flushes pending telemetry on document unload, with sendBeacon, a keepalive fetch or\n * emergency storage.\n */\nexport class ExitFlush {\n /** True while we are listening for the unload events. */\n private installed = false;\n\n /** Bytes used by the current exit flush's keepalive fetches. All batches share one budget. */\n private keepaliveBytes = 0;\n\n /** 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 /** Flushes on the window's pagehide event. */\n private readonly onPageHide = (): void => {\n this.flush(\"pagehide\");\n };\n\n /** Flushes on the document's freeze event. */\n private readonly onFreeze = (): void => {\n this.flush(\"freeze\");\n };\n\n /** 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 /** 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 = getFin()?.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 /** 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 = getFin()?.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 and sends them with a beacon, a keepalive fetch or\n * emergency storage. A hidden document gets a normal flush. Never awaits and never throws,\n * because the caller is an unload listener.\n * @param reason Reason code of the flush.\n */\n flush(reason: ExitReason): void {\n const { config, diagnostics } = this.deps;\n\n // Runs first, so that the drain below also takes the open metric interval's points.\n diagnostics.guard(\"pipeline.crashed\", \"The metric points before the exit flush failed.\", () => {\n this.deps.beforeExit?.();\n });\n\n // hidden fires on every tab switch, and the document keeps running. A normal flush keeps\n // the headers, gzip and the retry, none of which a beacon has. The in-flight batches\n // complete on their own. Taking them here would send the records again under a new id.\n if (reason === \"hidden\") {\n this.flushAlive();\n return;\n }\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 // An earlier flush's fetches are complete or lost by now, so they don't use this budget.\n this.keepaliveBytes = 0;\n\n for (const batch of this.deps.drainForExit()) {\n // resolveConfig keeps only a valid absolute metricsEndpoint and tracesEndpoint. A traces\n // batch without tracesEndpoint has no destination.\n const kind = batchKind(batch, config);\n const target = kind === \"logs\" ? url.href : endpointFor(kind, config);\n if (target) {\n this.flushBatch(batch, reason, new URL(target));\n } else {\n diagnostics.count(\"record.dropped_no_destination\");\n }\n }\n }\n\n /**\n * Sends one exit batch with a beacon, a keepalive fetch or emergency storage.\n * @param batch Batch to send.\n * @param reason Reason code of the flush.\n * @param url Endpoint of the batch.\n */\n private flushBatch(batch: LogBatch, reason: ExitReason, url: URL): void {\n const { config } = this.deps;\n\n if (batch.records.length === 0) {\n return;\n }\n\n const serialized = this.serialize(batch, reason);\n if (!serialized) {\n return;\n }\n\n // An oversized payload goes to the synchronous localStorage queue, because localStorage\n // is the only storage that accepts a write without an await.\n if (estimateBytes(serialized.body) > BEACON_LIMIT_BYTES) {\n this.park(batch);\n return;\n }\n\n // The batch ID and the reason go in query parameters, because sendBeacon can't 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\n // sendBeacon can't set a header, and an ingest server that needs the authorization header\n // drops a beacon. Send the last headers with a keepalive fetch instead.\n const custom = this.deps.exitHeaders();\n if (custom) {\n this.keepaliveFetch(target, batch, serialized.body, reason, () => {\n const headers = new Headers(custom);\n headers.set(HEADER_CONTENT_TYPE, serialized.contentType);\n headers.set(HEADER_BATCH_ID, batch.id);\n return headers;\n });\n return;\n }\n\n // A headers function has no cached result until it has been called once. The server refuses\n // a beacon without the headers, so let the next page load send the batch with them.\n if (config.headers) {\n this.park(batch);\n return;\n }\n\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 same budget and\n // fails the same way, and with the document closing nothing would retry the send.\n if (outcome === \"refused\") {\n this.park(batch);\n return;\n }\n\n const plain = (): Headers => new Headers({ [HEADER_CONTENT_TYPE]: CONTENT_TYPE_TEXT_PLAIN });\n this.keepaliveFetch(target, batch, serialized.body, reason, plain);\n }\n\n /** Runs a hidden document's normal flush, and reports it if it throws or rejects. */\n private flushAlive(): void {\n const { diagnostics } = this.deps;\n const message = \"The flush of the hidden document failed.\";\n\n diagnostics.guard(\"pipeline.crashed\", message, () => {\n void Promise.resolve(this.deps.flushAlive()).catch((error: unknown) => {\n diagnostics.report(\"pipeline.crashed\", message, undefined, error);\n });\n });\n }\n\n /**\n * Hands the pending records to a custom transport's exit hook, because a closing page can't\n * wait for the async transport. Without a hook, or when the hook refuses the batch, the\n * batch goes to the emergency queue and the next page load sends it.\n * @param reason Reason code of the flush.\n * @param onExit The custom transport's synchronous exit hook.\n */\n private flushCustom(reason: ExitReason, onExit: ExitTransport | undefined): void {\n const { config, diagnostics } = this.deps;\n\n for (const batch of this.deps.drainForExit()) {\n const serialized = this.serialize(batch, reason);\n if (!serialized) {\n continue;\n }\n\n const request = toTransportRequest(batch, serialized, batchKind(batch, config));\n const accepted =\n onExit !== undefined &&\n diagnostics.guard(\"transport.http_error\", \"The transportOnExit hook threw an error.\", () =>\n runAsLibraryRequest(() => onExit(request)),\n ) === true;\n\n if (!accepted) {\n this.park(batch);\n }\n }\n }\n\n /**\n * Parks a batch in the localStorage emergency queue for the next page load. With storage\n * \"memory\" or \"none\" the app wants nothing kept on the device, so the batch is lost.\n * @param batch Batch that the exit flush can't send.\n */\n private park(batch: LogBatch): void {\n const { config, diagnostics, onLoss } = this.deps;\n\n if (config.storage === \"memory\" || config.storage === \"none\") {\n onLoss?.(\"not_stored\", batch.records, [batch.id]);\n return;\n }\n\n saveToEmergencyQueue(batch, diagnostics, onLoss);\n }\n\n /**\n * Serializes the exit batch, and reports a serializer that throws.\n * @param batch Batch to serialize.\n * @param reason Reason code of the flush.\n * @returns The serialized batch, or undefined if the serializer threw.\n */\n private serialize(batch: LogBatch, reason: ExitReason): SerializedBatch | undefined {\n const serialized = serializeBatch(\n this.deps.config,\n batch,\n this.deps.diagnostics,\n `The ${reason} exit flush could not serialize its batch.`,\n );\n\n if (!serialized) {\n this.deps.onLoss?.(\"unserializable\", batch.records, [batch.id]);\n }\n\n return serialized;\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 browser's answer.\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 so that it keeps its receiver. A detached sendBeacon\n // throws when called.\n const nav = (globalThis as BeaconGlobal).navigator;\n if (!nav?.sendBeacon) {\n return \"unavailable\";\n }\n\n // Use text/plain to avoid a CORS preflight. During unload a preflight usually doesn't\n // complete, and 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 isn't a refusal. It means the method is there but unusable, and the keepalive\n // fetch can still succeed.\n return outcome ?? \"unavailable\";\n }\n\n /**\n * Sends a fallback POST with fetch and `keepalive: true`. A keepalive request continues\n * after the document closes, whereas the browser cancels a plain fetch at page close.\n * A failed fetch parks the batch in the emergency queue, and the server drops a second copy\n * by its batch id.\n * @param url Target endpoint URL.\n * @param batch Batch in the payload.\n * @param body Serialized payload string.\n * @param reason Reason code of the flush.\n * @param headers Builds the request headers. Without custom headers that is only a text/plain\n * content type. A header value outside ISO-8859-1 makes the Headers constructor throw.\n */\n private keepaliveFetch(\n url: string,\n batch: LogBatch,\n body: string,\n reason: ExitReason,\n headers: () => Headers,\n ): void {\n const { config, diagnostics } = this.deps;\n // A rejection only arrives while the document is alive, and the next page load then sends\n // the batch.\n const park = (): void => {\n this.park(batch);\n };\n\n // The browser rejects a fetch over the budget after the document closes. By then park()\n // doesn't run, and the batch is lost.\n const bytes = estimateBytes(body);\n if (this.keepaliveBytes + bytes > BEACON_LIMIT_BYTES) {\n park();\n return;\n }\n this.keepaliveBytes += bytes;\n\n const started = diagnostics.guard(\"transport.http_error\", \"The keepalive fetch failed.\", () => {\n void fetch(url, {\n method: \"POST\",\n body,\n headers: headers(),\n credentials: config.credentials,\n keepalive: true,\n }).catch((error: unknown) => {\n diagnostics.report(\"transport.http_error\", \"The exit flush failed.\", { reason }, error);\n park();\n });\n return true;\n });\n\n if (started !== true) {\n park();\n }\n }\n}\n","import type { Diagnostics } from \"../core/diagnostics\";\nimport type { ResolvedConfig } from \"../models/config\";\n\n/** One HTTP transport's header cache. The worker path shares its fallback transport's cache. */\ninterface CachedHeaders {\n source: unknown;\n endpoint: string | null;\n metricsEndpoint: string;\n tracesEndpoint: string;\n headers: Record<string, string>;\n}\n\nconst caches = new WeakMap<object, CachedHeaders>();\n\n/** Returns the last headers, but only while their source and all destinations are unchanged. */\nexport function lastHeaders(\n owner: object,\n config: ResolvedConfig,\n): Record<string, string> | undefined {\n const { headers } = config;\n if (!headers) {\n return undefined;\n }\n if (typeof headers !== \"function\") {\n return headers;\n }\n\n const cached = caches.get(owner);\n const current =\n cached?.source === headers &&\n cached.endpoint === config.endpoint &&\n cached.metricsEndpoint === config.metricsEndpoint &&\n cached.tracesEndpoint === config.tracesEndpoint;\n return current ? cached.headers : undefined;\n}\n\n/** Resolves a headers function on the main thread and keeps its result for the exit flush. */\nexport async function resolveHeaders(\n owner: object,\n config: ResolvedConfig,\n diagnostics: Diagnostics,\n): Promise<Record<string, string>> {\n const { headers } = config;\n if (!headers) {\n return {};\n }\n if (typeof headers !== \"function\") {\n return headers;\n }\n\n const { endpoint, metricsEndpoint, tracesEndpoint } = config;\n const resolved = await diagnostics.guardAsync(\n \"transport.http_error\",\n \"The headers() function threw an error.\",\n () => Promise.resolve(headers()),\n );\n if (resolved) {\n caches.set(owner, {\n source: headers,\n endpoint,\n metricsEndpoint,\n tracesEndpoint,\n headers: resolved,\n });\n }\n\n return resolved ?? {};\n}\n\n/** Forgets rejected credentials before the headers function is called again. */\nexport function resetHeaders(owner: object): void {\n caches.delete(owner);\n}\n","// src/transport/http-transport.ts\n//\n// Serializes, compresses and sends log batches over HTTP. Every failure is classified,\n// reported and thrown. The caller that owns storage decides what happens to a rejected batch.\n\nimport {\n BEACON_LIMIT_BYTES,\n COMPRESSION_THRESHOLD_BYTES,\n ENCODING_GZIP,\n HEADER_ATTEMPT,\n HEADER_BATCH_ID,\n HEADER_CONTENT_ENCODING,\n HEADER_CONTENT_TYPE,\n HEADER_DATE,\n HEADER_RETRY_AFTER,\n HEADER_SAMPLING,\n HTTP_FORBIDDEN,\n HTTP_PAYLOAD_TOO_LARGE,\n HTTP_UNAUTHORIZED,\n} from \"../constants\";\nimport type { LogBatch } from \"../models/batch\";\nimport type { BatchKind } from \"../models/config\";\nimport type { SerializedBatch } from \"../models/serializer\";\nimport { withDeadline } from \"../utils/deadline\";\nimport { runAsLibraryRequest } from \"../utils/library-request\";\nimport { isOnline } from \"../utils/platform\";\nimport { estimateBytes } from \"../utils/sanitize\";\nimport { unrefTimer } from \"../utils/unref\";\nimport { gzip } from \"./compression\";\nimport { lastHeaders, resetHeaders, resolveHeaders } from \"./headers\";\nimport { parseRetryAfter, TransportError } from \"./errors\";\nimport { batchKind, endpointFor } from \"./serializers/select\";\nimport { StatusTransport } from \"./status-transport\";\n\n/** Advice for an HTTP send answered with a 401 or a 403, on the main thread or in the worker. */\nexport const 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/** Body of one request, either text or gzip bytes. */\ntype RequestBody = string | Uint8Array<ArrayBuffer>;\n\n/** Lets us read document.visibilityState without global DOM type assertions. */\ninterface DocumentGlobal {\n document?: { visibilityState?: string };\n}\n\n/**\n * Sends serialized log batches over HTTP. Resolves headers, applies gzip compression and\n * classifies errors.\n */\nexport class HttpTransport extends StatusTransport {\n /**\n * Sends one log batch over HTTP. A metrics batch goes to metricsEndpoint and a traces batch\n * to tracesEndpoint. A batch without an endpoint goes nowhere.\n * @param batch Batch to send.\n * @param onKeepalive Runs when one of the batch's requests starts with keepalive.\n * @throws TransportError on transient, throttled, 413, or permanent network failures.\n */\n async send(batch: LogBatch, onKeepalive?: () => void): Promise<void> {\n this.assertContext(batch);\n const { config } = this;\n const kind = batchKind(batch, config);\n const endpoint = endpointFor(kind, config);\n\n // A traces batch without tracesEndpoint has no destination. Count the drop.\n if (!endpoint) {\n this.diagnostics.count(\"record.dropped_no_destination\");\n return;\n }\n\n if (batch.records.length === 0) {\n return;\n }\n\n await this.post(batch, kind, endpoint, onKeepalive);\n }\n\n /**\n * Returns the headers for the exit flush, because a closing document can't await headers().\n * @returns The static headers, the last result of the current headers function, or undefined.\n */\n lastHeaders(): Record<string, string> | undefined {\n return lastHeaders(this, this.config);\n }\n\n /**\n * Serializes, encodes and sends a batch. Throws a classified TransportError\n * on failure.\n * @param batch Batch to deliver.\n * @param kind Kind of the batch. The caller reads it together with the endpoint.\n * @param endpoint Ingest URL. The caller reads it once, so a reconfigure during the send\n * can't change it.\n * @param onKeepalive Runs when one of the batch's requests starts with keepalive.\n */\n private async post(\n batch: LogBatch,\n kind: BatchKind,\n endpoint: string,\n onKeepalive: (() => void) | undefined,\n ): Promise<void> {\n const serialized = this.serialize(batch);\n\n if (!serialized) {\n return;\n }\n\n let response = await this.attempt(batch, endpoint, serialized, onKeepalive);\n this.assertContext(batch);\n\n // A token can expire between two headers() calls, so send once more with fresh\n // headers. A second 401 or 403 drops the batch.\n if (this.rejectsCredentials(response.status) && typeof this.config.headers === \"function\") {\n resetHeaders(this);\n response = await this.attempt(batch, endpoint, serialized, onKeepalive);\n this.assertContext(batch);\n }\n\n if (response.ok) {\n // The server must list each header in Access-Control-Expose-Headers, or it reads as null.\n const { headers } = response;\n this.accept(kind, headers.get(HEADER_SAMPLING), headers.get(HEADER_DATE));\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, kind, {\n retryAfterMs,\n maxBytes,\n advice: CREDENTIAL_ADVICE,\n });\n }\n\n /**\n * Checks whether a status rejects the credentials.\n * @param status HTTP status code.\n * @returns True for 401 and 403.\n */\n private rejectsCredentials(status: number): boolean {\n return status === HTTP_UNAUTHORIZED || status === HTTP_FORBIDDEN;\n }\n\n /**\n * Resolves the headers, encodes the body and sends one request. One deadline covers all\n * three steps, otherwise a headers() that never settles holds a dispatch slot forever.\n * @param batch Batch to deliver.\n * @param endpoint Ingest URL.\n * @param serialized Serialized batch.\n * @param onKeepalive Runs when the request starts with keepalive.\n * @returns Promise that resolves to the HTTP Response.\n * @throws TransportError on timeout or network failure.\n */\n private async attempt(\n batch: LogBatch,\n endpoint: string,\n serialized: SerializedBatch,\n onKeepalive: (() => void) | undefined,\n ): Promise<Response> {\n const deadline = Date.now() + this.config.delivery.requestTimeoutMs;\n\n // Headers ignores case in header names, so a config header can't duplicate one set below.\n const headers = new Headers(await this.before(this.resolveHeaders(), deadline, endpoint));\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.before(this.encodeBody(serialized.body), deadline, endpoint);\n this.assertContext(batch);\n if (typeof body !== \"string\") {\n headers.set(HEADER_CONTENT_ENCODING, ENCODING_GZIP);\n }\n\n // A keepalive request continues after unload, so the exit flush must not send the batch\n // again.\n const keepalive = this.keepalive(body);\n if (keepalive) {\n onKeepalive?.();\n }\n\n return this.dispatch(endpoint, headers, body, deadline, keepalive);\n }\n\n /**\n * Waits for a step until the deadline.\n * @param work Step to wait for. It never rejects, so only the deadline rejects here.\n * @param deadline Epoch time in milliseconds at which the request times out.\n * @param endpoint Ingest URL of the request, for the timeout report.\n * @returns Promise that resolves to the step's value.\n * @throws TransportError of kind \"timeout\" at the deadline.\n */\n private async before<T>(work: Promise<T>, deadline: number, endpoint: string): Promise<T> {\n try {\n return await withDeadline(this.untilCancelled(work), Math.max(0, deadline - Date.now()));\n } catch {\n if (this.cancellation.signal.aborted)\n throw new TransportError(\"permanent\", \"The delivery context retired.\");\n throw this.timeout(endpoint);\n }\n }\n\n /**\n * Reports a timeout and builds its error.\n * @param endpoint Ingest URL of the request.\n * @returns TransportError of kind \"timeout\".\n */\n private timeout(endpoint: string): TransportError {\n const waited = String(this.config.delivery.requestTimeoutMs);\n const message = `The request took longer than ${waited} ms.`;\n\n this.diagnostics.report(\"transport.timeout\", message, { endpoint });\n return new TransportError(\"timeout\", message);\n }\n\n /**\n * Compresses the serialized payload when the config sets gzip and the payload is at or\n * above the threshold.\n * @param text Serialized payload string.\n * @returns Promise that resolves to the original string or the compressed byte array.\n */\n private async encodeBody(text: string): Promise<RequestBody> {\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, and 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 * @param deadline Epoch time in milliseconds at which the request times out.\n * @param keepalive True if the request continues after unload.\n * @returns Promise that resolves 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: RequestBody,\n deadline: number,\n keepalive: boolean,\n ): Promise<Response> {\n const { config } = this;\n const controller = new AbortController();\n const cancel = (): void => {\n controller.abort();\n };\n this.cancellation.signal.addEventListener(\"abort\", cancel, { once: true });\n if (this.cancellation.signal.aborted) controller.abort();\n // The fetch gets whatever time is left after the headers and the encoding.\n const timer = setTimeout(\n () => {\n controller.abort();\n },\n Math.max(0, deadline - Date.now()),\n );\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 keepalive,\n // The OS can stop a hidden page soon, so don't delay its keepalive send.\n priority: keepalive ? \"auto\" : config.delivery.priority,\n }),\n );\n } catch {\n if (this.cancellation.signal.aborted) {\n throw new TransportError(\"permanent\", \"The delivery context retired.\");\n }\n if (controller.signal.aborted) {\n throw this.timeout(endpoint);\n }\n throw new TransportError(isOnline() ? \"transient\" : \"offline\", \"A network error occurred.\");\n } finally {\n this.cancellation.signal.removeEventListener(\"abort\", cancel);\n clearTimeout(timer);\n }\n }\n\n /**\n * Checks whether a send uses keepalive. A mobile OS can stop a hidden page without a\n * pagehide, and a keepalive request continues after that. The browser limits the keepalive\n * bodies in flight.\n * @param body Request body string or byte array.\n * @returns True for a hidden document and a body of BEACON_LIMIT_BYTES or less.\n */\n private keepalive(body: RequestBody): boolean {\n const hidden = (globalThis as DocumentGlobal).document?.visibilityState === \"hidden\";\n const bytes = typeof body === \"string\" ? estimateBytes(body) : body.byteLength;\n\n return hidden && bytes <= BEACON_LIMIT_BYTES;\n }\n\n /**\n * Reads the optional maxBytes limit from a 413 response body.\n * @param response HTTP 413 Response instance.\n * @returns Promise that resolves 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, and keeps what headers()\n * returned for the exit flush.\n * @returns Promise that resolves to the header map.\n */\n private async resolveHeaders(): Promise<Record<string, string>> {\n return resolveHeaders(this, this.config, this.diagnostics);\n }\n}\n","// src/transport/retry-engine.ts\n//\n// Resends stored log batches in the background, with exponential backoff and jitter.\n// There is only ever one timer, never a chain of timers, because every scheduling path\n// clears the pending timer first.\n\nimport { DRAIN_LOCK_NAME, STORAGE_DEADLINE_MS } from \"../constants\";\nimport type { Diagnostics } from \"../core/diagnostics\";\nimport { type LogBatch, splitBatch } from \"../models/batch\";\nimport type { BatchKind, ResolvedConfig } from \"../models/config\";\nimport type { LossReporter } from \"../models/drop\";\nimport { type StorageAdapter, storageLimits } from \"../models/storage\";\nimport { withDeadline } from \"../utils/deadline\";\nimport { lockName, withDrainLock } from \"../utils/lock\";\nimport { isOnline } from \"../utils/platform\";\nimport { unrefTimer } from \"../utils/unref\";\nimport { TransportError } from \"./errors\";\nimport { batchKind } from \"./serializers/select\";\nimport type { BatchTransport } from \"./status-transport\";\n\n/** Result of one delivery. A number is the delay before a failed batch is tried again. */\ntype Outcome = \"next\" | \"stop\" | number;\n\n/**\n * Resends persisted offline batches on a timer, with backoff, a cross-tab drain lock and\n * batch splitting.\n */\nexport class RetryEngine {\n /** The active retry timer handle, or null when no timer is running. */\n private timer: ReturnType<typeof setTimeout> | null = null;\n\n /** Consecutive failed deliveries. Feeds the backoff calculation. */\n private attempt = 0;\n\n /** True while a storage drain is running. */\n private draining = false;\n\n /** True after stop(). */\n private stopped = false;\n\n /** Attempt limit for a stored batch. Retention can't change after the delivery stack loads. */\n private readonly maxAttempts: number;\n\n /** Runs on the online event. 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 * @param onLoss Receives the records of every batch that the engine drops.\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?: number,\n private readonly onLoss: LossReporter = () => undefined,\n ) {\n this.maxAttempts = storageLimits(config.retention).maxAttempts;\n }\n\n /** Starts the engine. 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(this.config.delivery.retryIdleDelayMs);\n }\n\n /** Schedules an earlier retry when storage receives a new offline batch. */\n nudge(): void {\n if (!this.draining) {\n this.schedule(this.config.delivery.retryBaseDelayMs);\n }\n }\n\n /**\n * Stores a batch that failed outside the drain loop, under the same rules as the drain.\n * A refused batch is never stored whole, because that would cause another request with a\n * payload the server already 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 /** Stops the engine. 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 * Tries one delivery pass over the stored batches before a context change. The caller sets\n * the deadline.\n * @returns Promise that resolves when this pass stops.\n */\n async flush(): Promise<void> {\n this.stopped = false;\n try {\n await this.drain();\n } finally {\n this.stop();\n }\n }\n\n /**\n * Clears the pending timer, 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 * Puts a deadline on a storage call. A call that never settles would keep\n * `draining` true, and this window would run no more drains.\n * @param work Storage promise to bound.\n * @returns The promise's value, 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 /** Clears the pending timer if there is one. */\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. Uses full jitter\n * instead of a fixed offset, because 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(\n this.config.delivery.retryBaseDelayMs * 2 ** this.attempt,\n this.config.delivery.retryMaxDelayMs,\n );\n\n return Math.random() * exponential;\n }\n\n /** 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 lock = lockName(DRAIN_LOCK_NAME, this.config.persistence.namespace);\n const ran = await withDrainLock(lock, this.diagnostics, () => this.drainLocked());\n\n // The value is undefined when another window holds the lock. Without this reschedule,\n // one lost lock race would stop all drains in this window.\n if (ran !== true) {\n this.schedule(this.config.delivery.retryIdleDelayMs);\n }\n } finally {\n this.draining = false;\n }\n }\n\n /**\n * Processes batches while holding the Web Lock, and schedules the next tick.\n * It always resolves, because a throw would leave the engine idle with no armed timer.\n * @returns Promise that resolves to true on completion.\n */\n private async drainLocked(): Promise<true> {\n try {\n if (!isOnline()) {\n this.schedule(this.config.delivery.retryIdleDelayMs);\n return true;\n }\n\n const batches = await this.bounded(\n this.storage.take(this.batchesPerDrain ?? this.config.delivery.batchesPerDrain),\n );\n\n if (batches.length === 0) {\n this.schedule(this.config.delivery.retryIdleDelayMs);\n return true;\n }\n\n // A failure blocks only its own batch kind. The other endpoints can still accept batches.\n const blocked = new Set<BatchKind>();\n let delayMs = 0;\n\n for (const batch of batches) {\n if (this.stopped) {\n return true;\n }\n\n const kind = batchKind(batch, this.config);\n if (blocked.has(kind)) {\n continue;\n }\n\n const outcome = await this.deliver(batch);\n if (outcome === \"stop\") {\n return true;\n }\n\n if (outcome !== \"next\") {\n blocked.add(kind);\n // Keep the longest delay. A shorter one would send before another server's\n // Retry-After.\n delayMs = Math.max(delayMs, outcome);\n }\n }\n\n if (blocked.size > 0) {\n this.schedule(delayMs);\n } else {\n this.schedule(\n batches.length === (this.batchesPerDrain ?? this.config.delivery.batchesPerDrain)\n ? 0\n : this.config.delivery.retryIdleDelayMs,\n );\n }\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. Removes it on success, and on failure applies the rule for\n * the failure kind.\n * @param batch Log batch to deliver.\n * @returns \"next\" to continue with the next batch, \"stop\" to stop the current drain, or a\n * delay in milliseconds that blocks the batch's kind until the next drain.\n */\n private async deliver(batch: LogBatch): Promise<Outcome> {\n if (batch.attempts >= this.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 this.onLoss(\"max_attempts\", batch.records, [batch.id]);\n await this.bounded(this.storage.remove(batch.id));\n return \"next\";\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 \"next\";\n } catch (error) {\n if (this.stopped) return \"stop\";\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 \"next\";\n }\n\n // Offline stops every kind, because the other endpoints aren't reachable either.\n if (failure?.kind === \"offline\") {\n this.schedule(this.config.delivery.retryIdleDelayMs);\n return \"stop\";\n }\n\n // A throttle rejects no records. The server only asks for the batch later, so don't bump\n // the stored attempts here. A bump would dead-letter the batch after\n // `retention.maxAttempts` throttled responses.\n if (failure?.kind === \"throttled\") {\n this.attempt++;\n return failure.retryAfterMs ?? this.backoffMs();\n }\n\n await this.bounded(this.storage.bumpAttempts(batch.id, batch.attempts + 1));\n this.attempt++;\n return failure?.retryAfterMs ?? this.backoffMs();\n }\n }\n\n /**\n * Replaces a stored batch with whatever survives its failure. That is the split halves,\n * 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 * Picks the batches to keep after a failure. A 413 response splits the batch in two, a\n * permanent refusal keeps nothing, and any 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 this.onLoss(\"rejected\", batch.records, [batch.id]);\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 this.onLoss(\"rejected\", batch.records, [batch.id]);\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// Buffers the log, metric and trace streams, builds batches and delivers them.\n//\n// Every stream has its own buffer and flush timer, so the exit flush can take every record\n// that hasn't reached the transport yet.\n\nimport {\n ATTR_CLOCK_OFFSET_MS,\n ATTR_LOG_TYPE,\n LOG_TYPE_METRIC,\n LOG_TYPE_SPAN,\n STORAGE_DEADLINE_MS,\n} from \"../constants\";\nimport type { ResolvedConfig } from \"../models/config\";\nimport type { LossReporter } from \"../models/drop\";\nimport { estimateBytes } from \"../utils/sanitize\";\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\" | \"traces\";\n\n/** Streams in exit-batch order. The logs get the beacon budget before the spans. */\nconst STREAM_ORDER: readonly StreamName[] = [\"metrics\", \"logs\", \"traces\"];\n\n/**\n * Returns the stream for a record. Each stream builds batches of one kind.\n * @param record Record to evaluate.\n * @returns \"metrics\" for a metric, \"traces\" for a span, otherwise \"logs\".\n */\nfunction streamOf(record: LogRecord): StreamName {\n const type = record.attributes[ATTR_LOG_TYPE];\n\n if (type === LOG_TYPE_METRIC) {\n return \"metrics\";\n }\n\n return type === LOG_TYPE_SPAN ? \"traces\" : \"logs\";\n}\n\n/** Batching policy for one record stream. */\nexport interface StreamOptions {\n /** Maximum time in milliseconds 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/** A closed batch in the queue or in flight. */\ninterface Pending {\n /** Batch to deliver. */\n batch: LogBatch;\n /** Resolves when the batch's dispatch ends, or on destroy. */\n done: Promise<void>;\n /** Resolves `done`. */\n resolve: () => void;\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, and below that\n * it starts the interval timer. Without the timer a small batch would wait for the next\n * record, which on a quiet page never comes.\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, and 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 /** Number of buffered records. */\n get size(): number {\n return this.pending.length;\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 the log, metric and trace streams, builds batches and sends them over HTTP. */\nexport class LogPipeline {\n /** Buffer instances for the logs, metrics and traces streams. */\n private readonly streams: Record<StreamName, RecordStream>;\n\n /** In-flight batches with no delivery confirmation yet. 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: Pending[] = [];\n\n /** Every batch in the queue or in flight. flushPending waits on them, destroy() resolves them. */\n private readonly open = new Set<Pending>();\n\n /** Ceiling on the ERROR and FATAL records that bypass sampling. */\n private readonly ceiling = new ErrorCeiling();\n\n /** Requests that haven't completed. Capped by delivery.maxConcurrentRequests. */\n private inFlight = 0;\n\n /** True while a pump is queued, so one microtask drains a whole burst. */\n private pumpScheduled = false;\n\n /** True after destroy() stops the pipeline. */\n private stopped = false;\n /** Encoded byte count of every record in the buffers or in requests. */\n private readonly held = new Map<LogRecord, number>();\n /** Total encoded bytes of the held records. */\n private heldBytes = 0;\n /** True while the overflow storage operation is still running. */\n private persisting = false;\n\n /**\n * Removes completed or dropped records from the buffer counts.\n * @param records Records to remove from the counts.\n */\n private release(records: readonly LogRecord[]): void {\n for (const record of records) {\n this.heldBytes -= this.held.get(record) ?? 0;\n this.held.delete(record);\n }\n }\n\n /**\n * Removes records that haven't reached the transport. A request that was already sent can't\n * be removed.\n * @returns True if a batch or a buffered group was removed.\n */\n private evict(): boolean {\n const pending = this.queue.shift();\n if (pending) {\n this.open.delete(pending);\n this.unconfirmed.delete(pending.batch.id);\n this.release(pending.batch.records);\n pending.resolve();\n this.onLoss(\"buffer_full\", pending.batch.records, [pending.batch.id]);\n return true;\n }\n for (const stream of Object.values(this.streams)) {\n const records = stream.take();\n if (records.length) {\n this.release(records);\n this.onLoss(\"buffer_full\", records);\n return true;\n }\n }\n return false;\n }\n\n /**\n * Checks the buffer limits and applies the overflow rule.\n * @param record New record to add.\n * @returns True if the record can enter the live buffer.\n */\n private admit(record: LogRecord): boolean {\n if (!this.policy) return true;\n const { maxPendingRecords, maxPendingBytes, overflow } = this.policy.buffering;\n // Encode every record, even without a byte budget. A record JSON can't encode is dropped\n // here on its own. Otherwise the transport would drop its whole batch.\n let bytes: number;\n try {\n bytes = estimateBytes(JSON.stringify(record));\n } catch {\n this.onLoss(\"unserializable\", [record]);\n return false;\n }\n const full = (): boolean =>\n Boolean(\n (maxPendingRecords && this.held.size >= maxPendingRecords) ||\n (maxPendingBytes && this.heldBytes + bytes > maxPendingBytes),\n );\n // A record larger than the byte budget never fits, so don't evict other records for it.\n const fits = !maxPendingBytes || bytes <= maxPendingBytes;\n while (fits && full() && overflow === \"drop-oldest\" && this.evict()) {\n /* Remove complete groups until the new record fits or no group remains. */\n }\n if (full()) {\n if (overflow === \"persist\" && !this.persisting) {\n this.persisting = true;\n const batch = this.toBatch([record]);\n void this.diagnostics.guardAsync(\n \"storage.degraded\",\n \"Could not persist an overflow record.\",\n async () => {\n try {\n await this.storage.save(batch);\n this.retry.nudge();\n } finally {\n this.persisting = false;\n }\n },\n );\n } else this.onLoss(\"buffer_full\", [record]);\n return false;\n }\n this.held.set(record, bytes);\n this.heldBytes += bytes;\n return true;\n }\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, from the batching config.\n * @param routingContextId Returns the delivery context id for a new batch.\n * @param policy Active configuration instance.\n * @param onLoss Receives the records the pipeline loses.\n * @param clockOffset Returns the clock offset for a new log or span record, if known.\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>,\n private readonly routingContextId?: () => string | undefined,\n private readonly policy?: ResolvedConfig,\n private readonly onLoss: LossReporter = () => undefined,\n private readonly clockOffset: () => number | undefined = () => undefined,\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 traces: new RecordStream(streamOptions.traces, 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 const queued = { ...record };\n if (!this.admit(queued)) return;\n this.route(queued);\n }\n\n /**\n * Drains all buffered and unconfirmed in-flight records into exit batches in one step.\n * Records already handed to fetch go out again under a new batch ID, and the server can't\n * deduplicate them. So the exit flush can deliver duplicates. That is intentional: a\n * closing document can't confirm delivery.\n * @returns One batch per stream, metrics first. A stream with no records gets no batch.\n * A mixed batch would send a metric to the logs endpoint.\n */\n drainForExit(): LogBatch[] {\n const inFlight = [...this.unconfirmed.values()].flatMap((batch) => batch.records);\n this.unconfirmed.clear();\n this.held.clear();\n this.heldBytes = 0;\n\n return STREAM_ORDER.map((name) =>\n this.toBatch([\n ...inFlight.filter((record) => streamOf(record) === name),\n ...this.streams[name].take(),\n ]),\n ).filter((batch) => batch !== null);\n }\n\n /**\n * Sends the buffered records through the normal dispatch path, then waits for every batch\n * in the queue and in flight. The throttle check and the concurrency limit apply. A direct\n * send would bypass both.\n * @returns Promise that resolves once every batch is sent or stored, or on destroy.\n */\n async flushPending(): Promise<void> {\n // One batch per stream, because a mixed batch would send a metric to the logs endpoint.\n // The claim leaves in-flight batches alone. A second copy under a new ID would be a\n // duplicate the server can't remove.\n if (!this.stopped) {\n for (const name of STREAM_ORDER) {\n this.claim(this.streams[name]);\n }\n }\n\n // Queued batches count too. Otherwise the exit flush would send them again under a new id.\n await Promise.all([...this.open].map((pending) => pending.done));\n }\n\n /**\n * Counts the waiting records and the records in requests.\n * @returns Records in the buffers and the queue, and records in dispatch.\n */\n counts(): { pending: number; inFlight: number } {\n const records = (items: Iterable<Pending>): number => {\n let total = 0;\n for (const item of items) {\n total += item.batch.records.length;\n }\n return total;\n };\n\n // Every batch in the queue is also in the open set.\n const queued = records(this.queue);\n\n const buffered = STREAM_ORDER.reduce((total, name) => total + this.streams[name].size, 0);\n\n return { pending: buffered + queued, inFlight: records(this.open) - queued };\n }\n\n /** Stops the flush timers and refuses further records. */\n destroy(): void {\n this.stopped = true;\n this.held.clear();\n this.heldBytes = 0;\n for (const name of STREAM_ORDER) {\n this.streams[name].stop();\n }\n this.queue.length = 0;\n\n // destroy() drops every queued batch, so release any flushPending waiting on one.\n for (const pending of this.open) {\n pending.resolve();\n }\n this.open.clear();\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 the drain takes nothing.\n */\n private toBatch(records: [LogRecord, ...LogRecord[]]): LogBatch;\n private toBatch(records: LogRecord[]): LogBatch | null;\n private toBatch(records: LogRecord[]): LogBatch | null {\n if (records.length === 0) {\n return null;\n }\n\n return {\n id: newId(this.diagnostics),\n records,\n createdAt: Date.now(),\n attempts: 0,\n routingContextId: this.routingContextId?.(),\n persistenceNamespace: this.policy?.persistence.namespace,\n };\n }\n\n /**\n * Sorts a record into its stream. Sampling has already run: RecordBuilder samples a local\n * record and the runtime samples a forwarded one. Every fault is caught here. A record\n * without `attributes` makes streamOf throw, and an uncaught throw would land in the\n * caller's log call.\n * @param record Record to sort.\n */\n private route(record: LogRecord): void {\n try {\n const name = streamOf(record);\n const stream = this.streams[name];\n\n // Records at or above alwaysSampleFrom bypass sampling upstream, so this ceiling is\n // their only limit. Metric points and spans have level INFO, and a lost point gives a\n // false sum.\n if (\n name === \"logs\" &&\n !this.ceiling.allow(\n record,\n this.policy?.capturePolicy.errorCeiling,\n this.policy?.capturePolicy.windowMs,\n this.policy?.sampling.alwaysSampleFrom,\n )\n ) {\n this.release([record]);\n this.diagnostics.count(\"record.dropped_by_ceiling\");\n return;\n }\n\n // A changing value on a metric point would start a new series, so only logs and spans\n // get it.\n const offset = this.clockOffset();\n if (offset !== undefined && name !== \"metrics\") {\n record.attributes = { ...record.attributes, [ATTR_CLOCK_OFFSET_MS]: offset };\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 it for dispatch. Called by a timer\n * or a flush. An empty buffer produces no batch. Every `take` stops the timer that calls\n * this method.\n * @param stream Stream buffer to drain.\n */\n private claim(stream: RecordStream): void {\n this.enqueue(this.toBatch(stream.take()));\n }\n\n /**\n * Queues a batch and schedules the pump on a microtask. Dispatching inline would start\n * a fetch inside the application's log call.\n * @param batch Batch ready for delivery, or null when the drain found no records.\n */\n private enqueue(batch: LogBatch | null): void {\n if (!batch) {\n return;\n }\n\n let resolve!: () => void;\n const done = new Promise<void>((settle) => {\n resolve = settle;\n });\n const pending: Pending = { batch, done, resolve };\n\n this.unconfirmed.set(batch.id, batch);\n this.open.add(pending);\n this.queue.push(pending);\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 if (this.stopped) return;\n while (this.inFlight < (this.policy?.delivery.maxConcurrentRequests ?? 2)) {\n const pending = this.queue.shift();\n if (!pending) {\n return;\n }\n\n this.inFlight++;\n void this.run(pending);\n }\n }\n\n /**\n * Delivers one batch, then frees the concurrency slot and resolves the batch's promise.\n * @param pending Batch to deliver.\n */\n private async run(pending: Pending): Promise<void> {\n const { batch } = pending;\n\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.release(batch.records);\n this.inFlight--;\n this.open.delete(pending);\n pending.resolve();\n this.pump();\n }\n }\n\n /**\n * Sends a batch over the HTTP transport. Stores the batch if the transport is throttled\n * or fails.\n * @param batch Batch to deliver.\n */\n private async dispatch(batch: LogBatch): Promise<void> {\n try {\n // Store the batch while the transport is throttled. Sending here would post a batch\n // through the throttle every flush interval. Leave the attempt count alone, because\n // nothing was sent.\n const throttledMs = this.transport.throttledForMs(batch);\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 // A keepalive request carries on after unload, so the exit flush must not send it\n // again. A failed send still reaches the retry engine through this batch reference.\n await this.transport.send(batch, () => {\n this.unconfirmed.delete(batch.id);\n });\n } catch (error) {\n if (this.stopped) return;\n // Increment the attempt count before storing. Left at 0, the batch would exceed\n // STORAGE_LIMITS.maxAttempts by one and the attempt headers would 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 drops a\n * batch the server won't 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, then starts the retry engine. A deadline caps the wait,\n * because a storage call that never settles holds this dispatch slot, and two of them\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// Builds the delivery stack for the sender role: storage, transport, retry, pipeline and\n// exit flush.\n// The runtime imports this module dynamically, and only when the config sets an endpoint,\n// so console-only mode never downloads it.\n\nimport { STORAGE_NAME_INDEXEDDB, STORAGE_NAME_LOCAL } from \"../constants\";\nimport type { LogBatch } from \"../models/batch\";\nimport type { ResolvedConfig } from \"../models/config\";\nimport type { LossReporter } from \"../models/drop\";\nimport type { LogRecord } from \"../models/log-record\";\nimport type { DeliveryStats } from \"../models/stats\";\nimport {\n type GapReporter,\n type StorageAdapter,\n type StoragePersistence,\n storageLimits,\n} from \"../models/storage\";\nimport { clearEmergencyContext, drainEmergencyQueue } from \"../storage/emergency-queue\";\nimport { createStorage, storageName } from \"../storage/factory\";\nimport { ContextStorage } from \"../storage/context-storage\";\nimport { requestPersistence } from \"../storage/persistence\";\nimport { withDeadline } from \"../utils/deadline\";\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 { StatusTransport } 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 /** Memory store that this runtime keeps when the security context changes. */\n storage?: StorageAdapter;\n onStorage?: (storage: StorageAdapter) => void;\n /** Receives the state of the persistent-storage request. */\n onPersistence?: (state: StoragePersistence) => void;\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 /** Receives the records lost by the transport, the retry engine and the exit flush. */\n onLoss: LossReporter;\n /** The runtime's slot for the sampling rules from the ingest server. */\n remote: RemoteSlot;\n /** Sends the open metric interval's points before the exit flush drains the buffers. */\n beforeExit?: () => void;\n}\n\n/** Delivery stack for one sender runtime. */\nexport class Sender {\n /** True after retire(), so a late emergency import doesn't wake the retry engine. */\n private retired = false;\n /** Emergency queue import. retire() waits for it before reading storage. */\n private emergencyImport: Promise<void> = Promise.resolve();\n\n /**\n * @param storage Storage adapter for undelivered batches.\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 * @param transport The transport that the pipeline and the retry engine use.\n */\n private constructor(\n private readonly storage: ContextStorage,\n private readonly retry: RetryEngine,\n private readonly pipeline: LogPipeline,\n private readonly exitFlush: ExitFlush,\n private readonly diagnostics: Diagnostics,\n private readonly transport: StatusTransport,\n ) {}\n\n /**\n * Builds the delivery stack and starts the retry loop. The emergency queue import runs\n * after the start, so a slow IndexedDB open doesn't hold up the boot buffer.\n * @param deps Configuration, diagnostics and gap reporter.\n * @returns Promise that resolves to the started sender.\n */\n static async create(deps: SenderDeps): Promise<Sender> {\n const { config, diagnostics } = deps;\n\n const backing =\n deps.storage ??\n (await createStorage(\n config.storage,\n storageName(config.persistence.namespace),\n storageLimits(config.retention),\n diagnostics,\n deps.onGap,\n config.persistence.namespace,\n ));\n deps.onStorage?.(backing);\n\n // Ask only for a store that outlives the page.\n if (\n config.persistence.requestPersistent &&\n (backing.name === STORAGE_NAME_INDEXEDDB || backing.name === STORAGE_NAME_LOCAL)\n ) {\n deps.onPersistence?.(\"pending\");\n void requestPersistence(diagnostics).then(deps.onPersistence);\n }\n\n const storage = new ContextStorage(\n backing,\n config.securityContext,\n config.persistence.namespace,\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 clock offset from the last accepted response. The pipeline adds it to new records.\n let clockOffsetMs: number | undefined;\n const onClock = (offsetMs: number): void => {\n clockOffsetMs = offsetMs;\n };\n\n // The stack keeps one transport for its whole life, and the runtime refuses a later change.\n // The exit flush reads the last headers from the HTTP transport.\n const { onLoss } = deps;\n const worker =\n !config.transport && config.transportWorker\n ? await diagnostics.guardAsync(\n \"transport.http_error\",\n \"The transport worker module did not load. The library uses HTTP.\",\n async () =>\n (await import(\"../transport/worker-transport\")).createWorkerTransport(\n config,\n diagnostics,\n onSampling,\n onLoss,\n onClock,\n ),\n )\n : undefined;\n const http =\n config.transport !== undefined || worker !== undefined\n ? undefined\n : new HttpTransport(config, diagnostics, onSampling, onLoss, onClock);\n const transport: StatusTransport =\n worker?.transport ??\n http ??\n new CustomTransport(config, diagnostics, onSampling, onLoss, onClock);\n const retry = new RetryEngine(storage, transport, diagnostics, config, undefined, onLoss);\n const { batching } = config;\n const pipeline = new LogPipeline(\n transport,\n storage,\n retry,\n diagnostics,\n {\n logs: { flushIntervalMs: batching.logFlushIntervalMs, batchSize: batching.logBatchSize },\n metrics: {\n flushIntervalMs: batching.metricFlushIntervalMs,\n batchSize: batching.metricBatchSize,\n },\n // A span is the size of a log record, so the traces stream uses the log batching.\n traces: { flushIntervalMs: batching.logFlushIntervalMs, batchSize: batching.logBatchSize },\n },\n () => config.securityContext.id || undefined,\n config,\n onLoss,\n () => (config.metadata.clockOffset ? clockOffsetMs : undefined),\n );\n\n const exitFlush = new ExitFlush({\n config,\n diagnostics,\n drainForExit: () => pipeline.drainForExit(),\n flushAlive: () => pipeline.flushPending(),\n exitHeaders: () => (worker ? worker.exitHeaders() : http?.lastHeaders()),\n onLoss,\n beforeExit: deps.beforeExit,\n });\n\n // If one step fails, stop both. A retry loop with no owner would keep sending after the\n // 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 const sender = new Sender(storage, retry, pipeline, exitFlush, diagnostics, transport);\n sender.emergencyImport = sender.importEmergency();\n return sender;\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 in the stream buffers, then waits for every batch in flight.\n * @returns Promise that resolves once the pipeline has sent or stored every batch.\n */\n async flush(): Promise<void> {\n await this.pipeline.flushPending();\n }\n\n /**\n * Removes stored normal and emergency batches without sending them.\n * @param scope Part of storage to clear.\n * @param contextId Active delivery context id.\n * @returns Promise that resolves when removal completes.\n */\n async clearPersisted(scope: \"context\" | \"namespace\", contextId: string): Promise<void> {\n if (scope === \"namespace\") await this.storage.clearNamespace();\n else await this.storage.clear();\n clearEmergencyContext(\n contextId,\n this.diagnostics,\n this.storage.namespace,\n scope === \"namespace\",\n );\n }\n\n /**\n * Counts the batches held in storage.\n * @returns Promise that resolves 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 * Reads the delivery state of the pipeline and the transport.\n * @returns Waiting records, records in requests and the last accepted send.\n */\n stats(): Omit<DeliveryStats, \"stored\"> {\n return { ...this.pipeline.counts(), lastSendAt: this.transport.lastSendAt() };\n }\n\n /**\n * Sends pending records with a normal flush, then with the exit flush, then stops all\n * timers and listeners and closes storage. The normal flush keeps the headers, gzip and\n * the retry. The exit flush picks up the records the normal flush didn't confirm.\n * @returns Promise that resolves when storage closes.\n */\n async destroy(): Promise<void> {\n await this.diagnostics.guardAsync(\"pipeline.crashed\", \"The flush before shutdown failed.\", () =>\n this.flush(),\n );\n\n this.exitFlush.flush(\"shutdown\");\n this.exitFlush.uninstall();\n this.retry.stop();\n this.transport.stop();\n this.pipeline.destroy();\n\n await this.storage.close();\n }\n\n /**\n * Stops this sender before a new delivery identity takes effect. Does not run exit delivery.\n * @param policy Rule for the old records.\n * @param timeoutMs Maximum wait for a flush, in milliseconds.\n * @param contextId Identity of the old delivery context.\n * @returns The records that were in memory and the batches that were stored, after the\n * delivery attempt.\n */\n async retire(\n policy: \"discard\" | \"flush\" | \"retain\" | \"carry\",\n timeoutMs: number,\n contextId: string,\n ): Promise<{ buffered: LogRecord[]; stored: LogBatch[] }> {\n this.retired = true;\n this.exitFlush.uninstall();\n this.retry.stop();\n if (policy === \"flush\") {\n try {\n await withDeadline(Promise.all([this.flush(), this.retry.flush()]), timeoutMs);\n } catch (error) {\n // The remaining records follow the selected rule.\n this.diagnostics.report(\n \"transport.timeout\",\n \"The flush of the old security context did not complete before its time limit.\",\n undefined,\n error,\n );\n }\n }\n this.retry.stop();\n this.transport.stop();\n const drained = this.pipeline.drainForExit();\n const buffered = drained.flatMap((batch) => batch.records);\n this.pipeline.destroy();\n await this.emergencyImport;\n const stored = await this.storage.take(Number.MAX_SAFE_INTEGER);\n if (policy === \"retain\") {\n // Store the drained batches whole. One batch per record would fill retention.maxBatches.\n for (const batch of drained) {\n await this.storage.save({\n ...batch,\n routingContextId: contextId,\n persistenceNamespace: this.storage.namespace,\n });\n }\n }\n // \"carry\" keeps the stored batches until adopt() stores each one again under the new id.\n // If the tab closes during the carry, the rest are parked, not lost.\n const discard = policy === \"discard\" || policy === \"flush\";\n await this.storage.retire(discard);\n if (discard) {\n clearEmergencyContext(contextId, this.diagnostics, this.storage.namespace);\n }\n return { buffered, stored };\n }\n\n /**\n * Stores an earlier context's batches under this context, and the retry engine then sends\n * them. They don't go through the live buffer, because a large backlog would exceed its\n * budget.\n * @param batches The earlier context's stored batches.\n * @param contextId Identity of this delivery context.\n * @returns Promise that resolves when the batches are stored.\n */\n async adopt(batches: readonly LogBatch[], contextId: string): Promise<void> {\n for (const batch of batches) {\n // The same id replaces the old copy. Attempts against the old destination don't count here.\n await this.storage.save({\n ...batch,\n attempts: 0,\n routingContextId: contextId,\n persistenceNamespace: this.storage.namespace,\n });\n }\n\n if (batches.length > 0) {\n this.retry.nudge();\n }\n }\n\n /**\n * Moves the emergency queue's batches into storage, then wakes the retry engine.\n * The previous page load parked them during its unload.\n */\n private async importEmergency(): Promise<void> {\n const moved = await this.diagnostics.guardAsync(\n \"storage.degraded\",\n \"The emergency import failed.\",\n () =>\n drainEmergencyQueue(\n this.storage,\n this.diagnostics,\n (batch) => this.storage.accepts(batch),\n this.storage.namespace,\n ),\n );\n\n if (!this.retired && moved !== undefined && moved > 0) {\n this.retry.nudge();\n }\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;AAiBA,eAAsBqC,EAAmB,GAAuD;CAC9F,IAAMC,IAAW,WAA6B,WAAW;CAYzD,OAVI,OAAOA,GAAS,WAAY,aAUzB,MANeC,EAAY,WAChC,uBACA,kEACMD,EAAQ,QAAQ,CACxB,MAEmB,KAAO,YAAY,WAT7B;AAUX;;ACFA,SAASE,EAAY,GAAmC;CACtD,IAAMC,IAAW,OAAOC,KAAS,WAAW,KAAK,MAAMA,CAAI,IAAI;CAE/D,OAAO,OAAO,MAAMD,CAAQ,IACx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,MAAM,GAA8B,GAAkC;EAC1E,KAAK,IAAM3H,KAASsE,GAElB,MAAM,KAAK,QAAQ,KAAK;GACtB,GAAGtE;GACH,UAAU;GACV,kBAAkB2H;GAClB,sBAAsB,KAAK,QAAQ;EACrC,CAAC;EAGH,AAAIrD,EAAQ,SAAS,KACnB,KAAK,MAAM,MAAM;CAErB;CAMA,MAAc,kBAAiC;EAC7C,IAAM2D,IAAQ,MAAM,KAAK,YAAY,WACnC,oBACA,sCAEEC,EACE,KAAK,SACL,KAAK,cACJ,MAAU,KAAK,QAAQ,QAAQlI,CAAK,GACrC,KAAK,QAAQ,SACf,CACJ;EAEA,AAAI,CAAC,KAAK,WAAWiI,MAAU,KAAA,KAAaA,IAAQ,KAClD,KAAK,MAAM,MAAM;CAErB;AACF"}
@@ -0,0 +1,2 @@
1
+ const e=require("./constants-DakMxVB2.cjs"),t=require("./storage-BA9RqRO-.cjs"),n=require("./emergency-queue-HBpL5r3V.cjs"),r=require("./factory-DLFDjdLv.cjs"),i=require("./context-storage-BjzeBSxH.cjs"),a=require("./deadline-CUGbto-y.cjs"),o=require("./library-request-Da-CHKzT.cjs"),s=require("./openfin-DtH2f7zX.cjs"),c=require("./sanitize-ChLn97Ch.cjs"),l=require("./library-console-BFWEuQsl.cjs"),u=require("./select-CTk-K5mG.cjs"),d=require("./platform-12uR7kBQ.cjs"),f=require("./unref-CU9Nyz_9.cjs"),p=require("./compression-lD9abCcO.cjs"),m=require("./batch-D5LlU4Q9.cjs"),h=require("./log-record-D7bA1RPb.cjs"),g=require("./identity-BlvlgjrU.cjs"),_=require("./sampling-Dd0wllyq.cjs"),v=require("./remote-rules-CJD3ToVk.cjs");async function y(e){let t=globalThis.navigator?.storage;return typeof t?.persist==`function`?await e.guardAsync(`storage.unavailable`,`The browser rejected the request for persistent storage.`,()=>t.persist())===!0?`granted`:`denied`:`unsupported`}function b(e){let t=typeof e==`string`?Date.parse(e):NaN;return Number.isNaN(t)?void 0:Math.round(t+500-Date.now())}var x=class{config;diagnostics;onSampling;onLoss;onClock;cancellation=new AbortController;stop(){this.cancellation.abort()}assertContext(e){if(this.cancellation.signal.aborted||this.config.securityContext.isolation&&this.config.securityContext.id&&e.routingContextId!==this.config.securityContext.id)throw this.diagnostics.count(`security.context_mismatch`),new u.s(`permanent`,`The delivery context is inactive or does not match the batch.`)}async untilCancelled(e){if(this.cancellation.signal.aborted)throw new u.s(`permanent`,`The delivery context retired.`);let t,n=new Promise((e,n)=>{t=()=>{n(new u.s(`permanent`,`The delivery context retired.`))},this.cancellation.signal.addEventListener(`abort`,t,{once:!0})});try{return await Promise.race([e,n])}finally{this.cancellation.signal.removeEventListener(`abort`,t)}}throttledUntil={logs:0,metrics:0,traces:0};acceptedAt=null;constructor(e,t,n=()=>void 0,r=()=>void 0,i=()=>void 0){this.config=e,this.diagnostics=t,this.onSampling=n,this.onLoss=r,this.onClock=i}throttledForMs(e){return Math.max(0,this.throttledUntil[u.t(e,this.config)]-Date.now())}lastSendAt(){return this.acceptedAt}serialize(e){let t=u.r(this.config,e,this.diagnostics,`The serializer threw an error. The library dropped the batch.`);return t||this.onLoss(`unserializable`,e.records,[e.id]),t}accept(e,t,n){this.throttledUntil[e]=0,this.acceptedAt=Date.now(),this.config.sampling.remote&&t!=null&&this.onSampling(t);let r=b(n);r!==void 0&&this.onClock(r)}reject(e,t,n,r){let i=String(e);if(e===401||e===403){let t=r.advice===void 0?``:` ${r.advice}`;return this.diagnostics.report(`transport.rejected_credentials`,`The server returned ${i}.${t}`,{status:e,endpoint:u.n(n,this.config)}),new u.s(`permanent`,`The server rejected the batch with ${i}.`,e)}if(e===413)return new u.s(`too_large`,`The payload is too large.`,e,void 0,r.maxBytes);if(e===429||e===503){let t=e===429,i=r.retryAfterMs===void 0?void 0:Math.min(r.retryAfterMs,this.config.delivery.retryMaxDelayMs);return this.throttledUntil[n]=Date.now()+(i??this.config.delivery.retryBaseDelayMs),t&&this.diagnostics.report(`transport.throttled`,`The server throttles the requests.`,{retryAfterMs:i}),new u.s(`throttled`,t?`The server throttles the requests.`:`The service is not available.`,e,i)}return e===408||e>=500?new u.s(`transient`,`The server returned the error ${i}.`,e):(this.diagnostics.report(`transport.dropped_permanent`,`The server rejected the batch with ${i}. The library dropped it.`,{batchId:t,status:e}),new u.s(`permanent`,`The server rejected the batch with ${i}.`,e))}};function S(e,t,n){return{kind:n,body:t.body,contentType:t.contentType,batchId:e.id,attempt:e.attempts,records:e.records,routingContextId:e.routingContextId}}function C(e){if(typeof e!=`object`||!e)return!1;let t=Reflect.get(e,`status`);return typeof t==`number`&&Number.isInteger(t)&&t>=100&&t<=599}function w(e){return typeof e==`number`&&Number.isFinite(e)?Math.max(0,e):void 0}var T=class extends x{async send(e){this.assertContext(e);let{transport:t}=this.config;if(!t||e.records.length===0)return;let n=this.serialize(e);if(!n)return;let r=u.t(e,this.config),i=S(e,n,r);i.signal=this.cancellation.signal;let s;try{s=await a.n(this.untilCancelled(o.i(()=>o.r(()=>l.n(()=>t(i))))),this.config.delivery.requestTimeoutMs)}catch(e){let t=e instanceof a.t?e:void 0,n=t?`timeout`:`transient`,r=t?.message??`The custom transport failed.`;throw new u.s(n,r,void 0,void 0,void 0,e)}if(this.assertContext(e),!C(s))throw this.diagnostics.report(`transport.http_error`,`The custom transport returned no valid status. The library sends the batch again later.`,{batchId:e.id}),new u.s(`transient`,`The custom transport returned no valid status.`);let{status:c}=s;if(c>=200&&c<300)this.accept(r,s.sampling,s.date);else throw this.reject(c,e.id,r,{retryAfterMs:w(s.retryAfterMs),maxBytes:w(s.maxBytes)})}},E=class{deps;installed=!1;keepaliveBytes=0;onVisibility=()=>{document.visibilityState===`hidden`&&this.flush(`hidden`)};onPageHide=()=>{this.flush(`pagehide`)};onFreeze=()=>{this.flush(`freeze`)};onOpenFinClose=()=>{this.flush(`openfin-close`)};constructor(e){this.deps=e}install(){if(this.installed||typeof addEventListener>`u`)return;this.installed=!0,typeof document<`u`&&(document.addEventListener(`visibilitychange`,this.onVisibility),document.addEventListener(`freeze`,this.onFreeze)),addEventListener(`pagehide`,this.onPageHide);let e=s.t()?.me;this.deps.diagnostics.guard(`openfin.unavailable`,`The library could not subscribe to close-requested.`,()=>{e?.on?.(`close-requested`,this.onOpenFinClose)})}uninstall(){if(!this.installed)return;this.installed=!1,typeof document<`u`&&(document.removeEventListener(`visibilitychange`,this.onVisibility),document.removeEventListener(`freeze`,this.onFreeze)),removeEventListener(`pagehide`,this.onPageHide);let e=s.t()?.me;this.deps.diagnostics.guard(`openfin.unavailable`,`The library could not unsubscribe from close-requested.`,()=>{e?.removeListener?.(`close-requested`,this.onOpenFinClose)})}flush(e){let{config:t,diagnostics:n}=this.deps;if(n.guard(`pipeline.crashed`,`The metric points before the exit flush failed.`,()=>{this.deps.beforeExit?.()}),e===`hidden`){this.flushAlive();return}if(t.transport){this.flushCustom(e,t.transportOnExit);return}let r=this.endpointUrl();if(r!==null){this.keepaliveBytes=0;for(let i of this.deps.drainForExit()){let a=u.t(i,t),o=a===`logs`?r.href:u.n(a,t);o?this.flushBatch(i,e,new URL(o)):n.count(`record.dropped_no_destination`)}}}flushBatch(t,n,r){let{config:i}=this.deps;if(t.records.length===0)return;let a=this.serialize(t,n);if(!a)return;if(c.t(a.body)>6e4){this.park(t);return}r.searchParams.set(e.Zt,t.id),r.searchParams.set(e.Qt,n);let o=r.toString(),s=this.deps.exitHeaders();if(s){this.keepaliveFetch(o,t,a.body,n,()=>{let n=new Headers(s);return n.set(e.lt,a.contentType),n.set(e.st,t.id),n});return}if(i.headers){this.park(t);return}let l=this.beacon(o,a.body);l!==`sent`&&(l===`refused`?this.park(t):this.keepaliveFetch(o,t,a.body,n,()=>new Headers({[e.lt]:e.B})))}flushAlive(){let{diagnostics:e}=this.deps,t=`The flush of the hidden document failed.`;e.guard(`pipeline.crashed`,t,()=>{Promise.resolve(this.deps.flushAlive()).catch(n=>{e.report(`pipeline.crashed`,t,void 0,n)})})}flushCustom(e,t){let{config:n,diagnostics:r}=this.deps;for(let i of this.deps.drainForExit()){let a=this.serialize(i,e);if(!a)continue;let s=S(i,a,u.t(i,n));(t===void 0||r.guard(`transport.http_error`,`The transportOnExit hook threw an error.`,()=>o.r(()=>t(s)))!==!0)&&this.park(i)}}park(e){let{config:t,diagnostics:r,onLoss:i}=this.deps;t.storage===`memory`||t.storage===`none`?i?.(`not_stored`,e.records,[e.id]):n.saveToEmergencyQueue(e,r,i)}serialize(e,t){let n=u.r(this.deps.config,e,this.deps.diagnostics,`The ${t} exit flush could not serialize its batch.`);return n||this.deps.onLoss?.(`unserializable`,e.records,[e.id]),n}endpointUrl(){let{endpoint:e}=this.deps.config;return e?this.deps.diagnostics.guard(`config.invalid`,`The exit flush cannot use the endpoint ${e}.`,()=>new URL(e))??null:null}beacon(e,t){return this.deps.diagnostics.guard(`transport.http_error`,`The sendBeacon call failed.`,()=>{let n=globalThis.navigator;return n?.sendBeacon?n.sendBeacon(e,new Blob([t],{type:`text/plain;charset=UTF-8`}))?`sent`:`refused`:`unavailable`})??`unavailable`}keepaliveFetch(e,t,n,r,i){let{config:a,diagnostics:o}=this.deps,s=()=>{this.park(t)},l=c.t(n);this.keepaliveBytes+l>6e4?s():(this.keepaliveBytes+=l,o.guard(`transport.http_error`,`The keepalive fetch failed.`,()=>(fetch(e,{method:`POST`,body:n,headers:i(),credentials:a.credentials,keepalive:!0}).catch(e=>{o.report(`transport.http_error`,`The exit flush failed.`,{reason:r},e),s()}),!0))!==!0&&s())}},D=new WeakMap;function O(e,t){let{headers:n}=t;if(!n)return;if(typeof n!=`function`)return n;let r=D.get(e);return r?.source===n&&r.endpoint===t.endpoint&&r.metricsEndpoint===t.metricsEndpoint&&r.tracesEndpoint===t.tracesEndpoint?r.headers:void 0}async function k(e,t,n){let{headers:r}=t;if(!r)return{};if(typeof r!=`function`)return r;let{endpoint:i,metricsEndpoint:a,tracesEndpoint:o}=t,s=await n.guardAsync(`transport.http_error`,`The headers() function threw an error.`,()=>Promise.resolve(r()));return s&&D.set(e,{source:r,endpoint:i,metricsEndpoint:a,tracesEndpoint:o,headers:s}),s??{}}function A(e){D.delete(e)}var j=`In a cross-origin iframe, the session cookie is a third-party cookie. The browser often blocks it. Forward the records to the platform document. As an alternative, issue the cookie with the Partitioned attribute.`,M=class extends x{async send(e,t){this.assertContext(e);let{config:n}=this,r=u.t(e,n),i=u.n(r,n);i?e.records.length!==0&&await this.post(e,r,i,t):this.diagnostics.count(`record.dropped_no_destination`)}lastHeaders(){return O(this,this.config)}async post(t,n,r,i){let a=this.serialize(t);if(!a)return;let o=await this.attempt(t,r,a,i);if(this.assertContext(t),this.rejectsCredentials(o.status)&&typeof this.config.headers==`function`&&(A(this),o=await this.attempt(t,r,a,i),this.assertContext(t)),o.ok){let{headers:t}=o;this.accept(n,t.get(e.ft),t.get(e.ut));return}let s=o.status,c=u.c(o.headers.get(e.dt)),l=s===413?await this.readMaxBytes(o):void 0;throw this.reject(s,t.id,n,{retryAfterMs:c,maxBytes:l,advice:j})}rejectsCredentials(e){return e===401||e===403}async attempt(t,n,r,i){let a=Date.now()+this.config.delivery.requestTimeoutMs,o=new Headers(await this.before(this.resolveHeaders(),a,n));o.set(e.lt,r.contentType),o.set(e.st,t.id),o.set(e.ot,String(t.attempts));let s=await this.before(this.encodeBody(r.body),a,n);this.assertContext(t),typeof s!=`string`&&o.set(e.ct,e.tt);let c=this.keepalive(s);return c&&i?.(),this.dispatch(n,o,s,a,c)}async before(e,t,n){try{return await a.n(this.untilCancelled(e),Math.max(0,t-Date.now()))}catch{throw this.cancellation.signal.aborted?new u.s(`permanent`,`The delivery context retired.`):this.timeout(n)}}timeout(e){let t=`The request took longer than ${String(this.config.delivery.requestTimeoutMs)} ms.`;return this.diagnostics.report(`transport.timeout`,t,{endpoint:e}),new u.s(`timeout`,t)}async encodeBody(e){let{config:t}=this;return t.compression!==`gzip`||c.t(e)<1024?e:await this.diagnostics.guardAsync(`transport.http_error`,`The library could not compress the payload.`,()=>p.t(e))??e}async dispatch(e,t,n,r,i){let{config:a}=this,s=new AbortController,c=()=>{s.abort()};this.cancellation.signal.addEventListener(`abort`,c,{once:!0}),this.cancellation.signal.aborted&&s.abort();let l=setTimeout(()=>{s.abort()},Math.max(0,r-Date.now()));f.t(l);try{return await o.r(()=>fetch(e,{method:`POST`,headers:t,body:n,credentials:a.credentials,signal:s.signal,cache:`no-store`,keepalive:i,priority:i?`auto`:a.delivery.priority}))}catch{throw this.cancellation.signal.aborted?new u.s(`permanent`,`The delivery context retired.`):s.signal.aborted?this.timeout(e):new u.s(d.r()?`transient`:`offline`,`A network error occurred.`)}finally{this.cancellation.signal.removeEventListener(`abort`,c),clearTimeout(l)}}keepalive(e){let t=globalThis.document?.visibilityState===`hidden`,n=typeof e==`string`?c.t(e):e.byteLength;return t&&n<=6e4}async readMaxBytes(e){return this.diagnostics.guardAsync(`transport.http_error`,`The library could not read the body of the 413 response.`,async()=>{let t=JSON.parse(await e.text());return typeof t.maxBytes==`number`?t.maxBytes:void 0})}async resolveHeaders(){return k(this,this.config,this.diagnostics)}},N=class{storage;transport;diagnostics;config;batchesPerDrain;onLoss;timer=null;attempt=0;draining=!1;stopped=!1;maxAttempts;onOnline=()=>{this.attempt=0,this.schedule(0)};constructor(e,n,r,i,a,o=()=>void 0){this.storage=e,this.transport=n,this.diagnostics=r,this.config=i,this.batchesPerDrain=a,this.onLoss=o,this.maxAttempts=t.storageLimits(i.retention).maxAttempts}start(){this.stopped=!1,typeof addEventListener<`u`&&addEventListener(`online`,this.onOnline),this.schedule(this.config.delivery.retryIdleDelayMs)}nudge(){this.draining||this.schedule(this.config.delivery.retryBaseDelayMs)}async storeFailed(e,t){let n=this.toStorable(e,t);for(let e of n)await this.bounded(this.storage.save(e));n.length>0&&this.nudge()}stop(){this.stopped=!0,typeof removeEventListener<`u`&&removeEventListener(`online`,this.onOnline),this.clearTimer()}async flush(){this.stopped=!1;try{await this.drain()}finally{this.stop()}}schedule(e){if(this.stopped)return;this.clearTimer();let t=setTimeout(()=>{this.drain()},e);this.timer=t,f.t(t)}bounded(t){return a.n(t,e.Fn)}clearTimer(){this.timer!==null&&(clearTimeout(this.timer),this.timer=null)}backoffMs(){let e=Math.min(this.config.delivery.retryBaseDelayMs*2**this.attempt,this.config.delivery.retryMaxDelayMs);return Math.random()*e}async drain(){if(!this.draining){this.draining=!0;try{let t=n.t(e.Y,this.config.persistence.namespace);await n.n(t,this.diagnostics,()=>this.drainLocked())!==!0&&this.schedule(this.config.delivery.retryIdleDelayMs)}finally{this.draining=!1}}}async drainLocked(){try{if(!d.r())return this.schedule(this.config.delivery.retryIdleDelayMs),!0;let e=await this.bounded(this.storage.take(this.batchesPerDrain??this.config.delivery.batchesPerDrain));if(e.length===0)return this.schedule(this.config.delivery.retryIdleDelayMs),!0;let t=new Set,n=0;for(let r of e){if(this.stopped)return!0;let e=u.t(r,this.config);if(t.has(e))continue;let i=await this.deliver(r);if(i===`stop`)return!0;i!==`next`&&(t.add(e),n=Math.max(n,i))}return t.size>0?this.schedule(n):this.schedule(e.length===(this.batchesPerDrain??this.config.delivery.batchesPerDrain)?0:this.config.delivery.retryIdleDelayMs),!0}catch(e){return this.diagnostics.report(`storage.degraded`,`The drain loop threw an error.`,void 0,e),this.attempt++,this.schedule(this.backoffMs()),!0}}async deliver(e){if(e.attempts>=this.maxAttempts)return this.diagnostics.report(`storage.dead_lettered`,`The library dropped a batch after ${e.attempts.toString()} attempts.`,{batchId:e.id,records:e.records.length}),this.onLoss(`max_attempts`,e.records,[e.id]),await this.bounded(this.storage.remove(e.id)),`next`;try{return await this.transport.send(e),await this.bounded(this.storage.remove(e.id)),this.attempt=0,`next`}catch(t){if(this.stopped)return`stop`;let n=t instanceof u.s?t:void 0;return n?.kind===`permanent`||n?.kind===`too_large`?(await this.replaceStored(e,t),`next`):n?.kind===`offline`?(this.schedule(this.config.delivery.retryIdleDelayMs),`stop`):n?.kind===`throttled`?(this.attempt++,n.retryAfterMs??this.backoffMs()):(await this.bounded(this.storage.bumpAttempts(e.id,e.attempts+1)),this.attempt++,n?.retryAfterMs??this.backoffMs())}}async replaceStored(e,t){let n=this.toStorable(e,t);await this.bounded(this.storage.remove(e.id));for(let e of n)await this.bounded(this.storage.save(e))}toStorable(e,t){let n=t instanceof u.s?t:void 0;if(n?.kind===`permanent`)return this.onLoss(`rejected`,e.records,[e.id]),[];if(n?.kind!==`too_large`)return[e];let r=m.a(e,this.diagnostics);return r?(this.diagnostics.report(`transport.batch_split`,`The server refused the batch because it is too large.`,{from:e.records.length,to:r[0].records.length,serverMaxBytes:n.maxBytes}),r):(this.diagnostics.report(`transport.dropped_permanent`,`One record is larger than the server limit. The library dropped it.`,{batchId:e.id,bodies:e.records.map(e=>e.body)}),this.onLoss(`rejected`,e.records,[e.id]),[])}},P=[`metrics`,`logs`,`traces`];function F(t){let n=t.attributes[e.g];return n===`metric`?`metrics`:n===`span`?`traces`:`logs`}var I=class{options;onFlush;pending=[];timer=null;constructor(e,t){this.options=e,this.onFlush=t}add(e){this.pending.push(e),this.pending.length>=this.options.batchSize?this.onFlush(this):this.arm()}take(){this.clearTimer();let e=this.pending;return this.pending=[],e}get size(){return this.pending.length}stop(){this.clearTimer()}arm(){if(this.timer!==null)return;let e=setTimeout(()=>{this.timer=null,this.onFlush(this)},this.options.flushIntervalMs);this.timer=e,f.t(e)}clearTimer(){this.timer!==null&&(clearTimeout(this.timer),this.timer=null)}},L=class{transport;storage;retry;diagnostics;routingContextId;policy;onLoss;clockOffset;streams;unconfirmed=new Map;queue=[];open=new Set;ceiling=new _.t;inFlight=0;pumpScheduled=!1;stopped=!1;held=new Map;heldBytes=0;persisting=!1;release(e){for(let t of e)this.heldBytes-=this.held.get(t)??0,this.held.delete(t)}evict(){let e=this.queue.shift();if(e)return this.open.delete(e),this.unconfirmed.delete(e.batch.id),this.release(e.batch.records),e.resolve(),this.onLoss(`buffer_full`,e.batch.records,[e.batch.id]),!0;for(let e of Object.values(this.streams)){let t=e.take();if(t.length)return this.release(t),this.onLoss(`buffer_full`,t),!0}return!1}admit(e){if(!this.policy)return!0;let{maxPendingRecords:t,maxPendingBytes:n,overflow:r}=this.policy.buffering,i;try{i=c.t(JSON.stringify(e))}catch{return this.onLoss(`unserializable`,[e]),!1}let a=()=>!!(t&&this.held.size>=t||n&&this.heldBytes+i>n),o=!n||i<=n;for(;o&&a()&&r===`drop-oldest`&&this.evict(););if(a()){if(r===`persist`&&!this.persisting){this.persisting=!0;let t=this.toBatch([e]);this.diagnostics.guardAsync(`storage.degraded`,`Could not persist an overflow record.`,async()=>{try{await this.storage.save(t),this.retry.nudge()}finally{this.persisting=!1}})}else this.onLoss(`buffer_full`,[e]);return!1}return this.held.set(e,i),this.heldBytes+=i,!0}constructor(e,t,n,r,i,a,o,s=()=>void 0,c=()=>void 0){this.transport=e,this.storage=t,this.retry=n,this.diagnostics=r,this.routingContextId=a,this.policy=o,this.onLoss=s,this.clockOffset=c;let l=e=>{this.claim(e)};this.streams={logs:new I(i.logs,l),metrics:new I(i.metrics,l),traces:new I(i.traces,l)}}push(e){if(this.stopped)return;e.observedTimeUnixNano=h.r();let t={...e};this.admit(t)&&this.route(t)}drainForExit(){let e=[...this.unconfirmed.values()].flatMap(e=>e.records);return this.unconfirmed.clear(),this.held.clear(),this.heldBytes=0,P.map(t=>this.toBatch([...e.filter(e=>F(e)===t),...this.streams[t].take()])).filter(e=>e!==null)}async flushPending(){if(!this.stopped)for(let e of P)this.claim(this.streams[e]);await Promise.all([...this.open].map(e=>e.done))}counts(){let e=e=>{let t=0;for(let n of e)t+=n.batch.records.length;return t},t=e(this.queue);return{pending:P.reduce((e,t)=>e+this.streams[t].size,0)+t,inFlight:e(this.open)-t}}destroy(){this.stopped=!0,this.held.clear(),this.heldBytes=0;for(let e of P)this.streams[e].stop();this.queue.length=0;for(let e of this.open)e.resolve();this.open.clear()}toBatch(e){return e.length===0?null:{id:g.i(this.diagnostics),records:e,createdAt:Date.now(),attempts:0,routingContextId:this.routingContextId?.(),persistenceNamespace:this.policy?.persistence.namespace}}route(t){try{let n=F(t),r=this.streams[n];if(n===`logs`&&!this.ceiling.allow(t,this.policy?.capturePolicy.errorCeiling,this.policy?.capturePolicy.windowMs,this.policy?.sampling.alwaysSampleFrom)){this.release([t]),this.diagnostics.count(`record.dropped_by_ceiling`);return}let i=this.clockOffset();i!==void 0&&n!==`metrics`&&(t.attributes={...t.attributes,[e.l]:i}),r.add(t)}catch(e){this.diagnostics.report(`pipeline.crashed`,`The pipeline dropped a record before it reached a stream.`,void 0,e)}}claim(e){this.enqueue(this.toBatch(e.take()))}enqueue(e){if(!e)return;let t,n={batch:e,done:new Promise(e=>{t=e}),resolve:t};this.unconfirmed.set(e.id,e),this.open.add(n),this.queue.push(n),this.pumpScheduled||(this.pumpScheduled=!0,queueMicrotask(()=>{this.pumpScheduled=!1,this.pump()}))}pump(){if(!this.stopped)for(;this.inFlight<(this.policy?.delivery.maxConcurrentRequests??2);){let e=this.queue.shift();if(!e)return;this.inFlight++,this.run(e)}}async run(e){let{batch:t}=e;try{await this.dispatch(t)}catch(e){this.diagnostics.report(`pipeline.crashed`,`A dispatch rejected its promise. This must not occur.`,{batchId:t.id},e)}finally{this.release(t.records),this.inFlight--,this.open.delete(e),e.resolve(),this.pump()}}async dispatch(e){try{let t=this.transport.throttledForMs(e);if(t>0){await this.store(e),this.diagnostics.report(`transport.throttled`,`The server throttles requests. The pipeline stored the batch and did not send it.`,{batchId:e.id,records:e.records.length,throttledMs:t});return}try{await this.transport.send(e,()=>{this.unconfirmed.delete(e.id)})}catch(t){if(this.stopped)return;await this.storeFailed({...e,attempts:e.attempts+1},t),this.diagnostics.report(`transport.http_error`,`The send failed. The pipeline stored the batch for a retry.`,{batchId:e.id,records:e.records.length},t)}}finally{this.unconfirmed.delete(e.id)}}async storeFailed(e,t){await this.diagnostics.guardAsync(`storage.degraded`,`The library could not store an undelivered batch.`,async()=>{await this.retry.storeFailed(e,t)})}async store(t){await this.diagnostics.guardAsync(`storage.degraded`,`The library could not store an undelivered batch.`,async()=>{await a.n(this.storage.save(t),e.Fn),this.retry.nudge()})}},R=class e{storage;retry;pipeline;exitFlush;diagnostics;transport;retired=!1;emergencyImport=Promise.resolve();constructor(e,t,n,r,i,a){this.storage=e,this.retry=t,this.pipeline=n,this.exitFlush=r,this.diagnostics=i,this.transport=a}static async create(n){let{config:a,diagnostics:o}=n,s=n.storage??await r.createStorage(a.storage,r.storageName(a.persistence.namespace),t.storageLimits(a.retention),o,n.onGap,a.persistence.namespace);n.onStorage?.(s),a.persistence.requestPersistent&&(s.name===`indexeddb`||s.name===`localstorage`)&&(n.onPersistence?.(`pending`),y(o).then(n.onPersistence));let c=new i.ContextStorage(s,a.securityContext,a.persistence.namespace),l=e=>{let t=v.n(e,o);t&&v.t(n.remote,a,t)},u,d=e=>{u=e},{onLoss:f}=n,p=!a.transport&&a.transportWorker?await o.guardAsync(`transport.http_error`,`The transport worker module did not load. The library uses HTTP.`,async()=>(await Promise.resolve().then(()=>require("./worker-transport-B-GF4Aqn.cjs"))).createWorkerTransport(a,o,l,f,d)):void 0,m=a.transport!==void 0||p!==void 0?void 0:new M(a,o,l,f,d),h=p?.transport??m??new T(a,o,l,f,d),g=new N(c,h,o,a,void 0,f),{batching:_}=a,b=new L(h,c,g,o,{logs:{flushIntervalMs:_.logFlushIntervalMs,batchSize:_.logBatchSize},metrics:{flushIntervalMs:_.metricFlushIntervalMs,batchSize:_.metricBatchSize},traces:{flushIntervalMs:_.logFlushIntervalMs,batchSize:_.logBatchSize}},()=>a.securityContext.id||void 0,a,f,()=>a.metadata.clockOffset?u:void 0),x=new E({config:a,diagnostics:o,drainForExit:()=>b.drainForExit(),flushAlive:()=>b.flushPending(),exitHeaders:()=>p?p.exitHeaders():m?.lastHeaders(),onLoss:f,beforeExit:n.beforeExit}),S=!1;try{x.install(),g.start(),S=!0}finally{S||(x.uninstall(),g.stop())}let C=new e(c,g,b,x,o,h);return C.emergencyImport=C.importEmergency(),C}push(e){this.pipeline.push(e)}async flush(){await this.pipeline.flushPending()}async clearPersisted(e,t){e===`namespace`?await this.storage.clearNamespace():await this.storage.clear(),n.clearEmergencyContext(t,this.diagnostics,this.storage.namespace,e===`namespace`)}async queueDepth(){return await this.diagnostics.guardAsync(`storage.degraded`,`The library could not count the batches in storage.`,()=>this.storage.count())??0}stats(){return{...this.pipeline.counts(),lastSendAt:this.transport.lastSendAt()}}async destroy(){await this.diagnostics.guardAsync(`pipeline.crashed`,`The flush before shutdown failed.`,()=>this.flush()),this.exitFlush.flush(`shutdown`),this.exitFlush.uninstall(),this.retry.stop(),this.transport.stop(),this.pipeline.destroy(),await this.storage.close()}async retire(e,t,r){if(this.retired=!0,this.exitFlush.uninstall(),this.retry.stop(),e===`flush`)try{await a.n(Promise.all([this.flush(),this.retry.flush()]),t)}catch(e){this.diagnostics.report(`transport.timeout`,`The flush of the old security context did not complete before its time limit.`,void 0,e)}this.retry.stop(),this.transport.stop();let i=this.pipeline.drainForExit(),o=i.flatMap(e=>e.records);this.pipeline.destroy(),await this.emergencyImport;let s=await this.storage.take(2**53-1);if(e===`retain`)for(let e of i)await this.storage.save({...e,routingContextId:r,persistenceNamespace:this.storage.namespace});let c=e===`discard`||e===`flush`;return await this.storage.retire(c),c&&n.clearEmergencyContext(r,this.diagnostics,this.storage.namespace),{buffered:o,stored:s}}async adopt(e,t){for(let n of e)await this.storage.save({...n,attempts:0,routingContextId:t,persistenceNamespace:this.storage.namespace});e.length>0&&this.retry.nudge()}async importEmergency(){let e=await this.diagnostics.guardAsync(`storage.degraded`,`The emergency import failed.`,()=>n.drainEmergencyQueue(this.storage,this.diagnostics,e=>this.storage.accepts(e),this.storage.namespace));!this.retired&&e!==void 0&&e>0&&this.retry.nudge()}};exports.Sender=R,exports.a=x,exports.i=k,exports.n=M,exports.r=A,exports.t=j;
2
+ //# sourceMappingURL=sender-Bfpv9tad.cjs.map