@utk09/ui-observability 0.11.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 (383) hide show
  1. package/CHANGELOG.md +61 -0
  2. package/README.md +273 -102
  3. package/bin/uiobs.mjs +1 -1
  4. package/dist/{batch-CL9uWYY3.js → batch-BjQUwjA6.js} +4 -4
  5. package/dist/batch-BjQUwjA6.js.map +1 -0
  6. package/dist/{batch-C8OcWR2L.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-BZ0GldpT.js → bus-ecxUNTja.js} +91 -91
  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-BPZCuSLc.cjs → console-CLz_PvFn.cjs} +2 -2
  39. package/dist/console-CLz_PvFn.cjs.map +1 -0
  40. package/dist/{console-BeCF7n59.js → console-cwgHKXvM.js} +4 -4
  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-BzkoHzkQ.js.map +1 -1
  49. package/dist/core/breadcrumbs.d.ts +16 -15
  50. package/dist/core/config.d.ts +3 -3
  51. package/dist/core/context.d.ts +7 -7
  52. package/dist/core/debug-buffer.d.ts +10 -10
  53. package/dist/core/debug-bundle.d.ts +3 -3
  54. package/dist/core/deferred.d.ts +2 -2
  55. package/dist/core/diagnostics.d.ts +24 -21
  56. package/dist/core/drops.d.ts +7 -7
  57. package/dist/core/hold-buffer.d.ts +1 -1
  58. package/dist/core/journey.d.ts +22 -23
  59. package/dist/core/logger.d.ts +22 -21
  60. package/dist/core/measure.d.ts +7 -7
  61. package/dist/core/meter.d.ts +25 -21
  62. package/dist/core/pipeline.d.ts +42 -41
  63. package/dist/core/profile-buckets.d.ts +31 -0
  64. package/dist/core/profiler.d.ts +218 -0
  65. package/dist/core/record.d.ts +23 -23
  66. package/dist/core/remote-rules.d.ts +4 -4
  67. package/dist/core/remote-sampling.d.ts +21 -20
  68. package/dist/core/runtime.d.ts +206 -137
  69. package/dist/core/sampling.d.ts +18 -18
  70. package/dist/core/sender.d.ts +22 -20
  71. package/dist/core/spans.d.ts +5 -5
  72. package/dist/{deadline-BOjOxNHj.js → deadline-C4ccAuk5.js} +3 -6
  73. package/dist/deadline-C4ccAuk5.js.map +1 -0
  74. package/dist/deadline-CUGbto-y.cjs +2 -0
  75. package/dist/deadline-CUGbto-y.cjs.map +1 -0
  76. package/dist/{debug-bundle-C7UkHZ-q.js → debug-bundle-BOdYmCeV.js} +10 -3
  77. package/dist/debug-bundle-BOdYmCeV.js.map +1 -0
  78. package/dist/debug-bundle-Ex4L_LSP.cjs +2 -0
  79. package/dist/debug-bundle-Ex4L_LSP.cjs.map +1 -0
  80. package/dist/doctor.cjs +1 -1
  81. package/dist/doctor.cjs.map +1 -1
  82. package/dist/doctor.d.ts +16 -6
  83. package/dist/doctor.js +147 -52
  84. package/dist/doctor.js.map +1 -1
  85. package/dist/{emergency-queue-Zy6lNafo.js → emergency-queue-B9WZxanZ.js} +4 -4
  86. package/dist/emergency-queue-B9WZxanZ.js.map +1 -0
  87. package/dist/{emergency-queue-CNTRui5t.cjs → emergency-queue-HBpL5r3V.cjs} +2 -2
  88. package/dist/emergency-queue-HBpL5r3V.cjs.map +1 -0
  89. package/dist/error-like-B11pB4aL.js.map +1 -1
  90. package/dist/error-like-gGRx2s36.cjs.map +1 -1
  91. package/dist/{errors-Dh7kef0i.js → errors-D6bwgJtO.js} +3 -3
  92. package/dist/errors-D6bwgJtO.js.map +1 -0
  93. package/dist/{errors-tfEr48bS.cjs → errors-DCOCRdSi.cjs} +2 -2
  94. package/dist/errors-DCOCRdSi.cjs.map +1 -0
  95. package/dist/{factory-CJXVYp0R.cjs → factory-DLFDjdLv.cjs} +2 -2
  96. package/dist/factory-DLFDjdLv.cjs.map +1 -0
  97. package/dist/{factory-BonqI3NL.js → factory-e9Qo3K0z.js} +13 -13
  98. package/dist/factory-e9Qo3K0z.js.map +1 -0
  99. package/dist/fixed-window-CvESpFYV.cjs.map +1 -1
  100. package/dist/fixed-window-Dq3MLUUv.js.map +1 -1
  101. package/dist/global-scope-BN-Io_yv.cjs.map +1 -1
  102. package/dist/global-scope-D9I8s-oN.js.map +1 -1
  103. package/dist/guards-Cidk71ME.js.map +1 -1
  104. package/dist/guards-nJ70syPt.cjs.map +1 -1
  105. package/dist/{identity-Cxgj6pZX.cjs → identity-BlvlgjrU.cjs} +2 -2
  106. package/dist/identity-BlvlgjrU.cjs.map +1 -0
  107. package/dist/{identity-DT5VmvXy.js → identity-BrQp_5J5.js} +19 -19
  108. package/dist/identity-BrQp_5J5.js.map +1 -0
  109. package/dist/index.cjs +1 -1
  110. package/dist/index.cjs.map +1 -1
  111. package/dist/index.d.ts +112 -79
  112. package/dist/index.js +783 -635
  113. package/dist/index.js.map +1 -1
  114. package/dist/{indexeddb-storage-CIoW21Xd.cjs → indexeddb-storage-CtLvZH1r.cjs} +2 -2
  115. package/dist/indexeddb-storage-CtLvZH1r.cjs.map +1 -0
  116. package/dist/{indexeddb-storage-BJVtiQKm.js → indexeddb-storage-DLXQzAGh.js} +4 -4
  117. package/dist/indexeddb-storage-DLXQzAGh.js.map +1 -0
  118. package/dist/{interactions-DTgKy_6K.js → interactions-B6z2I4tU.js} +3 -3
  119. package/dist/interactions-B6z2I4tU.js.map +1 -0
  120. package/dist/{interactions-fEN6FbVo.cjs → interactions-P6pz08Jn.cjs} +2 -2
  121. package/dist/interactions-P6pz08Jn.cjs.map +1 -0
  122. package/dist/{journey-CuJrHzEg.js → journey-35yCMNFo.js} +20 -19
  123. package/dist/journey-35yCMNFo.js.map +1 -0
  124. package/dist/journey-DAGh5h9k.cjs +2 -0
  125. package/dist/journey-DAGh5h9k.cjs.map +1 -0
  126. package/dist/keys-BHhw_0Wh.cjs.map +1 -1
  127. package/dist/keys-BU9j5YqW.js.map +1 -1
  128. package/dist/{library-console-D2GY9Or6.cjs → library-console-BFWEuQsl.cjs} +2 -2
  129. package/dist/library-console-BFWEuQsl.cjs.map +1 -0
  130. package/dist/{library-console-C1m6g1BR.js → library-console-Dl_Ly6DQ.js} +2 -2
  131. package/dist/library-console-Dl_Ly6DQ.js.map +1 -0
  132. package/dist/{library-request-1BX_UlaX.cjs → library-request-Da-CHKzT.cjs} +2 -2
  133. package/dist/library-request-Da-CHKzT.cjs.map +1 -0
  134. package/dist/{library-request-BQBT9N9Q.js → library-request-nI6pvI6I.js} +2 -2
  135. package/dist/library-request-nI6pvI6I.js.map +1 -0
  136. package/dist/{lifecycle-2EtUaRpo.cjs → lifecycle-BGGOcN4N.cjs} +2 -2
  137. package/dist/lifecycle-BGGOcN4N.cjs.map +1 -0
  138. package/dist/{lifecycle-BaKx_-32.js → lifecycle-CZ6RRXc6.js} +2 -2
  139. package/dist/lifecycle-CZ6RRXc6.js.map +1 -0
  140. package/dist/{log-record-i9zOTkpQ.cjs → log-record-D7bA1RPb.cjs} +2 -2
  141. package/dist/log-record-D7bA1RPb.cjs.map +1 -0
  142. package/dist/{log-record-CAoGBBf3.js → log-record-DIA6McNr.js} +2 -2
  143. package/dist/log-record-DIA6McNr.js.map +1 -0
  144. package/dist/{long-frames-Czk7IupC.js → long-frames-430_85Da.js} +8 -6
  145. package/dist/long-frames-430_85Da.js.map +1 -0
  146. package/dist/long-frames-Dd8tsi2U.cjs +2 -0
  147. package/dist/long-frames-Dd8tsi2U.cjs.map +1 -0
  148. package/dist/models/batch.d.ts +14 -15
  149. package/dist/models/bus.d.ts +24 -24
  150. package/dist/models/config.d.ts +402 -216
  151. package/dist/models/drop.d.ts +13 -11
  152. package/dist/models/health.d.ts +13 -13
  153. package/dist/models/log-record.d.ts +13 -14
  154. package/dist/models/metric.d.ts +82 -17
  155. package/dist/models/plugin.d.ts +13 -13
  156. package/dist/models/replay.d.ts +60 -0
  157. package/dist/models/serializer.d.ts +2 -3
  158. package/dist/models/stats.d.ts +2 -2
  159. package/dist/models/storage.d.ts +12 -11
  160. package/dist/{network-DBNwApoF.js → network-C7SkLf4v.js} +12 -12
  161. package/dist/network-C7SkLf4v.js.map +1 -0
  162. package/dist/{network-xbbuvG_6.cjs → network-pEX3PAJv.cjs} +2 -2
  163. package/dist/network-pEX3PAJv.cjs.map +1 -0
  164. package/dist/openfin-Bxelt0yg.js.map +1 -1
  165. package/dist/openfin-DtH2f7zX.cjs.map +1 -1
  166. package/dist/otlp-2MCrC3kd.cjs +2 -0
  167. package/dist/otlp-2MCrC3kd.cjs.map +1 -0
  168. package/dist/{otlp-BTJdIa6F.js → otlp-COq033e3.js} +25 -32
  169. package/dist/otlp-COq033e3.js.map +1 -0
  170. package/dist/patch-BX8KrPCT.cjs.map +1 -1
  171. package/dist/patch-UdPz1ea8.js.map +1 -1
  172. package/dist/{platform-C2Ez5kDc.cjs → platform-12uR7kBQ.cjs} +2 -2
  173. package/dist/platform-12uR7kBQ.cjs.map +1 -0
  174. package/dist/{platform-DkcuXwe-.js → platform-CVewe4wQ.js} +7 -7
  175. package/dist/platform-CVewe4wQ.js.map +1 -0
  176. package/dist/profiler-BVWIOgnq.js +310 -0
  177. package/dist/profiler-BVWIOgnq.js.map +1 -0
  178. package/dist/profiler-eVCknCzS.cjs +2 -0
  179. package/dist/profiler-eVCknCzS.cjs.map +1 -0
  180. package/dist/profiler-frames-CLXlT_xL.js +86 -0
  181. package/dist/profiler-frames-CLXlT_xL.js.map +1 -0
  182. package/dist/profiler-frames-Dg2OebB2.cjs +2 -0
  183. package/dist/profiler-frames-Dg2OebB2.cjs.map +1 -0
  184. package/dist/{remote-rules-Cfb4K-Nl.js → remote-rules-BJGDJGwA.js} +27 -27
  185. package/dist/remote-rules-BJGDJGwA.js.map +1 -0
  186. package/dist/{remote-rules-vzvk7aKf.cjs → remote-rules-CJD3ToVk.cjs} +2 -2
  187. package/dist/remote-rules-CJD3ToVk.cjs.map +1 -0
  188. package/dist/replay-0zAJv9T3.js +338 -0
  189. package/dist/replay-0zAJv9T3.js.map +1 -0
  190. package/dist/replay-DomJpXqW.cjs +2 -0
  191. package/dist/replay-DomJpXqW.cjs.map +1 -0
  192. package/dist/{reports-Dk2YhKIh.cjs → reports-BsbqmP8h.cjs} +2 -2
  193. package/dist/reports-BsbqmP8h.cjs.map +1 -0
  194. package/dist/{reports-TA-zInnq.js → reports-BuXekPOS.js} +3 -3
  195. package/dist/reports-BuXekPOS.js.map +1 -0
  196. package/dist/{resource-timing-BLv3EA2A.js → resource-timing-CXGHwFRD.js} +4 -4
  197. package/dist/resource-timing-CXGHwFRD.js.map +1 -0
  198. package/dist/{resource-timing-Cysw1S1f.cjs → resource-timing-DkycFGDa.cjs} +2 -2
  199. package/dist/resource-timing-DkycFGDa.cjs.map +1 -0
  200. package/dist/{sampling-Ckh2yW9k.cjs → sampling-Dd0wllyq.cjs} +2 -2
  201. package/dist/sampling-Dd0wllyq.cjs.map +1 -0
  202. package/dist/{sampling-C4VV-1MS.js → sampling-UUDbi3K0.js} +9 -9
  203. package/dist/sampling-UUDbi3K0.js.map +1 -0
  204. package/dist/{sanitize-6ymPlVvP.js → sanitize-CNmsD9r3.js} +2 -2
  205. package/dist/sanitize-CNmsD9r3.js.map +1 -0
  206. package/dist/{sanitize-BAWzkZt0.cjs → sanitize-ChLn97Ch.cjs} +2 -2
  207. package/dist/sanitize-ChLn97Ch.cjs.map +1 -0
  208. package/dist/{select-ZF4by-lF.cjs → select-CTk-K5mG.cjs} +3 -3
  209. package/dist/select-CTk-K5mG.cjs.map +1 -0
  210. package/dist/{select-xtQaenIi.js → select-DPv_j6wq.js} +61 -61
  211. package/dist/select-DPv_j6wq.js.map +1 -0
  212. package/dist/{sender-CiMHC9YG.js → sender-15zEsZpr.js} +61 -60
  213. package/dist/sender-15zEsZpr.js.map +1 -0
  214. package/dist/sender-Bfpv9tad.cjs +2 -0
  215. package/dist/sender-Bfpv9tad.cjs.map +1 -0
  216. package/dist/storage/context-storage.d.ts +34 -33
  217. package/dist/storage/emergency-queue.d.ts +9 -9
  218. package/dist/storage/eviction.d.ts +12 -12
  219. package/dist/storage/factory.d.ts +8 -7
  220. package/dist/storage/gap.d.ts +6 -6
  221. package/dist/storage/idb-driver.d.ts +31 -32
  222. package/dist/storage/indexeddb-storage.d.ts +26 -27
  223. package/dist/storage/keys.d.ts +7 -7
  224. package/dist/storage/local-storage.d.ts +38 -38
  225. package/dist/storage/memory-storage.d.ts +21 -22
  226. package/dist/storage/persistence.d.ts +1 -1
  227. package/dist/storage-BA9RqRO-.cjs.map +1 -1
  228. package/dist/storage-DZwed89z.js.map +1 -1
  229. package/dist/{storm-VR024_QN.js → storm-BTSNTIWI.js} +2 -2
  230. package/dist/storm-BTSNTIWI.js.map +1 -0
  231. package/dist/{storm-CYi9Swpx.cjs → storm-D0_qZOEg.cjs} +2 -2
  232. package/dist/storm-D0_qZOEg.cjs.map +1 -0
  233. package/dist/transport/compression.d.ts +2 -2
  234. package/dist/transport/errors.d.ts +7 -7
  235. package/dist/transport/exit-flush.d.ts +39 -39
  236. package/dist/transport/headers.d.ts +2 -2
  237. package/dist/transport/http-transport.d.ts +28 -27
  238. package/dist/transport/memory-transport.d.ts +6 -6
  239. package/dist/transport/retry-engine.d.ts +35 -34
  240. package/dist/transport/serializers/ecs.d.ts +1 -1
  241. package/dist/transport/serializers/otlp-metrics.d.ts +1 -1
  242. package/dist/transport/serializers/otlp-traces.d.ts +1 -1
  243. package/dist/transport/serializers/otlp.d.ts +16 -16
  244. package/dist/transport/serializers/select.d.ts +7 -7
  245. package/dist/transport/status-transport.d.ts +20 -20
  246. package/dist/transport/worker-protocol.d.ts +3 -3
  247. package/dist/types-BAerHgCq.js.map +1 -1
  248. package/dist/types-C7WNpnG1.cjs.map +1 -1
  249. package/dist/{unclean-exit-DFUN57wY.cjs → unclean-exit-ClGzrc2A.cjs} +2 -2
  250. package/dist/unclean-exit-ClGzrc2A.cjs.map +1 -0
  251. package/dist/{unclean-exit-CwcUhFOn.js → unclean-exit-Cob_jyTv.js} +2 -2
  252. package/dist/unclean-exit-Cob_jyTv.js.map +1 -0
  253. package/dist/unref-CU9Nyz_9.cjs +2 -0
  254. package/dist/unref-CU9Nyz_9.cjs.map +1 -0
  255. package/dist/unref-DgHPQeWv.js +7 -0
  256. package/dist/unref-DgHPQeWv.js.map +1 -0
  257. package/dist/user-timing-CdYqx3PF.cjs +2 -0
  258. package/dist/user-timing-CdYqx3PF.cjs.map +1 -0
  259. package/dist/{user-timing-_jZIhDKI.js → user-timing-DgHubxCI.js} +5 -3
  260. package/dist/user-timing-DgHubxCI.js.map +1 -0
  261. package/dist/utils/console.d.ts +2 -2
  262. package/dist/utils/deadline.d.ts +4 -4
  263. package/dist/utils/error-like.d.ts +7 -7
  264. package/dist/utils/fixed-window.d.ts +9 -8
  265. package/dist/utils/global-scope.d.ts +8 -8
  266. package/dist/utils/guards.d.ts +2 -2
  267. package/dist/utils/identity.d.ts +17 -17
  268. package/dist/utils/library-console.d.ts +4 -4
  269. package/dist/utils/library-request.d.ts +10 -10
  270. package/dist/utils/lock.d.ts +10 -9
  271. package/dist/utils/openfin.d.ts +5 -5
  272. package/dist/utils/patch.d.ts +6 -6
  273. package/dist/utils/platform.d.ts +13 -11
  274. package/dist/utils/sanitize.d.ts +4 -4
  275. package/dist/utils/timer.d.ts +1 -1
  276. package/dist/utils/tracing.d.ts +38 -38
  277. package/dist/utils/unref.d.ts +3 -3
  278. package/dist/{web-socket-BWUoqBh8.cjs → web-socket-BTuvYoJI.cjs} +2 -2
  279. package/dist/web-socket-BTuvYoJI.cjs.map +1 -0
  280. package/dist/{web-socket-CV7yIMnm.js → web-socket-DthJuSAg.js} +4 -4
  281. package/dist/web-socket-DthJuSAg.js.map +1 -0
  282. package/dist/web-vitals-Ch5BpDmo.cjs +2 -0
  283. package/dist/web-vitals-Ch5BpDmo.cjs.map +1 -0
  284. package/dist/web-vitals-CsGCWnUr.js +77 -0
  285. package/dist/web-vitals-CsGCWnUr.js.map +1 -0
  286. package/dist/{worker-protocol-CrsdSDLn.js → worker-protocol-B0_8rWy5.js} +4 -4
  287. package/dist/worker-protocol-B0_8rWy5.js.map +1 -0
  288. package/dist/{worker-protocol-Bai7GAIA.cjs → worker-protocol-BjzFORfq.cjs} +2 -2
  289. package/dist/worker-protocol-BjzFORfq.cjs.map +1 -0
  290. package/dist/worker-server-4en-Lt-3.cjs +2 -0
  291. package/dist/worker-server-4en-Lt-3.cjs.map +1 -0
  292. package/dist/{worker-server-Dp5HYm4b.js → worker-server-Cne9MX9I.js} +8 -8
  293. package/dist/{worker-server-Dp5HYm4b.js.map → worker-server-Cne9MX9I.js.map} +1 -1
  294. package/dist/worker-transport-B-GF4Aqn.cjs +2 -0
  295. package/dist/worker-transport-B-GF4Aqn.cjs.map +1 -0
  296. package/dist/{worker-transport-D6jtgpqN.js → worker-transport-C3SjJAEC.js} +62 -61
  297. package/dist/worker-transport-C3SjJAEC.js.map +1 -0
  298. package/package.json +8 -2
  299. package/dist/batch-C8OcWR2L.cjs.map +0 -1
  300. package/dist/batch-CL9uWYY3.js.map +0 -1
  301. package/dist/bus-BZ0GldpT.js.map +0 -1
  302. package/dist/bus-VWlmM5xs.cjs +0 -2
  303. package/dist/bus-VWlmM5xs.cjs.map +0 -1
  304. package/dist/console-BPZCuSLc.cjs.map +0 -1
  305. package/dist/console-BeCF7n59.js.map +0 -1
  306. package/dist/constants-DqKJH_MP.cjs +0 -2
  307. package/dist/constants-DqKJH_MP.cjs.map +0 -1
  308. package/dist/constants-zyrqveN4.js +0 -304
  309. package/dist/constants-zyrqveN4.js.map +0 -1
  310. package/dist/deadline-BOjOxNHj.js.map +0 -1
  311. package/dist/deadline-XSnm95pg.cjs +0 -2
  312. package/dist/deadline-XSnm95pg.cjs.map +0 -1
  313. package/dist/debug-bundle-BzJNpbF0.cjs +0 -2
  314. package/dist/debug-bundle-BzJNpbF0.cjs.map +0 -1
  315. package/dist/debug-bundle-C7UkHZ-q.js.map +0 -1
  316. package/dist/emergency-queue-CNTRui5t.cjs.map +0 -1
  317. package/dist/emergency-queue-Zy6lNafo.js.map +0 -1
  318. package/dist/errors-Dh7kef0i.js.map +0 -1
  319. package/dist/errors-tfEr48bS.cjs.map +0 -1
  320. package/dist/factory-BonqI3NL.js.map +0 -1
  321. package/dist/factory-CJXVYp0R.cjs.map +0 -1
  322. package/dist/identity-Cxgj6pZX.cjs.map +0 -1
  323. package/dist/identity-DT5VmvXy.js.map +0 -1
  324. package/dist/indexeddb-storage-BJVtiQKm.js.map +0 -1
  325. package/dist/indexeddb-storage-CIoW21Xd.cjs.map +0 -1
  326. package/dist/interactions-DTgKy_6K.js.map +0 -1
  327. package/dist/interactions-fEN6FbVo.cjs.map +0 -1
  328. package/dist/journey-CuJrHzEg.js.map +0 -1
  329. package/dist/journey-pffMVMfa.cjs +0 -2
  330. package/dist/journey-pffMVMfa.cjs.map +0 -1
  331. package/dist/library-console-C1m6g1BR.js.map +0 -1
  332. package/dist/library-console-D2GY9Or6.cjs.map +0 -1
  333. package/dist/library-request-1BX_UlaX.cjs.map +0 -1
  334. package/dist/library-request-BQBT9N9Q.js.map +0 -1
  335. package/dist/lifecycle-2EtUaRpo.cjs.map +0 -1
  336. package/dist/lifecycle-BaKx_-32.js.map +0 -1
  337. package/dist/log-record-CAoGBBf3.js.map +0 -1
  338. package/dist/log-record-i9zOTkpQ.cjs.map +0 -1
  339. package/dist/long-frames-BVg4i5SC.cjs +0 -2
  340. package/dist/long-frames-BVg4i5SC.cjs.map +0 -1
  341. package/dist/long-frames-Czk7IupC.js.map +0 -1
  342. package/dist/network-DBNwApoF.js.map +0 -1
  343. package/dist/network-xbbuvG_6.cjs.map +0 -1
  344. package/dist/otlp-BDvFrLnc.cjs +0 -2
  345. package/dist/otlp-BDvFrLnc.cjs.map +0 -1
  346. package/dist/otlp-BTJdIa6F.js.map +0 -1
  347. package/dist/platform-C2Ez5kDc.cjs.map +0 -1
  348. package/dist/platform-DkcuXwe-.js.map +0 -1
  349. package/dist/remote-rules-Cfb4K-Nl.js.map +0 -1
  350. package/dist/remote-rules-vzvk7aKf.cjs.map +0 -1
  351. package/dist/reports-Dk2YhKIh.cjs.map +0 -1
  352. package/dist/reports-TA-zInnq.js.map +0 -1
  353. package/dist/resource-timing-BLv3EA2A.js.map +0 -1
  354. package/dist/resource-timing-Cysw1S1f.cjs.map +0 -1
  355. package/dist/sampling-C4VV-1MS.js.map +0 -1
  356. package/dist/sampling-Ckh2yW9k.cjs.map +0 -1
  357. package/dist/sanitize-6ymPlVvP.js.map +0 -1
  358. package/dist/sanitize-BAWzkZt0.cjs.map +0 -1
  359. package/dist/select-ZF4by-lF.cjs.map +0 -1
  360. package/dist/select-xtQaenIi.js.map +0 -1
  361. package/dist/sender-CiMHC9YG.js.map +0 -1
  362. package/dist/sender-D5wBoXA8.cjs +0 -2
  363. package/dist/sender-D5wBoXA8.cjs.map +0 -1
  364. package/dist/storm-CYi9Swpx.cjs.map +0 -1
  365. package/dist/storm-VR024_QN.js.map +0 -1
  366. package/dist/unclean-exit-CwcUhFOn.js.map +0 -1
  367. package/dist/unclean-exit-DFUN57wY.cjs.map +0 -1
  368. package/dist/user-timing-C9kfRq3J.cjs +0 -2
  369. package/dist/user-timing-C9kfRq3J.cjs.map +0 -1
  370. package/dist/user-timing-_jZIhDKI.js.map +0 -1
  371. package/dist/web-socket-BWUoqBh8.cjs.map +0 -1
  372. package/dist/web-socket-CV7yIMnm.js.map +0 -1
  373. package/dist/web-vitals-Bq4WFHQo.js +0 -52
  374. package/dist/web-vitals-Bq4WFHQo.js.map +0 -1
  375. package/dist/web-vitals-DFuoTQbZ.cjs +0 -2
  376. package/dist/web-vitals-DFuoTQbZ.cjs.map +0 -1
  377. package/dist/worker-protocol-Bai7GAIA.cjs.map +0 -1
  378. package/dist/worker-protocol-CrsdSDLn.js.map +0 -1
  379. package/dist/worker-server-BrIYkfoa.cjs +0 -2
  380. package/dist/worker-server-BrIYkfoa.cjs.map +0 -1
  381. package/dist/worker-transport-Bwej4N2e.cjs +0 -2
  382. package/dist/worker-transport-Bwej4N2e.cjs.map +0 -1
  383. package/dist/worker-transport-D6jtgpqN.js.map +0 -1
@@ -1,2 +0,0 @@
1
- const e=require("./constants-DqKJH_MP.cjs"),t=require("./storage-BA9RqRO-.cjs"),n=require("./emergency-queue-CNTRui5t.cjs"),r=require("./factory-CJXVYp0R.cjs"),i=require("./context-storage-BjzeBSxH.cjs"),a=require("./deadline-XSnm95pg.cjs"),o=require("./library-request-1BX_UlaX.cjs"),s=require("./openfin-DtH2f7zX.cjs"),c=require("./sanitize-BAWzkZt0.cjs"),l=require("./library-console-D2GY9Or6.cjs"),u=require("./select-ZF4by-lF.cjs"),d=require("./platform-C2Ez5kDc.cjs"),f=require("./otlp-BDvFrLnc.cjs"),p=require("./batch-C8OcWR2L.cjs"),m=require("./log-record-i9zOTkpQ.cjs"),h=require("./identity-Cxgj6pZX.cjs"),g=require("./sampling-Ckh2yW9k.cjs"),_=require("./remote-rules-vzvk7aKf.cjs");async function v(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 y(e){let t=typeof e==`string`?Date.parse(e):NaN;return Number.isNaN(t)?void 0:Math.round(t+500-Date.now())}var b=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=y(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 x(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 S(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 C(e){return typeof e==`number`&&Number.isFinite(e)?Math.max(0,e):void 0}var w=class extends b{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=x(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),!S(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:C(s.retryAfterMs),maxBytes:C(s.maxBytes)})}},T=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.Ht,t.id),r.searchParams.set(e.Ut,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=x(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())}},E=new WeakMap;function D(e,t){let{headers:n}=t;if(!n)return;if(typeof n!=`function`)return n;let r=E.get(e);return r?.source===n&&r.endpoint===t.endpoint&&r.metricsEndpoint===t.metricsEndpoint&&r.tracesEndpoint===t.tracesEndpoint?r.headers:void 0}async function O(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&&E.set(e,{source:r,endpoint:i,metricsEndpoint:a,tracesEndpoint:o,headers:s}),s??{}}function k(e){E.delete(e)}var A=`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.`,j=class extends b{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 D(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`&&(k(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:A})}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.`,()=>f.a(e))??e}async dispatch(e,t,n,r,i){let{config:s}=this,c=new AbortController,l=()=>{c.abort()};this.cancellation.signal.addEventListener(`abort`,l,{once:!0}),this.cancellation.signal.aborted&&c.abort();let f=setTimeout(()=>{c.abort()},Math.max(0,r-Date.now()));a.r(f);try{return await o.r(()=>fetch(e,{method:`POST`,headers:t,body:n,credentials:s.credentials,signal:c.signal,cache:`no-store`,keepalive:i,priority:i?`auto`:s.delivery.priority}))}catch{throw this.cancellation.signal.aborted?new u.s(`permanent`,`The delivery context retired.`):c.signal.aborted?this.timeout(e):new u.s(d.r()?`transient`:`offline`,`A network error occurred.`)}finally{this.cancellation.signal.removeEventListener(`abort`,l),clearTimeout(f)}}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 O(this,this.config,this.diagnostics)}},M=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,a.r(t)}bounded(t){return a.n(t,e.Cn)}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=p.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]),[])}},N=[`metrics`,`logs`,`traces`];function P(t){let n=t.attributes[e.g];return n===`metric`?`metrics`:n===`span`?`traces`:`logs`}var F=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,a.r(e)}clearTimer(){this.timer!==null&&(clearTimeout(this.timer),this.timer=null)}},I=class{transport;storage;retry;diagnostics;routingContextId;policy;onLoss;clockOffset;streams;unconfirmed=new Map;queue=[];open=new Set;ceiling=new g.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 F(i.logs,l),metrics:new F(i.metrics,l),traces:new F(i.traces,l)}}push(e){if(this.stopped)return;e.observedTimeUnixNano=m.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,N.map(t=>this.toBatch([...e.filter(e=>P(e)===t),...this.streams[t].take()])).filter(e=>e!==null)}async flushPending(){if(!this.stopped)for(let e of N)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:N.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 N)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:h.i(this.diagnostics),records:e,createdAt:Date.now(),attempts:0,routingContextId:this.routingContextId?.(),persistenceNamespace:this.policy?.persistence.namespace}}route(t){try{let n=P(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.Cn),this.retry.nudge()})}},L=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`),v(o).then(n.onPersistence));let c=new i.ContextStorage(s,a.securityContext,a.persistence.namespace),l=e=>{let t=_.n(e,o);t&&_.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-Bwej4N2e.cjs"))).createWorkerTransport(a,o,l,f,d)):void 0,m=a.transport!==void 0||p!==void 0?void 0:new j(a,o,l,f,d),h=p?.transport??m??new w(a,o,l,f,d),g=new M(c,h,o,a,void 0,f),{batching:y}=a,b=new I(h,c,g,o,{logs:{flushIntervalMs:y.logFlushIntervalMs,batchSize:y.logBatchSize},metrics:{flushIntervalMs:y.metricFlushIntervalMs,batchSize:y.metricBatchSize},traces:{flushIntervalMs:y.logFlushIntervalMs,batchSize:y.logBatchSize}},()=>a.securityContext.id||void 0,a,f,()=>a.metadata.clockOffset?u:void 0),x=new T({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=L,exports.a=b,exports.i=O,exports.n=j,exports.r=k,exports.t=A;
2
- //# sourceMappingURL=sender-D5wBoXA8.cjs.map
@@ -1 +0,0 @@
1
- {"version":3,"file":"sender-D5wBoXA8.cjs","names":["TransportError","batchKind","serializeBatch","endpointFor","batchKind","withDeadline","trackTransportCall","runAsLibraryRequest","runAsLibraryConsole","DeadlineError","TransportError","getFin","batchKind","endpointFor","estimateBytes","QUERY_PARAM_BATCH_ID","QUERY_PARAM_EXIT_REASON","HEADER_CONTENT_TYPE","HEADER_BATCH_ID","CONTENT_TYPE_TEXT_PLAIN","runAsLibraryRequest","serializeBatch","batchKind","endpointFor","HEADER_SAMPLING","HEADER_DATE","parseRetryAfter","HEADER_RETRY_AFTER","HEADER_CONTENT_TYPE","HEADER_BATCH_ID","HEADER_ATTEMPT","HEADER_CONTENT_ENCODING","ENCODING_GZIP","withDeadline","TransportError","estimateBytes","gzip","runAsLibraryRequest","isOnline","storageLimits","withDeadline","STORAGE_DEADLINE_MS","lockName","DRAIN_LOCK_NAME","withDrainLock","isOnline","batchKind","TransportError","splitBatch","ATTR_LOG_TYPE","ErrorCeiling","estimateBytes","nowUnixNano","newId","ATTR_CLOCK_OFFSET_MS","withDeadline","STORAGE_DEADLINE_MS","createStorage","storageName","storageLimits","ContextStorage","parseRemoteRules","withDeadline","drainEmergencyQueue","require_constants","require_storage","require_emergency_queue","require_factory","require_context_storage","require_deadline","require_library_request","require_openfin","require_sanitize","require_library_console","require_select","require_platform","require_otlp","require_batch","require_log_record","require_identity","require_sampling","require_remote_rules","requestPersistence","storage","diagnostics","clockOffset","serverMs","date","StatusTransport","batch","cancel","cancelled","reject","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","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","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","resolve","settle","throttledMs","Sender","pipeline","exitFlush","backing","update","raw","clockOffsetMs","offsetMs","worker","http","batching","started","sender","scope","contextId","timeoutMs","drained","buffered","stored","discard","moved"],"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/** Global with the storage manager. A worker, Node and an insecure page 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 answer of the browser. It 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 the parts that the HTTP transport and the custom transport share. A status code then\n// has the same meaning on both paths. 2xx accepts the batch. 413 splits it. 429 and 503 throttle.\n// 408 and 5xx retry. Each other code drops the batch.\n\nimport {\n 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 the Date header of an answer.\n * @param date Value of the Date header. It has whole seconds.\n * @returns Server time minus client time in milliseconds, or undefined for no 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 a request of the batch starts with keepalive.\n * @throws TransportError when the batch is not accepted.\n */\n send(batch: LogBatch, onKeepalive?: () => void): Promise<void>;\n /**\n * Returns the remaining throttle delay of the endpoint of a batch.\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 work of this context. A custom transport receives the same abort signal. */\n stop(): void {\n this.cancellation.abort();\n }\n\n /**\n * Checks the batch context after each asynchronous step and before a send.\n * @param batch Batch to check.\n * @throws TransportError if the context stopped or the context id does not 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, for each endpoint. A 429 from\n * metricsEndpoint must not 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 the sampling rules of an accepted batch, before validation.\n * @param onLoss Receives the records of a batch that the serializer cannot encode.\n * @param onClock Receives the clock offset of an accepted batch, 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 a request of the batch starts with keepalive.\n * @throws TransportError when the batch is not accepted.\n */\n abstract send(batch: LogBatch, onKeepalive?: () => void): Promise<void>;\n\n /**\n * Returns the remaining throttle delay of the endpoint of a batch, 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. It reports a serializer that throws.\n * @param batch Batch to serialize.\n * @returns The serialized batch, or undefined if the serializer threw.\n */\n protected serialize(batch: LogBatch): SerializedBatch | undefined {\n 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. It ends the server throttle of the endpoint of the batch.\n * @param kind Kind of the accepted batch.\n * @param sampling Sampling rules of the answer, as text or as an object.\n * @param date Date header of the answer. It is null when the server does not 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 // Trust only the answer to a batch that the library sent. A null header means no rules.\n if (this.config.sampling.remote && sampling !== undefined && sampling !== null) {\n this.onSampling(sampling);\n }\n\n const offset = clockOffset(date);\n if (offset !== undefined) {\n this.onClock(offset);\n }\n }\n\n /**\n * Converts a status code that is not 2xx into a classified TransportError.\n * @param status Status code of the answer.\n * @param batchId Identifier of the rejected batch.\n * @param 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. A retry loop on a rejected credential blocks each batch after it.\n return new TransportError(\"permanent\", `The server rejected the batch with ${code}.`, status);\n }\n\n if (status === HTTP_PAYLOAD_TOO_LARGE) {\n return new TransportError(\n \"too_large\",\n \"The payload is too large.\",\n status,\n undefined,\n hints.maxBytes,\n );\n }\n\n if (status === HTTP_TOO_MANY_REQUESTS || status === HTTP_SERVICE_UNAVAILABLE) {\n const throttled = status === HTTP_TOO_MANY_REQUESTS;\n // Cap the server delay. Without the cap, a large Retry-After stops 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 transport function that the consumer supplies. The status codes\n// have the same meaning as on the HTTP path. Retry, storage and the exit flush do not change.\n\nimport { 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 * Tests if a value is a usable transport response.\n * @param value Value that the transport resolved to.\n * @returns True if the value has an integer status from 100 to 599.\n */\nfunction isResponse(value: unknown): value is TransportResponse {\n if (typeof value !== \"object\" || value === null) {\n return false;\n }\n\n const status: unknown = Reflect.get(value, \"status\");\n return (\n typeof status === \"number\" &&\n Number.isInteger(status) &&\n status >= HTTP_STATUS_MIN &&\n status <= HTTP_STATUS_MAX\n );\n}\n\n/**\n * Gives a number hint that the server can use. A string, NaN or Infinity breaks the throttle.\n * @param value Hint that the transport returned.\n * @returns The value, 0 or more, or undefined if it is not a finite number.\n */\nfunction finiteHint(value: unknown): number | undefined {\n return typeof value === \"number\" && Number.isFinite(value) ? Math.max(0, value) : undefined;\n}\n\n/** Sends batches through the consumer's transport function. */\nexport class CustomTransport extends StatusTransport {\n /**\n * Sends one batch through the configured transport function.\n * @param batch Batch to send.\n * @throws TransportError when the batch is not accepted.\n */\n async send(batch: LogBatch): Promise<void> {\n 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 holds a dispatch slot. The deadline frees the slot.\n response = await withDeadline(\n // The capture modules skip a request or a console line inside these scopes. Network\n // capture warns about a request after an await, which is outside the scopes.\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. Classify it here.\n const deadline = error instanceof DeadlineError ? error : undefined;\n const kind = deadline ? \"timeout\" : \"transient\";\n const message = deadline?.message ?? \"The custom transport failed.\";\n\n throw new TransportError(kind, message, undefined, undefined, undefined, error);\n }\n\n 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// This module flushes buffered batches on exit. It uses sendBeacon, a keepalive fetch or\n// emergency storage. It runs during unload. No code in it awaits. A hidden document\n// still runs. It 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/** This type names the lifecycle event or manual action that starts an exit flush. */\nexport type ExitReason = \"hidden\" | \"pagehide\" | \"freeze\" | \"openfin-close\" | \"shutdown\";\n\n/**\n * This type holds the answer of the browser to a beacon. `refused` means that the in-flight\n * budget is full. `unavailable` means that the host has no usable sendBeacon.\n */\ntype BeaconOutcome = \"sent\" | \"refused\" | \"unavailable\";\n\n/** This type reads navigator.sendBeacon without global DOM type assertions. */\ninterface BeaconGlobal {\n navigator?: { sendBeacon?: (url: string, data: Blob) => boolean };\n}\n\n/** This interface lists the dependencies of ExitFlush. */\nexport interface ExitFlushDeps {\n /** This field holds the active configuration. */\n config: ResolvedConfig;\n /** This field holds the diagnostics reporter. */\n diagnostics: Diagnostics;\n /** This callback drains all buffered and unconfirmed records into one batch for each kind. */\n drainForExit: () => LogBatch[];\n /**\n * This callback runs a normal flush with headers, gzip and retry. A hidden document uses it.\n * It does not touch an in-flight batch.\n */\n flushAlive: () => void | Promise<void>;\n /**\n * This callback gives the headers that the HTTP transport sent last, or undefined.\n * sendBeacon cannot set a header. With headers, the exit flush uses a keepalive fetch.\n */\n exitHeaders: () => Record<string, string> | undefined;\n /** This callback receives the records that the exit flush loses. */\n onLoss?: LossReporter;\n /** This callback sends the points of the open metric interval into the buffers. */\n beforeExit?: () => void;\n}\n\n/**\n * This class flushes pending telemetry on document unload. It uses sendBeacon, a keepalive\n * fetch or emergency storage.\n */\nexport class ExitFlush {\n /** This flag is true while the library listens for the unload events. */\n private installed = false;\n\n /** Bytes of the keepalive fetches of the current exit flush. All batches share one budget. */\n private keepaliveBytes = 0;\n\n /** This listener flushes on visibilitychange when the document becomes hidden. */\n private readonly onVisibility = (): void => {\n if (document.visibilityState === \"hidden\") {\n this.flush(\"hidden\");\n }\n };\n\n /** This listener flushes on the window pagehide event. */\n private readonly onPageHide = (): void => {\n this.flush(\"pagehide\");\n };\n\n /** This listener flushes on the document freeze event. */\n private readonly onFreeze = (): void => {\n this.flush(\"freeze\");\n };\n\n /** This listener flushes on the OpenFin close-requested event. */\n private readonly onOpenFinClose = (): void => {\n this.flush(\"openfin-close\");\n };\n\n /**\n * @param deps Injected configuration, diagnostics, and drain callback.\n */\n constructor(private readonly deps: ExitFlushDeps) {}\n\n /** This method attaches the unload listeners to the document, the window and OpenFin. */\n install(): void {\n if (this.installed || typeof addEventListener === \"undefined\") {\n return;\n }\n this.installed = true;\n\n if (typeof document !== \"undefined\") {\n // visibilitychange and freeze fire on the document. pagehide fires on the window.\n document.addEventListener(\"visibilitychange\", this.onVisibility);\n document.addEventListener(\"freeze\", this.onFreeze);\n }\n\n addEventListener(\"pagehide\", this.onPageHide);\n\n const me = 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 /** This method removes all unload listeners and subscriptions. */\n uninstall(): void {\n if (!this.installed) {\n return;\n }\n this.installed = false;\n\n if (typeof document !== \"undefined\") {\n document.removeEventListener(\"visibilitychange\", this.onVisibility);\n document.removeEventListener(\"freeze\", this.onFreeze);\n }\n\n removeEventListener(\"pagehide\", this.onPageHide);\n\n const me = 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. It sends them with a beacon, a\n * keepalive fetch or emergency storage. A hidden document gets a normal flush. It never\n * awaits and never throws. 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 // The drain below then takes the points of the open metric interval.\n diagnostics.guard(\"pipeline.crashed\", \"The metric points before the exit flush failed.\", () => {\n this.deps.beforeExit?.();\n });\n\n // hidden fires at each tab switch. The document keeps running. A normal flush keeps the\n // headers, gzip and the retry. A beacon has none of them. The in-flight batches complete\n // by themselves. A take of them here sends 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 // The fetches of an earlier flush are complete or lost. They do not 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 // Save an oversized payload to the synchronous localStorage queue. localStorage is the\n // only storage that accepts a write without await.\n if (estimateBytes(serialized.body) > BEACON_LIMIT_BYTES) {\n this.park(batch);\n return;\n }\n\n // Send the batch ID and the reason as query parameters. sendBeacon cannot set headers.\n url.searchParams.set(QUERY_PARAM_BATCH_ID, batch.id);\n url.searchParams.set(QUERY_PARAM_EXIT_REASON, reason);\n\n const target = url.toString();\n\n // sendBeacon cannot set a header. An ingest server that needs the authorization header\n // drops a beacon. Send the last headers with a keepalive fetch.\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 a call gives one. The server refuses a\n // beacon without the headers. The next page load sends 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\n // same budget and fails the same way. The document closes. No code retries 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 the normal flush of a hidden document. It reports a flush that 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 * Gives the pending records to the exit hook of a custom transport. A page that closes cannot\n * wait for the async transport. Without a hook, or when the hook refuses the batch, the batch\n * goes to the emergency queue. The next page load sends it.\n * @param reason Reason code of the flush.\n * @param onExit Synchronous exit hook of the custom transport.\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 * Keeps a batch for the next page load in the emergency queue in localStorage. With storage\n * \"memory\" or \"none\", the app wants nothing on the device. The batch is then lost.\n * @param batch Batch that the exit flush cannot 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. It 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 answer of the browser.\n */\n private beacon(url: string, body: string): BeaconOutcome {\n const outcome = this.deps.diagnostics.guard<BeaconOutcome>(\n \"transport.http_error\",\n \"The sendBeacon call failed.\",\n () => {\n // Call sendBeacon on navigator to keep its receiver. A detached sendBeacon throws when\n // called.\n const nav = (globalThis as BeaconGlobal).navigator;\n if (!nav?.sendBeacon) {\n return \"unavailable\";\n }\n\n // Use text/plain to prevent a CORS preflight during unload. A preflight during unload\n // usually does not complete. The browser then drops the beacon without an error.\n const accepted = nav.sendBeacon(url, new Blob([body], { type: CONTENT_TYPE_TEXT_PLAIN }));\n return accepted ? \"sent\" : \"refused\";\n },\n );\n\n // A throw is not a refusal. The method is present but unusable. The keepalive fetch can\n // still succeed.\n return outcome ?? \"unavailable\";\n }\n\n /**\n * Sends a fallback POST with fetch and `keepalive: true`. A keepalive request\n * continues after the document closes. The browser cancels a plain fetch at page close.\n * A failed fetch parks the batch in the emergency queue. The server drops a second copy by\n * 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, 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 arrives only while the document is alive. The next page load sends 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. park() then does\n // not 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/** Header cache of one HTTP transport. 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/** Reads the last headers only while their source and all destinations stay in force. */\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/** Removes rejected credentials before the next call of the headers function. */\nexport function resetHeaders(owner: object): void {\n caches.delete(owner);\n}\n","// src/transport/http-transport.ts\n//\n// This module serializes, compresses and sends log batches over HTTP. It classifies each\n// failure, reports it and throws it. The caller that owns storage decides what happens to a\n// rejected batch.\n\nimport {\n 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 a 401 or a 403 answer of an HTTP send, 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. It is text or gzip bytes. */\ntype RequestBody = string | Uint8Array<ArrayBuffer>;\n\n/** This type reads document.visibilityState without global DOM type assertions. */\ninterface DocumentGlobal {\n document?: { visibilityState?: string };\n}\n\n/**\n * This class sends serialized log batches over HTTP. It resolves headers, applies gzip\n * compression and classifies errors.\n */\nexport class HttpTransport extends StatusTransport {\n /**\n * Sends one log batch over HTTP. A metrics batch goes to metricsEndpoint. A traces batch goes to\n * tracesEndpoint. A batch without an endpoint goes nowhere.\n * @param batch Batch to send.\n * @param onKeepalive Runs when a request of the batch 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 * Gives the headers for the exit flush. A closing document cannot await headers().\n * @returns The static headers, the headers that the function in force gave last, 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. It throws a classified TransportError\n * on failure.\n * @param batch Batch to deliver.\n * @param kind Kind of the batch. The caller reads it with the endpoint.\n * @param endpoint Ingest URL. The caller reads it one time. A reconfigure during the send\n * cannot change it.\n * @param onKeepalive Runs when a request of the batch 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 calls of headers(). Send one time more with new\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. If not, it is 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 * Tests if 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 the\n * three steps. Without it, 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 the case of header names. A config header cannot duplicate a header 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. The exit flush must not send the batch 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 does not reject. 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 value of the step.\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. The payload size must\n * be at or above the threshold.\n * @param text Serialized payload string.\n * @returns Promise that resolves to original string or 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. It maps network errors to\n * TransportError.\n * @param endpoint Ingest URL.\n * @param headers HTTP request headers.\n * @param body Request body string or byte array.\n * @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 the rest of the time 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. Do not 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 * Tests if a send uses keepalive. A mobile OS can stop a hidden page with no pagehide.\n * A keepalive request continues after that. The browser limits the keepalive 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. It keeps the headers that\n * headers() gave, for the exit flush.\n * @returns Promise that resolves to resolved 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// This module sends stored log batches again in the background. It uses exponential\n// backoff with jitter. It keeps one timer, never a chain of timers. Each scheduling path\n// clears the pending timer first.\n\nimport { 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 the next try of a failed batch. */\ntype Outcome = \"next\" | \"stop\" | number;\n\n/**\n * This class sends persisted offline batches again on a timer. It uses backoff, a cross-tab\n * drain lock and batch splitting.\n */\nexport class RetryEngine {\n /** This field holds the active retry timer handle. It is null when no timer runs. */\n private timer: ReturnType<typeof setTimeout> | null = null;\n\n /** This field counts consecutive failed deliveries. The backoff calculation uses it. */\n private attempt = 0;\n\n /** This flag is true while a storage drain runs. */\n private draining = false;\n\n /** This flag is true after stop(). */\n private stopped = false;\n\n /** Attempt limit of a stored batch. Retention cannot change after the delivery stack loads. */\n private readonly maxAttempts: number;\n\n /** This listener runs on the online event. It resets the attempt count and starts a drain. */\n private readonly onOnline = (): void => {\n this.attempt = 0;\n this.schedule(0);\n };\n\n /**\n * @param storage Storage adapter holding undelivered batches.\n * @param transport HTTP transport for batch delivery.\n * @param diagnostics Diagnostics reporter.\n * @param config Active configuration instance.\n * @param batchesPerDrain Maximum batches processed per drain tick.\n * @param onLoss Receives the records of each 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 /** This method starts the engine. It listens for online events and arms the first timer. */\n start(): void {\n this.stopped = false;\n\n if (typeof addEventListener !== \"undefined\") {\n addEventListener(\"online\", this.onOnline);\n }\n\n this.schedule(this.config.delivery.retryIdleDelayMs);\n }\n\n /** This method schedules an earlier retry when storage receives a new offline batch. */\n nudge(): void {\n if (!this.draining) {\n this.schedule(this.config.delivery.retryBaseDelayMs);\n }\n }\n\n /**\n * Stores a batch that failed outside the drain loop. It applies the same rules\n * as the drain. It does not store a refused batch whole. A whole batch causes another request\n * with a payload that the server refused.\n * @param batch Rejected batch, with its attempt already counted.\n * @param error Failure thrown by the transport.\n */\n async storeFailed(batch: LogBatch, error: unknown): Promise<void> {\n const parts = this.toStorable(batch, error);\n\n for (const part of parts) {\n await this.bounded(this.storage.save(part));\n }\n\n if (parts.length > 0) {\n this.nudge();\n }\n }\n\n /** This method stops the engine. It removes the listener and clears the pending timer. */\n stop(): void {\n this.stopped = true;\n\n if (typeof removeEventListener !== \"undefined\") {\n removeEventListener(\"online\", this.onOnline);\n }\n\n this.clearTimer();\n }\n\n /**\n * Tries one delivery pass of stored batches before a context change. The caller sets 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. It then schedules a drain after the delay.\n * @param delayMs Delay duration in milliseconds.\n */\n private schedule(delayMs: number): void {\n if (this.stopped) {\n return;\n }\n\n this.clearTimer();\n\n const timer = setTimeout(() => {\n void this.drain();\n }, delayMs);\n\n this.timer = timer;\n unrefTimer(timer);\n }\n\n /**\n * Sets a deadline on a storage call. A call that does not settle keeps\n * `draining` true. This window then runs no more drains.\n * @param work Storage promise to bound.\n * @returns The value of the promise, or a rejection after the deadline.\n */\n private bounded<T>(work: Promise<T>): Promise<T> {\n return withDeadline(work, STORAGE_DEADLINE_MS);\n }\n\n /** This method clears the pending timer when a timer is active. */\n private clearTimer(): void {\n if (this.timer !== null) {\n clearTimeout(this.timer);\n this.timer = null;\n }\n }\n\n /**\n * Calculates the exponential backoff delay from consecutive failures. It applies\n * full jitter, not a fixed offset. With a fixed offset, tabs that reconnect together send\n * their requests at the same time.\n * @returns Backoff duration in milliseconds.\n */\n private backoffMs(): number {\n const exponential = Math.min(\n this.config.delivery.retryBaseDelayMs * 2 ** this.attempt,\n this.config.delivery.retryMaxDelayMs,\n );\n\n return Math.random() * exponential;\n }\n\n /** This method runs a drain under the origin-wide Web Lock. */\n private async drain(): Promise<void> {\n if (this.draining) {\n return;\n }\n this.draining = true;\n\n try {\n const 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 stops 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 it holds the Web Lock. It schedules the next tick.\n * It always resolves. A throw leaves the engine idle with no armed timer.\n * @returns Promise 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 the kind of its batch. The other endpoint can accept its 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 sends before the Retry-After of the other server.\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. It removes the batch on success. On failure, it applies the\n * rule for 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. A delay\n * in milliseconds blocks the kind of the batch 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 both kinds. The other endpoint is not 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 asks for the batch later. Do not bump the\n // stored attempts here. A bump dead-letters the batch after five throttled responses.\n if (failure?.kind === \"throttled\") {\n this.attempt++;\n 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 the parts that survive its failure. The parts\n * are the split halves, or nothing after a permanent refusal.\n * @param batch Rejected log batch, already held in storage.\n * @param error Failure thrown by the transport.\n */\n private async replaceStored(batch: LogBatch, error: unknown): Promise<void> {\n const parts = this.toStorable(batch, error);\n await this.bounded(this.storage.remove(batch.id));\n\n for (const part of parts) {\n await this.bounded(this.storage.save(part));\n }\n }\n\n /**\n * Selects the batches to keep after a failure. A 413 response splits the batch\n * in two. A permanent refusal keeps nothing. Each other failure keeps the batch whole.\n * @param batch Rejected log batch.\n * @param error Failure thrown by the transport.\n * @returns Batches to persist. The array is empty when the engine drops the records.\n */\n private toStorable(batch: LogBatch, error: unknown): LogBatch[] {\n const failure = error instanceof TransportError ? error : undefined;\n\n if (failure?.kind === \"permanent\") {\n 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// This module buffers the log and metric streams. It makes batches. It delivers them.\n//\n// Each stream has its own buffer and flush timer. Thus the exit flush can take each\n// record that is not yet at the transport.\n\nimport {\n ATTR_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 the order of the exit batches. The logs get the beacon budget before the spans. */\nconst STREAM_ORDER: readonly StreamName[] = [\"metrics\", \"logs\", \"traces\"];\n\n/**\n * Gives the stream of a record. Each stream makes batches of one kind.\n * @param record Record to evaluate.\n * @returns \"metrics\" for a metric, \"traces\" for a span, else \"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 that a partial batch waits before the pipeline sends it. */\n flushIntervalMs: number;\n /** Maximum records in a batch. At this count, the pipeline sends the batch early. */\n batchSize: number;\n}\n\n/** A closed batch in the queue or in flight. */\ninterface Pending {\n /** Batch to deliver. */\n batch: LogBatch;\n /** Resolves when the dispatch of the batch 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.\n * Below batchSize, it starts the interval timer. Without the timer, a small batch\n * waits for the next record. On a quiet page, the next record does not come.\n * @param record Record to enqueue.\n */\n add(record: LogRecord): void {\n this.pending.push(record);\n\n if (this.pending.length >= this.options.batchSize) {\n this.onFlush(this);\n return;\n }\n\n this.arm();\n }\n\n /**\n * Removes and returns all buffered records. It also stops the flush timer.\n * @returns Array of buffered records.\n */\n take(): LogRecord[] {\n this.clearTimer();\n\n const records = this.pending;\n this.pending = [];\n\n return records;\n }\n\n /** 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 and metric streams. It makes batches. It sends them over HTTP. */\nexport class LogPipeline {\n /** Buffer instances for logs and metrics streams. */\n private readonly streams: Record<StreamName, RecordStream>;\n\n /** In-flight batches without delivery confirmation. The exit flush sends them again. */\n private readonly unconfirmed = new Map<string, LogBatch>();\n\n /** Closed batches waiting for a free dispatch slot. */\n private readonly queue: Pending[] = [];\n\n /** Each batch in the queue or in flight. flushPending waits for 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 have not completed. delivery.maxConcurrentRequests sets their limit. */\n private inFlight = 0;\n\n /** It is true when a pump is in the queue. One microtask then drains a burst. */\n private pumpScheduled = false;\n\n /** True after destroy() stops the pipeline. */\n private stopped = false;\n /** Encoded byte count of each record in the buffers or 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 has not completed. */\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 have not reached the transport. A request already sent cannot be removed.\n * @returns True if the method removed a batch or a buffered group.\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 each record, also without a byte budget. A record that JSON cannot encode is dropped\n // here alone. If not, the transport drops 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. Do not remove 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 Gives the delivery context id of a new batch.\n * @param policy Active configuration instance.\n * @param onLoss Receives the records that the pipeline loses.\n * @param clockOffset Gives 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 given to fetch go again under a new batch ID. The server cannot\n * deduplicate them. Thus the exit flush can deliver duplicates. This is intentional.\n * A closing document cannot confirm delivery.\n * @returns One batch for each stream, metrics first. A stream with no records has no batch.\n * A mixed batch sends a metric to the endpoint of the logs.\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 it waits for each\n * batch in the queue and in flight. The throttle check and the concurrency limit apply.\n * A direct send goes around both.\n * @returns Promise that resolves when the pipeline sends or stores each batch, or on destroy.\n */\n async flushPending(): Promise<void> {\n // One batch for each stream. A mixed batch sends a metric to the endpoint of the logs.\n // The claim does not take an in-flight batch. A second copy under a new ID is a duplicate\n // that the server cannot remove.\n if (!this.stopped) {\n for (const name of STREAM_ORDER) {\n this.claim(this.streams[name]);\n }\n }\n\n // A batch in the queue counts too. If not, the exit flush sends it again under a new id.\n await Promise.all([...this.open].map((pending) => pending.done));\n }\n\n /**\n * Counts the records that wait 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 // Each 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 each queued batch. Release each flushPending that waits for 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 already ran. RecordBuilder samples a local\n * record. The runtime samples a forwarded record. This method catches each fault.\n * A record without `attributes` makes streamOf throw. An uncaught throw goes into the\n * log call of the caller.\n * @param record Record to sort.\n */\n private route(record: LogRecord): void {\n try {\n const name = streamOf(record);\n const stream = this.streams[name];\n\n // Records at or above alwaysSampleFrom bypass sampling upstream. This ceiling is their\n // only limit. A metric point or a span has the level INFO. A lost point gives a 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 starts a new series. Only logs and spans 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 the batch for dispatch.\n * A timer or a flush calls it. An empty buffer gives no batch.\n * Each `take` stops the timer that calls this method.\n * @param stream Stream buffer to drain.\n */\n private claim(stream: RecordStream): void {\n this.enqueue(this.toBatch(stream.take()));\n }\n\n /**\n * Queues a batch and schedules the pump on a microtask. An inline dispatch starts\n * a fetch inside the log call of the application.\n * @param batch Batch ready for delivery, 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. It then frees the concurrency slot. It resolves the promise of the batch.\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. If the transport throttles or fails, it stores\n * the batch.\n * @param batch Batch to deliver.\n */\n private async dispatch(batch: LogBatch): Promise<void> {\n try {\n // Store the batch while the transport throttles. A send here posts a batch each\n // flush interval through the throttle. Do not change the attempt count.\n // The pipeline sent nothing.\n const throttledMs = this.transport.throttledForMs(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 continues after unload. The exit flush must not send it again.\n // A failed send still goes to the retry engine from 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 the store. At 0, the batch exceeds\n // STORAGE_LIMITS.maxAttempts by one. The attempt headers then report one too few.\n await this.storeFailed({ ...batch, attempts: batch.attempts + 1 }, error);\n this.diagnostics.report(\n \"transport.http_error\",\n \"The send failed. The pipeline stored the batch for a retry.\",\n { batchId: batch.id, records: batch.records.length },\n error,\n );\n }\n } finally {\n this.unconfirmed.delete(batch.id);\n }\n }\n\n /**\n * Stores a batch that the transport refused. The retry engine splits a 413 and\n * drops a batch that the server does not accept.\n * @param batch Batch to persist, with its attempt already counted.\n * @param error Failure thrown by the transport.\n */\n private async storeFailed(batch: LogBatch, error: unknown): Promise<void> {\n await this.diagnostics.guardAsync(\n \"storage.degraded\",\n \"The library could not store an undelivered batch.\",\n async () => {\n await this.retry.storeFailed(batch, error);\n },\n );\n }\n\n /**\n * Stores an undelivered batch. Then it starts the retry engine. A deadline limits the\n * wait. A storage call that does not settle holds this dispatch slot. Two such calls\n * stop the pipeline.\n * @param batch Batch to persist.\n */\n private async store(batch: LogBatch): Promise<void> {\n await this.diagnostics.guardAsync(\n \"storage.degraded\",\n \"The library could not store an undelivered batch.\",\n async () => {\n await withDeadline(this.storage.save(batch), STORAGE_DEADLINE_MS);\n this.retry.nudge();\n },\n );\n }\n}\n","// src/core/sender.ts\n//\n// This module builds the delivery stack of the sender role.\n// The stack has storage, transport, retry, pipeline and exit flush.\n// The runtime imports this module dynamically only when the config sets an endpoint.\n// Console-only mode does not download this module.\n\nimport { STORAGE_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 request for persistent storage. */\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 that the transport, the retry engine and the exit flush lose. */\n onLoss: LossReporter;\n /** Slot of the runtime for the sampling rules from the ingest server. */\n remote: RemoteSlot;\n /** Sends the points of the open metric interval 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(). A late emergency import then does not wake the retry engine. */\n private retired = false;\n /** Emergency queue import. retire() waits for it before it reads 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 Transport of the pipeline and the retry engine.\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. A slow IndexedDB open then does not hold 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 of the last accepted answer. 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 life. 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 has the size of a log record. 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 sends after load reports failure.\n let started = false;\n\n try {\n exitFlush.install();\n retry.start();\n started = true;\n } finally {\n if (!started) {\n exitFlush.uninstall();\n retry.stop();\n }\n }\n\n 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 it waits for each batch in flight.\n * @returns Promise that resolves when the pipeline sends or stores each 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 Records that wait, 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 it stops all\n * timers and listeners. Then it closes storage. The normal flush keeps the headers, gzip\n * and the retry. The exit flush takes the records that the normal flush did not 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. It 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 Records that were in memory, and the batches that were stored, after the 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 for each record fills 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 // A tab that closes during the carry then parks the rest. It does not lose them.\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 batches of an earlier context under this context. Then the retry engine sends them.\n * The live buffer does not take them. A large backlog would exceed its budget.\n * @param batches Stored batches of the earlier context.\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. The attempts of the old destination do not 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 batches of the emergency queue 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":"A,urBAiBA,eAAsBkF,EAAmB,EAAuD,CAC9F,IAAMC,EAAW,WAA6B,WAAW,QAYzD,OAVI,OAAOA,GAAS,SAAY,WAUzB,MANeC,EAAY,WAChC,sBACA,+DACMD,EAAQ,QAAQ,CACxB,IAEmB,GAAO,UAAY,SAT7B,aAUX,CCFA,SAASE,EAAY,EAAmC,CACtD,IAAMC,EAAW,OAAOC,GAAS,SAAW,KAAK,MAAMA,CAAI,EAAI,IAE/D,OAAO,OAAO,MAAMD,CAAQ,EACxB,IAAA,GACA,KAAK,MAAMA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,SACrC,CAAC,EAKL,IAAMK,EAAU/B,IAAW,WAAaA,IAAW,QAKnD,OAJA,MAAM,KAAK,QAAQ,OAAO+B,CAAO,EAC7BA,GACFjJ,EAAA,sBAAsB4I,EAAW,KAAK,YAAa,KAAK,QAAQ,SAAS,EAEpE,CAAE,WAAU,QAAO,CAC5B,CASA,MAAM,MAAM,EAA8B,EAAkC,CAC1E,IAAK,IAAMrH,KAASqE,EAElB,MAAM,KAAK,QAAQ,KAAK,CACtB,GAAGrE,EACH,SAAU,EACV,iBAAkBqH,EAClB,qBAAsB,KAAK,QAAQ,SACrC,CAAC,EAGChD,EAAQ,OAAS,GACnB,KAAK,MAAM,MAAM,CAErB,CAMA,MAAc,iBAAiC,CAC7C,IAAMsD,EAAQ,MAAM,KAAK,YAAY,WACnC,mBACA,mCAEErJ,EAAAA,oBACE,KAAK,QACL,KAAK,YACJ,GAAU,KAAK,QAAQ,QAAQ0B,CAAK,EACrC,KAAK,QAAQ,SACf,CACJ,EAEI,CAAC,KAAK,SAAW2H,IAAU,IAAA,IAAaA,EAAQ,GAClD,KAAK,MAAM,MAAM,CAErB,CACF,E"}
@@ -1 +0,0 @@
1
- {"version":3,"file":"storm-CYi9Swpx.cjs","names":["ERROR_STORM_WINDOW_MS","countInWindow","require_constants","require_fixed_window","allowInWindow","limit","window","windowMs","diagnostics","what"],"sources":["../src/capture/storm.ts"],"sourcesContent":["// src/capture/storm.ts\n//\n// Fixed-window rate limit for the capture modules. A render loop that throws or freezes\n// makes thousands of events each second. Sending all of them floods the ingest endpoint.\n\nimport { ERROR_STORM_WINDOW_MS } from \"../constants\";\nimport type { Diagnostics } from \"../core/diagnostics\";\nimport { countInWindow, type StormWindow } from \"../utils/fixed-window\";\n\nexport type { StormWindow } from \"../utils/fixed-window\";\n\n/**\n * Counts one event in a fixed window. It reports each event over the limit.\n * @param window Window state to change.\n * @param limit Maximum events in each window.\n * @param diagnostics Diagnostics reporter.\n * @param what Plural name of the events, for the diagnostic message.\n * @param windowMs Rate limit window, in milliseconds.\n * @returns False when the window has no allowance left. The caller must drop the event.\n */\nexport function allowInWindow(\n window: StormWindow,\n limit: number,\n diagnostics: Diagnostics,\n what: string,\n windowMs = ERROR_STORM_WINDOW_MS,\n): boolean {\n if (limit === 0 || countInWindow(window, limit, windowMs)) {\n return true;\n }\n\n diagnostics.report(\n \"capture.rate_limited\",\n `More than ${String(limit)} ${what} occurred in ${String(windowMs)} ms. The library ignores the other ${what} in this window.`,\n );\n return false;\n}\n"],"mappings":"A,qFAoBA,SAAgBI,EACd,EACA,EACA,EACA,EACA,EAAWJ,EAAAA,GACF,CAST,OARIK,IAAU,GAAKJ,EAAAA,EAAcK,EAAQD,EAAOE,CAAQ,EAC/C,IAGTC,EAAY,OACV,uBACA,aAAa,OAAOH,CAAK,EAAE,GAAGI,EAAK,eAAe,OAAOF,CAAQ,EAAE,qCAAqCE,EAAK,iBAC/G,EACO,GACT,C"}
@@ -1 +0,0 @@
1
- {"version":3,"file":"storm-VR024_QN.js","names":["ERROR_STORM_WINDOW_MS","allowInWindow","limit","countInWindow","window","windowMs","diagnostics","what"],"sources":["../src/capture/storm.ts"],"sourcesContent":["// src/capture/storm.ts\n//\n// Fixed-window rate limit for the capture modules. A render loop that throws or freezes\n// makes thousands of events each second. Sending all of them floods the ingest endpoint.\n\nimport { ERROR_STORM_WINDOW_MS } from \"../constants\";\nimport type { Diagnostics } from \"../core/diagnostics\";\nimport { countInWindow, type StormWindow } from \"../utils/fixed-window\";\n\nexport type { StormWindow } from \"../utils/fixed-window\";\n\n/**\n * Counts one event in a fixed window. It reports each event over the limit.\n * @param window Window state to change.\n * @param limit Maximum events in each window.\n * @param diagnostics Diagnostics reporter.\n * @param what Plural name of the events, for the diagnostic message.\n * @param windowMs Rate limit window, in milliseconds.\n * @returns False when the window has no allowance left. The caller must drop the event.\n */\nexport function allowInWindow(\n window: StormWindow,\n limit: number,\n diagnostics: Diagnostics,\n what: string,\n windowMs = ERROR_STORM_WINDOW_MS,\n): boolean {\n if (limit === 0 || countInWindow(window, limit, windowMs)) {\n return true;\n }\n\n diagnostics.report(\n \"capture.rate_limited\",\n `More than ${String(limit)} ${what} occurred in ${String(windowMs)} ms. The library ignores the other ${what} in this window.`,\n );\n return false;\n}\n"],"mappings":";;;AAoBA,SAAgBC,EACd,GACA,GACA,GACA,GACA,IAAWD,GACF;CAST,OARIE,MAAU,KAAKC,EAAcC,GAAQF,GAAOG,CAAQ,IAC/C,MAGTC,EAAY,OACV,wBACA,aAAa,OAAOJ,CAAK,EAAE,GAAGK,EAAK,eAAe,OAAOF,CAAQ,EAAE,qCAAqCE,EAAK,iBAC/G,GACO;AACT"}
@@ -1 +0,0 @@
1
- {"version":3,"file":"unclean-exit-CwcUhFOn.js","names":["ALIVE_KEY","ALIVE_UPDATE_MS","readMarker","value","text","sessionId","at","visibility","UncleanExitCapture","ctx","marker","event"],"sources":["../src/capture/unclean-exit.ts"],"sourcesContent":["// src/capture/unclean-exit.ts\n//\n// Finds a page of this tab that stopped without a clean close, for example after a crash. The top\n// document keeps a marker in sessionStorage. A clean close removes it. The next page of the tab\n// reports a marker that it finds.\n\nimport { ALIVE_KEY, ALIVE_UPDATE_MS } from \"../constants\";\nimport type { Capture, CaptureContext } from \"./types\";\n\n/** Marker of a page that is alive. */\ninterface AliveMarker {\n /** Session id of the page. */\n sessionId: string;\n /** Epoch time in milliseconds of the last update. */\n at: number;\n /** Visibility of the page at the last update. */\n visibility: string;\n}\n\n/** Document with the flag of a page that the browser discarded to free memory. */\ninterface DiscardDocument {\n wasDiscarded?: boolean;\n}\n\n/**\n * Reads a marker from its sessionStorage text.\n * @param text Stored text, or null without a marker.\n * @returns The marker, or null for no marker or a marker of another shape.\n * @throws SyntaxError for text that is not JSON. The caller reports it.\n */\nfunction readMarker(text: string | null): AliveMarker | null {\n const value: unknown = text === null ? null : JSON.parse(text);\n if (typeof value !== \"object\" || value === null) {\n return null;\n }\n\n const { sessionId, at, visibility } = value as Partial<Record<keyof AliveMarker, unknown>>;\n const valid =\n typeof sessionId === \"string\" && Number.isFinite(at) && typeof visibility === \"string\";\n\n return valid ? { sessionId, at: at as number, visibility } : null;\n}\n\n/** Reports the unclean exit of the previous page, and keeps the marker of this page. */\nexport class UncleanExitCapture implements Capture {\n /** Capture module identifier. */\n readonly name = \"uncleanExit\";\n\n /** Prevents duplicate listener registration. */\n private installed = false;\n\n /** Timer that updates the marker. */\n private timer: ReturnType<typeof setInterval> | undefined;\n\n /** True after pagehide. The browser fires visibilitychange after pagehide. */\n private closing = false;\n\n /**\n * @param ctx Capture context with the config, diagnostics, logger and session id.\n */\n constructor(private readonly ctx: CaptureContext) {}\n\n /** Reports the marker of the previous page one time. Then it keeps the marker of this page. */\n install(): void {\n // Only the top document keeps the marker. A same-origin frame shares its sessionStorage.\n if (this.installed || typeof document === \"undefined\" || window.parent !== window) {\n return;\n }\n\n // The marker holds the session id. Memory identity writes nothing to the device.\n if (this.ctx.config.identity === \"memory\") {\n this.ctx.diagnostics.report(\n \"capture.install_failed\",\n 'capture.uncleanExit needs sessionStorage. identity: \"memory\" turns it off.',\n );\n return;\n }\n this.installed = true;\n\n if (!this.ctx.once.uncleanExit) {\n this.ctx.once.uncleanExit = true;\n // A popup copies the sessionStorage of its live opener. That marker is not a crash.\n if (!window.opener) {\n this.reportPrevious();\n }\n }\n\n this.mark();\n addEventListener(\"pagehide\", this.onPageHide);\n addEventListener(\"pageshow\", this.onPageShow);\n document.addEventListener(\"visibilitychange\", this.mark);\n this.timer = setInterval(this.mark, ALIVE_UPDATE_MS);\n }\n\n /** Removes the listeners, the timer and the marker. The capture stopped with no crash. */\n uninstall(): void {\n if (!this.installed) {\n return;\n }\n this.installed = false;\n\n removeEventListener(\"pagehide\", this.onPageHide);\n removeEventListener(\"pageshow\", this.onPageShow);\n document.removeEventListener(\"visibilitychange\", this.mark);\n clearInterval(this.timer);\n this.clear();\n }\n\n /** Logs WARN `ui.unclean_exit` when the previous page of this tab left its marker. */\n private reportPrevious(): void {\n const marker = this.ctx.diagnostics.guard(\n \"storage.unavailable\",\n \"The library could not read the alive marker in sessionStorage.\",\n () => readMarker(sessionStorage.getItem(ALIVE_KEY)),\n );\n if (!marker) {\n return;\n }\n\n this.ctx.logger.warn(\"ui.unclean_exit\", {\n \"exit.session_id\": marker.sessionId,\n \"exit.last_seen_ms\": marker.at,\n \"exit.visibility\": marker.visibility,\n \"exit.discarded\": (document as DiscardDocument).wasDiscarded === true,\n });\n }\n\n /** Writes the marker of this page with the time and the visibility of now. */\n private readonly mark = (): void => {\n if (this.closing) {\n return;\n }\n\n const marker: AliveMarker = {\n sessionId: this.ctx.sessionId(),\n at: Date.now(),\n visibility: document.visibilityState,\n };\n\n this.ctx.diagnostics.guard(\n \"storage.unavailable\",\n \"The library could not write the alive marker to sessionStorage.\",\n () => {\n sessionStorage.setItem(ALIVE_KEY, JSON.stringify(marker));\n },\n );\n };\n\n /** Removes the marker of this page. */\n private clear(): void {\n this.ctx.diagnostics.guard(\n \"storage.unavailable\",\n \"The library could not remove the alive marker from sessionStorage.\",\n () => {\n sessionStorage.removeItem(ALIVE_KEY);\n },\n );\n }\n\n /** A clean close removes the marker. The back-forward cache can keep the page. */\n private readonly onPageHide = (): void => {\n this.closing = true;\n this.clear();\n };\n\n /** A page that comes back from the back-forward cache is alive again. */\n private readonly onPageShow = (event: Event): void => {\n if ((event as PageTransitionEvent).persisted) {\n this.closing = false;\n this.mark();\n }\n };\n}\n"],"mappings":";;AA8BA,SAASE,EAAW,GAAyC;CAC3D,IAAMC,IAAiBC,MAAS,OAAO,OAAO,KAAK,MAAMA,CAAI;CAC7D,IAAI,OAAOD,KAAU,aAAYA,GAC/B,OAAO;CAGT,IAAM,EAAE,cAAW,OAAI,kBAAeA;CAItC,OAFE,OAAOE,KAAc,YAAY,OAAO,SAASC,CAAE,KAAK,OAAOC,KAAe,WAEjE;EAAE;EAAe;EAAc;CAAW,IAAI;AAC/D;AAGA,IAAaC,IAAb,MAAmD;CAgBpB;CAd7B,OAAgB;CA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CAGA,QAAsB;EACpB,KAAK,IAAI,YAAY,MACnB,uBACA,4EACM;GACJ,eAAe,WAAWV,CAAS;EACrC,CACF;CACF;CAGA,mBAA0C;EAExC,AADA,KAAK,UAAU,IACf,KAAK,MAAM;CACb;CAGA,cAA+B,MAAuB;EACpD,AAAKW,EAA8B,cACjC,KAAK,UAAU,IACf,KAAK,KAAK;CAEd;AACF"}
@@ -1 +0,0 @@
1
- {"version":3,"file":"unclean-exit-DFUN57wY.cjs","names":["ALIVE_UPDATE_MS","ALIVE_KEY","require_constants","readMarker","value","text","sessionId","at","visibility","UncleanExitCapture","ctx","marker","event"],"sources":["../src/capture/unclean-exit.ts"],"sourcesContent":["// src/capture/unclean-exit.ts\n//\n// Finds a page of this tab that stopped without a clean close, for example after a crash. The top\n// document keeps a marker in sessionStorage. A clean close removes it. The next page of the tab\n// reports a marker that it finds.\n\nimport { ALIVE_KEY, ALIVE_UPDATE_MS } from \"../constants\";\nimport type { Capture, CaptureContext } from \"./types\";\n\n/** Marker of a page that is alive. */\ninterface AliveMarker {\n /** Session id of the page. */\n sessionId: string;\n /** Epoch time in milliseconds of the last update. */\n at: number;\n /** Visibility of the page at the last update. */\n visibility: string;\n}\n\n/** Document with the flag of a page that the browser discarded to free memory. */\ninterface DiscardDocument {\n wasDiscarded?: boolean;\n}\n\n/**\n * Reads a marker from its sessionStorage text.\n * @param text Stored text, or null without a marker.\n * @returns The marker, or null for no marker or a marker of another shape.\n * @throws SyntaxError for text that is not JSON. The caller reports it.\n */\nfunction readMarker(text: string | null): AliveMarker | null {\n const value: unknown = text === null ? null : JSON.parse(text);\n if (typeof value !== \"object\" || value === null) {\n return null;\n }\n\n const { sessionId, at, visibility } = value as Partial<Record<keyof AliveMarker, unknown>>;\n const valid =\n typeof sessionId === \"string\" && Number.isFinite(at) && typeof visibility === \"string\";\n\n return valid ? { sessionId, at: at as number, visibility } : null;\n}\n\n/** Reports the unclean exit of the previous page, and keeps the marker of this page. */\nexport class UncleanExitCapture implements Capture {\n /** Capture module identifier. */\n readonly name = \"uncleanExit\";\n\n /** Prevents duplicate listener registration. */\n private installed = false;\n\n /** Timer that updates the marker. */\n private timer: ReturnType<typeof setInterval> | undefined;\n\n /** True after pagehide. The browser fires visibilitychange after pagehide. */\n private closing = false;\n\n /**\n * @param ctx Capture context with the config, diagnostics, logger and session id.\n */\n constructor(private readonly ctx: CaptureContext) {}\n\n /** Reports the marker of the previous page one time. Then it keeps the marker of this page. */\n install(): void {\n // Only the top document keeps the marker. A same-origin frame shares its sessionStorage.\n if (this.installed || typeof document === \"undefined\" || window.parent !== window) {\n return;\n }\n\n // The marker holds the session id. Memory identity writes nothing to the device.\n if (this.ctx.config.identity === \"memory\") {\n this.ctx.diagnostics.report(\n \"capture.install_failed\",\n 'capture.uncleanExit needs sessionStorage. identity: \"memory\" turns it off.',\n );\n return;\n }\n this.installed = true;\n\n if (!this.ctx.once.uncleanExit) {\n this.ctx.once.uncleanExit = true;\n // A popup copies the sessionStorage of its live opener. That marker is not a crash.\n if (!window.opener) {\n this.reportPrevious();\n }\n }\n\n this.mark();\n addEventListener(\"pagehide\", this.onPageHide);\n addEventListener(\"pageshow\", this.onPageShow);\n document.addEventListener(\"visibilitychange\", this.mark);\n this.timer = setInterval(this.mark, ALIVE_UPDATE_MS);\n }\n\n /** Removes the listeners, the timer and the marker. The capture stopped with no crash. */\n uninstall(): void {\n if (!this.installed) {\n return;\n }\n this.installed = false;\n\n removeEventListener(\"pagehide\", this.onPageHide);\n removeEventListener(\"pageshow\", this.onPageShow);\n document.removeEventListener(\"visibilitychange\", this.mark);\n clearInterval(this.timer);\n this.clear();\n }\n\n /** Logs WARN `ui.unclean_exit` when the previous page of this tab left its marker. */\n private reportPrevious(): void {\n const marker = this.ctx.diagnostics.guard(\n \"storage.unavailable\",\n \"The library could not read the alive marker in sessionStorage.\",\n () => readMarker(sessionStorage.getItem(ALIVE_KEY)),\n );\n if (!marker) {\n return;\n }\n\n this.ctx.logger.warn(\"ui.unclean_exit\", {\n \"exit.session_id\": marker.sessionId,\n \"exit.last_seen_ms\": marker.at,\n \"exit.visibility\": marker.visibility,\n \"exit.discarded\": (document as DiscardDocument).wasDiscarded === true,\n });\n }\n\n /** Writes the marker of this page with the time and the visibility of now. */\n private readonly mark = (): void => {\n if (this.closing) {\n return;\n }\n\n const marker: AliveMarker = {\n sessionId: this.ctx.sessionId(),\n at: Date.now(),\n visibility: document.visibilityState,\n };\n\n this.ctx.diagnostics.guard(\n \"storage.unavailable\",\n \"The library could not write the alive marker to sessionStorage.\",\n () => {\n sessionStorage.setItem(ALIVE_KEY, JSON.stringify(marker));\n },\n );\n };\n\n /** Removes the marker of this page. */\n private clear(): void {\n this.ctx.diagnostics.guard(\n \"storage.unavailable\",\n \"The library could not remove the alive marker from sessionStorage.\",\n () => {\n sessionStorage.removeItem(ALIVE_KEY);\n },\n );\n }\n\n /** A clean close removes the marker. The back-forward cache can keep the page. */\n private readonly onPageHide = (): void => {\n this.closing = true;\n this.clear();\n };\n\n /** A page that comes back from the back-forward cache is alive again. */\n private readonly onPageShow = (event: Event): void => {\n if ((event as PageTransitionEvent).persisted) {\n this.closing = false;\n this.mark();\n }\n };\n}\n"],"mappings":"A,4CA8BA,SAASG,EAAW,EAAyC,CAC3D,IAAMC,EAAiBC,IAAS,KAAO,KAAO,KAAK,MAAMA,CAAI,EAC7D,GAAI,OAAOD,GAAU,WAAYA,EAC/B,OAAO,KAGT,GAAM,CAAE,YAAW,KAAI,cAAeA,EAItC,OAFE,OAAOE,GAAc,UAAY,OAAO,SAASC,CAAE,GAAK,OAAOC,GAAe,SAEjE,CAAE,YAAe,KAAc,YAAW,EAAI,IAC/D,CAGA,IAAaC,EAAb,KAAmD,CAgBpB,IAd7B,KAAgB,cAGhB,UAAoB,GAGpB,MAGA,QAAkB,GAKlB,YAAY,EAAsC,CAArB,KAAA,IAAAC,CAAsB,CAGnD,SAAgB,CAEV,KAAK,WAAa,OAAO,SAAa,KAAe,OAAO,SAAW,SAKvE,KAAK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b,EAGA,WAA+B,GAAuB,CAC/CW,EAA8B,YACjC,KAAK,QAAU,GACf,KAAK,KAAK,EAEd,CACF,E"}
@@ -1,2 +0,0 @@
1
- const e=require("./platform-C2Ez5kDc.cjs"),t=require("./types-C7WNpnG1.cjs");var n={name:`ui.user_timing.duration`,kind:`histogram`,unit:`ms`,boundaries:[1,5,10,25,50,100,250,500,1e3,2500,5e3,1e4]},r=class{ctx;name=`userTiming`;observer;constructor(e){this.ctx=e}install(){if(this.observer)return;let{once:e}=this.ctx,t=!e.userTiming;e.userTiming=!0;let n=typeof PerformanceObserver>`u`?void 0:PerformanceObserver.supportedEntryTypes;n?.includes(`measure`)?(this.observer=new PerformanceObserver(e=>{this.record(e.getEntries())}),this.observer.observe({type:`measure`,buffered:t}),n.includes(`mark`)&&this.observer.observe({type:`mark`,buffered:t})):t&&this.ctx.diagnostics.report(`capture.install_failed`,`The browser does not report User Timing entries. The user timing capture is off.`)}uninstall(){this.observer?.disconnect(),this.observer=void 0}record(r){if(this.ctx.isActive?.()===!1)return;let{fullUrls:i,userTimingInclude:a}=this.ctx.config.capture;for(let o of r){if(a.length>0&&!t.t(o.name,a))continue;let r=e.i(o.name,i);o.entryType===`measure`?this.ctx.recordMetric(n,o.duration,{"user_timing.name":r}):this.ctx.breadcrumbs.push({t:Math.round(performance.timeOrigin+o.startTime),category:`event`,message:r.slice(0,this.ctx.config.limits.maxBodyChars)})}}};exports.UserTimingCapture=r;
2
- //# sourceMappingURL=user-timing-C9kfRq3J.cjs.map
@@ -1 +0,0 @@
1
- {"version":3,"file":"user-timing-C9kfRq3J.cjs","names":["matchesAny","recordedUrl","require_platform","require_types","USER_TIMING_DURATION","UserTimingCapture","ctx","first","once","supported","list","entry","entries","userTimingInclude","name","fullUrls"],"sources":["../src/capture/user-timing.ts"],"sourcesContent":["// src/capture/user-timing.ts\n//\n// Records the marks and measures of the app from the User Timing API. A measure goes into a\n// histogram. A mark adds a breadcrumb.\n\nimport type { InstrumentDef } from \"../models/metric\";\nimport { recordedUrl } from \"../utils/platform\";\nimport { type Capture, type CaptureContext, matchesAny } from \"./types\";\n\n/** Histogram of the measures of the app, in milliseconds. */\nconst USER_TIMING_DURATION: InstrumentDef = {\n name: \"ui.user_timing.duration\",\n kind: \"histogram\",\n unit: \"ms\",\n boundaries: [1, 5, 10, 25, 50, 100, 250, 500, 1000, 2500, 5000, 10000],\n};\n\n/** Observes the marks and measures of the app. */\nexport class UserTimingCapture implements Capture {\n /** Capture module identifier. */\n readonly name = \"userTiming\";\n\n /** Observer of the mark and measure entries. */\n private observer: PerformanceObserver | undefined;\n\n /**\n * @param ctx Capture context with the config, the meter and the breadcrumbs.\n */\n constructor(private readonly ctx: CaptureContext) {}\n\n /** Observes marks and measures. Only the first install in a document reads buffered entries. */\n install(): void {\n if (this.observer) {\n return;\n }\n\n const { once } = this.ctx;\n const first = !once.userTiming;\n once.userTiming = true;\n\n // Older browsers have no supportedEntryTypes. The capture is then off.\n const supported: readonly string[] | undefined =\n typeof PerformanceObserver === \"undefined\"\n ? undefined\n : PerformanceObserver.supportedEntryTypes;\n if (!supported?.includes(\"measure\")) {\n if (first) {\n this.ctx.diagnostics.report(\n \"capture.install_failed\",\n \"The browser does not report User Timing entries. The user timing capture is off.\",\n );\n }\n return;\n }\n\n this.observer = new PerformanceObserver((list) => {\n this.record(list.getEntries());\n });\n // Buffered entries include the marks and measures before this chunk loads.\n this.observer.observe({ type: \"measure\", buffered: first });\n if (supported.includes(\"mark\")) {\n this.observer.observe({ type: \"mark\", buffered: first });\n }\n }\n\n /** Disconnects the observer. */\n uninstall(): void {\n this.observer?.disconnect();\n this.observer = undefined;\n }\n\n /**\n * Records the entries with a name that `userTimingInclude` selects.\n * @param entries Mark and measure entries.\n */\n private record(entries: PerformanceEntryList): void {\n if (this.ctx.isActive?.() === false) {\n return;\n }\n\n const { fullUrls, userTimingInclude } = this.ctx.config.capture;\n for (const entry of entries) {\n if (userTimingInclude.length > 0 && !matchesAny(entry.name, userTimingInclude)) {\n continue;\n }\n\n // A name can hold a URL with a token. A third-party script can write any name.\n const name = recordedUrl(entry.name, fullUrls);\n if (entry.entryType === \"measure\") {\n this.ctx.recordMetric(USER_TIMING_DURATION, entry.duration, { \"user_timing.name\": name });\n } else {\n this.ctx.breadcrumbs.push({\n // A buffered entry reaches the observer late. The trail needs the time of the mark.\n t: Math.round(performance.timeOrigin + entry.startTime),\n category: \"event\",\n message: name.slice(0, this.ctx.config.limits.maxBodyChars),\n });\n }\n }\n }\n}\n"],"mappings":"A,6EAUA,IAAMI,EAAsC,CAC1C,KAAM,0BACN,KAAM,YACN,KAAM,KACN,WAAY,CAAC,EAAG,EAAG,GAAI,GAAI,GAAI,IAAK,IAAK,IAAK,IAAM,KAAM,IAAM,GAAK,CACvE,EAGaC,EAAb,KAAkD,CAUnB,IAR7B,KAAgB,aAGhB,SAKA,YAAY,EAAsC,CAArB,KAAA,IAAAC,CAAsB,CAGnD,SAAgB,CACd,GAAI,KAAK,SACP,OAGF,GAAM,CAAE,QAAS,KAAK,IAChBC,EAAQ,CAACC,EAAK,WACpB,EAAK,WAAa,GAGlB,IAAMC,EACJ,OAAO,oBAAwB,IAC3B,IAAA,GACA,oBAAoB,oBACrBA,GAAW,SAAS,SAAS,GAUlC,KAAK,SAAW,IAAI,oBAAqB,GAAS,CAChD,KAAK,OAAOC,EAAK,WAAW,CAAC,CAC/B,CAAC,EAED,KAAK,SAAS,QAAQ,CAAE,KAAM,UAAW,SAAUH,CAAM,CAAC,EACtDE,EAAU,SAAS,MAAM,GAC3B,KAAK,SAAS,QAAQ,CAAE,KAAM,OAAQ,SAAUF,CAAM,CAAC,GAfnDA,GACF,KAAK,IAAI,YAAY,OACnB,yBACA,kFACF,CAaN,CAGA,WAAkB,CAChB,KAAK,UAAU,WAAW,EAC1B,KAAK,SAAW,IAAA,EAClB,CAMA,OAAe,EAAqC,CAClD,GAAI,KAAK,IAAI,WAAW,IAAM,GAC5B,OAGF,GAAM,CAAE,WAAU,qBAAsB,KAAK,IAAI,OAAO,QACxD,IAAK,IAAMI,KAASC,EAAS,CAC3B,GAAIC,EAAkB,OAAS,GAAK,CAACb,EAAAA,EAAWW,EAAM,KAAME,CAAiB,EAC3E,SAIF,IAAMC,EAAOb,EAAAA,EAAYU,EAAM,KAAMI,CAAQ,EACzCJ,EAAM,YAAc,UACtB,KAAK,IAAI,aAAaP,EAAsBO,EAAM,SAAU,CAAE,mBAAoBG,CAAK,CAAC,EAExF,KAAK,IAAI,YAAY,KAAK,CAExB,EAAG,KAAK,MAAM,YAAY,WAAaH,EAAM,SAAS,EACtD,SAAU,QACV,QAASG,EAAK,MAAM,EAAG,KAAK,IAAI,OAAO,OAAO,YAAY,CAC5D,CAAC,CAEL,CACF,CACF,E"}
@@ -1 +0,0 @@
1
- {"version":3,"file":"user-timing-_jZIhDKI.js","names":["recordedUrl","USER_TIMING_DURATION","UserTimingCapture","ctx","first","once","supported","list","entry","entries","userTimingInclude","matchesAny","name","fullUrls"],"sources":["../src/capture/user-timing.ts"],"sourcesContent":["// src/capture/user-timing.ts\n//\n// Records the marks and measures of the app from the User Timing API. A measure goes into a\n// histogram. A mark adds a breadcrumb.\n\nimport type { InstrumentDef } from \"../models/metric\";\nimport { recordedUrl } from \"../utils/platform\";\nimport { type Capture, type CaptureContext, matchesAny } from \"./types\";\n\n/** Histogram of the measures of the app, in milliseconds. */\nconst USER_TIMING_DURATION: InstrumentDef = {\n name: \"ui.user_timing.duration\",\n kind: \"histogram\",\n unit: \"ms\",\n boundaries: [1, 5, 10, 25, 50, 100, 250, 500, 1000, 2500, 5000, 10000],\n};\n\n/** Observes the marks and measures of the app. */\nexport class UserTimingCapture implements Capture {\n /** Capture module identifier. */\n readonly name = \"userTiming\";\n\n /** Observer of the mark and measure entries. */\n private observer: PerformanceObserver | undefined;\n\n /**\n * @param ctx Capture context with the config, the meter and the breadcrumbs.\n */\n constructor(private readonly ctx: CaptureContext) {}\n\n /** Observes marks and measures. Only the first install in a document reads buffered entries. */\n install(): void {\n if (this.observer) {\n return;\n }\n\n const { once } = this.ctx;\n const first = !once.userTiming;\n once.userTiming = true;\n\n // Older browsers have no supportedEntryTypes. The capture is then off.\n const supported: readonly string[] | undefined =\n typeof PerformanceObserver === \"undefined\"\n ? undefined\n : PerformanceObserver.supportedEntryTypes;\n if (!supported?.includes(\"measure\")) {\n if (first) {\n this.ctx.diagnostics.report(\n \"capture.install_failed\",\n \"The browser does not report User Timing entries. The user timing capture is off.\",\n );\n }\n return;\n }\n\n this.observer = new PerformanceObserver((list) => {\n this.record(list.getEntries());\n });\n // Buffered entries include the marks and measures before this chunk loads.\n this.observer.observe({ type: \"measure\", buffered: first });\n if (supported.includes(\"mark\")) {\n this.observer.observe({ type: \"mark\", buffered: first });\n }\n }\n\n /** Disconnects the observer. */\n uninstall(): void {\n this.observer?.disconnect();\n this.observer = undefined;\n }\n\n /**\n * Records the entries with a name that `userTimingInclude` selects.\n * @param entries Mark and measure entries.\n */\n private record(entries: PerformanceEntryList): void {\n if (this.ctx.isActive?.() === false) {\n return;\n }\n\n const { fullUrls, userTimingInclude } = this.ctx.config.capture;\n for (const entry of entries) {\n if (userTimingInclude.length > 0 && !matchesAny(entry.name, userTimingInclude)) {\n continue;\n }\n\n // A name can hold a URL with a token. A third-party script can write any name.\n const name = recordedUrl(entry.name, fullUrls);\n if (entry.entryType === \"measure\") {\n this.ctx.recordMetric(USER_TIMING_DURATION, entry.duration, { \"user_timing.name\": name });\n } else {\n this.ctx.breadcrumbs.push({\n // A buffered entry reaches the observer late. The trail needs the time of the mark.\n t: Math.round(performance.timeOrigin + entry.startTime),\n category: \"event\",\n message: name.slice(0, this.ctx.config.limits.maxBodyChars),\n });\n }\n }\n }\n}\n"],"mappings":";;;AAUA,IAAMC,IAAsC;CAC1C,MAAM;CACN,MAAM;CACN,MAAM;CACN,YAAY;EAAC;EAAG;EAAG;EAAI;EAAI;EAAI;EAAK;EAAK;EAAK;EAAM;EAAM;EAAM;CAAK;AACvE,GAGaC,IAAb,MAAkD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":"web-socket-BWUoqBh8.cjs","names":["recordedUrl","isLibraryRequest","patch","matchesAny","allowInWindow","require_library_request","require_platform","require_patch","require_storm","require_types","MESSAGES_METRIC","socketTarget","parsed","url","config","diagnostics","count","server","state","socket","own","direction","attributes","WebSocketCapture","ctx","track","Original","value","protocols","data","target","lifecycle","write","logger","event"],"sources":["../src/capture/web-socket.ts"],"sourcesContent":["// src/capture/web-socket.ts\n//\n// Records the open, close and error events of each WebSocket. It counts the messages by direction\n// and server. It never reads the content of a message. It is a capture plugin, and the runtime\n// loads it as a separate chunk.\n\nimport type { Diagnostics } from \"../core/diagnostics\";\nimport type { ResolvedConfig } from \"../models/config\";\nimport type { Counter, MetricAttributes } from \"../models/metric\";\nimport type { CapturePlugin, PluginContext } from \"../models/plugin\";\nimport { isLibraryRequest } from \"../utils/library-request\";\nimport { recordedUrl } from \"../utils/platform\";\nimport { patch } from \"../utils/patch\";\nimport { allowInWindow, type StormWindow } from \"./storm\";\nimport { matchesAny } from \"./types\";\n\n/** Name of the message counter. */\nconst MESSAGES_METRIC = \"ui.websocket.messages\";\n\n/** Data of one WebSocket.send call. */\ntype SendData = Parameters<WebSocket[\"send\"]>[0];\n\n/** State of one install. A wrapper that stays after uninstall reads it and records nothing. */\ninterface InstallState {\n /** False after uninstall. */\n active: boolean;\n /** Tools of the plugin. */\n ctx: PluginContext;\n /** Counter of the messages. */\n messages: Counter;\n /** Server host name of each tracked socket. */\n servers: WeakMap<WebSocket, string>;\n /** Delivery context in force when each socket opened. */\n contexts: WeakMap<WebSocket, string>;\n /** Active capture settings and isolation rule. */\n config: ResolvedConfig;\n}\n\n/**\n * Removes the user info, the query and the fragment from a socket URL. They can hold a token.\n * @param url Absolute URL of the socket.\n * @param config Active capture settings.\n * @param diagnostics Diagnostics reporter for a URL transform that throws.\n * @returns The URL to record and the host name of the server.\n */\nfunction socketTarget(\n url: string,\n config: ResolvedConfig,\n diagnostics: Diagnostics,\n): { target: string; server: string } {\n const parsed = new URL(url);\n\n return {\n // Ignore fullUrls. A browser cannot set a header on a socket. Thus apps often put a token in\n // the query. Only urlTransform can record more of the URL.\n target: recordedUrl(url, false, config.capture.urlTransform, diagnostics),\n server: parsed.hostname,\n };\n}\n\n/**\n * Counts one message of a tracked socket.\n * @param state State of the install that made the socket.\n * @param socket Socket of the message.\n * @param direction Direction of the message.\n */\nfunction count(state: InstallState, socket: WebSocket, direction: \"transmit\" | \"receive\"): void {\n const server = state.servers.get(socket);\n\n // A send of the library, for example a custom transport, must not make the next send.\n const own = direction === \"transmit\" && isLibraryRequest();\n if (\n !state.active ||\n server === undefined ||\n own ||\n (state.config.securityContext.isolation &&\n state.contexts.get(socket) !== state.config.securityContext.id)\n ) {\n return;\n }\n\n const attributes: MetricAttributes = {\n \"network.io.direction\": direction,\n \"server.address\": server,\n };\n state.messages.add(1, attributes);\n}\n\n/** Records the lifecycle and the message counts of each WebSocket that the app opens. */\nexport class WebSocketCapture implements CapturePlugin {\n /** Capture module identifier. */\n readonly name = \"websocket\";\n\n /** Restores the WebSocket constructor. Undefined when the capture is not installed. */\n private restore: (() => boolean) | undefined;\n\n /** State of the active install. */\n private state: InstallState | undefined;\n\n /** Rate limit of the lifecycle records. A reconnect loop must not flood the pipeline. */\n private readonly window: StormWindow = { start: 0, count: 0 };\n\n /**\n * @param diagnostics Diagnostics reporter.\n * @param config Active configuration. The capture reads `capture.ignoreUrls`.\n */\n constructor(\n private readonly diagnostics: Diagnostics,\n private readonly config: ResolvedConfig,\n ) {}\n\n /**\n * Replaces the WebSocket constructor with a subclass that tracks each socket.\n * @param ctx Tools of the plugin.\n */\n install(ctx: PluginContext): void {\n if (this.restore || typeof WebSocket === \"undefined\") {\n return;\n }\n\n const state: InstallState = {\n active: true,\n ctx,\n messages: ctx.counter(MESSAGES_METRIC),\n servers: new WeakMap(),\n contexts: new WeakMap(),\n config: this.config,\n };\n this.state = state;\n\n const track = (socket: WebSocket): void => {\n this.track(socket, state);\n };\n\n this.restore = patch(\n globalThis,\n \"WebSocket\",\n (Original) =>\n class TrackedWebSocket extends Original {\n /**\n * Keeps instanceof true for a socket that the app opened before the install.\n * @param value Value to test.\n * @returns True for each native socket.\n */\n static override [Symbol.hasInstance](value: unknown): boolean {\n return value instanceof Original;\n }\n\n /**\n * @param url URL of the server.\n * @param protocols Sub-protocols of the app.\n */\n constructor(url: string | URL, protocols?: string | string[]) {\n super(url, protocols);\n track(this);\n }\n\n /**\n * Sends the data, then counts one message. A send that throws counts nothing.\n * @param data Data of the app. The library does not read it.\n */\n override send(data: SendData): void {\n super.send(data);\n count(state, this, \"transmit\");\n }\n },\n );\n }\n\n /** Restores the WebSocket constructor and stops each tracked socket from recording. */\n uninstall(): void {\n if (this.state) {\n this.state.active = false;\n }\n\n // Another script can wrap the constructor after the library. Keep its wrapper.\n if (this.restore && !this.restore()) {\n this.diagnostics.report(\n \"capture.install_failed\",\n \"Another script wrapped WebSocket after the library. The library keeps that wrapper.\",\n );\n }\n\n this.restore = undefined;\n this.state = undefined;\n }\n\n /**\n * Adds the listeners that record the lifecycle and the received messages of one socket.\n * @param socket New socket of the app.\n * @param state State of the install that made the socket.\n */\n private track(socket: WebSocket, state: InstallState): void {\n if (!state.active) {\n return;\n }\n\n // A read here runs inside the constructor call of the app. A throw must not fail it.\n this.diagnostics.guard(\n \"capture.record_failed\",\n \"The library could not track a WebSocket. The socket works without capture.\",\n () => {\n // ignoreUrls matches the full URL. A custom transport can send over its own socket.\n if (matchesAny(socket.url, this.config.capture.ignoreUrls)) {\n return;\n }\n\n const { target, server } = socketTarget(socket.url, this.config, this.diagnostics);\n const attributes = { \"url.full\": target, \"server.address\": server };\n const { logger } = state.ctx;\n state.servers.set(socket, server);\n state.contexts.set(socket, this.config.securityContext.id);\n\n const lifecycle = (write: () => void): void => {\n if (\n (!this.config.securityContext.isolation ||\n state.contexts.get(socket) === this.config.securityContext.id) &&\n this.allow(state)\n ) {\n write();\n }\n };\n\n socket.addEventListener(\"open\", () => {\n lifecycle(() => {\n logger.logEvent(\"websocket.open\", attributes);\n });\n });\n socket.addEventListener(\"error\", () => {\n lifecycle(() => {\n logger.warn(\"websocket.error\", attributes);\n });\n });\n socket.addEventListener(\"close\", (event) => {\n lifecycle(() => {\n logger.logEvent(\"websocket.close\", {\n ...attributes,\n \"websocket.close.code\": event.code,\n \"websocket.close.clean\": event.wasClean,\n });\n });\n });\n socket.addEventListener(\"message\", () => {\n count(state, socket, \"receive\");\n });\n },\n );\n }\n\n /**\n * Tests if a lifecycle record can go out.\n * @param state State of the install that made the socket.\n * @returns False after uninstall, or when the window has no allowance left.\n */\n private allow(state: InstallState): boolean {\n return (\n state.active &&\n allowInWindow(\n this.window,\n this.config.capturePolicy.webSocketPerWindow,\n this.diagnostics,\n \"WebSocket events\",\n this.config.capturePolicy.windowMs,\n )\n );\n }\n}\n"],"mappings":"A,6LAiBA,IAAMU,EAAkB,wBA4BxB,SAASC,EACP,EACA,EACA,EACoC,CACpC,IAAMC,EAAS,IAAI,IAAIC,CAAG,EAE1B,MAAO,CAGL,OAAQb,EAAAA,EAAYa,EAAK,GAAOC,EAAO,QAAQ,aAAcC,CAAW,EACxE,OAAQH,EAAO,QACjB,CACF,CAQA,SAASI,EAAM,EAAqB,EAAmB,EAAyC,CAC9F,IAAMC,EAASC,EAAM,QAAQ,IAAIC,CAAM,EAGjCC,EAAMC,IAAc,YAAcpB,EAAAA,EAAiB,EACzD,GACE,CAACiB,EAAM,QACPD,IAAW,IAAA,IACXG,GACCF,EAAM,OAAO,gBAAgB,WAC5BA,EAAM,SAAS,IAAIC,CAAM,IAAMD,EAAM,OAAO,gBAAgB,GAE9D,OAGF,IAAMI,EAA+B,CACnC,uBAAwBD,EACxB,iBAAkBJ,CACpB,EACAC,EAAM,SAAS,IAAI,EAAGI,CAAU,CAClC,CAGA,IAAaC,EAAb,KAAuD,CAkBlC,YACA,OAjBnB,KAAgB,YAGhB,QAGA,MAGA,OAAuC,CAAE,MAAO,EAAG,MAAO,CAAE,EAM5D,YACE,EACA,EACA,CAF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1C,CAAC,KAAK,OAAO,gBAAgB,WAC5Bb,EAAM,SAAS,IAAIC,CAAM,IAAM,KAAK,OAAO,gBAAgB,KAC7D,KAAK,MAAMD,CAAK,GAEhBc,EAAM,CAEV,EAEAb,EAAO,iBAAiB,WAAc,CACpCY,MAAgB,CACdE,EAAO,SAAS,iBAAkBX,CAAU,CAC9C,CAAC,CACH,CAAC,EACDH,EAAO,iBAAiB,YAAe,CACrCY,MAAgB,CACdE,EAAO,KAAK,kBAAmBX,CAAU,CAC3C,CAAC,CACH,CAAC,EACDH,EAAO,iBAAiB,QAAU,GAAU,CAC1CY,MAAgB,CACdE,EAAO,SAAS,kBAAmB,CACjC,GAAGX,EACH,uBAAwBY,EAAM,KAC9B,wBAAyBA,EAAM,QACjC,CAAC,CACH,CAAC,CACH,CAAC,EACDf,EAAO,iBAAiB,cAAiB,CACvCH,EAAME,EAAOC,EAAQ,SAAS,CAChC,CAAC,CACH,CACF,CACF,CAOA,MAAc,EAA8B,CAC1C,OACED,EAAM,QACNd,EAAAA,EACE,KAAK,OACL,KAAK,OAAO,cAAc,mBAC1B,KAAK,YACL,mBACA,KAAK,OAAO,cAAc,QAC5B,CAEJ,CACF,E"}
@@ -1 +0,0 @@
1
- {"version":3,"file":"web-socket-CV7yIMnm.js","names":["isLibraryRequest","recordedUrl","patch","allowInWindow","matchesAny","MESSAGES_METRIC","socketTarget","parsed","url","config","diagnostics","count","server","state","socket","own","direction","attributes","WebSocketCapture","ctx","track","Original","value","protocols","data","target","lifecycle","write","event"],"sources":["../src/capture/web-socket.ts"],"sourcesContent":["// src/capture/web-socket.ts\n//\n// Records the open, close and error events of each WebSocket. It counts the messages by direction\n// and server. It never reads the content of a message. It is a capture plugin, and the runtime\n// loads it as a separate chunk.\n\nimport type { Diagnostics } from \"../core/diagnostics\";\nimport type { ResolvedConfig } from \"../models/config\";\nimport type { Counter, MetricAttributes } from \"../models/metric\";\nimport type { CapturePlugin, PluginContext } from \"../models/plugin\";\nimport { isLibraryRequest } from \"../utils/library-request\";\nimport { recordedUrl } from \"../utils/platform\";\nimport { patch } from \"../utils/patch\";\nimport { allowInWindow, type StormWindow } from \"./storm\";\nimport { matchesAny } from \"./types\";\n\n/** Name of the message counter. */\nconst MESSAGES_METRIC = \"ui.websocket.messages\";\n\n/** Data of one WebSocket.send call. */\ntype SendData = Parameters<WebSocket[\"send\"]>[0];\n\n/** State of one install. A wrapper that stays after uninstall reads it and records nothing. */\ninterface InstallState {\n /** False after uninstall. */\n active: boolean;\n /** Tools of the plugin. */\n ctx: PluginContext;\n /** Counter of the messages. */\n messages: Counter;\n /** Server host name of each tracked socket. */\n servers: WeakMap<WebSocket, string>;\n /** Delivery context in force when each socket opened. */\n contexts: WeakMap<WebSocket, string>;\n /** Active capture settings and isolation rule. */\n config: ResolvedConfig;\n}\n\n/**\n * Removes the user info, the query and the fragment from a socket URL. They can hold a token.\n * @param url Absolute URL of the socket.\n * @param config Active capture settings.\n * @param diagnostics Diagnostics reporter for a URL transform that throws.\n * @returns The URL to record and the host name of the server.\n */\nfunction socketTarget(\n url: string,\n config: ResolvedConfig,\n diagnostics: Diagnostics,\n): { target: string; server: string } {\n const parsed = new URL(url);\n\n return {\n // Ignore fullUrls. A browser cannot set a header on a socket. Thus apps often put a token in\n // the query. Only urlTransform can record more of the URL.\n target: recordedUrl(url, false, config.capture.urlTransform, diagnostics),\n server: parsed.hostname,\n };\n}\n\n/**\n * Counts one message of a tracked socket.\n * @param state State of the install that made the socket.\n * @param socket Socket of the message.\n * @param direction Direction of the message.\n */\nfunction count(state: InstallState, socket: WebSocket, direction: \"transmit\" | \"receive\"): void {\n const server = state.servers.get(socket);\n\n // A send of the library, for example a custom transport, must not make the next send.\n const own = direction === \"transmit\" && isLibraryRequest();\n if (\n !state.active ||\n server === undefined ||\n own ||\n (state.config.securityContext.isolation &&\n state.contexts.get(socket) !== state.config.securityContext.id)\n ) {\n return;\n }\n\n const attributes: MetricAttributes = {\n \"network.io.direction\": direction,\n \"server.address\": server,\n };\n state.messages.add(1, attributes);\n}\n\n/** Records the lifecycle and the message counts of each WebSocket that the app opens. */\nexport class WebSocketCapture implements CapturePlugin {\n /** Capture module identifier. */\n readonly name = \"websocket\";\n\n /** Restores the WebSocket constructor. Undefined when the capture is not installed. */\n private restore: (() => boolean) | undefined;\n\n /** State of the active install. */\n private state: InstallState | undefined;\n\n /** Rate limit of the lifecycle records. A reconnect loop must not flood the pipeline. */\n private readonly window: StormWindow = { start: 0, count: 0 };\n\n /**\n * @param diagnostics Diagnostics reporter.\n * @param config Active configuration. The capture reads `capture.ignoreUrls`.\n */\n constructor(\n private readonly diagnostics: Diagnostics,\n private readonly config: ResolvedConfig,\n ) {}\n\n /**\n * Replaces the WebSocket constructor with a subclass that tracks each socket.\n * @param ctx Tools of the plugin.\n */\n install(ctx: PluginContext): void {\n if (this.restore || typeof WebSocket === \"undefined\") {\n return;\n }\n\n const state: InstallState = {\n active: true,\n ctx,\n messages: ctx.counter(MESSAGES_METRIC),\n servers: new WeakMap(),\n contexts: new WeakMap(),\n config: this.config,\n };\n this.state = state;\n\n const track = (socket: WebSocket): void => {\n this.track(socket, state);\n };\n\n this.restore = patch(\n globalThis,\n \"WebSocket\",\n (Original) =>\n class TrackedWebSocket extends Original {\n /**\n * Keeps instanceof true for a socket that the app opened before the install.\n * @param value Value to test.\n * @returns True for each native socket.\n */\n static override [Symbol.hasInstance](value: unknown): boolean {\n return value instanceof Original;\n }\n\n /**\n * @param url URL of the server.\n * @param protocols Sub-protocols of the app.\n */\n constructor(url: string | URL, protocols?: string | string[]) {\n super(url, protocols);\n track(this);\n }\n\n /**\n * Sends the data, then counts one message. A send that throws counts nothing.\n * @param data Data of the app. The library does not read it.\n */\n override send(data: SendData): void {\n super.send(data);\n count(state, this, \"transmit\");\n }\n },\n );\n }\n\n /** Restores the WebSocket constructor and stops each tracked socket from recording. */\n uninstall(): void {\n if (this.state) {\n this.state.active = false;\n }\n\n // Another script can wrap the constructor after the library. Keep its wrapper.\n if (this.restore && !this.restore()) {\n this.diagnostics.report(\n \"capture.install_failed\",\n \"Another script wrapped WebSocket after the library. The library keeps that wrapper.\",\n );\n }\n\n this.restore = undefined;\n this.state = undefined;\n }\n\n /**\n * Adds the listeners that record the lifecycle and the received messages of one socket.\n * @param socket New socket of the app.\n * @param state State of the install that made the socket.\n */\n private track(socket: WebSocket, state: InstallState): void {\n if (!state.active) {\n return;\n }\n\n // A read here runs inside the constructor call of the app. A throw must not fail it.\n this.diagnostics.guard(\n \"capture.record_failed\",\n \"The library could not track a WebSocket. The socket works without capture.\",\n () => {\n // ignoreUrls matches the full URL. A custom transport can send over its own socket.\n if (matchesAny(socket.url, this.config.capture.ignoreUrls)) {\n return;\n }\n\n const { target, server } = socketTarget(socket.url, this.config, this.diagnostics);\n const attributes = { \"url.full\": target, \"server.address\": server };\n const { logger } = state.ctx;\n state.servers.set(socket, server);\n state.contexts.set(socket, this.config.securityContext.id);\n\n const lifecycle = (write: () => void): void => {\n if (\n (!this.config.securityContext.isolation ||\n state.contexts.get(socket) === this.config.securityContext.id) &&\n this.allow(state)\n ) {\n write();\n }\n };\n\n socket.addEventListener(\"open\", () => {\n lifecycle(() => {\n logger.logEvent(\"websocket.open\", attributes);\n });\n });\n socket.addEventListener(\"error\", () => {\n lifecycle(() => {\n logger.warn(\"websocket.error\", attributes);\n });\n });\n socket.addEventListener(\"close\", (event) => {\n lifecycle(() => {\n logger.logEvent(\"websocket.close\", {\n ...attributes,\n \"websocket.close.code\": event.code,\n \"websocket.close.clean\": event.wasClean,\n });\n });\n });\n socket.addEventListener(\"message\", () => {\n count(state, socket, \"receive\");\n });\n },\n );\n }\n\n /**\n * Tests if a lifecycle record can go out.\n * @param state State of the install that made the socket.\n * @returns False after uninstall, or when the window has no allowance left.\n */\n private allow(state: InstallState): boolean {\n return (\n state.active &&\n allowInWindow(\n this.window,\n this.config.capturePolicy.webSocketPerWindow,\n this.diagnostics,\n \"WebSocket events\",\n this.config.capturePolicy.windowMs,\n )\n );\n }\n}\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