@utk09/ui-observability 0.12.0 → 1.0.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 (515) hide show
  1. package/CHANGELOG.md +420 -0
  2. package/README.md +72 -839
  3. package/dist/{batch-BjQUwjA6.js → batch-CXmPmTse.js} +4 -4
  4. package/dist/{batch-BjQUwjA6.js.map → batch-CXmPmTse.js.map} +1 -1
  5. package/dist/{batch-D5LlU4Q9.cjs → batch-mmPigCpi.cjs} +2 -2
  6. package/dist/{batch-D5LlU4Q9.cjs.map → batch-mmPigCpi.cjs.map} +1 -1
  7. package/dist/bus/bus.d.cts +331 -0
  8. package/dist/bus/bus.d.ts +60 -10
  9. package/dist/bus/links.d.cts +132 -0
  10. package/dist/bus/links.d.ts +18 -3
  11. package/dist/bus/validation.d.cts +16 -0
  12. package/dist/bus/validation.d.ts +10 -1
  13. package/dist/{bus-ecxUNTja.js → bus-C39wspFV.js} +308 -193
  14. package/dist/bus-C39wspFV.js.map +1 -0
  15. package/dist/bus-_EaOVPGq.cjs +2 -0
  16. package/dist/bus-_EaOVPGq.cjs.map +1 -0
  17. package/dist/capture/console.d.cts +37 -0
  18. package/dist/capture/console.d.ts +1 -1
  19. package/dist/capture/errors.d.cts +32 -0
  20. package/dist/capture/errors.d.ts +1 -1
  21. package/dist/capture/interactions.d.cts +48 -0
  22. package/dist/capture/interactions.d.ts +1 -1
  23. package/dist/capture/lifecycle.d.cts +20 -0
  24. package/dist/capture/lifecycle.d.ts +1 -1
  25. package/dist/capture/long-frames.d.cts +31 -0
  26. package/dist/capture/long-frames.d.ts +1 -1
  27. package/dist/capture/network.d.cts +57 -0
  28. package/dist/capture/network.d.ts +1 -1
  29. package/dist/capture/profiler-frames.d.cts +44 -0
  30. package/dist/capture/profiler-frames.d.ts +1 -1
  31. package/dist/capture/replay-buffer.d.cts +45 -0
  32. package/dist/capture/replay-buffer.d.ts +9 -10
  33. package/dist/capture/replay-upload.d.cts +79 -0
  34. package/dist/capture/replay-upload.d.ts +7 -2
  35. package/dist/capture/replay.d.cts +114 -0
  36. package/dist/capture/replay.d.ts +1 -1
  37. package/dist/capture/reports.d.cts +17 -0
  38. package/dist/capture/reports.d.ts +1 -1
  39. package/dist/capture/resource-timing.d.cts +14 -0
  40. package/dist/capture/resource-timing.d.ts +1 -1
  41. package/dist/capture/server-timing.d.cts +19 -0
  42. package/dist/capture/storm.d.cts +13 -0
  43. package/dist/capture/storm.d.ts +5 -5
  44. package/dist/capture/types.d.cts +128 -0
  45. package/dist/capture/types.d.ts +10 -9
  46. package/dist/capture/unclean-exit.d.cts +31 -0
  47. package/dist/capture/unclean-exit.d.ts +1 -1
  48. package/dist/capture/user-timing.d.cts +22 -0
  49. package/dist/capture/user-timing.d.ts +2 -2
  50. package/dist/capture/web-socket.d.cts +40 -0
  51. package/dist/capture/web-socket.d.ts +3 -3
  52. package/dist/capture/web-vitals.d.cts +40 -0
  53. package/dist/capture/web-vitals.d.ts +1 -1
  54. package/dist/{compression-lD9abCcO.cjs → compression-CvED_Jel.cjs} +2 -2
  55. package/dist/{compression-lD9abCcO.cjs.map → compression-CvED_Jel.cjs.map} +1 -1
  56. package/dist/{compression-AJJCMBOa.js → compression-tVtXwVjX.js} +2 -2
  57. package/dist/{compression-AJJCMBOa.js.map → compression-tVtXwVjX.js.map} +1 -1
  58. package/dist/config-DUs7uHHt.cjs +2 -0
  59. package/dist/config-DUs7uHHt.cjs.map +1 -0
  60. package/dist/config-SgQcCP1_.js +560 -0
  61. package/dist/config-SgQcCP1_.js.map +1 -0
  62. package/dist/console-BGgGnjSi.js +81 -0
  63. package/dist/console-BGgGnjSi.js.map +1 -0
  64. package/dist/console-CSZ5_Vx5.cjs +2 -0
  65. package/dist/console-CSZ5_Vx5.cjs.map +1 -0
  66. package/dist/constants-CUyd9cTZ.js +357 -0
  67. package/dist/constants-CUyd9cTZ.js.map +1 -0
  68. package/dist/constants-CqdJhTxH.cjs +2 -0
  69. package/dist/constants-CqdJhTxH.cjs.map +1 -0
  70. package/dist/constants.d.cts +751 -0
  71. package/dist/constants.d.ts +88 -20
  72. package/dist/core/breadcrumbs.d.cts +54 -0
  73. package/dist/core/breadcrumbs.d.ts +5 -0
  74. package/dist/core/config.d.cts +45 -0
  75. package/dist/core/config.d.ts +30 -2
  76. package/dist/core/context.d.cts +24 -0
  77. package/dist/core/context.d.ts +3 -8
  78. package/dist/core/debug-buffer.d.cts +34 -0
  79. package/dist/core/debug-buffer.d.ts +3 -3
  80. package/dist/core/debug-bundle.d.cts +12 -0
  81. package/dist/core/debug-bundle.d.ts +3 -3
  82. package/dist/core/deferred.d.cts +7 -0
  83. package/dist/core/deferred.d.ts +2 -2
  84. package/dist/core/diagnostics.d.cts +86 -0
  85. package/dist/core/diagnostics.d.ts +1 -1
  86. package/dist/core/drops.d.cts +39 -0
  87. package/dist/core/drops.d.ts +16 -6
  88. package/dist/core/hold-buffer.d.cts +36 -0
  89. package/dist/core/hold-buffer.d.ts +16 -7
  90. package/dist/core/journey.d.cts +148 -0
  91. package/dist/core/journey.d.ts +7 -7
  92. package/dist/core/logger.d.cts +141 -0
  93. package/dist/core/logger.d.ts +23 -30
  94. package/dist/core/measure.d.cts +30 -0
  95. package/dist/core/measure.d.ts +14 -3
  96. package/dist/core/meter.d.cts +78 -0
  97. package/dist/core/meter.d.ts +14 -8
  98. package/dist/core/pipeline.d.cts +227 -0
  99. package/dist/core/pipeline.d.ts +73 -10
  100. package/dist/core/profile-buckets.d.cts +31 -0
  101. package/dist/core/profiler.d.cts +218 -0
  102. package/dist/core/profiler.d.ts +2 -2
  103. package/dist/core/record.d.cts +190 -0
  104. package/dist/core/record.d.ts +44 -12
  105. package/dist/core/remote-rules.d.cts +17 -0
  106. package/dist/core/remote-rules.d.ts +3 -3
  107. package/dist/core/remote-sampling.d.cts +74 -0
  108. package/dist/core/remote-sampling.d.ts +3 -3
  109. package/dist/core/rotation.d.cts +75 -0
  110. package/dist/core/rotation.d.ts +75 -0
  111. package/dist/core/runtime.d.cts +765 -0
  112. package/dist/core/runtime.d.ts +245 -70
  113. package/dist/core/sampling.d.cts +86 -0
  114. package/dist/core/sampling.d.ts +5 -5
  115. package/dist/core/sender.d.cts +161 -0
  116. package/dist/core/sender.d.ts +59 -15
  117. package/dist/core/spans.d.cts +39 -0
  118. package/dist/core/spans.d.ts +1 -1
  119. package/dist/debug-bundle-BXIlwDKM.cjs +2 -0
  120. package/dist/debug-bundle-BXIlwDKM.cjs.map +1 -0
  121. package/dist/debug-bundle-CRpYV_ui.js +35 -0
  122. package/dist/debug-bundle-CRpYV_ui.js.map +1 -0
  123. package/dist/defineProperty-X1c4tIPD.cjs +1 -0
  124. package/dist/defineProperty-s2S8BXUc.js +35 -0
  125. package/dist/doctor.cjs +1 -1
  126. package/dist/doctor.cjs.map +1 -1
  127. package/dist/doctor.d.cts +36 -0
  128. package/dist/doctor.d.ts +5 -2
  129. package/dist/doctor.js +121 -89
  130. package/dist/doctor.js.map +1 -1
  131. package/dist/errors-BE_EZV7Q.js +86 -0
  132. package/dist/errors-BE_EZV7Q.js.map +1 -0
  133. package/dist/errors-CNPbesMs.cjs +3 -0
  134. package/dist/errors-CNPbesMs.cjs.map +1 -0
  135. package/dist/factory-CTi0Is3F.js +404 -0
  136. package/dist/factory-CTi0Is3F.js.map +1 -0
  137. package/dist/factory-hRrH32v5.cjs +2 -0
  138. package/dist/factory-hRrH32v5.cjs.map +1 -0
  139. package/dist/guards-BlYGRK4l.js +10 -0
  140. package/dist/guards-BlYGRK4l.js.map +1 -0
  141. package/dist/guards-EjG3ahFp.cjs +2 -0
  142. package/dist/guards-EjG3ahFp.cjs.map +1 -0
  143. package/dist/{identity-BrQp_5J5.js → identity-DdhKgrpk.js} +20 -24
  144. package/dist/identity-DdhKgrpk.js.map +1 -0
  145. package/dist/identity-DlWRIuwy.cjs +2 -0
  146. package/dist/identity-DlWRIuwy.cjs.map +1 -0
  147. package/dist/index.cjs +1 -1
  148. package/dist/index.cjs.map +1 -1
  149. package/dist/index.d.cts +300 -0
  150. package/dist/index.d.ts +89 -98
  151. package/dist/index.js +1173 -1506
  152. package/dist/index.js.map +1 -1
  153. package/dist/indexeddb-storage-CL9uqBCy.cjs +2 -0
  154. package/dist/indexeddb-storage-CL9uqBCy.cjs.map +1 -0
  155. package/dist/{indexeddb-storage-DLXQzAGh.js → indexeddb-storage-GHdl0t8A.js} +51 -47
  156. package/dist/indexeddb-storage-GHdl0t8A.js.map +1 -0
  157. package/dist/interactions-CUkzK8sR.cjs +2 -0
  158. package/dist/interactions-CUkzK8sR.cjs.map +1 -0
  159. package/dist/{interactions-B6z2I4tU.js → interactions-DiFvCosX.js} +41 -49
  160. package/dist/interactions-DiFvCosX.js.map +1 -0
  161. package/dist/journey-B4Adltjm.cjs +2 -0
  162. package/dist/journey-B4Adltjm.cjs.map +1 -0
  163. package/dist/{journey-35yCMNFo.js → journey-D2_sia57.js} +45 -48
  164. package/dist/journey-D2_sia57.js.map +1 -0
  165. package/dist/{library-console-Dl_Ly6DQ.js → library-console-Btrzt814.js} +2 -2
  166. package/dist/{library-console-Dl_Ly6DQ.js.map → library-console-Btrzt814.js.map} +1 -1
  167. package/dist/{library-console-BFWEuQsl.cjs → library-console-CPW6bvZH.cjs} +2 -2
  168. package/dist/{library-console-BFWEuQsl.cjs.map → library-console-CPW6bvZH.cjs.map} +1 -1
  169. package/dist/{library-request-nI6pvI6I.js → library-request-BJ9PLRaD.js} +2 -2
  170. package/dist/{library-request-nI6pvI6I.js.map → library-request-BJ9PLRaD.js.map} +1 -1
  171. package/dist/{library-request-Da-CHKzT.cjs → library-request-D7OvTxZV.cjs} +2 -2
  172. package/dist/{library-request-Da-CHKzT.cjs.map → library-request-D7OvTxZV.cjs.map} +1 -1
  173. package/dist/{lifecycle-CZ6RRXc6.js → lifecycle-22CUCrc9.js} +21 -29
  174. package/dist/lifecycle-22CUCrc9.js.map +1 -0
  175. package/dist/lifecycle-IaAm1mOC.cjs +2 -0
  176. package/dist/lifecycle-IaAm1mOC.cjs.map +1 -0
  177. package/dist/{log-record-DIA6McNr.js → log-record-BNiLfqtL.js} +8 -7
  178. package/dist/log-record-BNiLfqtL.js.map +1 -0
  179. package/dist/log-record-CkivuiEl.cjs +2 -0
  180. package/dist/log-record-CkivuiEl.cjs.map +1 -0
  181. package/dist/long-frames-BUUbXd-B.cjs +2 -0
  182. package/dist/long-frames-BUUbXd-B.cjs.map +1 -0
  183. package/dist/{long-frames-430_85Da.js → long-frames-DNFaRnC3.js} +18 -22
  184. package/dist/long-frames-DNFaRnC3.js.map +1 -0
  185. package/dist/models/batch.d.cts +57 -0
  186. package/dist/models/batch.d.ts +2 -2
  187. package/dist/models/bus.d.cts +158 -0
  188. package/dist/models/bus.d.ts +22 -2
  189. package/dist/models/config.d.cts +1540 -0
  190. package/dist/models/config.d.ts +360 -259
  191. package/dist/models/drop.d.cts +54 -0
  192. package/dist/models/drop.d.ts +16 -3
  193. package/dist/models/health.d.cts +148 -0
  194. package/dist/models/health.d.ts +108 -12
  195. package/dist/models/log-record.d.cts +61 -0
  196. package/dist/models/metric.d.cts +139 -0
  197. package/dist/models/metric.d.ts +13 -2
  198. package/dist/models/plugin.d.cts +47 -0
  199. package/dist/models/plugin.d.ts +3 -3
  200. package/dist/models/replay.d.cts +60 -0
  201. package/dist/models/serializer.d.cts +23 -0
  202. package/dist/models/serializer.d.ts +1 -1
  203. package/dist/models/storage.d.cts +95 -0
  204. package/dist/models/storage.d.ts +7 -5
  205. package/dist/network-CGMLQ-mA.cjs +2 -0
  206. package/dist/network-CGMLQ-mA.cjs.map +1 -0
  207. package/dist/{network-C7SkLf4v.js → network-on2zZT6H.js} +51 -51
  208. package/dist/network-on2zZT6H.js.map +1 -0
  209. package/dist/{otlp-2MCrC3kd.cjs → otlp-BENHf3g9.cjs} +2 -2
  210. package/dist/{otlp-2MCrC3kd.cjs.map → otlp-BENHf3g9.cjs.map} +1 -1
  211. package/dist/{otlp-COq033e3.js → otlp-DimfrRor.js} +12 -12
  212. package/dist/{otlp-COq033e3.js.map → otlp-DimfrRor.js.map} +1 -1
  213. package/dist/{platform-CVewe4wQ.js → platform-BaaFIPCU.js} +10 -10
  214. package/dist/{platform-CVewe4wQ.js.map → platform-BaaFIPCU.js.map} +1 -1
  215. package/dist/{platform-12uR7kBQ.cjs → platform-CfA3-7sJ.cjs} +2 -2
  216. package/dist/{platform-12uR7kBQ.cjs.map → platform-CfA3-7sJ.cjs.map} +1 -1
  217. package/dist/{profiler-BVWIOgnq.js → profiler-BAZoh7A4.js} +89 -107
  218. package/dist/profiler-BAZoh7A4.js.map +1 -0
  219. package/dist/profiler-D4tJpDRc.cjs +2 -0
  220. package/dist/profiler-D4tJpDRc.cjs.map +1 -0
  221. package/dist/profiler-frames-C4xr7KfH.cjs +2 -0
  222. package/dist/profiler-frames-C4xr7KfH.cjs.map +1 -0
  223. package/dist/{profiler-frames-CLXlT_xL.js → profiler-frames-cJMx9wNM.js} +29 -37
  224. package/dist/profiler-frames-cJMx9wNM.js.map +1 -0
  225. package/dist/remote-rules-Dz9MRAsB.js +95 -0
  226. package/dist/remote-rules-Dz9MRAsB.js.map +1 -0
  227. package/dist/remote-rules-_tY0zj5o.cjs +2 -0
  228. package/dist/remote-rules-_tY0zj5o.cjs.map +1 -0
  229. package/dist/replay-B3gFXIZd.cjs +2 -0
  230. package/dist/replay-B3gFXIZd.cjs.map +1 -0
  231. package/dist/replay-Ds-ANH34.js +310 -0
  232. package/dist/replay-Ds-ANH34.js.map +1 -0
  233. package/dist/reports-BDSe4dFH.cjs +2 -0
  234. package/dist/reports-BDSe4dFH.cjs.map +1 -0
  235. package/dist/{reports-BuXekPOS.js → reports-C-thq-bk.js} +25 -30
  236. package/dist/reports-C-thq-bk.js.map +1 -0
  237. package/dist/resource-timing-C576gFIQ.cjs +2 -0
  238. package/dist/resource-timing-C576gFIQ.cjs.map +1 -0
  239. package/dist/{resource-timing-CXGHwFRD.js → resource-timing-eUl2dNgC.js} +20 -23
  240. package/dist/resource-timing-eUl2dNgC.js.map +1 -0
  241. package/dist/response-body-YdNl-HkR.cjs +3 -0
  242. package/dist/response-body-YdNl-HkR.cjs.map +1 -0
  243. package/dist/response-body-eoSQpLiH.js +331 -0
  244. package/dist/response-body-eoSQpLiH.js.map +1 -0
  245. package/dist/rotation-Cwct4ckk.js +94 -0
  246. package/dist/rotation-Cwct4ckk.js.map +1 -0
  247. package/dist/rotation-D4qUAHAu.cjs +2 -0
  248. package/dist/rotation-D4qUAHAu.cjs.map +1 -0
  249. package/dist/sampling-BlrI8jor.js +63 -0
  250. package/dist/sampling-BlrI8jor.js.map +1 -0
  251. package/dist/sampling-mXt4dstx.cjs +2 -0
  252. package/dist/sampling-mXt4dstx.cjs.map +1 -0
  253. package/dist/{sanitize-CNmsD9r3.js → sanitize-Ba0KqU06.js} +2 -2
  254. package/dist/sanitize-Ba0KqU06.js.map +1 -0
  255. package/dist/{sanitize-ChLn97Ch.cjs → sanitize-DQyiI_KY.cjs} +2 -2
  256. package/dist/sanitize-DQyiI_KY.cjs.map +1 -0
  257. package/dist/sender-BdRuNVhF.cjs +2 -0
  258. package/dist/sender-BdRuNVhF.cjs.map +1 -0
  259. package/dist/sender-Dv8rAmpV.js +979 -0
  260. package/dist/sender-Dv8rAmpV.js.map +1 -0
  261. package/dist/storage/context-storage.d.cts +90 -0
  262. package/dist/storage/context-storage.d.ts +5 -5
  263. package/dist/storage/emergency-queue.d.cts +27 -0
  264. package/dist/storage/emergency-queue.d.ts +4 -4
  265. package/dist/storage/eviction.d.cts +40 -0
  266. package/dist/storage/eviction.d.ts +1 -1
  267. package/dist/storage/factory.d.cts +21 -0
  268. package/dist/storage/factory.d.ts +3 -3
  269. package/dist/storage/gap.d.cts +20 -0
  270. package/dist/storage/gap.d.ts +3 -3
  271. package/dist/storage/idb-driver.d.cts +93 -0
  272. package/dist/storage/idb-driver.d.ts +1 -1
  273. package/dist/storage/indexeddb-storage.d.cts +97 -0
  274. package/dist/storage/indexeddb-storage.d.ts +12 -4
  275. package/dist/storage/keys.d.cts +17 -0
  276. package/dist/storage/keys.d.ts +2 -2
  277. package/dist/storage/local-storage.d.cts +139 -0
  278. package/dist/storage/local-storage.d.ts +11 -4
  279. package/dist/storage/memory-storage.d.cts +73 -0
  280. package/dist/storage/memory-storage.d.ts +4 -3
  281. package/dist/storage/persistence.d.cts +8 -0
  282. package/dist/storage/persistence.d.ts +2 -2
  283. package/dist/storage/stored-context.d.cts +34 -0
  284. package/dist/storage/stored-context.d.ts +34 -0
  285. package/dist/stored-context-B2EzVuYm.js +51 -0
  286. package/dist/stored-context-B2EzVuYm.js.map +1 -0
  287. package/dist/stored-context-CXt7eHZL.cjs +2 -0
  288. package/dist/stored-context-CXt7eHZL.cjs.map +1 -0
  289. package/dist/storm-C-zYSdDX.cjs +2 -0
  290. package/dist/storm-C-zYSdDX.cjs.map +1 -0
  291. package/dist/storm-DjKetLKZ.js +9 -0
  292. package/dist/storm-DjKetLKZ.js.map +1 -0
  293. package/dist/transport/compression.d.cts +7 -0
  294. package/dist/transport/custom-transport.d.cts +22 -0
  295. package/dist/transport/custom-transport.d.ts +6 -5
  296. package/dist/transport/errors.d.cts +31 -0
  297. package/dist/transport/exit-flush.d.cts +135 -0
  298. package/dist/transport/exit-flush.d.ts +30 -13
  299. package/dist/transport/headers.d.cts +8 -0
  300. package/dist/transport/headers.d.ts +2 -2
  301. package/dist/transport/http-transport.d.cts +116 -0
  302. package/dist/transport/http-transport.d.ts +20 -8
  303. package/dist/transport/memory-transport.d.cts +30 -0
  304. package/dist/transport/memory-transport.d.ts +2 -2
  305. package/dist/transport/response-body.d.cts +49 -0
  306. package/dist/transport/response-body.d.ts +49 -0
  307. package/dist/transport/retry-engine.d.cts +129 -0
  308. package/dist/transport/retry-engine.d.ts +27 -9
  309. package/dist/transport/serializers/ecs.d.cts +3 -0
  310. package/dist/transport/serializers/ecs.d.ts +1 -1
  311. package/dist/transport/serializers/otlp-metrics.d.cts +3 -0
  312. package/dist/transport/serializers/otlp-metrics.d.ts +1 -1
  313. package/dist/transport/serializers/otlp-traces.d.cts +3 -0
  314. package/dist/transport/serializers/otlp-traces.d.ts +1 -1
  315. package/dist/transport/serializers/otlp.d.cts +47 -0
  316. package/dist/transport/serializers/otlp.d.ts +2 -2
  317. package/dist/transport/serializers/select.d.cts +38 -0
  318. package/dist/transport/serializers/select.d.ts +5 -5
  319. package/dist/transport/status-transport.d.cts +129 -0
  320. package/dist/transport/status-transport.d.ts +25 -8
  321. package/dist/transport/worker-client.d.cts +23 -0
  322. package/dist/transport/worker-client.d.ts +12 -3
  323. package/dist/transport/worker-entry.d.cts +5 -0
  324. package/dist/transport/worker-entry.d.ts +1 -1
  325. package/dist/transport/worker-protocol.d.cts +38 -0
  326. package/dist/transport/worker-protocol.d.ts +4 -2
  327. package/dist/transport/worker-server.d.cts +3 -0
  328. package/dist/transport/worker-server.d.ts +1 -1
  329. package/dist/transport/worker-transport.d.cts +10 -0
  330. package/dist/transport/worker-transport.d.ts +5 -4
  331. package/dist/types-BAerHgCq.js.map +1 -1
  332. package/dist/types-C7WNpnG1.cjs.map +1 -1
  333. package/dist/{unclean-exit-Cob_jyTv.js → unclean-exit-DQD1cT7c.js} +23 -30
  334. package/dist/unclean-exit-DQD1cT7c.js.map +1 -0
  335. package/dist/unclean-exit-py99ApzT.cjs +2 -0
  336. package/dist/unclean-exit-py99ApzT.cjs.map +1 -0
  337. package/dist/{user-timing-DgHubxCI.js → user-timing-BePqb1uN.js} +15 -17
  338. package/dist/user-timing-BePqb1uN.js.map +1 -0
  339. package/dist/user-timing-D6XTmpuM.cjs +2 -0
  340. package/dist/user-timing-D6XTmpuM.cjs.map +1 -0
  341. package/dist/utils/console.d.cts +36 -0
  342. package/dist/utils/console.d.ts +4 -4
  343. package/dist/utils/deadline.d.cts +14 -0
  344. package/dist/utils/error-like.d.cts +25 -0
  345. package/dist/utils/fixed-window.d.cts +25 -0
  346. package/dist/utils/global-scope.d.cts +20 -0
  347. package/dist/utils/guards.d.cts +14 -0
  348. package/dist/utils/guards.d.ts +8 -0
  349. package/dist/utils/identity.d.cts +109 -0
  350. package/dist/utils/identity.d.ts +3 -4
  351. package/dist/utils/library-console.d.cts +11 -0
  352. package/dist/utils/library-request.d.cts +24 -0
  353. package/dist/utils/lock.d.cts +24 -0
  354. package/dist/utils/lock.d.ts +1 -1
  355. package/dist/utils/openfin.d.cts +48 -0
  356. package/dist/utils/patch.d.cts +9 -0
  357. package/dist/utils/platform.d.cts +62 -0
  358. package/dist/utils/platform.d.ts +2 -2
  359. package/dist/utils/sanitize.d.cts +52 -0
  360. package/dist/utils/sanitize.d.ts +1 -1
  361. package/dist/utils/sequence.d.cts +10 -0
  362. package/dist/utils/tracing.d.cts +158 -0
  363. package/dist/utils/tracing.d.ts +11 -4
  364. package/dist/utils/unref.d.cts +9 -0
  365. package/dist/web-socket-CoIUBM3C.cjs +2 -0
  366. package/dist/{web-socket-DthJuSAg.js.map → web-socket-CoIUBM3C.cjs.map} +1 -1
  367. package/dist/{web-socket-DthJuSAg.js → web-socket-DSHgDiZ6.js} +23 -28
  368. package/dist/web-socket-DSHgDiZ6.js.map +1 -0
  369. package/dist/{web-vitals-CsGCWnUr.js → web-vitals-4pWACwaR.js} +15 -21
  370. package/dist/web-vitals-4pWACwaR.js.map +1 -0
  371. package/dist/web-vitals-__X7t4pj.cjs +2 -0
  372. package/dist/web-vitals-__X7t4pj.cjs.map +1 -0
  373. package/dist/worker-protocol-QbvqNazn.cjs +2 -0
  374. package/dist/worker-protocol-QbvqNazn.cjs.map +1 -0
  375. package/dist/{worker-protocol-B0_8rWy5.js → worker-protocol-x074Rpet.js} +14 -11
  376. package/dist/worker-protocol-x074Rpet.js.map +1 -0
  377. package/dist/worker-server-CFe4nvos.cjs +2 -0
  378. package/dist/worker-server-CFe4nvos.cjs.map +1 -0
  379. package/dist/worker-server-iUVSjH8L.js +94 -0
  380. package/dist/worker-server-iUVSjH8L.js.map +1 -0
  381. package/dist/worker-transport-CRAX-09c.cjs +2 -0
  382. package/dist/worker-transport-CRAX-09c.cjs.map +1 -0
  383. package/dist/worker-transport-Dy1KMA7t.js +190 -0
  384. package/dist/worker-transport-Dy1KMA7t.js.map +1 -0
  385. package/llms.txt +397 -0
  386. package/package.json +54 -46
  387. package/dist/bus-D_7pd7RN.cjs +0 -2
  388. package/dist/bus-D_7pd7RN.cjs.map +0 -1
  389. package/dist/bus-ecxUNTja.js.map +0 -1
  390. package/dist/console-CLz_PvFn.cjs +0 -2
  391. package/dist/console-CLz_PvFn.cjs.map +0 -1
  392. package/dist/console-cwgHKXvM.js +0 -82
  393. package/dist/console-cwgHKXvM.js.map +0 -1
  394. package/dist/constants-Bwl_YtQi.js +0 -349
  395. package/dist/constants-Bwl_YtQi.js.map +0 -1
  396. package/dist/constants-DakMxVB2.cjs +0 -2
  397. package/dist/constants-DakMxVB2.cjs.map +0 -1
  398. package/dist/context-storage-BjzeBSxH.cjs +0 -2
  399. package/dist/context-storage-BjzeBSxH.cjs.map +0 -1
  400. package/dist/context-storage-BzkoHzkQ.js +0 -51
  401. package/dist/context-storage-BzkoHzkQ.js.map +0 -1
  402. package/dist/debug-bundle-BOdYmCeV.js +0 -32
  403. package/dist/debug-bundle-BOdYmCeV.js.map +0 -1
  404. package/dist/debug-bundle-Ex4L_LSP.cjs +0 -2
  405. package/dist/debug-bundle-Ex4L_LSP.cjs.map +0 -1
  406. package/dist/emergency-queue-B9WZxanZ.js +0 -67
  407. package/dist/emergency-queue-B9WZxanZ.js.map +0 -1
  408. package/dist/emergency-queue-HBpL5r3V.cjs +0 -2
  409. package/dist/emergency-queue-HBpL5r3V.cjs.map +0 -1
  410. package/dist/errors-D6bwgJtO.js +0 -92
  411. package/dist/errors-D6bwgJtO.js.map +0 -1
  412. package/dist/errors-DCOCRdSi.cjs +0 -3
  413. package/dist/errors-DCOCRdSi.cjs.map +0 -1
  414. package/dist/factory-DLFDjdLv.cjs +0 -2
  415. package/dist/factory-DLFDjdLv.cjs.map +0 -1
  416. package/dist/factory-e9Qo3K0z.js +0 -276
  417. package/dist/factory-e9Qo3K0z.js.map +0 -1
  418. package/dist/guards-Cidk71ME.js +0 -7
  419. package/dist/guards-Cidk71ME.js.map +0 -1
  420. package/dist/guards-nJ70syPt.cjs +0 -2
  421. package/dist/guards-nJ70syPt.cjs.map +0 -1
  422. package/dist/identity-BlvlgjrU.cjs +0 -2
  423. package/dist/identity-BlvlgjrU.cjs.map +0 -1
  424. package/dist/identity-BrQp_5J5.js.map +0 -1
  425. package/dist/indexeddb-storage-CtLvZH1r.cjs +0 -2
  426. package/dist/indexeddb-storage-CtLvZH1r.cjs.map +0 -1
  427. package/dist/indexeddb-storage-DLXQzAGh.js.map +0 -1
  428. package/dist/interactions-B6z2I4tU.js.map +0 -1
  429. package/dist/interactions-P6pz08Jn.cjs +0 -2
  430. package/dist/interactions-P6pz08Jn.cjs.map +0 -1
  431. package/dist/journey-35yCMNFo.js.map +0 -1
  432. package/dist/journey-DAGh5h9k.cjs +0 -2
  433. package/dist/journey-DAGh5h9k.cjs.map +0 -1
  434. package/dist/keys-BHhw_0Wh.cjs +0 -2
  435. package/dist/keys-BHhw_0Wh.cjs.map +0 -1
  436. package/dist/keys-BU9j5YqW.js +0 -16
  437. package/dist/keys-BU9j5YqW.js.map +0 -1
  438. package/dist/lifecycle-BGGOcN4N.cjs +0 -2
  439. package/dist/lifecycle-BGGOcN4N.cjs.map +0 -1
  440. package/dist/lifecycle-CZ6RRXc6.js.map +0 -1
  441. package/dist/log-record-D7bA1RPb.cjs +0 -2
  442. package/dist/log-record-D7bA1RPb.cjs.map +0 -1
  443. package/dist/log-record-DIA6McNr.js.map +0 -1
  444. package/dist/long-frames-430_85Da.js.map +0 -1
  445. package/dist/long-frames-Dd8tsi2U.cjs +0 -2
  446. package/dist/long-frames-Dd8tsi2U.cjs.map +0 -1
  447. package/dist/models/stats.d.ts +0 -11
  448. package/dist/network-C7SkLf4v.js.map +0 -1
  449. package/dist/network-pEX3PAJv.cjs +0 -2
  450. package/dist/network-pEX3PAJv.cjs.map +0 -1
  451. package/dist/profiler-BVWIOgnq.js.map +0 -1
  452. package/dist/profiler-eVCknCzS.cjs +0 -2
  453. package/dist/profiler-eVCknCzS.cjs.map +0 -1
  454. package/dist/profiler-frames-CLXlT_xL.js.map +0 -1
  455. package/dist/profiler-frames-Dg2OebB2.cjs +0 -2
  456. package/dist/profiler-frames-Dg2OebB2.cjs.map +0 -1
  457. package/dist/remote-rules-BJGDJGwA.js +0 -98
  458. package/dist/remote-rules-BJGDJGwA.js.map +0 -1
  459. package/dist/remote-rules-CJD3ToVk.cjs +0 -2
  460. package/dist/remote-rules-CJD3ToVk.cjs.map +0 -1
  461. package/dist/replay-0zAJv9T3.js +0 -338
  462. package/dist/replay-0zAJv9T3.js.map +0 -1
  463. package/dist/replay-DomJpXqW.cjs +0 -2
  464. package/dist/replay-DomJpXqW.cjs.map +0 -1
  465. package/dist/reports-BsbqmP8h.cjs +0 -2
  466. package/dist/reports-BsbqmP8h.cjs.map +0 -1
  467. package/dist/reports-BuXekPOS.js.map +0 -1
  468. package/dist/resource-timing-CXGHwFRD.js.map +0 -1
  469. package/dist/resource-timing-DkycFGDa.cjs +0 -2
  470. package/dist/resource-timing-DkycFGDa.cjs.map +0 -1
  471. package/dist/sampling-Dd0wllyq.cjs +0 -2
  472. package/dist/sampling-Dd0wllyq.cjs.map +0 -1
  473. package/dist/sampling-UUDbi3K0.js +0 -60
  474. package/dist/sampling-UUDbi3K0.js.map +0 -1
  475. package/dist/sanitize-CNmsD9r3.js.map +0 -1
  476. package/dist/sanitize-ChLn97Ch.cjs.map +0 -1
  477. package/dist/select-CTk-K5mG.cjs +0 -3
  478. package/dist/select-CTk-K5mG.cjs.map +0 -1
  479. package/dist/select-DPv_j6wq.js +0 -270
  480. package/dist/select-DPv_j6wq.js.map +0 -1
  481. package/dist/sender-15zEsZpr.js +0 -857
  482. package/dist/sender-15zEsZpr.js.map +0 -1
  483. package/dist/sender-Bfpv9tad.cjs +0 -2
  484. package/dist/sender-Bfpv9tad.cjs.map +0 -1
  485. package/dist/storage-BA9RqRO-.cjs +0 -2
  486. package/dist/storage-BA9RqRO-.cjs.map +0 -1
  487. package/dist/storage-DZwed89z.js +0 -16
  488. package/dist/storage-DZwed89z.js.map +0 -1
  489. package/dist/storm-BTSNTIWI.js +0 -9
  490. package/dist/storm-BTSNTIWI.js.map +0 -1
  491. package/dist/storm-D0_qZOEg.cjs +0 -2
  492. package/dist/storm-D0_qZOEg.cjs.map +0 -1
  493. package/dist/unclean-exit-ClGzrc2A.cjs +0 -2
  494. package/dist/unclean-exit-ClGzrc2A.cjs.map +0 -1
  495. package/dist/unclean-exit-Cob_jyTv.js.map +0 -1
  496. package/dist/user-timing-CdYqx3PF.cjs +0 -2
  497. package/dist/user-timing-CdYqx3PF.cjs.map +0 -1
  498. package/dist/user-timing-DgHubxCI.js.map +0 -1
  499. package/dist/utils/timer.d.ts +0 -19
  500. package/dist/web-socket-BTuvYoJI.cjs +0 -2
  501. package/dist/web-socket-BTuvYoJI.cjs.map +0 -1
  502. package/dist/web-vitals-Ch5BpDmo.cjs +0 -2
  503. package/dist/web-vitals-Ch5BpDmo.cjs.map +0 -1
  504. package/dist/web-vitals-CsGCWnUr.js.map +0 -1
  505. package/dist/worker-protocol-B0_8rWy5.js.map +0 -1
  506. package/dist/worker-protocol-BjzFORfq.cjs +0 -2
  507. package/dist/worker-protocol-BjzFORfq.cjs.map +0 -1
  508. package/dist/worker-server-4en-Lt-3.cjs +0 -2
  509. package/dist/worker-server-4en-Lt-3.cjs.map +0 -1
  510. package/dist/worker-server-Cne9MX9I.js +0 -83
  511. package/dist/worker-server-Cne9MX9I.js.map +0 -1
  512. package/dist/worker-transport-B-GF4Aqn.cjs +0 -2
  513. package/dist/worker-transport-B-GF4Aqn.cjs.map +0 -1
  514. package/dist/worker-transport-C3SjJAEC.js +0 -200
  515. package/dist/worker-transport-C3SjJAEC.js.map +0 -1
@@ -1,2 +0,0 @@
1
- const e=require("./constants-DakMxVB2.cjs"),t=require("./library-request-Da-CHKzT.cjs"),n=require("./unref-CU9Nyz_9.cjs"),r=require("./compression-lD9abCcO.cjs"),i=require("./deadline-CUGbto-y.cjs"),a=require("./storm-D0_qZOEg.cjs"),o=require("./types-C7WNpnG1.cjs");var s=4,c=3,l=class{maxBytes;parts=[];sizes=[];total=0;starved=!1;lost=0;constructor(e){this.maxBytes=e}add(e,t,n){let r=n&&t===s;if(this.starved&&!r)return this.lost++,!1;(r||this.parts.length===0)&&(this.starved=!1,this.parts.push([]),this.sizes.push(0),this.parts.length>c&&this.dropOldest());let i=this.parts.length-1;this.parts[i].push(e),this.sizes[i]+=e.length,this.total+=e.length;let a=this.maxBytes();for(;this.total>a&&this.parts.length>0;)this.starved=this.parts.length===1,this.lost+=this.dropOldest();return this.starved}take(){let e=this.parts.flat();return this.clear(),e}clear(){this.parts=[],this.sizes=[],this.total=0,this.starved=!1}takeLost(){let{lost:e}=this;return this.lost=0,e}dropOldest(){let[e]=this.parts.splice(0,1),[t]=this.sizes.splice(0,1);return this.total-=t,e.length}},u=[401,403],d=`Error`,f=429,p=500,m=class{config;diagnostics;open=[];openBytes=0;flushTimer;queue=[];queueBytes=0;busy=!1;retryTimer;ids;sequence=0;generation=0;inFlight;constructor(e,t){this.config=e,this.diagnostics=t}begin(e){e.replayId!==this.ids?.replayId&&(this.sequence=0),this.ids=e}push(e){let{batchSize:t,batchBytes:r,flushIntervalMs:i}=this.config().replay;for(let n of e)this.open.length>0&&this.openBytes+n.length>r&&this.flush(),this.open.push(n),this.openBytes+=n.length,(this.open.length>=t||this.openBytes>=r)&&this.flush();this.open.length>0&&this.flushTimer===void 0&&(this.flushTimer=setTimeout(()=>{this.flushTimer=void 0,this.flush()},i),n.t(this.flushTimer))}flush(){clearTimeout(this.flushTimer),this.flushTimer=void 0;let{ids:e}=this;if(this.open.length===0||!e)return;let t=`[${this.open.join(`,`)}]`,n={"replay.id":e.replayId,"session.id":e.sessionId,"tab.id":e.tabId,"service.name":this.config().serviceName,sequence:this.sequence++,events:this.open.length,bytes:t.length,payload:t};this.open=[],this.openBytes=0,this.queue.push(n),this.queueBytes+=n.bytes;let r=0;for(;this.queueBytes>this.config().replay.maxQueueBytes&&this.queue.length>1;){let[e]=this.queue.splice(0,1);this.queueBytes-=e.bytes,r++}r>0&&this.diagnostics.report(`transport.dropped_permanent`,`The replay queue is above replay.maxQueueBytes. The library dropped ${String(r)} segments.`),this.drain()}stop(){this.generation++,this.inFlight?.abort(),this.inFlight=void 0,clearTimeout(this.flushTimer),clearTimeout(this.retryTimer),this.flushTimer=void 0,this.retryTimer=void 0,this.open=[],this.openBytes=0,this.queue=[],this.queueBytes=0,this.busy=!1}drain(){if(this.busy||this.queue.length===0)return;let[e]=this.queue.splice(0,1);this.queueBytes-=e.bytes,this.busy=!0,this.deliver(e,1,this.generation)}async deliver(e,t,r){let i=await this.send(e,t,r);if(r!==this.generation)return;let{replay:a,delivery:o}=this.config();if(i===`retry`&&t<a.maxAttempts){let i=Math.min(o.retryBaseDelayMs*2**(t-1),o.retryMaxDelayMs);this.retryTimer=setTimeout(()=>{this.retryTimer=void 0,this.deliver(e,t+1,r)},i),n.t(this.retryTimer)}else i!==`sent`&&this.diagnostics.report(`transport.dropped_permanent`,`The library dropped the replay segment ${String(e.sequence)} after ${String(t)} attempts.`,{"replay.id":e[`replay.id`],sequence:e.sequence}),this.busy=!1,this.drain()}async send(a,o,s){let c=this.config(),{onSegment:l,endpoint:m,headers:h}=c.replay,g=c.delivery.requestTimeoutMs;if(l)try{return await i.n(Promise.resolve(l(a)),g),`sent`}catch(e){return this.diagnostics.report(`capture.record_failed`,`The replay.onSegment function threw an error, or it did not end in ${String(g)} ms.`,void 0,e),`drop`}let _=new AbortController,v=setTimeout(()=>{_.abort()},g);n.t(v);try{let n=typeof h==`function`?await i.n(Promise.resolve(h()),g):h,l=new Headers(n??{});l.set(e.lt,e.R),l.set(e.st,`${a[`replay.id`]}-${String(a.sequence)}`),l.set(e.ot,String(o-1));let{payload:d,events:v,...y}=a,b=`${JSON.stringify(y).slice(0,-1)},"events":${d}}`,x=b;if(c.compression===`gzip`&&b.length>=1024){let t=await r.t(b);t&&(x=t,l.set(e.ct,e.tt))}if(s!==this.generation)return`drop`;this.inFlight=_;let S=await t.r(()=>fetch(m,{method:`POST`,headers:l,body:x,credentials:c.credentials,cache:`no-store`,signal:_.signal}));return S.ok?`sent`:(this.diagnostics.report(`transport.http_error`,`The replay endpoint returned ${String(S.status)}.`),u.includes(S.status)||S.status===f||S.status>=p?`retry`:`drop`)}catch(e){return this.diagnostics.report(`transport.http_error`,`The replay request failed with ${e instanceof Error?e.name:d}.`),`retry`}finally{clearTimeout(v),this.inFlight=void 0}}},h=`session.id`,g=`tab.id`,_=`*`,v=[`sampling`,`slimDOMOptions`,`ignoreClass`,`ignoreSelector`,`ignoreCSSAttributes`,`userTriggeredOnInput`,`recordAfter`,`inlineStylesheet`,`dataURLOptions`],y={input:!0,textarea:!0,select:!0},b=`********`,x=4,S=3,C=0,w=3,T=class{ctx;name=`replay`;buffer;uploader;window={start:0,count:0};record;stopRecorder;replayId=``;installed=!1;starting=!1;generation=0;live=!1;starvedReported=!1;liveTimer;constructor(e){this.ctx=e,this.buffer=new l(()=>this.ctx.config.replay.maxBufferBytes),this.uploader=new m(()=>this.ctx.config,this.ctx.diagnostics)}install(){this.installed||(this.installed=!0,this.ctx.onError?.(this.onError),(this.ctx.replayConsent?.()??!this.ctx.config.replay.requireConsent)&&this.start())}uninstall(){this.installed=!1,this.ctx.onError?.(void 0),this.stop()}async start(){let{diagnostics:t}=this.ctx,{loader:n,endpoint:r,onSegment:i,plugins:a}=this.ctx.config.replay;if(!this.installed||this.record||this.starting)return;if(typeof document>`u`){this.reportOnce(`This context has no document. The session replay is off.`);return}if(!n||r===``&&!i){t.report(`config.invalid`,`The session replay needs replay.loader, and replay.endpoint or replay.onSegment. The session replay is off.`);return}let o=this.selectors();if(!o)return;let{generation:s}=this;this.starting=!0;let c=await t.guardAsync(`capture.install_failed`,`The library could not load the replay recorder.`,n),l={transformRequest:this.transformRequest},u=await Promise.all(a.map(e=>t.guardAsync(`capture.install_failed`,`The library could not load a replay plugin.`,()=>Promise.resolve(e(l)))));if(s!==this.generation||(this.starting=!1,!c))return;let{record:d}=c;if(typeof d!=`function`){t.report(`capture.install_failed`,`The replay loader gave no record function. The session replay is off.`);return}let f=this.ctx.config.replay;t.guard(`capture.install_failed`,`The replay recorder did not start.`,()=>{let n={},r=[];for(let[e,t]of Object.entries(f.recordOptions))v.includes(e)?n[e]=t:r.push(e);r.length>0&&t.report(`config.invalid`,`The library ignores these keys of replay.recordOptions: ${r.join(`, `)}. It sets the mask, block, canvas, plugin and event options itself.`);let i=d({...n,emit:this.emit,checkoutEveryNms:f.bufferMs/2,maskAllInputs:!1,maskInputOptions:f.maskInputs?y:{password:!0},maskInputFn:this.maskInput,maskTextSelector:o.mask,maskTextFn:this.maskText,blockSelector:o.block,recordCanvas:f.recordCanvas,errorHandler:this.onFault,plugins:u.filter(e=>e!==void 0)});typeof i==`function`?(this.stopRecorder=i,this.record=d,this.starvedReported=!1,this.replayId=crypto.randomUUID(),this.ctx.setContext?.(e.on,this.replayId)):t.report(`capture.install_failed`,`The replay recorder did not start.`)})}reset(){let e=this.record!==void 0||this.starting;this.stop(),e&&this.start()}stop(){let{stopRecorder:t}=this;this.generation++,this.starting=!1,this.record=void 0,this.stopRecorder=void 0,this.live=!1,clearTimeout(this.liveTimer),this.liveTimer=void 0,this.buffer.clear(),this.uploader.stop(),t&&(this.ctx.setContext?.(e.on,void 0),this.ctx.diagnostics.guard(`capture.install_failed`,`The replay recorder did not stop.`,t))}selectors(){let{maskText:e,maskSelectors:t,blockSelectors:n}=this.ctx.config.replay;for(let e of[...t,...n])try{document.createDocumentFragment().querySelector(e)}catch(t){this.ctx.diagnostics.report(`config.invalid`,`The replay selector ${e} is not a valid CSS selector. The session replay is off.`,void 0,t);return}let r=e=>e.length>0?e.join(`,`):void 0;return{mask:e?`*`:r(t),block:r(n)}}maskText=(e,t)=>{let{maskText:n,maskSelectors:r}=this.ctx.config.replay,i=r.length>0&&t?.closest(r.join(`,`));return n&&!i&&t?.closest(`[data-observability-unmask]`)?e:e.replace(/\S/g,_)};maskInput=e=>e===``?``:b;scrub(e){let{data:t}=e;if(t){if(e.type===x)typeof t.href==`string`&&!this.ctx.config.capture.fullUrls&&(t.href=t.href.split(/[?#]/)[0]);else if(e.type===S&&t.source===C){for(let e of t.texts??[])e.value=this.shadowText(e.value,e.id);for(let e of t.adds??[])e.node?.type===w&&(e.node={...e.node,textContent:this.shadowText(e.node.textContent,e.node.id)})}}}shadowText(e,t){let n=this.record?.mirror?.getNode(t);if(typeof e!=`string`||!n||n.parentElement)return e;let{maskText:r,maskSelectors:i}=this.ctx.config.replay,a=n.parentNode?.host??null;return r?this.maskText(e,a):i.length>0&&a?.closest(i.join(`,`))?e.replace(/\S/g,_):e}transformRequest=e=>{try{let{capture:n}=this.ctx.config,r=e.name;return t.t()||o.t(r,n.ignoreUrls)?void 0:n.fullUrls?e:{...e,name:r.split(/[?#]/)[0]}}catch(e){this.onFault(e);return}};emit=(e,t)=>{try{this.scrub(e);let n=JSON.stringify(e);if(this.live){this.uploader.push([n]);return}this.buffer.add(n,e.type,t===!0)&&!this.starvedReported&&(this.starvedReported=!0,this.ctx.diagnostics.report(`capture.rate_limited`,`One part of the replay is above replay.maxBufferBytes. The buffer is empty until the next full snapshot. Raise the limit, or block a large element with replay.blockSelectors.`))}catch(e){this.onFault(e)}};onFault=e=>{this.ctx.diagnostics.report(`capture.record_failed`,`The replay recorder had an error.`,void 0,e)};onError=e=>{let{diagnostics:t,config:r}=this.ctx;t.guard(`capture.record_failed`,`The replay upload did not start.`,()=>{if(!this.record)return;let{afterErrorMs:i,uploadsPerWindow:o}=r.replay;if(this.live||!a.t(this.window,o,t,`replay uploads`,r.capturePolicy.windowMs))return;let s=this.buffer.takeLost();s>0&&t.report(`capture.rate_limited`,`The replay buffer was above replay.maxBufferBytes. The library dropped ${String(s)} events.`);let c=this.buffer.take(),{takeFullSnapshot:l}=this.record;(c.length!==0||l)&&(this.uploader.begin({replayId:this.replayId,sessionId:String(e.resource[h]),tabId:String(e.resource[g])}),this.live=!0,c.length===0?this.record.takeFullSnapshot?.(!0):this.uploader.push(c),this.liveTimer=setTimeout(this.endLive,i),n.t(this.liveTimer))})};endLive=()=>{this.liveTimer=void 0,this.live=!1,this.uploader.flush(),this.ctx.diagnostics.guard(`capture.record_failed`,`The replay recorder did not take a full snapshot.`,()=>{this.record?.takeFullSnapshot?.(!0)})};reportOnce(e){let{once:t}=this.ctx;t.replay||(t.replay=!0,this.ctx.diagnostics.report(`capture.install_failed`,e))}};exports.ReplayCapture=T;
2
- //# sourceMappingURL=replay-DomJpXqW.cjs.map
@@ -1 +0,0 @@
1
- {"version":3,"file":"replay-DomJpXqW.cjs","names":["META_EVENT","withDeadline","HEADER_CONTENT_TYPE","CONTENT_TYPE_JSON","HEADER_BATCH_ID","HEADER_ATTEMPT","gzip","HEADER_CONTENT_ENCODING","ENCODING_GZIP","runAsLibraryRequest","REPLAY_ID_KEY","isLibraryRequest","matchesAny","allowInWindow","require_constants","require_library_request","require_unref","require_compression","require_deadline","require_storm","require_types","META_EVENT$1","KEPT_PARTS","ReplayBuffer","maxBytes","opens","isCheckout","type","last","text","limit","texts","lost","part","size","CREDENTIAL_STATUSES","UNKNOWN_ERROR","STATUS_TOO_MANY","STATUS_SERVER_FAULT","ReplayUploader","config","diagnostics","ids","batchBytes","batchSize","flushIntervalMs","payload","segment","dropped","oldest","result","attempt","generation","replay","wait","delivery","source","timeoutMs","onSegment","error","controller","timer","given","headers","_count","head","body","zipped","response","endpoint","SESSION_ID","TAB_ID","MASK_CHARACTER","RECORD_OPTION_KEYS","MASK_EACH_INPUT","MASKED_INPUT","META_EVENT","INCREMENTAL_EVENT","MUTATION_SOURCE","TEXT_NODE","ReplayCapture","ctx","loader","selectors","loaded","tools","made","plugins","make","record","extra","ignored","key","value","stopRecorder","plugin","running","selector","maskSelectors","blockSelectors","join","list","maskText","forced","element","event","data","change","add","node","id","host","url","request","capture","uploadsPerWindow","takeFullSnapshot","afterErrorMs","once","message"],"sources":["../src/capture/replay-buffer.ts","../src/capture/replay-upload.ts","../src/capture/replay.ts"],"sourcesContent":["// src/capture/replay-buffer.ts\n//\n// Keeps the recent session replay events in memory as JSON text. Events are grouped into\n// parts, and every part starts with a full snapshot, so a player can start from any of them.\n\n/** Event type of the meta event. The recorder sends it right before a full snapshot. */\nconst META_EVENT = 4;\n\n/** How many parts we keep. With a snapshot every half window, 3 parts cover a full window. */\nconst KEPT_PARTS = 3;\n\n/** Size-limited ring of recent replay events. */\nexport class ReplayBuffer {\n /** Events per part, as JSON text. The last part is the open one. */\n private parts: string[][] = [];\n\n /** Size of each part: the sum of its text lengths. */\n private sizes: number[] = [];\n\n /** Size of all parts together. */\n private total = 0;\n\n /**\n * True after the buffer had to drop its only part. Everything up to the next full snapshot\n * has no snapshot in front of it, which makes it useless to a player.\n */\n private starved = false;\n\n /** Events dropped by the size limit since this was last read. */\n private lost = 0;\n\n /**\n * @param maxBytes Returns the size limit for all parts together.\n */\n constructor(private readonly maxBytes: () => number) {}\n\n /**\n * Adds one event.\n * @param text The event as JSON text.\n * @param type The recorder's event type.\n * @param isCheckout True for the events of a new full snapshot.\n * @returns True if this event made the buffer drop its only part.\n */\n add(text: string, type: number, isCheckout: boolean): boolean {\n // The meta event and the snapshot both carry the flag, but only the meta event opens a part.\n const opens = isCheckout && type === META_EVENT;\n\n if (this.starved && !opens) {\n this.lost++;\n return false;\n }\n\n if (opens || this.parts.length === 0) {\n this.starved = false;\n this.parts.push([]);\n this.sizes.push(0);\n\n if (this.parts.length > KEPT_PARTS) {\n this.dropOldest();\n }\n }\n\n const last = this.parts.length - 1;\n this.parts[last].push(text);\n this.sizes[last] += text.length;\n this.total += text.length;\n\n const limit = this.maxBytes();\n while (this.total > limit && this.parts.length > 0) {\n // Nothing with a snapshot comes after the last part, so once it goes the events that\n // follow can't be played.\n this.starved = this.parts.length === 1;\n this.lost += this.dropOldest();\n }\n\n return this.starved;\n }\n\n /**\n * Returns every event in order and empties the buffer.\n * @returns The events as JSON text.\n */\n take(): string[] {\n const texts = this.parts.flat();\n this.clear();\n return texts;\n }\n\n /** Empties the buffer. */\n clear(): void {\n this.parts = [];\n this.sizes = [];\n this.total = 0;\n this.starved = false;\n }\n\n /**\n * Returns how many events the size limit dropped, and resets the count.\n * @returns The number of dropped events.\n */\n takeLost(): number {\n const { lost } = this;\n this.lost = 0;\n return lost;\n }\n\n /**\n * Removes the oldest part.\n * @returns The number of events in that part.\n */\n private dropOldest(): number {\n const [part] = this.parts.splice(0, 1);\n const [size] = this.sizes.splice(0, 1);\n this.total -= size;\n return part.length;\n }\n}\n","// src/capture/replay-upload.ts\n//\n// Cuts session replay events into segments and sends them. A segment closes on an event count,\n// on a size, or after a wait. Only one segment is in flight at a time, which keeps them in\n// order. Segments live in memory only, and the exit flush doesn't send them.\n\nimport {\n COMPRESSION_THRESHOLD_BYTES,\n CONTENT_TYPE_JSON,\n ENCODING_GZIP,\n HEADER_ATTEMPT,\n HEADER_BATCH_ID,\n HEADER_CONTENT_ENCODING,\n HEADER_CONTENT_TYPE,\n} from \"../constants\";\nimport type { Diagnostics } from \"../core/diagnostics\";\nimport type { ResolvedConfig } from \"../models/config\";\nimport type { ReplaySegment } from \"../models/replay\";\nimport { gzip } from \"../transport/compression\";\nimport { withDeadline } from \"../utils/deadline\";\nimport { runAsLibraryRequest } from \"../utils/library-request\";\nimport { unrefTimer } from \"../utils/unref\";\n\n/** The ids stamped on every segment of a recording. */\nexport interface ReplayIds {\n /** Recording id. */\n replayId: string;\n /** Session id from the record that triggered the upload. */\n sessionId: string;\n /** Tab id from the record that triggered the upload. */\n tabId: string;\n}\n\n/** Outcome of one send. `retry` means a later attempt might work. */\ntype SendResult = \"sent\" | \"retry\" | \"drop\";\n\n/** Statuses that mean our credentials were rejected. The next attempt re-reads the headers. */\nconst CREDENTIAL_STATUSES = [401, 403];\n\n/** Name used for a thrown value that isn't an Error. Reports only ever show the error name. */\nconst UNKNOWN_ERROR = \"Error\";\n\n/** The server is asking us to slow down. */\nconst STATUS_TOO_MANY = 429;\n\n/** Server faults start here. */\nconst STATUS_SERVER_FAULT = 500;\n\n/** Cuts replay events into segments and sends them in order. */\nexport class ReplayUploader {\n /** Events in the open segment, as JSON text. */\n private open: string[] = [];\n\n /** Size of the open segment. */\n private openBytes = 0;\n\n /** Closes a segment that didn't fill up in time. */\n private flushTimer: ReturnType<typeof setTimeout> | undefined;\n\n /** Closed segments waiting to be sent. The one in flight isn't in here. */\n private queue: ReplaySegment[] = [];\n\n /** Total size of the queued segments. */\n private queueBytes = 0;\n\n /** True while a segment is in flight or waiting for its next attempt. */\n private busy = false;\n\n /** Timer for the in-flight segment's next attempt. */\n private retryTimer: ReturnType<typeof setTimeout> | undefined;\n\n /** Ids for the segments we cut next. */\n private ids: ReplayIds | undefined;\n\n /** Sequence number for the recording's next segment. */\n private sequence = 0;\n\n /** Bumped on every stop, so a send that finishes after a stop changes nothing. */\n private generation = 0;\n\n /** Aborts the request in flight. Once stopped, the uploader must not send anything else. */\n private inFlight: AbortController | undefined;\n\n /**\n * @param config Returns the current configuration.\n * @param diagnostics Diagnostics reporter.\n */\n constructor(\n private readonly config: () => ResolvedConfig,\n private readonly diagnostics: Diagnostics,\n ) {}\n\n /**\n * Sets the ids for the segments that follow. A new recording restarts the sequence at 0.\n * @param ids Ids of the recording and of the record that triggered the upload.\n */\n begin(ids: ReplayIds): void {\n if (ids.replayId !== this.ids?.replayId) {\n this.sequence = 0;\n }\n\n this.ids = ids;\n }\n\n /**\n * Adds events. A full segment closes right away, a partial one closes after the wait.\n * @param texts The events as JSON text, in order.\n */\n push(texts: readonly string[]): void {\n const { batchSize, batchBytes, flushIntervalMs } = this.config().replay;\n\n for (const text of texts) {\n // If this event doesn't fit, close the segment first. A huge event ends up in its own.\n if (this.open.length > 0 && this.openBytes + text.length > batchBytes) {\n this.flush();\n }\n\n this.open.push(text);\n this.openBytes += text.length;\n\n if (this.open.length >= batchSize || this.openBytes >= batchBytes) {\n this.flush();\n }\n }\n\n if (this.open.length > 0 && this.flushTimer === undefined) {\n this.flushTimer = setTimeout(() => {\n this.flushTimer = undefined;\n this.flush();\n }, flushIntervalMs);\n unrefTimer(this.flushTimer);\n }\n }\n\n /** Closes the open segment and gets it sent. */\n flush(): void {\n clearTimeout(this.flushTimer);\n this.flushTimer = undefined;\n\n const { ids } = this;\n if (this.open.length === 0 || !ids) {\n return;\n }\n\n const payload = `[${this.open.join(\",\")}]`;\n const segment: ReplaySegment = {\n \"replay.id\": ids.replayId,\n \"session.id\": ids.sessionId,\n \"tab.id\": ids.tabId,\n \"service.name\": this.config().serviceName,\n sequence: this.sequence++,\n events: this.open.length,\n bytes: payload.length,\n payload,\n };\n this.open = [];\n this.openBytes = 0;\n this.queue.push(segment);\n this.queueBytes += segment.bytes;\n\n let dropped = 0;\n while (this.queueBytes > this.config().replay.maxQueueBytes && this.queue.length > 1) {\n const [oldest] = this.queue.splice(0, 1);\n this.queueBytes -= oldest.bytes;\n dropped++;\n }\n\n if (dropped > 0) {\n this.diagnostics.report(\n \"transport.dropped_permanent\",\n `The replay queue is above replay.maxQueueBytes. The library dropped ${String(dropped)} segments.`,\n );\n }\n\n this.drain();\n }\n\n /** Drops everything that is waiting. A send still in flight no longer changes any state. */\n stop(): void {\n this.generation++;\n this.inFlight?.abort();\n this.inFlight = undefined;\n clearTimeout(this.flushTimer);\n clearTimeout(this.retryTimer);\n this.flushTimer = undefined;\n this.retryTimer = undefined;\n this.open = [];\n this.openBytes = 0;\n this.queue = [];\n this.queueBytes = 0;\n this.busy = false;\n }\n\n /** Sends the next segment, unless one is already in flight. */\n private drain(): void {\n if (this.busy || this.queue.length === 0) {\n return;\n }\n\n const [segment] = this.queue.splice(0, 1);\n this.queueBytes -= segment.bytes;\n this.busy = true;\n void this.deliver(segment, 1, this.generation);\n }\n\n /**\n * Sends one segment, backing off before each retry.\n * @param segment The segment to send.\n * @param attempt Attempt number, starting at 1.\n * @param generation The uploader's generation when the send started.\n */\n private async deliver(\n segment: ReplaySegment,\n attempt: number,\n generation: number,\n ): Promise<void> {\n const result = await this.send(segment, attempt, generation);\n\n if (generation !== this.generation) {\n return;\n }\n\n const { replay, delivery } = this.config();\n if (result === \"retry\" && attempt < replay.maxAttempts) {\n const wait = Math.min(\n delivery.retryBaseDelayMs * 2 ** (attempt - 1),\n delivery.retryMaxDelayMs,\n );\n this.retryTimer = setTimeout(() => {\n this.retryTimer = undefined;\n void this.deliver(segment, attempt + 1, generation);\n }, wait);\n unrefTimer(this.retryTimer);\n return;\n }\n\n if (result !== \"sent\") {\n this.diagnostics.report(\n \"transport.dropped_permanent\",\n `The library dropped the replay segment ${String(segment.sequence)} after ${String(attempt)} attempts.`,\n { \"replay.id\": segment[\"replay.id\"], sequence: segment.sequence },\n );\n }\n\n this.busy = false;\n this.drain();\n }\n\n /**\n * Hands a segment to the app's onSegment function, or posts it to the endpoint. Never throws.\n * @param segment The segment to send.\n * @param attempt Attempt number, starting at 1.\n * @param generation The uploader's generation when the send started.\n * @returns How the send went.\n */\n private async send(\n segment: ReplaySegment,\n attempt: number,\n generation: number,\n ): Promise<SendResult> {\n const config = this.config();\n const { onSegment, endpoint, headers: source } = config.replay;\n const timeoutMs = config.delivery.requestTimeoutMs;\n\n if (onSegment) {\n try {\n // Don't let a callback that never settles block the uploader forever.\n await withDeadline(Promise.resolve(onSegment(segment)), timeoutMs);\n return \"sent\";\n } catch (error) {\n this.diagnostics.report(\n \"capture.record_failed\",\n `The replay.onSegment function threw an error, or it did not end in ${String(timeoutMs)} ms.`,\n undefined,\n error,\n );\n return \"drop\";\n }\n }\n\n const controller = new AbortController();\n const timer = setTimeout(() => {\n controller.abort();\n }, timeoutMs);\n unrefTimer(timer);\n\n try {\n // The replay endpoint only gets replay.headers. The log endpoint's headers may carry a\n // token meant for a different host.\n const given =\n typeof source === \"function\"\n ? await withDeadline(Promise.resolve(source()), timeoutMs)\n : source;\n const headers = new Headers(given ?? {});\n headers.set(HEADER_CONTENT_TYPE, CONTENT_TYPE_JSON);\n headers.set(HEADER_BATCH_ID, `${segment[\"replay.id\"]}-${String(segment.sequence)}`);\n headers.set(HEADER_ATTEMPT, String(attempt - 1));\n\n // In the body \"events\" is the event list itself. Its length is the count.\n const { payload, events: _count, ...head } = segment;\n const text = `${JSON.stringify(head).slice(0, -1)},\"events\":${payload}}`;\n let body: string | Uint8Array<ArrayBuffer> = text;\n\n if (config.compression === ENCODING_GZIP && text.length >= COMPRESSION_THRESHOLD_BYTES) {\n const zipped = await gzip(text);\n\n if (zipped) {\n body = zipped;\n headers.set(HEADER_CONTENT_ENCODING, ENCODING_GZIP);\n }\n }\n\n // If we were stopped during the awaits above, send nothing.\n if (generation !== this.generation) {\n return \"drop\";\n }\n\n this.inFlight = controller;\n\n // Network capture skips requests started in this scope. The replay endpoint is also in\n // capture.ignoreUrls, in case some wrapper starts the request later.\n const response = await runAsLibraryRequest(() =>\n fetch(endpoint, {\n method: \"POST\",\n headers,\n body,\n credentials: config.credentials,\n cache: \"no-store\",\n signal: controller.signal,\n }),\n );\n\n if (response.ok) {\n return \"sent\";\n }\n\n this.diagnostics.report(\n \"transport.http_error\",\n `The replay endpoint returned ${String(response.status)}.`,\n );\n\n return CREDENTIAL_STATUSES.includes(response.status) ||\n response.status === STATUS_TOO_MANY ||\n response.status >= STATUS_SERVER_FAULT\n ? \"retry\"\n : \"drop\";\n } catch (error) {\n // A request error's message can contain the URL, and a URL can contain a credential.\n this.diagnostics.report(\n \"transport.http_error\",\n `The replay request failed with ${error instanceof Error ? error.name : UNKNOWN_ERROR}.`,\n );\n return \"retry\";\n } finally {\n clearTimeout(timer);\n this.inFlight = undefined;\n }\n }\n}\n","// src/capture/replay.ts\n//\n// Session replay. The app's recorder package records the DOM, and this capture keeps the recent\n// events in memory. When an ERROR or FATAL record comes through, it uploads the buffer plus a\n// few seconds of what happens next. All text and input values are masked by default.\n\nimport { REPLAY_ID_KEY, REPLAY_UNMASK_ATTRIBUTE } from \"../constants\";\nimport type { LogRecord } from \"../models/log-record\";\nimport type { ReplayEvent, ReplayPluginTools, ReplayRecord } from \"../models/replay\";\nimport { isLibraryRequest } from \"../utils/library-request\";\nimport { unrefTimer } from \"../utils/unref\";\nimport { ReplayBuffer } from \"./replay-buffer\";\nimport { ReplayUploader } from \"./replay-upload\";\nimport { allowInWindow, type StormWindow } from \"./storm\";\nimport { type Capture, type CaptureContext, matchesAny } from \"./types\";\n\n/** Resource attribute for the session id. */\nconst SESSION_ID = \"session.id\";\n\n/** Resource attribute for the tab id. */\nconst TAB_ID = \"tab.id\";\n\n/** Every non-space character of masked text becomes this. */\nconst MASK_CHARACTER = \"*\";\n\n/**\n * The replay.recordOptions keys we pass through to the recorder. Everything else the recorder\n * accepts is a mask, block, canvas, plugin or event option, and those are ours to set.\n */\nconst RECORD_OPTION_KEYS = [\n \"sampling\",\n \"slimDOMOptions\",\n \"ignoreClass\",\n \"ignoreSelector\",\n \"ignoreCSSAttributes\",\n \"userTriggeredOnInput\",\n \"recordAfter\",\n \"inlineStylesheet\",\n \"dataURLOptions\",\n];\n\n/**\n * Per-element input mask for the recorder. We don't use its \"mask all inputs\" switch because\n * that list leaves out hidden and file inputs.\n */\nconst MASK_EACH_INPUT = { input: true, textarea: true, select: true };\n\n/** What every masked input value turns into. Fixed length, so it doesn't give away a PIN's. */\nconst MASKED_INPUT = \"********\";\n\n/** Event type of the meta event, which carries the page URL. */\nconst META_EVENT = 4;\n\n/** Event type of an incremental snapshot. */\nconst INCREMENTAL_EVENT = 3;\n\n/** Incremental snapshot source for DOM mutations. */\nconst MUTATION_SOURCE = 0;\n\n/** Node type of a text node in the recorder's serialized nodes. */\nconst TEXT_NODE = 3;\n\n/** The bits of a recorder event we rewrite before keeping it. */\ninterface ScrubData {\n /** Page URL, on a meta event. */\n href?: unknown;\n /** Source of an incremental snapshot. */\n source?: unknown;\n /** Text changes in a mutation. */\n texts?: { id: number; value: unknown }[];\n /** Nodes added by a mutation. */\n adds?: { node?: { id: number; type: number; textContent?: unknown } }[];\n}\n\n/** Records the DOM and uploads the recent events after an error. */\nexport class ReplayCapture implements Capture {\n /** Capture module identifier. */\n readonly name = \"replay\";\n\n /** Recent events. An upload empties it. */\n private readonly buffer: ReplayBuffer;\n\n /** Cuts the events into segments and sends them. */\n private readonly uploader: ReplayUploader;\n\n /** Upload rate limit, so an error storm doesn't upload the page over and over. */\n private readonly window: StormWindow = { start: 0, count: 0 };\n\n /** The recorder's record function. Undefined while the recorder isn't running. */\n private record: ReplayRecord | undefined;\n\n /** Stops the recorder. */\n private stopRecorder: (() => void) | undefined;\n\n /** Id of the current recording. */\n private replayId = \"\";\n\n /** True between install() and uninstall(). */\n private installed = false;\n\n /** True while start() is loading the recorder. */\n private starting = false;\n\n /** Bumped on every stop, so a start that finishes after a stop records nothing. */\n private generation = 0;\n\n /** True right after an error, while new events go straight to the uploader. */\n private live = false;\n\n /** True once we've reported a full snapshot that doesn't fit in the buffer. */\n private starvedReported = false;\n\n /** Ends the live period after an error. */\n private liveTimer: ReturnType<typeof setTimeout> | undefined;\n\n /**\n * @param ctx Capture context: configuration, diagnostics and the runtime hooks.\n */\n constructor(private readonly ctx: CaptureContext) {\n this.buffer = new ReplayBuffer(() => this.ctx.config.replay.maxBufferBytes);\n this.uploader = new ReplayUploader(() => this.ctx.config, this.ctx.diagnostics);\n }\n\n /** Starts listening for error records, and starts the recorder unless consent is still needed. */\n install(): void {\n if (this.installed) {\n return;\n }\n\n this.installed = true;\n this.ctx.onError?.(this.onError);\n\n // If the app called stopReplay(), that still holds after the captures are reinstalled.\n if (this.ctx.replayConsent?.() ?? !this.ctx.config.replay.requireConsent) {\n void this.start();\n }\n }\n\n /** Stops the recorder and drops whatever hasn't been sent. */\n uninstall(): void {\n this.installed = false;\n this.ctx.onError?.(undefined);\n this.stop();\n }\n\n /**\n * Loads the recorder and starts it. Never rejects.\n * @returns A promise that resolves once the recorder is running, or can't run.\n */\n async start(): Promise<void> {\n const { diagnostics } = this.ctx;\n const { loader, endpoint, onSegment, plugins } = this.ctx.config.replay;\n\n if (!this.installed || this.record || this.starting) {\n return;\n }\n\n if (typeof document === \"undefined\") {\n this.reportOnce(\"This context has no document. The session replay is off.\");\n return;\n }\n\n if (!loader || (endpoint === \"\" && !onSegment)) {\n diagnostics.report(\n \"config.invalid\",\n \"The session replay needs replay.loader, and replay.endpoint or replay.onSegment. The session replay is off.\",\n );\n return;\n }\n\n const selectors = this.selectors();\n if (!selectors) {\n return;\n }\n\n const { generation } = this;\n this.starting = true;\n const loaded = await diagnostics.guardAsync(\n \"capture.install_failed\",\n \"The library could not load the replay recorder.\",\n loader,\n );\n const tools: ReplayPluginTools = { transformRequest: this.transformRequest };\n const made = await Promise.all(\n plugins.map((make) =>\n diagnostics.guardAsync(\n \"capture.install_failed\",\n \"The library could not load a replay plugin.\",\n () => Promise.resolve(make(tools)),\n ),\n ),\n );\n\n // A stop or an uninstall while we were loading cancels this start.\n if (generation !== this.generation) {\n return;\n }\n\n this.starting = false;\n\n // The loader failed, and the guard has already reported it.\n if (!loaded) {\n return;\n }\n\n const { record } = loaded;\n if (typeof record !== \"function\") {\n diagnostics.report(\n \"capture.install_failed\",\n \"The replay loader gave no record function. The session replay is off.\",\n );\n return;\n }\n\n const config = this.ctx.config.replay;\n diagnostics.guard(\"capture.install_failed\", \"The replay recorder did not start.\", () => {\n const extra: Record<string, unknown> = {};\n const ignored: string[] = [];\n\n for (const [key, value] of Object.entries(config.recordOptions)) {\n if (RECORD_OPTION_KEYS.includes(key)) {\n extra[key] = value;\n } else {\n ignored.push(key);\n }\n }\n\n if (ignored.length > 0) {\n diagnostics.report(\n \"config.invalid\",\n `The library ignores these keys of replay.recordOptions: ${ignored.join(\", \")}. It sets the mask, block, canvas, plugin and event options itself.`,\n );\n }\n\n const stopRecorder = record({\n ...extra,\n emit: this.emit,\n // Take a full snapshot every half window, so the buffer always begins with one.\n checkoutEveryNms: config.bufferMs / 2,\n // The per-element list covers every input type. Passwords are masked no matter what.\n maskAllInputs: false,\n maskInputOptions: config.maskInputs ? MASK_EACH_INPUT : { password: true },\n maskInputFn: this.maskInput,\n maskTextSelector: selectors.mask,\n maskTextFn: this.maskText,\n blockSelector: selectors.block,\n recordCanvas: config.recordCanvas,\n errorHandler: this.onFault,\n plugins: made.filter((plugin) => plugin !== undefined),\n });\n\n // The recorder swallows errors from its own startup and just returns no stop function.\n if (typeof stopRecorder !== \"function\") {\n diagnostics.report(\"capture.install_failed\", \"The replay recorder did not start.\");\n return;\n }\n\n this.stopRecorder = stopRecorder;\n this.record = record;\n this.starvedReported = false;\n this.replayId = crypto.randomUUID();\n this.ctx.setContext?.(REPLAY_ID_KEY, this.replayId);\n });\n }\n\n /**\n * Drops the buffer and, if the recorder was running, starts a fresh recording. The runtime\n * calls this on a new session, so the next user never gets the previous user's page.\n */\n reset(): void {\n const running = this.record !== undefined || this.starting;\n\n this.stop();\n if (running) {\n void this.start();\n }\n }\n\n /** Stops the recorder and drops whatever hasn't been sent. */\n stop(): void {\n const { stopRecorder } = this;\n\n this.generation++;\n this.starting = false;\n this.record = undefined;\n this.stopRecorder = undefined;\n this.live = false;\n clearTimeout(this.liveTimer);\n this.liveTimer = undefined;\n this.buffer.clear();\n this.uploader.stop();\n\n if (stopRecorder) {\n this.ctx.setContext?.(REPLAY_ID_KEY, undefined);\n this.ctx.diagnostics.guard(\n \"capture.install_failed\",\n \"The replay recorder did not stop.\",\n stopRecorder,\n );\n }\n }\n\n /**\n * Reads the mask and block selectors. An invalid selector aborts the start: a replay with a\n * missing mask would show text the app meant to hide.\n * @returns The selectors for the recorder, or undefined if one of them is invalid.\n */\n private selectors(): { mask: string | undefined; block: string | undefined } | undefined {\n const { maskText, maskSelectors, blockSelectors } = this.ctx.config.replay;\n\n for (const selector of [...maskSelectors, ...blockSelectors]) {\n try {\n document.createDocumentFragment().querySelector(selector);\n } catch (error) {\n this.ctx.diagnostics.report(\n \"config.invalid\",\n `The replay selector ${selector} is not a valid CSS selector. The session replay is off.`,\n undefined,\n error,\n );\n return undefined;\n }\n }\n\n const join = (list: string[]): string | undefined =>\n list.length > 0 ? list.join(\",\") : undefined;\n\n return { mask: maskText ? \"*\" : join(maskSelectors), block: join(blockSelectors) };\n }\n\n /**\n * Masks one piece of page text. The recorder calls this for every text the mask selector\n * matches.\n * @param text The node's text.\n * @param element The element that holds the text, or null.\n * @returns The text to record.\n */\n private readonly maskText = (text: string, element: Element | null): string => {\n const { maskText, maskSelectors } = this.ctx.config.replay;\n const forced = maskSelectors.length > 0 && element?.closest(maskSelectors.join(\",\"));\n\n // With maskText off, the recorder only calls us for text under a mask selector.\n if (maskText && !forced && element?.closest(`[${REPLAY_UNMASK_ATTRIBUTE}]`)) {\n return text;\n }\n\n return text.replace(/\\S/g, MASK_CHARACTER);\n };\n\n /**\n * Masks an input value. The result always has the same length.\n * @param text The input's value.\n * @returns The text to record.\n */\n private readonly maskInput = (text: string): string => (text === \"\" ? \"\" : MASKED_INPUT);\n\n /**\n * Strips what the recorder's own masking misses: the query string of the page URL, and text\n * sitting directly in a shadow root that changed after the snapshot.\n * @param event Recorder event.\n */\n private scrub(event: ReplayEvent): void {\n const { data } = event as { data?: ScrubData };\n\n if (!data) {\n return;\n }\n\n if (event.type === META_EVENT) {\n // A signed URL is a credential. Only keep the query when fullUrls is on.\n if (typeof data.href === \"string\" && !this.ctx.config.capture.fullUrls) {\n data.href = data.href.split(/[?#]/)[0];\n }\n return;\n }\n\n if (event.type !== INCREMENTAL_EVENT || data.source !== MUTATION_SOURCE) {\n return;\n }\n\n for (const change of data.texts ?? []) {\n change.value = this.shadowText(change.value, change.id);\n }\n\n for (const add of data.adds ?? []) {\n if (add.node?.type === TEXT_NODE) {\n // The recorder holds on to this node object, so change a copy.\n add.node = {\n ...add.node,\n textContent: this.shadowText(add.node.textContent, add.node.id),\n };\n }\n }\n }\n\n /**\n * Masks text that sits directly in a shadow root. The recorder masks it in a full snapshot\n * but not in later mutations.\n * @param text Text from the mutation.\n * @param id The recorder's id for the text node.\n * @returns The text to record.\n */\n private shadowText(text: unknown, id: number): unknown {\n const node = this.record?.mirror?.getNode(id) as Node | null | undefined;\n\n // Text with an element parent has already been through the recorder's mask function.\n if (typeof text !== \"string\" || !node || node.parentElement) {\n return text;\n }\n\n const { maskText, maskSelectors } = this.ctx.config.replay;\n const host = (node.parentNode as ShadowRoot | null)?.host ?? null;\n\n if (maskText) {\n return this.maskText(text, host);\n }\n\n return maskSelectors.length > 0 && host?.closest(maskSelectors.join(\",\"))\n ? text.replace(/\\S/g, MASK_CHARACTER)\n : text;\n }\n\n /**\n * Vets a request from the recorder's network plugin.\n * @param request The plugin's request.\n * @returns The request to record, or undefined to skip it.\n */\n private readonly transformRequest: ReplayPluginTools[\"transformRequest\"] = (request) => {\n // The plugin calls this from inside its fetch wrapper, so a throw here could reach the\n // app's request.\n try {\n const { capture } = this.ctx.config;\n const url = request.name;\n\n // The plugin calls us after the request, outside the library-request scope, so also check\n // the ignore list. It has every library endpoint, including the replay one. Otherwise a\n // recorded upload becomes a new event, which becomes a new upload.\n if (isLibraryRequest() || matchesAny(url, capture.ignoreUrls)) {\n return undefined;\n }\n\n // A signed URL is a credential. Only keep the query when fullUrls is on.\n return capture.fullUrls ? request : { ...request, name: url.split(/[?#]/)[0] };\n } catch (error) {\n this.onFault(error);\n return undefined;\n }\n };\n\n /**\n * Receives one event from the recorder, which calls this from its observers.\n * @param event Recorder event.\n * @param isCheckout True for the events of a new full snapshot.\n */\n private readonly emit = (event: ReplayEvent, isCheckout?: boolean): void => {\n try {\n this.scrub(event);\n\n // Stringify once: we need the text for the upload and for the size limit anyway.\n const text = JSON.stringify(event);\n\n if (this.live) {\n this.uploader.push([text]);\n return;\n }\n\n if (this.buffer.add(text, event.type, isCheckout === true) && !this.starvedReported) {\n this.starvedReported = true;\n this.ctx.diagnostics.report(\n \"capture.rate_limited\",\n \"One part of the replay is above replay.maxBufferBytes. The buffer is empty until the next full snapshot. Raise the limit, or block a large element with replay.blockSelectors.\",\n );\n }\n } catch (error) {\n this.onFault(error);\n }\n };\n\n /**\n * Reports an error from the recorder, or from serializing an event.\n * @param error What the recorder caught.\n */\n private readonly onFault = (error: unknown): void => {\n this.ctx.diagnostics.report(\n \"capture.record_failed\",\n \"The replay recorder had an error.\",\n undefined,\n error,\n );\n };\n\n /**\n * Starts an upload when an ERROR or FATAL record comes through.\n * @param record The record the runtime emitted.\n */\n private readonly onError = (record: LogRecord): void => {\n const { diagnostics, config } = this.ctx;\n\n diagnostics.guard(\"capture.record_failed\", \"The replay upload did not start.\", () => {\n if (!this.record) {\n return;\n }\n\n const { afterErrorMs, uploadsPerWindow } = config.replay;\n\n // An error during the live period rides along in the same upload and doesn't extend it.\n // That way a stream of errors can't hold the upload open, and the upload limit still bites.\n if (\n this.live ||\n !allowInWindow(\n this.window,\n uploadsPerWindow,\n diagnostics,\n \"replay uploads\",\n config.capturePolicy.windowMs,\n )\n ) {\n return;\n }\n\n const lost = this.buffer.takeLost();\n if (lost > 0) {\n diagnostics.report(\n \"capture.rate_limited\",\n `The replay buffer was above replay.maxBufferBytes. The library dropped ${String(lost)} events.`,\n );\n }\n\n const texts = this.buffer.take();\n const { takeFullSnapshot } = this.record;\n\n // An empty buffer has no full snapshot, and a player can't do anything without one.\n if (texts.length === 0 && !takeFullSnapshot) {\n return;\n }\n\n this.uploader.begin({\n replayId: this.replayId,\n sessionId: String(record.resource[SESSION_ID]),\n tabId: String(record.resource[TAB_ID]),\n });\n this.live = true;\n\n if (texts.length === 0) {\n // We're live, so this snapshot goes straight to the uploader.\n this.record.takeFullSnapshot?.(true);\n } else {\n this.uploader.push(texts);\n }\n\n this.liveTimer = setTimeout(this.endLive, afterErrorMs);\n unrefTimer(this.liveTimer);\n });\n };\n\n /** Ends the live period. The buffer starts over with a full snapshot. */\n private readonly endLive = (): void => {\n this.liveTimer = undefined;\n this.live = false;\n this.uploader.flush();\n this.ctx.diagnostics.guard(\n \"capture.record_failed\",\n \"The replay recorder did not take a full snapshot.\",\n () => {\n this.record?.takeFullSnapshot?.(true);\n },\n );\n };\n\n /**\n * Reports why the replay is off, once per document.\n * @param message Report text.\n */\n private reportOnce(message: string): void {\n const { once } = this.ctx;\n\n if (!once.replay) {\n once.replay = true;\n this.ctx.diagnostics.report(\"capture.install_failed\", message);\n }\n }\n}\n"],"mappings":"A,2QAMA,IAAMA,EAAa,EAGbsB,EAAa,EAGNC,EAAb,KAA0B,CAsBK,SApB7B,MAA4B,CAAC,EAG7B,MAA0B,CAAC,EAG3B,MAAgB,EAMhB,QAAkB,GAGlB,KAAe,EAKf,YAAY,EAAyC,CAAxB,KAAA,SAAAC,CAAyB,CAStD,IAAI,EAAc,EAAc,EAA8B,CAE5D,IAAMC,EAAQC,GAAcC,IAAS3B,EAErC,GAAI,KAAK,SAAW,CAACyB,EAEnB,MADA,MAAK,OACE,IAGLA,GAAS,KAAK,MAAM,SAAW,KACjC,KAAK,QAAU,GACf,KAAK,MAAM,KAAK,CAAC,CAAC,EAClB,KAAK,MAAM,KAAK,CAAC,EAEb,KAAK,MAAM,OAASH,GACtB,KAAK,WAAW,GAIpB,IAAMM,EAAO,KAAK,MAAM,OAAS,EACjC,KAAK,MAAMA,EAAK,CAAC,KAAKC,CAAI,EAC1B,KAAK,MAAMD,IAASC,EAAK,OACzB,KAAK,OAASA,EAAK,OAEnB,IAAMC,EAAQ,KAAK,SAAS,EAC5B,KAAO,KAAK,MAAQA,GAAS,KAAK,MAAM,OAAS,GAG/C,KAAK,QAAU,KAAK,MAAM,SAAW,EACrC,KAAK,MAAQ,KAAK,WAAW,EAG/B,OAAO,KAAK,OACd,CAMA,MAAiB,CACf,IAAMC,EAAQ,KAAK,MAAM,KAAK,EAE9B,OADA,KAAK,MAAM,EACJA,CACT,CAGA,OAAc,CACZ,KAAK,MAAQ,CAAC,EACd,KAAK,MAAQ,CAAC,EACd,KAAK,MAAQ,EACb,KAAK,QAAU,EACjB,CAMA,UAAmB,CACj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ASsF,CAAY,EACtDrG,EAAA,EAAW,KAAK,SAAS,EAC3B,CAAC,CACH,EAGA,YAAuC,CACrC,KAAK,UAAY,IAAA,GACjB,KAAK,KAAO,GACZ,KAAK,SAAS,MAAM,EACpB,KAAK,IAAI,YAAY,MACnB,wBACA,wDACM,CACJ,KAAK,QAAQ,mBAAmB,EAAI,CACtC,CACF,CACF,EAMA,WAAmB,EAAuB,CACxC,GAAM,CAAE,QAAS,KAAK,IAEjBsG,EAAK,SACR,EAAK,OAAS,GACd,KAAK,IAAI,YAAY,OAAO,yBAA0BC,CAAO,EAEjE,CACF,E"}
@@ -1,2 +0,0 @@
1
- const e=require("./platform-12uR7kBQ.cjs"),t=require("./storm-D0_qZOEg.cjs");var n=class{ctx;name=`reports`;installed=!1;observer;window={start:0,count:0};constructor(e){this.ctx=e}install(){if(this.installed)return;this.installed=!0,document.addEventListener(`securitypolicyviolation`,this.onCsp);let e=typeof ReportingObserver>`u`?void 0:ReportingObserver;e?(this.observer=new e(e=>{for(let t of e)this.record(t)},{types:[`deprecation`,`intervention`],buffered:!1}),this.observer.observe()):this.ctx.diagnostics.report(`capture.install_failed`,`The browser does not support ReportingObserver. Only CSP events are captured.`)}uninstall(){this.installed=!1,this.observer?.disconnect(),this.observer=void 0,document.removeEventListener(`securitypolicyviolation`,this.onCsp)}onCsp=e=>{this.ctx.diagnostics.guard(`capture.record_failed`,`The library could not read a CSP event.`,()=>{this.record({type:`csp-violation`,url:e.documentURI,body:{sourceFile:e.sourceFile,lineNumber:e.lineNumber,columnNumber:e.columnNumber,effectiveDirective:e.effectiveDirective,blockedURL:e.blockedURI}})})};record(n){if(!this.installed||this.ctx.isActive?.()===!1)return;let{capturePolicy:r,limits:i}=this.ctx.config;t.t(this.window,r.reportsPerWindow,this.ctx.diagnostics,`browser reports`,r.windowMs)&&this.ctx.diagnostics.guard(`capture.record_failed`,`The library could not record a browser report.`,()=>{if(![`deprecation`,`intervention`,`csp-violation`].includes(n.type))return;let t=n.body,r=t=>e.i(t,!1,void 0,this.ctx.diagnostics);this.ctx.logger.warn(`ui.report`,{"report.type":n.type,"report.url":r(n.url),...t.id?{"report.id":t.id.slice(0,i.maxAttributeChars)}:{},...t.sourceFile?{"report.source":r(t.sourceFile)}:{},...t.lineNumber===void 0?{}:{"report.line":t.lineNumber},...t.columnNumber===void 0?{}:{"report.column":t.columnNumber},...t.effectiveDirective?{"report.directive":t.effectiveDirective}:{},...t.blockedURL?{"report.blocked_url":r(t.blockedURL)}:{}})})}};exports.ReportCapture=n;
2
- //# sourceMappingURL=reports-BsbqmP8h.cjs.map
@@ -1 +0,0 @@
1
- {"version":3,"file":"reports-BsbqmP8h.cjs","names":["allowInWindow","recordedUrl","require_platform","require_storm","ReportCapture","ctx","Observer","report","reports","event","capturePolicy","body","url","value","limits"],"sources":["../src/capture/reports.ts"],"sourcesContent":["import { recordedUrl } from \"../utils/platform\";\nimport { allowInWindow, type StormWindow } from \"./storm\";\nimport type { Capture, CaptureContext } from \"./types\";\n\n/** The report fields this capture reads. Message text and samples stay out. */\ninterface BrowserReport {\n type: string;\n url: string;\n body: {\n id?: string;\n sourceFile?: string;\n lineNumber?: number;\n columnNumber?: number;\n effectiveDirective?: string;\n blockedURL?: string;\n };\n}\n\n/** Records browser reports without message text, code samples or URL queries. */\nexport class ReportCapture implements Capture {\n readonly name = \"reports\";\n\n private installed = false;\n\n private observer: ReportingObserver | undefined;\n\n private readonly window: StormWindow = { start: 0, count: 0 };\n\n constructor(private readonly ctx: CaptureContext) {}\n\n /** Installs the report and CSP listeners. CSP reports don't need ReportingObserver. */\n install(): void {\n if (this.installed) {\n return;\n }\n this.installed = true;\n document.addEventListener(\"securitypolicyviolation\", this.onCsp);\n\n const Observer = typeof ReportingObserver === \"undefined\" ? undefined : ReportingObserver;\n\n if (!Observer) {\n this.ctx.diagnostics.report(\n \"capture.install_failed\",\n \"The browser does not support ReportingObserver. Only CSP events are captured.\",\n );\n return;\n }\n\n this.observer = new Observer(\n (reports) => {\n for (const report of reports) {\n this.record(report as unknown as BrowserReport);\n }\n },\n { types: [\"deprecation\", \"intervention\"], buffered: false },\n );\n this.observer.observe();\n }\n\n /** Disconnects the observer and removes the CSP listener. */\n uninstall(): void {\n this.installed = false;\n this.observer?.disconnect();\n this.observer = undefined;\n document.removeEventListener(\"securitypolicyviolation\", this.onCsp);\n }\n\n private readonly onCsp = (event: SecurityPolicyViolationEvent): void => {\n this.ctx.diagnostics.guard(\n \"capture.record_failed\",\n \"The library could not read a CSP event.\",\n () => {\n this.record({\n type: \"csp-violation\",\n url: event.documentURI,\n body: {\n sourceFile: event.sourceFile,\n lineNumber: event.lineNumber,\n columnNumber: event.columnNumber,\n effectiveDirective: event.effectiveDirective,\n blockedURL: event.blockedURI,\n },\n });\n },\n );\n };\n\n /** Reads only a fixed set of report fields. The diagnostics guard contains a failed read. */\n private record(report: BrowserReport): void {\n if (!this.installed || this.ctx.isActive?.() === false) {\n return;\n }\n\n const { capturePolicy, limits } = this.ctx.config;\n if (\n !allowInWindow(\n this.window,\n capturePolicy.reportsPerWindow,\n this.ctx.diagnostics,\n \"browser reports\",\n capturePolicy.windowMs,\n )\n ) {\n return;\n }\n\n this.ctx.diagnostics.guard(\n \"capture.record_failed\",\n \"The library could not record a browser report.\",\n () => {\n if (![\"deprecation\", \"intervention\", \"csp-violation\"].includes(report.type)) {\n return;\n }\n\n const body = report.body;\n const url = (value: string): string =>\n recordedUrl(value, false, undefined, this.ctx.diagnostics);\n this.ctx.logger.warn(\"ui.report\", {\n \"report.type\": report.type,\n \"report.url\": url(report.url),\n ...(body.id ? { \"report.id\": body.id.slice(0, limits.maxAttributeChars) } : {}),\n ...(body.sourceFile ? { \"report.source\": url(body.sourceFile) } : {}),\n ...(body.lineNumber !== undefined ? { \"report.line\": body.lineNumber } : {}),\n ...(body.columnNumber !== undefined ? { \"report.column\": body.columnNumber } : {}),\n ...(body.effectiveDirective ? { \"report.directive\": body.effectiveDirective } : {}),\n ...(body.blockedURL ? { \"report.blocked_url\":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GAAI,CAAC,CAAC,cAAe,eAAgB,eAAe,CAAC,CAAC,SAASH,EAAO,IAAI,EACxE,OAGF,IAAMI,EAAOJ,EAAO,KACdK,EAAO,GACXX,EAAAA,EAAYY,EAAO,GAAO,IAAA,GAAW,KAAK,IAAI,WAAW,EAC3D,KAAK,IAAI,OAAO,KAAK,YAAa,CAChC,cAAeN,EAAO,KACtB,aAAcK,EAAIL,EAAO,GAAG,EAC5B,GAAII,EAAK,GAAK,CAAE,YAAaA,EAAK,GAAG,MAAM,EAAGG,EAAO,iBAAiB,CAAE,EAAI,CAAC,EAC7E,GAAIH,EAAK,WAAa,CAAE,gBAAiBC,EAAID,EAAK,UAAU,CAAE,EAAI,CAAC,EACnE,GAAIA,EAAK,aAAe,IAAA,GAAiD,CAAC,EAAtC,CAAE,cAAeA,EAAK,UAAW,EACrE,GAAIA,EAAK,eAAiB,IAAA,GAAqD,CAAC,EAA1C,CAAE,gBAAiBA,EAAK,YAAa,EAC3E,GAAIA,EAAK,mBAAqB,CAAE,mBAAoBA,EAAK,kBAAmB,EAAI,CAAC,EACjF,GAAIA,EAAK,WAAa,CAAE,qBAAsBC,EAAID,EAAK,UAAU,CAAE,EAAI,CAAC,CAC1E,CAAC,CACH,CACF,CACF,CACF,E"}
@@ -1 +0,0 @@
1
- {"version":3,"file":"reports-BuXekPOS.js","names":["recordedUrl","ReportCapture","ctx","Observer","report","reports","event","allowInWindow","capturePolicy","body","url","value","limits"],"sources":["../src/capture/reports.ts"],"sourcesContent":["import { recordedUrl } from \"../utils/platform\";\nimport { allowInWindow, type StormWindow } from \"./storm\";\nimport type { Capture, CaptureContext } from \"./types\";\n\n/** The report fields this capture reads. Message text and samples stay out. */\ninterface BrowserReport {\n type: string;\n url: string;\n body: {\n id?: string;\n sourceFile?: string;\n lineNumber?: number;\n columnNumber?: number;\n effectiveDirective?: string;\n blockedURL?: string;\n };\n}\n\n/** Records browser reports without message text, code samples or URL queries. */\nexport class ReportCapture implements Capture {\n readonly name = \"reports\";\n\n private installed = false;\n\n private observer: ReportingObserver | undefined;\n\n private readonly window: StormWindow = { start: 0, count: 0 };\n\n constructor(private readonly ctx: CaptureContext) {}\n\n /** Installs the report and CSP listeners. CSP reports don't need ReportingObserver. */\n install(): void {\n if (this.installed) {\n return;\n }\n this.installed = true;\n document.addEventListener(\"securitypolicyviolation\", this.onCsp);\n\n const Observer = typeof ReportingObserver === \"undefined\" ? undefined : ReportingObserver;\n\n if (!Observer) {\n this.ctx.diagnostics.report(\n \"capture.install_failed\",\n \"The browser does not support ReportingObserver. Only CSP events are captured.\",\n );\n return;\n }\n\n this.observer = new Observer(\n (reports) => {\n for (const report of reports) {\n this.record(report as unknown as BrowserReport);\n }\n },\n { types: [\"deprecation\", \"intervention\"], buffered: false },\n );\n this.observer.observe();\n }\n\n /** Disconnects the observer and removes the CSP listener. */\n uninstall(): void {\n this.installed = false;\n this.observer?.disconnect();\n this.observer = undefined;\n document.removeEventListener(\"securitypolicyviolation\", this.onCsp);\n }\n\n private readonly onCsp = (event: SecurityPolicyViolationEvent): void => {\n this.ctx.diagnostics.guard(\n \"capture.record_failed\",\n \"The library could not read a CSP event.\",\n () => {\n this.record({\n type: \"csp-violation\",\n url: event.documentURI,\n body: {\n sourceFile: event.sourceFile,\n lineNumber: event.lineNumber,\n columnNumber: event.columnNumber,\n effectiveDirective: event.effectiveDirective,\n blockedURL: event.blockedURI,\n },\n });\n },\n );\n };\n\n /** Reads only a fixed set of report fields. The diagnostics guard contains a failed read. */\n private record(report: BrowserReport): void {\n if (!this.installed || this.ctx.isActive?.() === false) {\n return;\n }\n\n const { capturePolicy, limits } = this.ctx.config;\n if (\n !allowInWindow(\n this.window,\n capturePolicy.reportsPerWindow,\n this.ctx.diagnostics,\n \"browser reports\",\n capturePolicy.windowMs,\n )\n ) {\n return;\n }\n\n this.ctx.diagnostics.guard(\n \"capture.record_failed\",\n \"The library could not record a browser report.\",\n () => {\n if (![\"deprecation\", \"intervention\", \"csp-violation\"].includes(report.type)) {\n return;\n }\n\n const body = report.body;\n const url = (value: string): string =>\n recordedUrl(value, false, undefined, this.ctx.diagnostics);\n this.ctx.logger.warn(\"ui.report\", {\n \"report.type\": report.type,\n \"report.url\": url(report.url),\n ...(body.id ? { \"report.id\": body.id.slice(0, limits.maxAttributeChars) } : {}),\n ...(body.sourceFile ? { \"report.source\": url(body.sourceFile) } : {}),\n ...(body.lineNumber !== undefined ? { \"report.line\": body.lineNumber } : {}),\n ...(body.columnNumber !== undefined ? { \"report.column\": body.columnNumber } : {}),\n ...(body.effectiveDirective ? { \"report.directive\": body.effectiveDirective } : {}),\n ...(body.blockedURL ? { \"report.blocked_url\": url(body.blockedURL) } : {}),\n });\n },\n );\n }\n}\n"],"mappings":";;;AAmBA,IAAaC,IAAb,MAA8C;CASf;CAR7B,OAAgB;CAEhB,YAAoB;CAEpB;CAEA,SAAuC;EAAE,OAAO;EAAG,OAAO;CAAE;CAE5D,YAAY,GAAsC;EAArB,KAAA,MAAAC;CAAsB;CAGnD,UAAgB;EACd,IAAI,KAAK,WACP;EAGF,AADA,KAAK,YAAY,IACjB,SAAS,iBAAiB,2BAA2B,KAAK,KAAK;EAE/D,IAAMC,IAAW,OAAO,oBAAsB,MAAc,KAAA,IAAY;EAExE,AAAKA,KAQL,KAAK,WAAW,IAAIA,GACjB,MAAY;GACX,KAAK,IAAMC,KAAUC,GACnB,KAAK,OAAOD,CAAkC;EAElD,GACA;GAAE,OAAO,CAAC,eAAe,cAAc;GAAG,UAAU;EAAM,CAC5D,GACA,KAAK,SAAS,QAAQ,KAfpB,KAAK,IAAI,YAAY,OACnB,0BACA,+EACF;CAaJ;CAGA,YAAkB;EAIhB,AAHA,KAAK,YAAY,IACjB,KAAK,UAAU,WAAW,GAC1B,KAAK,WAAW,KAAA,GAChB,SAAS,oBAAoB,2BAA2B,KAAK,KAAK;CACpE;CAEA,SAA0B,MAA8C;EACtE,KAAK,IAAI,YAAY,MACnB,yBACA,iDACM;GACJ,KAAK,OAAO;IACV,MAAM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wFRD.js","names":["RESOURCE_SLOW_MS","recordedUrl","allowInWindow","matchesAny","RESOURCE_DURATION","ResourceTimingCapture","ctx","first","entry","list","url","endpoints","capture","endpoint","capturePolicy","attributes","slowMs"],"sources":["../src/capture/resource-timing.ts"],"sourcesContent":["import { RESOURCE_SLOW_MS } from \"../constants\";\nimport type { InstrumentDef } from \"../models/metric\";\nimport { recordedUrl } from \"../utils/platform\";\nimport { allowInWindow, type StormWindow } from \"./storm\";\nimport { type Capture, type CaptureContext, matchesAny } from \"./types\";\n\n/** Resource durations in milliseconds. URLs and paths never create metric series. */\nconst RESOURCE_DURATION: InstrumentDef = {\n name: \"ui.resource.duration\",\n kind: \"histogram\",\n unit: \"ms\",\n boundaries: [1, 5, 10, 25, 50, 100, 250, 500, 1000, 2500, 5000, 10000],\n};\n\n/** Records bounded resource timings and slow resource events. */\nexport class ResourceTimingCapture implements Capture {\n readonly name = \"resourceTiming\";\n\n private observer: PerformanceObserver | undefined;\n\n private readonly window: StormWindow = { start: 0, count: 0 };\n\n constructor(private readonly ctx: CaptureContext) {}\n\n /** Reads buffered resources only on the first install in this document. */\n install(): void {\n if (this.observer) {\n return;\n }\n\n const supported: readonly string[] | undefined =\n typeof PerformanceObserver === \"undefined\"\n ? undefined\n : PerformanceObserver.supportedEntryTypes;\n if (!supported?.includes(\"resource\")) {\n this.ctx.diagnostics.report(\n \"capture.install_failed\",\n \"The browser does not report resource timing entries. The resource timing capture is off.\",\n );\n return;\n }\n\n const first = !this.ctx.once.resourceTiming;\n this.observer = new PerformanceObserver((list) => {\n for (const entry of list.getEntries()) {\n this.record(entry as PerformanceResourceTiming);\n }\n });\n this.observer.observe({ type: \"resource\", buffered: first });\n this.ctx.once.resourceTiming = true;\n }\n\n /** Disconnects the observer. */\n uninstall(): void {\n this.observer?.disconnect();\n this.observer = undefined;\n }\n\n private record(entry: PerformanceResourceTiming): void {\n if (!this.observer || this.ctx.isActive?.() === false) {\n return;\n }\n\n this.ctx.diagnostics.guard(\n \"capture.record_failed\",\n \"The library could not record a resource timing entry.\",\n () => {\n const { capture, capturePolicy } = this.ctx.config;\n const url = new URL(entry.name, location.href);\n const endpoints = [\n this.ctx.config.endpoint,\n this.ctx.config.metricsEndpoint,\n this.ctx.config.tracesEndpoint,\n ];\n if (\n matchesAny(entry.name, capture.ignoreUrls) ||\n endpoints.some(\n (endpoint) => endpoint && url.href.startsWith(new URL(endpoint, location.href).href),\n )\n ) {\n return;\n }\n if (\n !Number.isFinite(entry.duration) ||\n entry.duration < 0 ||\n ![\"http:\", \"https:\"].includes(url.protocol)\n ) {\n return;\n }\n if (\n !allowInWindow(\n this.window,\n capturePolicy.resourcesPerWindow,\n this.ctx.diagnostics,\n \"resource entries\",\n capturePolicy.windowMs,\n )\n ) {\n return;\n }\n\n const attributes = {\n \"resource.initiator_type\": entry.initiatorType,\n \"server.address\": url.hostname,\n };\n this.ctx.recordMetric(RESOURCE_DURATION, entry.duration, attributes);\n\n const slowMs =\n typeof capture.resourceTiming === \"object\"\n ? (capture.resourceTiming.slowMs ?? RESOURCE_SLOW_MS)\n : RESOURCE_SLOW_MS;\n if (slowMs > 0 && entry.duration >= slowMs) {\n this.ctx.logger.logEvent(\"ui.resource.slow\", {\n ...attributes,\n \"resource.duration_ms\": entry.duration,\n \"url.full\": recordedUrl(\n entry.name,\n capture.fullUrls,\n capture.urlTransform,\n this.ctx.diagnostics,\n ),\n });\n }\n },\n );\n }\n}\n"],"mappings":";;;;;AAOA,IAAMI,IAAmC;CACvC,MAAM;CACN,MAAM;CACN,MAAM;CACN,YAAY;EAAC;EAAG;EAAG;EAAI;EAAI;EAAI;EAAK;EAAK;EAAK;EAAM;EAAM;EAAM;CAAK;AACvE,GAGaC,IAAb,MAAsD;CAOvB;CAN7B,OAAgB;CAEhB;CAEA,SAAuC;EAAE,OAAO;EAAG,OAAO;CAAE;CAE5D,YAAY,GAAsC;EAArB,KAAA,MAAAC;CAAsB;CAGnD,UAAgB;EACd,IAAI,KAAK,UACP;EAOF,I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AM,UAAUO,CAAU;GAEnE,IAAMC,IACJ,OAAOJ,EAAQ,kBAAmB,WAC7BA,EAAQ,eAAe,UAAA,MACxBZ;GACN,AAAIgB,IAAS,KAAKR,EAAM,YAAYQ,KAClC,KAAK,IAAI,OAAO,SAAS,oBAAoB;IAC3C,GAAGD;IACH,wBAAwBP,EAAM;IAC9B,YAAYP,EACVO,EAAM,MACNI,EAAQ,UACRA,EAAQ,cACR,KAAK,IAAI,WACX;GACF,CAAC;EAEL,CACF;CACF;AACF"}
@@ -1,2 +0,0 @@
1
- const e=require("./constants-DakMxVB2.cjs"),t=require("./platform-12uR7kBQ.cjs"),n=require("./storm-D0_qZOEg.cjs"),r=require("./types-C7WNpnG1.cjs");var i={name:`ui.resource.duration`,kind:`histogram`,unit:`ms`,boundaries:[1,5,10,25,50,100,250,500,1e3,2500,5e3,1e4]},a=class{ctx;name=`resourceTiming`;observer;window={start:0,count:0};constructor(e){this.ctx=e}install(){if(this.observer)return;if(!(typeof PerformanceObserver>`u`?void 0:PerformanceObserver.supportedEntryTypes)?.includes(`resource`)){this.ctx.diagnostics.report(`capture.install_failed`,`The browser does not report resource timing entries. The resource timing capture is off.`);return}let e=!this.ctx.once.resourceTiming;this.observer=new PerformanceObserver(e=>{for(let t of e.getEntries())this.record(t)}),this.observer.observe({type:`resource`,buffered:e}),this.ctx.once.resourceTiming=!0}uninstall(){this.observer?.disconnect(),this.observer=void 0}record(a){this.observer&&this.ctx.isActive?.()!==!1&&this.ctx.diagnostics.guard(`capture.record_failed`,`The library could not record a resource timing entry.`,()=>{let{capture:o,capturePolicy:s}=this.ctx.config,c=new URL(a.name,location.href),l=[this.ctx.config.endpoint,this.ctx.config.metricsEndpoint,this.ctx.config.tracesEndpoint];if(r.t(a.name,o.ignoreUrls)||l.some(e=>e&&c.href.startsWith(new URL(e,location.href).href))||!Number.isFinite(a.duration)||a.duration<0||![`http:`,`https:`].includes(c.protocol)||!n.t(this.window,s.resourcesPerWindow,this.ctx.diagnostics,`resource entries`,s.windowMs))return;let u={"resource.initiator_type":a.initiatorType,"server.address":c.hostname};this.ctx.recordMetric(i,a.duration,u);let d=typeof o.resourceTiming==`object`?o.resourceTiming.slowMs??1e3:e.vn;d>0&&a.duration>=d&&this.ctx.logger.logEvent(`ui.resource.slow`,{...u,"resource.duration_ms":a.duration,"url.full":t.i(a.name,o.fullUrls,o.urlTransform,this.ctx.diagnostics)})})}};exports.ResourceTimingCapture=a;
2
- //# sourceMappingURL=resource-timing-DkycFGDa.cjs.map
@@ -1 +0,0 @@
1
- {"version":3,"file":"resource-timing-DkycFGDa.cjs","names":["matchesAny","allowInWindow","RESOURCE_SLOW_MS","recordedUrl","require_constants","require_platform","require_storm","require_types","RESOURCE_DURATION","ResourceTimingCapture","ctx","first","entry","list","url","endpoints","capture","endpoint","capturePolicy","attributes","slowMs"],"sources":["../src/capture/resource-timing.ts"],"sourcesContent":["import { RESOURCE_SLOW_MS } from \"../constants\";\nimport type { InstrumentDef } from \"../models/metric\";\nimport { recordedUrl } from \"../utils/platform\";\nimport { allowInWindow, type StormWindow } from \"./storm\";\nimport { type Capture, type CaptureContext, matchesAny } from \"./types\";\n\n/** Resource durations in milliseconds. URLs and paths never create metric series. */\nconst RESOURCE_DURATION: InstrumentDef = {\n name: \"ui.resource.duration\",\n kind: \"histogram\",\n unit: \"ms\",\n boundaries: [1, 5, 10, 25, 50, 100, 250, 500, 1000, 2500, 5000, 10000],\n};\n\n/** Records bounded resource timings and slow resource events. */\nexport class ResourceTimingCapture implements Capture {\n readonly name = \"resourceTiming\";\n\n private observer: PerformanceObserver | undefined;\n\n private readonly window: StormWindow = { start: 0, count: 0 };\n\n constructor(private readonly ctx: CaptureContext) {}\n\n /** Reads buffered resources only on the first install in this document. */\n install(): void {\n if (this.observer) {\n return;\n }\n\n const supported: readonly string[] | undefined =\n typeof PerformanceObserver === \"undefined\"\n ? undefined\n : PerformanceObserver.supportedEntryTypes;\n if (!supported?.includes(\"resource\")) {\n this.ctx.diagnostics.report(\n \"capture.install_failed\",\n \"The browser does not report resource timing entries. The resource timing capture is off.\",\n );\n return;\n }\n\n const first = !this.ctx.once.resourceTiming;\n this.observer = new PerformanceObserver((list) => {\n for (const entry of list.getEntries()) {\n this.record(entry as PerformanceResourceTiming);\n }\n });\n this.observer.observe({ type: \"resource\", buffered: first });\n this.ctx.once.resourceTiming = true;\n }\n\n /** Disconnects the observer. */\n uninstall(): void {\n this.observer?.disconnect();\n this.observer = undefined;\n }\n\n private record(entry: PerformanceResourceTiming): void {\n if (!this.observer || this.ctx.isActive?.() === false) {\n return;\n }\n\n this.ctx.diagnostics.guard(\n \"capture.record_failed\",\n \"The library could not record a resource timing entry.\",\n () => {\n const { capture, capturePolicy } = this.ctx.config;\n const url = new URL(entry.name, location.href);\n const endpoints = [\n this.ctx.config.endpoint,\n this.ctx.config.metricsEndpoint,\n this.ctx.config.tracesEndpoint,\n ];\n if (\n matchesAny(entry.name, capture.ignoreUrls) ||\n endpoints.some(\n (endpoint) => endpoint && url.href.startsWith(new URL(endpoint, location.href).href),\n )\n ) {\n return;\n }\n if (\n !Number.isFinite(entry.duration) ||\n entry.duration < 0 ||\n ![\"http:\", \"https:\"].includes(url.protocol)\n ) {\n return;\n }\n if (\n !allowInWindow(\n this.window,\n capturePolicy.resourcesPerWindow,\n this.ctx.diagnostics,\n \"resource entries\",\n capturePolicy.windowMs,\n )\n ) {\n return;\n }\n\n const attributes = {\n \"resource.initiator_type\": entry.initiatorType,\n \"server.address\": url.hostname,\n };\n this.ctx.recordMetric(RESOURCE_DURATION, entry.duration, attributes);\n\n const slowMs =\n typeof capture.resourceTiming === \"object\"\n ? (capture.resourceTiming.slowMs ?? RESOURCE_SLOW_MS)\n : RESOURCE_SLOW_MS;\n if (slowMs > 0 && entry.duration >= slowMs) {\n this.ctx.logger.logEvent(\"ui.resource.slow\", {\n ...attributes,\n \"resource.duration_ms\": entry.duration,\n \"url.full\": recordedUrl(\n entry.name,\n capture.fullUrls,\n capture.urlTransform,\n this.ct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AI,KAAK,WAAW,IAAI,IAAIG,EAAU,SAAS,IAAI,CAAC,CAAC,IAAI,CACrF,GAKA,CAAC,OAAO,SAASL,EAAM,QAAQ,GAC/BA,EAAM,SAAW,GACjB,CAAC,CAAC,QAAS,QAAQ,CAAC,CAAC,SAASE,EAAI,QAAQ,GAK1C,CAACb,EAAAA,EACC,KAAK,OACLiB,EAAc,mBACd,KAAK,IAAI,YACT,mBACAA,EAAc,QAChB,EAEA,OAGF,IAAMC,EAAa,CACjB,0BAA2BP,EAAM,cACjC,iBAAkBE,EAAI,QACxB,EACA,KAAK,IAAI,aAAaN,EAAmBI,EAAM,SAAUO,CAAU,EAEnE,IAAMC,EACJ,OAAOJ,EAAQ,gBAAmB,SAC7BA,EAAQ,eAAe,QAAA,IACxBd,EAAAA,GACFkB,EAAS,GAAKR,EAAM,UAAYQ,GAClC,KAAK,IAAI,OAAO,SAAS,mBAAoB,CAC3C,GAAGD,EACH,uBAAwBP,EAAM,SAC9B,WAAYT,EAAAA,EACVS,EAAM,KACNI,EAAQ,SACRA,EAAQ,aACR,KAAK,IAAI,WACX,CACF,CAAC,CAEL,CACF,CACF,CACF,E"}
@@ -1,2 +0,0 @@
1
- const e=require("./constants-DakMxVB2.cjs"),t=require("./fixed-window-CvESpFYV.cjs");function n(t){let n=e.rt;for(let r=0;r<t.length;r++)n^=t.charCodeAt(r),n=Math.imul(n,e.it);return n>>>0}function r(e,t){let n=e.attributes[t];return typeof n==`string`?n:``}function i(e,t){let n;for(let[r,i]of Object.entries(t))(e===r||e.startsWith(`${r}.`))&&r.length>(n?.length??-1)&&(n={value:i,length:r.length});return n}function a(e,t){return i(e,t.minLevels)?.value??t.minLevel}function o(e,t,n){let{rates:r,defaultRate:a,remoteMaxRate:o}=t.sampling,s=i(e,r),c=n?i(e,n.rates):void 0;return c&&c.length>=(s?.length??-1)?Math.min(c.value,o):s?s.value:n?.defaultRate===void 0?a:Math.min(n.defaultRate,o)}function s(t,n){return e.Tt[t]>=e.Tt[n]}function c(t,r){return r>=1?!0:r<=0?!1:n(t)/e.$n<r}function l(t,n,r){if(t.aggregated===!0||t.type===`span`||s(t.level,n.sampling.alwaysSampleFrom)||n.sampling.alwaysSampleTypes.includes(t.type))return!0;let i=o(t.namespace,n,r),l=a(t.namespace,n),u=e.Tt[t.level]<e.Tt[l];return r&&u&&!e.wt.includes(t.type)&&(i=Math.min(i,n.sampling.remoteMaxRate)),c(t.journeyId||t.traceId,i)}function u(t,n,i=null){return l({level:t.severityText,type:r(t,e.g),namespace:r(t,e.a),journeyId:r(t,e.f),traceId:t.traceId,aggregated:r(t,`log.type`)===`metric`&&r(t,e.Pt.start)!==``},n,i)}var d=class{window={start:0,count:0};allow(n,r=500,i=e.nt,a=`ERROR`){return!s(n.severityText,a)||r===0||t.t(this.window,r,i)}};Object.defineProperty(exports,"a",{enumerable:!0,get:function(){return u}}),Object.defineProperty(exports,"i",{enumerable:!0,get:function(){return c}}),Object.defineProperty(exports,"n",{enumerable:!0,get:function(){return a}}),Object.defineProperty(exports,"o",{enumerable:!0,get:function(){return l}}),Object.defineProperty(exports,"r",{enumerable:!0,get:function(){return i}}),Object.defineProperty(exports,"t",{enumerable:!0,get:function(){return d}});
2
- //# sourceMappingURL=sampling-Dd0wllyq.cjs.map
@@ -1 +0,0 @@
1
- {"version":3,"file":"sampling-Dd0wllyq.cjs","names":["FNV_OFFSET_BASIS","FNV_PRIME","LEVEL_ORDER","UINT32_MAX","LEVEL_BYPASS_TYPES","ATTR_LOG_TYPE","ATTR_APP_NAMESPACE","ATTR_JOURNEY_ID","METRIC_KEYS","ERROR_STORM_WINDOW_MS","countInWindow","require_constants","require_fixed_window","hash","h","i","value","readAttr","record","key","longestPrefix","best","prefix","values","namespace","levelFor","config","rateFor","local","rates","fromRemote","remote","remoteMaxRate","defaultRate","atOrAbove","level","from","sampleKey","rate","shouldSampleInput","input","configLevel","belowMinLevel","shouldSample","ErrorCeiling","limit","windowMs"],"sources":["../src/core/sampling.ts"],"sourcesContent":["// src/core/sampling.ts\n//\n// Samples records by namespace rule, journey ID and trace ID.\n// The journey ID is the sampling key, so a whole journey is kept or dropped together and\n// the result is the same across windows and reloads.\n\nimport {\n ATTR_APP_NAMESPACE,\n ATTR_JOURNEY_ID,\n ATTR_LOG_TYPE,\n ERROR_CEILING_MAX_PER_WINDOW,\n ERROR_STORM_WINDOW_MS,\n FNV_OFFSET_BASIS,\n FNV_PRIME,\n LEVEL_BYPASS_TYPES,\n LEVEL_ORDER,\n LOG_TYPE_SPAN,\n METRIC_KEYS,\n SAMPLING_RATE_MAX,\n SAMPLING_RATE_MIN,\n UINT32_MAX,\n} from \"../constants\";\nimport type { ResolvedConfig } from \"../models/config\";\nimport type { LogLevel, LogRecord, LogType } from \"../models/log-record\";\nimport { countInWindow, type StormWindow } from \"../utils/fixed-window\";\nimport type { RemoteRules } from \"./remote-sampling\";\n\n/**\n * Computes the 32-bit FNV-1a hash of a string. Do not use it as a security hash.\n * @param value Key string to hash.\n * @returns Unsigned 32-bit integer hash.\n */\nfunction hash(value: string): number {\n let h = FNV_OFFSET_BASIS;\n\n for (let i = 0; i < value.length; i++) {\n h ^= value.charCodeAt(i);\n h = Math.imul(h, FNV_PRIME);\n }\n\n return h >>> 0;\n}\n\n/**\n * Reads a string attribute from a log record. Returns an empty string for an absent\n * or non-string value, because a forwarded record has only passed a shape check.\n * @param record Log record to read from.\n * @param key Attribute key.\n * @returns String attribute value, or empty string if missing or non-string.\n */\nfunction readAttr(record: LogRecord, key: string): string {\n const value: unknown = record.attributes[key];\n return typeof value === \"string\" ? value : \"\";\n}\n\n/** Value of the longest prefix that matches a namespace. */\ninterface PrefixMatch<T> {\n /** The prefix's value, for example a rate or a level. */\n value: T;\n /** Length of the prefix. */\n length: number;\n}\n\n/**\n * Finds the longest prefix in a map that matches a namespace.\n * For example, trading.ticks overrides trading.\n * @param namespace Target application namespace.\n * @param values Value for each namespace prefix.\n * @returns The match, or undefined if no prefix matches.\n */\nexport function longestPrefix<T>(\n namespace: string,\n values: Record<string, T>,\n): PrefixMatch<T> | undefined {\n let best: PrefixMatch<T> | undefined;\n\n for (const [prefix, value] of Object.entries(values)) {\n const matches = namespace === prefix || namespace.startsWith(`${prefix}.`);\n\n if (matches && prefix.length > (best?.length ?? -1)) {\n best = { value, length: prefix.length };\n }\n }\n\n return best;\n}\n\n/**\n * Finds a namespace's minimum level in the config. The longest matching prefix in\n * `minLevels` wins, and a namespace with no match uses `minLevel`.\n * @param namespace Target application namespace.\n * @param config Active configuration instance.\n * @returns The namespace's minimum level.\n */\nexport function levelFor(namespace: string, config: ResolvedConfig): LogLevel {\n return longestPrefix(namespace, config.minLevels)?.value ?? config.minLevel;\n}\n\n/**\n * Finds the sampling rate for a namespace. The longest matching prefix wins.\n * A remote prefix wins over a config prefix of the same length.\n * @param namespace Target application namespace.\n * @param config Active configuration instance.\n * @param remote Current remote rules, or null.\n * @returns Matched namespace sampling rate or default rate.\n */\nfunction rateFor(namespace: string, config: ResolvedConfig, remote: RemoteRules | null): number {\n const { rates, defaultRate, remoteMaxRate } = config.sampling;\n const local = longestPrefix(namespace, rates);\n const fromRemote = remote ? longestPrefix(namespace, remote.rates) : undefined;\n\n // Cap a remote rate at the point where sampling reads it, so a configure() that lowers the\n // cap takes effect immediately.\n if (fromRemote && fromRemote.length >= (local?.length ?? -1)) {\n return Math.min(fromRemote.value, remoteMaxRate);\n }\n\n if (local) {\n return local.value;\n }\n\n return remote?.defaultRate === undefined\n ? defaultRate\n : Math.min(remote.defaultRate, remoteMaxRate);\n}\n\n/**\n * Checks whether a level is at or above a threshold level.\n * @param level The record's level. A forwarded record can hold any string.\n * @param from Threshold level.\n * @returns True for a known level that isn't below the threshold.\n */\nfunction atOrAbove(level: string, from: LogLevel): boolean {\n return LEVEL_ORDER[level as LogLevel] >= LEVEL_ORDER[from];\n}\n\n/**\n * Decides whether sampling keeps a key at a rate. The same key always gets the same result.\n * @param key Journey ID or trace ID.\n * @param rate Sampling rate, 0..1.\n * @returns True if sampling keeps the key.\n */\nexport function sampleKey(key: string, rate: number): boolean {\n if (rate >= SAMPLING_RATE_MAX) {\n return true;\n }\n if (rate <= SAMPLING_RATE_MIN) {\n return false;\n }\n\n return hash(key) / UINT32_MAX < rate;\n}\n\n/** Fields that sampling reads. The caller knows all of them before it builds a record. */\nexport interface SampleInput {\n /** Severity level of the entry. */\n level: string;\n /** Telemetry type classification. */\n type: string;\n /** Originating application namespace. */\n namespace: string;\n /** Active journey ID. Empty when no journey is running. */\n journeyId: string;\n /** Trace ID. Used as the sampling key when no journey is running. */\n traceId: string;\n /** True for a counter or histogram point. Sampling a sum would give a false sum. */\n aggregated?: boolean;\n}\n\n/**\n * Decides whether sampling keeps an entry. Reads fields, not a record, so the caller can\n * drop an entry before the attribute walk runs.\n * @param input Fields the sampling decision reads.\n * @param config Active configuration instance.\n * @param remote Current remote rules, or null.\n * @returns True if the runtime keeps and sends the entry.\n */\nexport function shouldSampleInput(\n input: SampleInput,\n config: ResolvedConfig,\n remote: RemoteRules | null,\n): boolean {\n // Records at or above alwaysSampleFrom and aggregated points bypass sampling filters. The\n // runtime samples a span by its trace before it records the span.\n if (\n input.aggregated === true ||\n input.type === LOG_TYPE_SPAN ||\n atOrAbove(input.level, config.sampling.alwaysSampleFrom)\n ) {\n return true;\n }\n\n if (config.sampling.alwaysSampleTypes.includes(input.type)) {\n return true;\n }\n\n let rate = rateFor(input.namespace, config, remote);\n\n // A remote level lets in records below the namespace's config level. Cap those too, or they\n // ship at the config rate. The level doesn't apply to an action or a metric, so don't cap\n // them.\n const configLevel = levelFor(input.namespace, config);\n const belowMinLevel = LEVEL_ORDER[input.level as LogLevel] < LEVEL_ORDER[configLevel];\n if (remote && belowMinLevel && !LEVEL_BYPASS_TYPES.includes(input.type as LogType)) {\n rate = Math.min(rate, config.sampling.remoteMaxRate);\n }\n\n // Fall back to the trace ID when there is no journey ID. It still groups one operation.\n return sampleKey(input.journeyId || input.traceId, rate);\n}\n\n/**\n * Decides whether sampling keeps a built log record. The runtime uses it for records\n * that a child context sends over the bus.\n * @param record Record to evaluate.\n * @param config Active configuration instance.\n * @param remote Current remote rules, or null.\n * @returns True if the runtime keeps and sends the record.\n */\nexport function shouldSample(\n record: LogRecord,\n config: ResolvedConfig,\n remote: RemoteRules | null = null,\n): boolean {\n return shouldSampleInput(\n {\n level: record.severityText,\n type: readAttr(record, ATTR_LOG_TYPE),\n namespace: readAttr(record, ATTR_APP_NAMESPACE),\n journeyId: readAttr(record, ATTR_JOURNEY_ID),\n traceId: record.traceId,\n aggregated:\n readAttr(record, ATTR_LOG_TYPE) === \"metric\" && readAttr(record, METRIC_KEYS.start) !== \"\",\n },\n config,\n remote,\n );\n}\n\n/**\n * Puts a fixed-window limit on the records that bypass sampling because of their level.\n *\n * ErrorCapture already limits auto-captured errors. This class covers what is left, for\n * example application code that calls logger.error in a render loop.\n */\nexport class ErrorCeiling {\n /** Records at or above the threshold level admitted in the current window. */\n private readonly window: StormWindow = { start: 0, count: 0 };\n\n /**\n * Checks a record against the limit. Only records at or above `from` are counted.\n * @param record Record about to enter a stream.\n * @param limit Maximum records in one window. Pass 0 for no limit.\n * @param windowMs Rate limit window, in milliseconds.\n * @param from Lowest level that bypasses sampling.\n * @returns False when the window has no allowance left. The caller must drop the record.\n */\n allow(\n record: LogRecord,\n limit = ERROR_CEILING_MAX_PER_WINDOW,\n windowMs = ERROR_STORM_WINDOW_MS,\n from: LogLevel = \"ERROR\",\n ): boolean {\n if (!atOrAbove(record.severityText, from)) {\n return true;\n }\n\n // Use a fixed window, not a sliding one, so a quiet period adds no allowance.\n return limit === 0 || countInWindow(this.window, limit, windowMs);\n }\n}\n"],"mappings":"A,qFAgCA,SAASa,EAAK,EAAuB,CACnC,IAAIC,EAAId,EAAAA,GAER,IAAK,IAAIe,EAAI,EAAGA,EAAIC,EAAM,OAAQ,IAChC,GAAKA,EAAM,WAAWD,CAAC,EACvB,EAAI,KAAK,KAAKD,EAAGb,EAAAA,EAAS,EAG5B,OAAOa,IAAM,CACf,CAS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ACvD,MAAO,GAGT,IAAIF,EAAOX,EAAQa,EAAM,UAAWd,EAAQK,CAAM,EAK5CU,EAAchB,EAASe,EAAM,UAAWd,CAAM,EAC9CgB,EAAgBxC,EAAAA,GAAYsC,EAAM,OAAqBtC,EAAAA,GAAYuC,GAMzE,OALIV,GAAUW,GAAiB,CAACtC,EAAAA,GAAmB,SAASoC,EAAM,IAAe,IAC/E,EAAO,KAAK,IAAIF,EAAMZ,EAAO,SAAS,aAAa,GAI9CW,EAAUG,EAAM,WAAaA,EAAM,QAASF,CAAI,CACzD,CAUA,SAAgBK,EACd,EACA,EACA,EAA6B,KACpB,CACT,OAAOJ,EACL,CACE,MAAOrB,EAAO,aACd,KAAMD,EAASC,EAAQb,EAAAA,CAAa,EACpC,UAAWY,EAASC,EAAQZ,EAAAA,CAAkB,EAC9C,UAAWW,EAASC,EAAQX,EAAAA,CAAe,EAC3C,QAASW,EAAO,QAChB,WACED,EAASC,EAAA,UAAqB,IAAM,UAAYD,EAASC,EAAQV,EAAAA,GAAY,KAAK,IAAM,EAC5F,EACAkB,EACAK,CACF,CACF,CAQA,IAAaa,EAAb,KAA0B,CAExB,OAAuC,CAAE,MAAO,EAAG,MAAO,CAAE,EAU5D,MACE,EACA,EAAA,IACA,EAAWnC,EAAAA,GACX,EAAiB,QACR,CAMT,MALA,CAAKyB,EAAUhB,EAAO,aAAckB,CAAI,GAKjCS,IAAU,GAAKnC,EAAAA,EAAc,KAAK,OAAQmC,EAAOC,CAAQ,CAClE,CACF,E"}
@@ -1,60 +0,0 @@
1
- import { $n as e, Pt as t, Tt as n, a as r, f as i, g as a, it as o, nt as s, rt as c, wt as l } from "./constants-Bwl_YtQi.js";
2
- import { t as u } from "./fixed-window-Dq3MLUUv.js";
3
- // src/core/sampling.ts
4
- function d(e) {
5
- let t = c;
6
- for (let n = 0; n < e.length; n++) t ^= e.charCodeAt(n), t = Math.imul(t, o);
7
- return t >>> 0;
8
- }
9
- function f(e, t) {
10
- let n = e.attributes[t];
11
- return typeof n == "string" ? n : "";
12
- }
13
- function p(e, t) {
14
- let n;
15
- for (let [r, i] of Object.entries(t)) (e === r || e.startsWith(`${r}.`)) && r.length > (n?.length ?? -1) && (n = {
16
- value: i,
17
- length: r.length
18
- });
19
- return n;
20
- }
21
- function m(e, t) {
22
- return p(e, t.minLevels)?.value ?? t.minLevel;
23
- }
24
- function h(e, t, n) {
25
- let { rates: r, defaultRate: i, remoteMaxRate: a } = t.sampling, o = p(e, r), s = n ? p(e, n.rates) : void 0;
26
- return s && s.length >= (o?.length ?? -1) ? Math.min(s.value, a) : o ? o.value : n?.defaultRate === void 0 ? i : Math.min(n.defaultRate, a);
27
- }
28
- function g(e, t) {
29
- return n[e] >= n[t];
30
- }
31
- function _(t, n) {
32
- return n >= 1 ? !0 : n <= 0 ? !1 : d(t) / e < n;
33
- }
34
- function v(e, t, r) {
35
- if (e.aggregated === !0 || e.type === "span" || g(e.level, t.sampling.alwaysSampleFrom) || t.sampling.alwaysSampleTypes.includes(e.type)) return !0;
36
- let i = h(e.namespace, t, r), a = m(e.namespace, t), o = n[e.level] < n[a];
37
- return r && o && !l.includes(e.type) && (i = Math.min(i, t.sampling.remoteMaxRate)), _(e.journeyId || e.traceId, i);
38
- }
39
- function y(e, n, o = null) {
40
- return v({
41
- level: e.severityText,
42
- type: f(e, a),
43
- namespace: f(e, r),
44
- journeyId: f(e, i),
45
- traceId: e.traceId,
46
- aggregated: f(e, "log.type") === "metric" && f(e, t.start) !== ""
47
- }, n, o);
48
- }
49
- var b = class {
50
- window = {
51
- start: 0,
52
- count: 0
53
- };
54
- allow(e, t = 500, n = s, r = "ERROR") {
55
- return !g(e.severityText, r) || t === 0 || u(this.window, t, n);
56
- }
57
- };
58
- export { y as a, _ as i, m as n, v as o, p as r, b as t };
59
-
60
- //# sourceMappingURL=sampling-UUDbi3K0.js.map
@@ -1 +0,0 @@
1
- {"version":3,"file":"sampling-UUDbi3K0.js","names":["UINT32_MAX","METRIC_KEYS","LEVEL_ORDER","ATTR_APP_NAMESPACE","ATTR_JOURNEY_ID","ATTR_LOG_TYPE","FNV_PRIME","ERROR_STORM_WINDOW_MS","FNV_OFFSET_BASIS","LEVEL_BYPASS_TYPES","countInWindow","hash","h","i","value","readAttr","record","key","longestPrefix","best","prefix","values","namespace","levelFor","config","rateFor","local","rates","fromRemote","remote","remoteMaxRate","defaultRate","atOrAbove","level","from","sampleKey","rate","shouldSampleInput","input","configLevel","belowMinLevel","shouldSample","ErrorCeiling","limit","windowMs"],"sources":["../src/core/sampling.ts"],"sourcesContent":["// src/core/sampling.ts\n//\n// Samples records by namespace rule, journey ID and trace ID.\n// The journey ID is the sampling key, so a whole journey is kept or dropped together and\n// the result is the same across windows and reloads.\n\nimport {\n ATTR_APP_NAMESPACE,\n ATTR_JOURNEY_ID,\n ATTR_LOG_TYPE,\n ERROR_CEILING_MAX_PER_WINDOW,\n ERROR_STORM_WINDOW_MS,\n FNV_OFFSET_BASIS,\n FNV_PRIME,\n LEVEL_BYPASS_TYPES,\n LEVEL_ORDER,\n LOG_TYPE_SPAN,\n METRIC_KEYS,\n SAMPLING_RATE_MAX,\n SAMPLING_RATE_MIN,\n UINT32_MAX,\n} from \"../constants\";\nimport type { ResolvedConfig } from \"../models/config\";\nimport type { LogLevel, LogRecord, LogType } from \"../models/log-record\";\nimport { countInWindow, type StormWindow } from \"../utils/fixed-window\";\nimport type { RemoteRules } from \"./remote-sampling\";\n\n/**\n * Computes the 32-bit FNV-1a hash of a string. Do not use it as a security hash.\n * @param value Key string to hash.\n * @returns Unsigned 32-bit integer hash.\n */\nfunction hash(value: string): number {\n let h = FNV_OFFSET_BASIS;\n\n for (let i = 0; i < value.length; i++) {\n h ^= value.charCodeAt(i);\n h = Math.imul(h, FNV_PRIME);\n }\n\n return h >>> 0;\n}\n\n/**\n * Reads a string attribute from a log record. Returns an empty string for an absent\n * or non-string value, because a forwarded record has only passed a shape check.\n * @param record Log record to read from.\n * @param key Attribute key.\n * @returns String attribute value, or empty string if missing or non-string.\n */\nfunction readAttr(record: LogRecord, key: string): string {\n const value: unknown = record.attributes[key];\n return typeof value === \"string\" ? value : \"\";\n}\n\n/** Value of the longest prefix that matches a namespace. */\ninterface PrefixMatch<T> {\n /** The prefix's value, for example a rate or a level. */\n value: T;\n /** Length of the prefix. */\n length: number;\n}\n\n/**\n * Finds the longest prefix in a map that matches a namespace.\n * For example, trading.ticks overrides trading.\n * @param namespace Target application namespace.\n * @param values Value for each namespace prefix.\n * @returns The match, or undefined if no prefix matches.\n */\nexport function longestPrefix<T>(\n namespace: string,\n values: Record<string, T>,\n): PrefixMatch<T> | undefined {\n let best: PrefixMatch<T> | undefined;\n\n for (const [prefix, value] of Object.entries(values)) {\n const matches = namespace === prefix || namespace.startsWith(`${prefix}.`);\n\n if (matches && prefix.length > (best?.length ?? -1)) {\n best = { value, length: prefix.length };\n }\n }\n\n return best;\n}\n\n/**\n * Finds a namespace's minimum level in the config. The longest matching prefix in\n * `minLevels` wins, and a namespace with no match uses `minLevel`.\n * @param namespace Target application namespace.\n * @param config Active configuration instance.\n * @returns The namespace's minimum level.\n */\nexport function levelFor(namespace: string, config: ResolvedConfig): LogLevel {\n return longestPrefix(namespace, config.minLevels)?.value ?? config.minLevel;\n}\n\n/**\n * Finds the sampling rate for a namespace. The longest matching prefix wins.\n * A remote prefix wins over a config prefix of the same length.\n * @param namespace Target application namespace.\n * @param config Active configuration instance.\n * @param remote Current remote rules, or null.\n * @returns Matched namespace sampling rate or default rate.\n */\nfunction rateFor(namespace: string, config: ResolvedConfig, remote: RemoteRules | null): number {\n const { rates, defaultRate, remoteMaxRate } = config.sampling;\n const local = longestPrefix(namespace, rates);\n const fromRemote = remote ? longestPrefix(namespace, remote.rates) : undefined;\n\n // Cap a remote rate at the point where sampling reads it, so a configure() that lowers the\n // cap takes effect immediately.\n if (fromRemote && fromRemote.length >= (local?.length ?? -1)) {\n return Math.min(fromRemote.value, remoteMaxRate);\n }\n\n if (local) {\n return local.value;\n }\n\n return remote?.defaultRate === undefined\n ? defaultRate\n : Math.min(remote.defaultRate, remoteMaxRate);\n}\n\n/**\n * Checks whether a level is at or above a threshold level.\n * @param level The record's level. A forwarded record can hold any string.\n * @param from Threshold level.\n * @returns True for a known level that isn't below the threshold.\n */\nfunction atOrAbove(level: string, from: LogLevel): boolean {\n return LEVEL_ORDER[level as LogLevel] >= LEVEL_ORDER[from];\n}\n\n/**\n * Decides whether sampling keeps a key at a rate. The same key always gets the same result.\n * @param key Journey ID or trace ID.\n * @param rate Sampling rate, 0..1.\n * @returns True if sampling keeps the key.\n */\nexport function sampleKey(key: string, rate: number): boolean {\n if (rate >= SAMPLING_RATE_MAX) {\n return true;\n }\n if (rate <= SAMPLING_RATE_MIN) {\n return false;\n }\n\n return hash(key) / UINT32_MAX < rate;\n}\n\n/** Fields that sampling reads. The caller knows all of them before it builds a record. */\nexport interface SampleInput {\n /** Severity level of the entry. */\n level: string;\n /** Telemetry type classification. */\n type: string;\n /** Originating application namespace. */\n namespace: string;\n /** Active journey ID. Empty when no journey is running. */\n journeyId: string;\n /** Trace ID. Used as the sampling key when no journey is running. */\n traceId: string;\n /** True for a counter or histogram point. Sampling a sum would give a false sum. */\n aggregated?: boolean;\n}\n\n/**\n * Decides whether sampling keeps an entry. Reads fields, not a record, so the caller can\n * drop an entry before the attribute walk runs.\n * @param input Fields the sampling decision reads.\n * @param config Active configuration instance.\n * @param remote Current remote rules, or null.\n * @returns True if the runtime keeps and sends the entry.\n */\nexport function shouldSampleInput(\n input: SampleInput,\n config: ResolvedConfig,\n remote: RemoteRules | null,\n): boolean {\n // Records at or above alwaysSampleFrom and aggregated points bypass sampling filters. The\n // runtime samples a span by its trace before it records the span.\n if (\n input.aggregated === true ||\n input.type === LOG_TYPE_SPAN ||\n atOrAbove(input.level, config.sampling.alwaysSampleFrom)\n ) {\n return true;\n }\n\n if (config.sampling.alwaysSampleTypes.includes(input.type)) {\n return true;\n }\n\n let rate = rateFor(input.namespace, config, remote);\n\n // A remote level lets in records below the namespace's config level. Cap those too, or they\n // ship at the config rate. The level doesn't apply to an action or a metric, so don't cap\n // them.\n const configLevel = levelFor(input.namespace, config);\n const belowMinLevel = LEVEL_ORDER[input.level as LogLevel] < LEVEL_ORDER[configLevel];\n if (remote && belowMinLevel && !LEVEL_BYPASS_TYPES.includes(input.type as LogType)) {\n rate = Math.min(rate, config.sampling.remoteMaxRate);\n }\n\n // Fall back to the trace ID when there is no journey ID. It still groups one operation.\n return sampleKey(input.journeyId || input.traceId, rate);\n}\n\n/**\n * Decides whether sampling keeps a built log record. The runtime uses it for records\n * that a child context sends over the bus.\n * @param record Record to evaluate.\n * @param config Active configuration instance.\n * @param remote Current remote rules, or null.\n * @returns True if the runtime keeps and sends the record.\n */\nexport function shouldSample(\n record: LogRecord,\n config: ResolvedConfig,\n remote: RemoteRules | null = null,\n): boolean {\n return shouldSampleInput(\n {\n level: record.severityText,\n type: readAttr(record, ATTR_LOG_TYPE),\n namespace: readAttr(record, ATTR_APP_NAMESPACE),\n journeyId: readAttr(record, ATTR_JOURNEY_ID),\n traceId: record.traceId,\n aggregated:\n readAttr(record, ATTR_LOG_TYPE) === \"metric\" && readAttr(record, METRIC_KEYS.start) !== \"\",\n },\n config,\n remote,\n );\n}\n\n/**\n * Puts a fixed-window limit on the records that bypass sampling because of their level.\n *\n * ErrorCapture already limits auto-captured errors. This class covers what is left, for\n * example application code that calls logger.error in a render loop.\n */\nexport class ErrorCeiling {\n /** Records at or above the threshold level admitted in the current window. */\n private readonly window: StormWindow = { start: 0, count: 0 };\n\n /**\n * Checks a record against the limit. Only records at or above `from` are counted.\n * @param record Record about to enter a stream.\n * @param limit Maximum records in one window. Pass 0 for no limit.\n * @param windowMs Rate limit window, in milliseconds.\n * @param from Lowest level that bypasses sampling.\n * @returns False when the window has no allowance left. The caller must drop the record.\n */\n allow(\n record: LogRecord,\n limit = ERROR_CEILING_MAX_PER_WINDOW,\n windowMs = ERROR_STORM_WINDOW_MS,\n from: LogLevel = \"ERROR\",\n ): boolean {\n if (!atOrAbove(record.severityText, from)) {\n return true;\n }\n\n // Use a fixed window, not a sliding one, so a quiet period adds no allowance.\n return limit === 0 || countInWindow(this.window, limit, windowMs);\n }\n}\n"],"mappings":";;;AAgCA,SAASW,EAAK,GAAuB;CACnC,IAAIC,IAAIJ;CAER,KAAK,IAAIK,IAAI,GAAGA,IAAIC,EAAM,QAAQ,KAEhC,AADA,KAAKA,EAAM,WAAWD,CAAC,GACvB,IAAI,KAAK,KAAKD,GAAGN,CAAS;CAG5B,OAAOM,MAAM;AACf;AASA,SAASG,EAAS,GAAmB,GAAqB;CACxD,IAAMD,IAAiBE,EAAO,WAAWC;CACzC,OAAO,OAAOH,KAAU,WAAWA,IAAQ;AAC7C;AAiBA,SAAgBI,EACd,GACA,GAC4B;CAC5B,IAAIC;CAEJ,KAAK,IAAM,CAACC,GAAQN,MAAU,OAAO,QAAQO,CAAM,GAGjD,CAFgBC,MAAcF,KAAUE,EAAU,WAAW,GAAGF,EAAO,EAAE,MAE1DA,EAAO,UAAUD,GAAM,UAAU,QAC9C,IAAO;EAAE;EAAO,QAAQC,EAAO;CAAO;CAI1C,OAAOD;AACT;AASA,SAAgBI,EAAS,GAAmB,GAAkC;CAC5E,OAAOL,EAAcI,GAAWE,EAAO,SAAS,CAAC,EAAE,SAASA,EAAO;AACrE;AAUA,SAASC,EAAQ,GAAmB,GAAwB,GAAoC;CAC9F,IAAM,EAAE,UAAO,gBAAa,qBAAkBD,EAAO,UAC/CE,IAAQR,EAAcI,GAAWK,CAAK,GACtCC,IAAaC,IAASX,EAAcI,GAAWO,EAAO,KAAK,IAAI,KAAA;CAYrE,OARID,KAAcA,EAAW,WAAWF,GAAO,UAAU,MAChD,KAAK,IAAIE,EAAW,OAAOE,CAAa,IAG7CJ,IACKA,EAAM,QAGRG,GAAQ,gBAAgB,KAAA,IAC3BE,IACA,KAAK,IAAIF,EAAO,aAAaC,CAAa;AAChD;AAQA,SAASE,EAAU,GAAe,GAAyB;CACzD,OAAO9B,EAA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ize-CNmsD9r3.js","names":["set","toJson","isDataField","truncate","value","max","end","isHighSurrogate","code","describeNode","node","sanitize","sanitizeWithSize","limits","diagnostics","state","walk","counted","estimateBytes","text","depth","seen","error","extra","extraCount","key","field","ERROR_OWN_KEYS","map","out","shown","entry","name","length","items","item","maybeToJson","record","keys","count","bytes","i"],"sources":["../src/utils/sanitize.ts"],"sourcesContent":["// src/utils/sanitize.ts\n//\n// Converts arbitrary data into JSON-safe structures, detecting cycles and estimating the byte\n// size. Never throws and never returns a circular structure.\n\nimport {\n BYTES_PER_BOOLEAN,\n BYTES_PER_CONTAINER,\n BYTES_PER_KEY_OVERHEAD,\n BYTES_PER_NULL,\n BYTES_PER_NUMBER,\n BYTES_PER_QUOTED_STRING,\n HIGH_SURROGATE_MAX,\n HIGH_SURROGATE_MIN,\n MAX_NODE_CLASS_NAMES,\n UTF8_ONE_BYTE_CEILING,\n UTF8_TWO_BYTE_CEILING,\n} from \"../constants\";\nimport type { Diagnostics } from \"../core/diagnostics\";\nimport { ERROR_OWN_KEYS, isDataField } from \"./error-like\";\n\n/** Structural depth and size limits enforced during object sanitization. */\nexport interface SanitizeLimits {\n /** Maximum recursion depth before truncating nested objects. */\n maxDepth: number;\n /** Maximum items retained in arrays, sets, and maps before truncating. */\n maxArrayLength: number;\n /** Maximum string attribute length in characters. */\n maxAttributeChars: number;\n /** Maximum key-value properties retained in a single object. */\n maxAttributeCount: number;\n /** Maximum error stack trace length in characters. */\n maxStackChars: number;\n /** Maximum values visited in one pass, across the whole tree. */\n maxNodes: number;\n}\n\n/**\n * Truncates a string to a maximum character length while preserving UTF-16 surrogate pairs.\n * @param value Target string.\n * @param max Maximum allowed character length.\n * @returns The truncated string, with a suffix that gives the dropped character count.\n */\nexport function truncate(value: string, max: number): string {\n if (value.length <= max) {\n return value;\n }\n\n // Don't split a UTF-16 surrogate pair at the cut. slice works in code units, and half a\n // pair serializes as U+FFFD.\n const end = isHighSurrogate(value.charCodeAt(max - 1)) ? max - 1 : max;\n return `${value.slice(0, end)}… [truncated ${String(value.length - end)} chars]`;\n}\n\n/**\n * Checks whether a UTF-16 code unit is a leading surrogate.\n * @param code UTF-16 character code.\n * @returns True if the character is a high surrogate.\n */\nfunction isHighSurrogate(code: number): boolean {\n return code >= HIGH_SURROGATE_MIN && code <= HIGH_SURROGATE_MAX;\n}\n\n/** Structural interface for DOM Node inspection across realms. */\ninterface NodeLike {\n nodeName?: string;\n id?: string;\n className?: unknown;\n}\n\n/**\n * Formats a DOM node as a descriptive CSS selector string.\n * @param node Node-like object to format.\n * @returns Formatted selector string.\n */\nfunction describeNode(node: NodeLike): string {\n const tag = (node.nodeName ?? \"NODE\").toLowerCase();\n const id = node.id ? `#${node.id}` : \"\";\n const cls =\n typeof node.className === \"string\" && node.className\n ? `.${node.className.trim().split(/\\s+/).slice(0, MAX_NODE_CLASS_NAMES).join(\".\")}`\n : \"\";\n return `[Element ${tag}${id}${cls}]`;\n}\n\n/** Sanitized JSON-safe output with estimated serialized byte size. */\nexport interface SanitizeResult {\n /** JSON-safe sanitized structure. */\n value: unknown;\n /** Approximate serialized byte count. */\n bytes: number;\n}\n\n/** Mutable accumulators passed through recursive sanitization passes. */\ninterface WalkState {\n /** Running estimate of the serialized byte count. */\n bytes: number;\n /** Count of values visited so far. */\n nodes: number;\n /** Diagnostics reporter. Counts a value that throws during the walk. */\n diagnostics: Diagnostics;\n}\n\n/**\n * Sanitizes arbitrary values into JSON-safe structures without throwing.\n * @param value Raw value to sanitize.\n * @param limits Configuration limits for depth, count, and character lengths.\n * @param diagnostics Diagnostics reporter. Counts a value that throws during the walk.\n * @returns JSON-safe sanitized value.\n */\nexport function sanitize(\n value: unknown,\n limits: SanitizeLimits,\n diagnostics: Diagnostics,\n): unknown {\n return sanitizeWithSize(value, limits, diagnostics).value;\n}\n\n/**\n * Sanitizes arbitrary values and calculates approximate serialized byte sizes.\n * @param value Raw value to sanitize.\n * @param limits Configuration limits.\n * @param diagnostics Diagnostics reporter. Counts a value that throws during the walk.\n * @returns SanitizeResult containing sanitized value and byte count.\n */\nexport function sanitizeWithSize(\n value: unknown,\n limits: SanitizeLimits,\n diagnostics: Diagnostics,\n): SanitizeResult {\n const state: WalkState = { bytes: 0, nodes: 0, diagnostics };\n const result = walk(value, limits, new WeakSet(), 0, state);\n return { value: result, bytes: state.bytes };\n}\n\n/**\n * Adds a string's length plus quote overhead to the size accumulator.\n * @param text Serialized string token.\n * @param state Byte size accumulator.\n * @returns The input text, unchanged.\n */\nfunction counted(text: string, state: WalkState): string {\n state.bytes += estimateBytes(text) + BYTES_PER_QUOTED_STRING;\n return text;\n}\n\n/**\n * Walks an object tree recursively, replacing cyclic references, hostile getters, and\n * invalid primitives.\n * @param value Target value to sanitize.\n * @param limits Truncation and depth limits.\n * @param seen Set of active ancestor objects for cycle detection.\n * @param depth Current recursion depth.\n * @param state Running byte size accumulator.\n * @returns JSON-safe sanitized representation.\n */\nfunction walk(\n value: unknown,\n limits: SanitizeLimits,\n seen: WeakSet<object>,\n depth: number,\n state: WalkState,\n): unknown {\n state.nodes++;\n // The per-level limits don't bound a wide tree: 128 keys over 6 levels is 128^6 values, and\n // the walk would visit all of them synchronously on the main thread.\n if (state.nodes > limits.maxNodes) {\n return counted(\"[MaxNodes]\", state);\n }\n\n if (value === null || value === undefined) {\n state.bytes += BYTES_PER_NULL;\n return value;\n }\n\n if (typeof value === \"string\") {\n return counted(truncate(value, limits.maxAttributeChars), state);\n }\n if (typeof value === \"number\") {\n state.bytes += BYTES_PER_NUMBER;\n return Number.isFinite(value) ? value : String(value);\n }\n if (typeof value === \"boolean\") {\n state.bytes += BYTES_PER_BOOLEAN;\n return value;\n }\n if (typeof value === \"bigint\") {\n return counted(`${value.toString()}n`, state);\n }\n if (typeof value === \"symbol\") {\n return counted(value.toString(), state);\n }\n if (typeof value === \"function\") {\n return counted(`[Function ${value.name === \"\" ? \"anonymous\" : value.name}]`, state);\n }\n\n if (depth >= limits.maxDepth) {\n return counted(\"[MaxDepth]\", state);\n }\n\n if (seen.has(value)) {\n return counted(\"[Circular]\", state);\n }\n seen.add(value);\n state.bytes += BYTES_PER_CONTAINER;\n\n try {\n // An Error from another realm fails instanceof, but its built-in tag still names an Error.\n if (value instanceof Error || Object.prototype.toString.call(value) === \"[object Error]\") {\n const error = value as Error;\n // Keep the error's own fields, for example a code or an HTTP status.\n const extra: Record<string, unknown> = {};\n let extraCount = 0;\n for (const key of Object.keys(error)) {\n const field = (error as unknown as Record<string, unknown>)[key];\n if (!ERROR_OWN_KEYS.has(key) && isDataField(field)) {\n extra[key] = field;\n extraCount++;\n }\n }\n\n return {\n name: counted(error.name, state),\n message: counted(truncate(error.message, limits.maxAttributeChars), state),\n stack: error.stack\n ? counted(truncate(error.stack, limits.maxStackChars), state)\n : undefined,\n cause: error.cause ? walk(error.cause, limits, seen, depth + 1, state) : undefined,\n data: extraCount > 0 ? walk(extra, limits, seen, depth + 1, state) : undefined,\n };\n }\n if (value instanceof Date) {\n return counted(value.toISOString(), state);\n }\n if (value instanceof RegExp) {\n return counted(value.toString(), state);\n }\n if (value instanceof Map) {\n const map: ReadonlyMap<unknown, unknown> = value;\n const out: Record<string, unknown> = {};\n let shown = 0;\n for (const [key, entry] of map) {\n if (shown >= limits.maxArrayLength) {\n out[\"…\"] = counted(`[${String(map.size - limits.maxArrayLength)} more entries]`, state);\n break;\n }\n shown++;\n const name = String(key);\n state.bytes += estimateBytes(name) + BYTES_PER_KEY_OVERHEAD;\n out[name] = walk(entry, limits, seen, depth + 1, state);\n }\n return out;\n }\n if (value instanceof Set) {\n const set: ReadonlySet<unknown> = value;\n return walk([...set].slice(0, limits.maxArrayLength), limits, seen, depth, state);\n }\n if (ArrayBuffer.isView(value)) {\n const length = (value as { length?: number }).length ?? 0;\n return counted(`[${value.constructor.name}(${String(length)})]`, state);\n }\n if (value instanceof Promise) {\n return counted(\"[Promise]\", state);\n }\n if (typeof Node !== \"undefined\" && value instanceof Node) {\n return counted(describeNode(value), state);\n }\n\n if (Array.isArray(value)) {\n const items: readonly unknown[] = value;\n const out: unknown[] = items\n .slice(0, limits.maxArrayLength)\n .map((item) => walk(item, limits, seen, depth + 1, state));\n if (items.length > limits.maxArrayLength) {\n out.push(counted(`[${String(items.length - limits.maxArrayLength)} more items]`, state));\n }\n return out;\n }\n\n const maybeToJson: unknown = (value as { toJSON?: unknown }).toJSON;\n if (typeof maybeToJson === \"function\") {\n const toJson = maybeToJson as () => unknown;\n return walk(toJson.call(value), limits, seen, depth + 1, state);\n }\n\n const record = value as Record<string, unknown>;\n const keys = Object.keys(record);\n const out: Record<string, unknown> = {};\n let count = 0;\n for (const key of keys) {\n if (count >= limits.maxAttributeCount) {\n out[\"…\"] = counted(`[${String(keys.length - count)} more keys]`, state);\n break;\n }\n count++;\n state.bytes += estimateBytes(key) + BYTES_PER_KEY_OVERHEAD;\n out[key] = walk(record[key], limits, seen, depth + 1, state);\n }\n return out;\n } catch (error) {\n // Catch hostile getters and throwing proxies. A failure replaces one attribute, not the\n // whole record. Count the fault, because a report for every attribute would be noise.\n state.diagnostics.count(\"record.sanitize_failed\");\n const name = error instanceof Error ? error.name : \"error\";\n return counted(`[Unserializable: ${name}]`, state);\n } finally {\n // Remove the object from the ancestor set on unwind, or a repeated sibling would show\n // up as a cycle.\n seen.delete(value);\n }\n}\n\n/**\n * Estimates UTF-8 encoded byte length for a string.\n * @param value Target string.\n * @returns Estimated UTF-8 byte length.\n */\nexport function estimateBytes(value: string): number {\n let bytes = 0;\n for (let i = 0; i < value.length; i++) {\n const code = value.charCodeAt(i);\n if (code < UTF8_ONE_BYTE_CEILING) {\n bytes += 1;\n } else if (code < UTF8_TWO_BYTE_CEILING) {\n bytes += 2;\n } else if (code >= HIGH_SURROGATE_MIN && code <= HIGH_SURROGATE_MAX) {\n bytes += 4;\n i++;\n } else {\n bytes += 3;\n }\n }\n return bytes;\n}\n"],"mappings":";;;AA2CA,SAAgBG,EAAS,GAAe,GAAqB;CAC3D,IAAIC,EAAM,UAAUC,GAClB,OAAOD;CAKT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_error_like","truncate","value","max","end","isHighSurrogate","code","describeNode","node","sanitize","sanitizeWithSize","limits","diagnostics","state","walk","counted","estimateBytes","text","depth","seen","error","extra","extraCount","key","field","map","out","shown","entry","name","length","items","item","maybeToJson","record","keys","count","bytes","i"],"sources":["../src/utils/sanitize.ts"],"sourcesContent":["// src/utils/sanitize.ts\n//\n// Converts arbitrary data into JSON-safe structures, detecting cycles and estimating the byte\n// size. Never throws and never returns a circular structure.\n\nimport {\n BYTES_PER_BOOLEAN,\n BYTES_PER_CONTAINER,\n BYTES_PER_KEY_OVERHEAD,\n BYTES_PER_NULL,\n BYTES_PER_NUMBER,\n BYTES_PER_QUOTED_STRING,\n HIGH_SURROGATE_MAX,\n HIGH_SURROGATE_MIN,\n MAX_NODE_CLASS_NAMES,\n UTF8_ONE_BYTE_CEILING,\n UTF8_TWO_BYTE_CEILING,\n} from \"../constants\";\nimport type { Diagnostics } from \"../core/diagnostics\";\nimport { ERROR_OWN_KEYS, isDataField } from \"./error-like\";\n\n/** Structural depth and size limits enforced during object sanitization. */\nexport interface SanitizeLimits {\n /** Maximum recursion depth before truncating nested objects. */\n maxDepth: number;\n /** Maximum items retained in arrays, sets, and maps before truncating. */\n maxArrayLength: number;\n /** Maximum string attribute length in characters. */\n maxAttributeChars: number;\n /** Maximum key-value properties retained in a single object. */\n maxAttributeCount: number;\n /** Maximum error stack trace length in characters. */\n maxStackChars: number;\n /** Maximum values visited in one pass, across the whole tree. */\n maxNodes: number;\n}\n\n/**\n * Truncates a string to a maximum character length while preserving UTF-16 surrogate pairs.\n * @param value Target string.\n * @param max Maximum allowed character length.\n * @returns The truncated string, with a suffix that gives the dropped character count.\n */\nexport function truncate(value: string, max: number): string {\n if (value.length <= max) {\n return value;\n }\n\n // Don't split a UTF-16 surrogate pair at the cut. slice works in code units, and half a\n // pair serializes as U+FFFD.\n const end = isHighSurrogate(value.charCodeAt(max - 1)) ? max - 1 : max;\n return `${value.slice(0, end)}… [truncated ${String(value.length - end)} chars]`;\n}\n\n/**\n * Checks whether a UTF-16 code unit is a leading surrogate.\n * @param code UTF-16 character code.\n * @returns True if the character is a high surrogate.\n */\nfunction isHighSurrogate(code: number): boolean {\n return code >= HIGH_SURROGATE_MIN && code <= HIGH_SURROGATE_MAX;\n}\n\n/** Structural interface for DOM Node inspection across realms. */\ninterface NodeLike {\n nodeName?: string;\n id?: string;\n className?: unknown;\n}\n\n/**\n * Formats a DOM node as a descriptive CSS selector string.\n * @param node Node-like object to format.\n * @returns Formatted selector string.\n */\nfunction describeNode(node: NodeLike): string {\n const tag = (node.nodeName ?? \"NODE\").toLowerCase();\n const id = node.id ? `#${node.id}` : \"\";\n const cls =\n typeof node.className === \"string\" && node.className\n ? `.${node.className.trim().split(/\\s+/).slice(0, MAX_NODE_CLASS_NAMES).join(\".\")}`\n : \"\";\n return `[Element ${tag}${id}${cls}]`;\n}\n\n/** Sanitized JSON-safe output with estimated serialized byte size. */\nexport interface SanitizeResult {\n /** JSON-safe sanitized structure. */\n value: unknown;\n /** Approximate serialized byte count. */\n bytes: number;\n}\n\n/** Mutable accumulators passed through recursive sanitization passes. */\ninterface WalkState {\n /** Running estimate of the serialized byte count. */\n bytes: number;\n /** Count of values visited so far. */\n nodes: number;\n /** Diagnostics reporter. Counts a value that throws during the walk. */\n diagnostics: Diagnostics;\n}\n\n/**\n * Sanitizes arbitrary values into JSON-safe structures without throwing.\n * @param value Raw value to sanitize.\n * @param limits Configuration limits for depth, count, and character lengths.\n * @param diagnostics Diagnostics reporter. Counts a value that throws during the walk.\n * @returns JSON-safe sanitized value.\n */\nexport function sanitize(\n value: unknown,\n limits: SanitizeLimits,\n diagnostics: Diagnostics,\n): unknown {\n return sanitizeWithSize(value, limits, diagnostics).value;\n}\n\n/**\n * Sanitizes arbitrary values and calculates approximate serialized byte sizes.\n * @param value Raw value to sanitize.\n * @param limits Configuration limits.\n * @param diagnostics Diagnostics reporter. Counts a value that throws during the walk.\n * @returns SanitizeResult containing sanitized value and byte count.\n */\nexport function sanitizeWithSize(\n value: unknown,\n limits: SanitizeLimits,\n diagnostics: Diagnostics,\n): SanitizeResult {\n const state: WalkState = { bytes: 0, nodes: 0, diagnostics };\n const result = walk(value, limits, new WeakSet(), 0, state);\n return { value: result, bytes: state.bytes };\n}\n\n/**\n * Adds a string's length plus quote overhead to the size accumulator.\n * @param text Serialized string token.\n * @param state Byte size accumulator.\n * @returns The input text, unchanged.\n */\nfunction counted(text: string, state: WalkState): string {\n state.bytes += estimateBytes(text) + BYTES_PER_QUOTED_STRING;\n return text;\n}\n\n/**\n * Walks an object tree recursively, replacing cyclic references, hostile getters, and\n * invalid primitives.\n * @param value Target value to sanitize.\n * @param limits Truncation and depth limits.\n * @param seen Set of active ancestor objects for cycle detection.\n * @param depth Current recursion depth.\n * @param state Running byte size accumulator.\n * @returns JSON-safe sanitized representation.\n */\nfunction walk(\n value: unknown,\n limits: SanitizeLimits,\n seen: WeakSet<object>,\n depth: number,\n state: WalkState,\n): unknown {\n state.nodes++;\n // The per-level limits don't bound a wide tree: 128 keys over 6 levels is 128^6 values, and\n // the walk would visit all of them synchronously on the main thread.\n if (state.nodes > limits.maxNodes) {\n return counted(\"[MaxNodes]\", state);\n }\n\n if (value === null || value === undefined) {\n state.bytes += BYTES_PER_NULL;\n return value;\n }\n\n if (typeof value === \"string\") {\n return counted(truncate(value, limits.maxAttributeChars), state);\n }\n if (typeof value === \"number\") {\n state.bytes += BYTES_PER_NUMBER;\n return Number.isFinite(value) ? value : String(value);\n }\n if (typeof value === \"boolean\") {\n state.bytes += BYTES_PER_BOOLEAN;\n return value;\n }\n if (typeof value === \"bigint\") {\n return counted(`${value.toString()}n`, state);\n }\n if (typeof value === \"symbol\") {\n return counted(value.toString(), state);\n }\n if (typeof value === \"function\") {\n return counted(`[Function ${value.name === \"\" ? \"anonymous\" : value.name}]`, state);\n }\n\n if (depth >= limits.maxDepth) {\n return counted(\"[MaxDepth]\", state);\n }\n\n if (seen.has(value)) {\n return counted(\"[Circular]\", state);\n }\n seen.add(value);\n state.bytes += BYTES_PER_CONTAINER;\n\n try {\n // An Error from another realm fails instanceof, but its built-in tag still names an Error.\n if (value instanceof Error || Object.prototype.toString.call(value) === \"[object Error]\") {\n const error = value as Error;\n // Keep the error's own fields, for example a code or an HTTP status.\n const extra: Record<string, unknown> = {};\n let extraCount = 0;\n for (const key of Object.keys(error)) {\n const field = (error as unknown as Record<string, unknown>)[key];\n if (!ERROR_OWN_KEYS.has(key) && isDataField(field)) {\n extra[key] = field;\n extraCount++;\n }\n }\n\n return {\n name: counted(error.name, state),\n message: counted(truncate(error.message, limits.maxAttributeChars), state),\n stack: error.stack\n ? counted(truncate(error.stack, limits.maxStackChars), state)\n : undefined,\n cause: error.cause ? walk(error.cause, limits, seen, depth + 1, state) : undefined,\n data: extraCount > 0 ? walk(extra, limits, seen, depth + 1, state) : undefined,\n };\n }\n if (value instanceof Date) {\n return counted(value.toISOString(), state);\n }\n if (value instanceof RegExp) {\n return counted(value.toString(), state);\n }\n if (value instanceof Map) {\n const map: ReadonlyMap<unknown, unknown> = value;\n const out: Record<string, unknown> = {};\n let shown = 0;\n for (const [key, entry] of map) {\n if (shown >= limits.maxArrayLength) {\n out[\"…\"] = counted(`[${String(map.size - limits.maxArrayLength)} more entries]`, state);\n break;\n }\n shown++;\n const name = String(key);\n state.bytes += estimateBytes(name) + BYTES_PER_KEY_OVERHEAD;\n out[name] = walk(entry, limits, seen, depth + 1, state);\n }\n return out;\n }\n if (value instanceof Set) {\n const set: ReadonlySet<unknown> = value;\n return walk([...set].slice(0, limits.maxArrayLength), limits, seen, depth, state);\n }\n if (ArrayBuffer.isView(value)) {\n const length = (value as { length?: number }).length ?? 0;\n return counted(`[${value.constructor.name}(${String(length)})]`, state);\n }\n if (value instanceof Promise) {\n return counted(\"[Promise]\", state);\n }\n if (typeof Node !== \"undefined\" && value instanceof Node) {\n return counted(describeNode(value), state);\n }\n\n if (Array.isArray(value)) {\n const items: readonly unknown[] = value;\n const out: unknown[] = items\n .slice(0, limits.maxArrayLength)\n .map((item) => walk(item, limits, seen, depth + 1, state));\n if (items.length > limits.maxArrayLength) {\n out.push(counted(`[${String(items.length - limits.maxArrayLength)} more items]`, state));\n }\n return out;\n }\n\n const maybeToJson: unknown = (value as { toJSON?: unknown }).toJSON;\n if (typeof maybeToJson === \"function\") {\n const toJson = maybeToJson as () => unknown;\n return walk(toJson.call(value), limits, seen, depth + 1, state);\n }\n\n const record = value as Record<string, unknown>;\n const keys = Object.keys(record);\n const out: Record<string, unknown> = {};\n let count = 0;\n for (const key of keys) {\n if (count >= limits.maxAttributeCount) {\n out[\"…\"] = counted(`[${String(keys.length - count)} more keys]`, state);\n break;\n }\n count++;\n state.bytes += estimateBytes(key) + BYTES_PER_KEY_OVERHEAD;\n out[key] = walk(record[key], limits, seen, depth + 1, state);\n }\n return out;\n } catch (error) {\n // Catch hostile getters and throwing proxies. A failure replaces one attribute, not the\n // whole record. Count the fault, because a report for every attribute would be noise.\n state.diagnostics.count(\"record.sanitize_failed\");\n const name = error instanceof Error ? error.name : \"error\";\n return counted(`[Unserializable: ${name}]`, state);\n } finally {\n // Remove the object from the ancestor set on unwind, or a repeated sibling would show\n // up as a cycle.\n seen.delete(value);\n }\n}\n\n/**\n * Estimates UTF-8 encoded byte length for a string.\n * @param value Target string.\n * @returns Estimated UTF-8 byte length.\n */\nexport function estimateBytes(value: string): number {\n let bytes = 0;\n for (let i = 0; i < value.length; i++) {\n const code = value.charCodeAt(i);\n if (code < UTF8_ONE_BYTE_CEILING) {\n bytes += 1;\n } else if (code < UTF8_TWO_BYTE_CEILING) {\n bytes += 2;\n } else if (code >= HIGH_SURROGATE_MIN && code <= HIGH_SURROGATE_MAX) {\n bytes += 4;\n i++;\n } else {\n bytes += 3;\n }\n }\n return bytes;\n}\n"],"mappings":"A,iFA2CA,SAAgBK,EAAS,EAAe,EAAqB,CAC3D,GAAIC,EAAM,QAAUC,EAClB,OAAOD,EAKT,IAAME,EAAMC,EAAgBH,EAAM,WAAWC,EAAM,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EAAQ,IAAI,OAAOgB,EAAM,OAASpB,EAAO,cAAc,EAAE,cAAeE,CAAK,CAAC,EAElFa,CACT,CAEA,IAAMO,EAAwB/B,EAA+B,OAC7D,GAAI,OAAO+B,GAAgB,WAEzB,OAAOnB,EAAKf,EAAO,KAAKG,CAAK,EAAGS,EAAQQ,EAAMD,EAAQ,EAAGL,CAAK,EAGhE,IAAMqB,EAAShC,EACTiC,EAAO,OAAO,KAAKD,CAAM,EACzBR,EAA+B,CAAC,EAClCU,EAAQ,EACZ,IAAK,IAAMb,KAAOY,EAAM,CACtB,GAAIC,GAASzB,EAAO,kBAAmB,CACrC,EAAI,KAAOI,EAAQ,IAAI,OAAOoB,EAAK,OAASC,CAAK,EAAE,aAAcvB,CAAK,EACtE,KACF,CACA,IACA,EAAM,OAASG,EAAcO,CAAG,EAAA,EAChC,EAAIA,GAAOT,EAAKoB,EAAOX,GAAMZ,EAAQQ,EAAMD,EAAQ,EAAGL,CAAK,CAC7D,CACA,OAAOa,CACT,OAASN,EAAO,CAKd,OAFAP,EAAM,YAAY,MAAM,wBAAwB,EAEzCE,EAAQ,oBADFK,aAAiB,MAAQA,EAAM,KAAO,QACX,GAAIP,CAAK,CACnD,QAAU,CAGRM,EAAK,OAAOjB,CAAK,CACnB,CACF,CAOA,SAAgBc,EAAc,EAAuB,CACnD,IAAIqB,EAAQ,EACZ,IAAK,IAAIC,EAAI,EAAGA,EAAIpC,EAAM,OAAQ,IAAK,CACrC,IAAMI,EAAOJ,EAAM,WAAWoC,CAAC,EAC3BhC,EAAA,IACF,GAAS,EACAA,EAAA,KACT,GAAS,EACAA,GAAA,OAA8BA,GAAA,OACvC,GAAS,EACT,KAEA,GAAS,CAEb,CACA,OAAO+B,CACT,C"}
@@ -1,3 +0,0 @@
1
- const e=require("./constants-DakMxVB2.cjs"),t=require("./batch-D5LlU4Q9.cjs"),n=require("./otlp-2MCrC3kd.cjs");var r=class extends Error{kind;status;retryAfterMs;maxBytes;constructor(e,t,n,r,i,a){super(t,a===void 0?void 0:{cause:a}),this.kind=e,this.status=n,this.retryAfterMs=r,this.maxBytes=i,this.name=`TransportError`}};function i(t){if(!t)return;let n=Number(t);if(Number.isFinite(n))return Math.max(0,n*e.It);let r=Date.parse(t);return Number.isNaN(r)?void 0:Math.max(0,r-Date.now())}var a={"error.type":`type`,"error.message":`message`,"error.stack_trace":`stack_trace`},o=new Set([e.a,...Object.keys(a)]);function s(t){return e.Rt.test(t)?Number(BigInt(t)/e.zt):Date.now()}function c(e){return typeof e==`string`||typeof e==`number`||typeof e==`boolean`?e:typeof e==`bigint`?e.toString():null}function l(e,t,n){let r=e[t];r===void 0?e[t]=n:Array.isArray(r)?r.push(n):e[t]=[r,n]}function u(e,t,n,r){let i=c(n);if(i!==null)l(e,t,i);else if(typeof n==`object`&&n&&!r.has(n)){if(r.add(n),Array.isArray(n))for(let i of n)u(e,t,i,r);else for(let[i,a]of Object.entries(n))u(e,`${t}.${i}`,a,r);r.delete(n)}}function d(e){let t=Object.create(null),n=new WeakSet;for(let[r,i]of Object.entries(e))u(t,r,i,n);return t}function f(e){let t=[];for(let[n,r]of Object.entries(a)){let i=e[n];typeof i==`string`&&t.push([r,i])}return t.length>0?Object.fromEntries(t):void 0}function p(e){return Object.fromEntries(Object.entries(e).filter(([e,t])=>!(o.has(e)&&typeof t==`string`)))}var m={name:`ecs`,serialize(t){return{body:`${t.map(t=>{let n=s(t.timeUnixNano),{attributes:r}=t,i=r[e.a];return JSON.stringify({"@timestamp":new Date(n).toISOString(),message:t.body,ecs:{version:e.Q},log:{level:e.Z[t.severityText]??t.severityText.toLowerCase(),logger:typeof i==`string`?i:void 0},event:{kind:r[`log.type`]===`metric`?`metric`:`event`},error:f(r),trace:{id:t.traceId},span:{id:t.spanId},service:{name:t.resource[e.hn],version:t.resource[e.gn],environment:t.resource[e.dn]},user_agent:{original:t.resource[e.ln]},url:{full:r[`url.full`]??r[`page.url`]},labels:{...d(t.resource),...d(p(r))}})}).join(`
2
- `)}\n`,contentType:e.z}}},h=1;function g(e,t){let n=e.attributes[t];return typeof n==`number`&&Number.isFinite(n)?n:void 0}function _(e){return Array.isArray(e)&&e.every(e=>typeof e==`number`&&Number.isFinite(e))}function v(t){let n=t.attributes[e.Pt.attributeKeys],r={};if(!Array.isArray(n))return r;for(let e of n){let n=typeof e==`string`&&!e.startsWith(`metric.`)?t.attributes[e]:void 0;(typeof n==`string`||typeof n==`number`||typeof n==`boolean`)&&(r[e]=n)}return r}function y(t){let n=g(t,e.Pt.count);if(n===void 0){let e=g(t,`metric.value`);return e===void 0?null:{count:`1`,sum:e<0?void 0:e,min:e,max:e,bucketCounts:[`1`],explicitBounds:[]}}let r=t.attributes[e.Pt.bounds],i=t.attributes[e.Pt.buckets];if(!_(r)||!_(i)||i.length!==r.length+1)return null;let a=g(t,e.Pt.min);return{count:String(n),sum:a!==void 0&&a<0?void 0:g(t,e.Pt.sum),min:a,max:g(t,e.Pt.max),bucketCounts:i.map(String),explicitBounds:r}}function b(e){let t=g(e,`metric.value`);return t===void 0?null:{asDouble:t}}function x(t,r){let i=t.attributes[e.Pt.start],a=r===`histogram`?y(t):b(t);return a===null?null:{attributes:n.i(v(t)),startTimeUnixNano:typeof i==`string`?i:t.timeUnixNano,timeUnixNano:t.timeUnixNano,...a}}function S({name:e,unit:t,field:n,points:r}){if(n===`gauge`)return{name:e,unit:t,gauge:{dataPoints:r}};let i={aggregationTemporality:h,dataPoints:r};return n===`sum`&&(i.isMonotonic=r.every(e=>e.asDouble>=0)),{name:e,unit:t,[n]:i}}var C={name:e.En,serialize(t){let r=n.t(t).map(t=>{let r=new Map;for(let e of t.records){let t=e.attributes[`metric.type`],n=t===`counter`?`sum`:t===`histogram`?`histogram`:`gauge`,i=x(e,n);if(i===null)continue;let a=e.attributes[`metric.name`],o=e.attributes[`metric.unit`],s={name:typeof a==`string`?a:e.body,unit:typeof o==`string`?o:``,field:n,points:[]},c=JSON.stringify([s.field,s.name,s.unit]),l=r.get(c)??s;l.points.push(i),r.set(c,l)}return{resource:{attributes:n.i(t.resource)},scopeMetrics:[{scope:{name:e.Wn,version:e.Gn},metrics:[...r.values()].map(S)}]}});return{body:JSON.stringify({resourceMetrics:r}),contentType:e.R}}},w={internal:1,client:3},T=2,E=0,D=new Set([e.g,...Object.values(e.Nn)]);function O(e,t){let n=e.attributes[t];return typeof n==`string`?n:void 0}function k(t){let r=Object.fromEntries(Object.entries(t.attributes).filter(([e])=>!D.has(e))),i=O(t,e.Nn.parentId),a=O(t,e.Nn.linkTraceId),o=O(t,e.Nn.linkSpanId);return{traceId:t.traceId,spanId:t.spanId,...i?{parentSpanId:i}:{},...a&&o?{links:[{traceId:a,spanId:o}]}:{},name:t.body,kind:O(t,e.Nn.kind)===`client`?w.client:w.internal,startTimeUnixNano:O(t,e.Nn.start)??t.timeUnixNano,endTimeUnixNano:O(t,e.Nn.end)??t.timeUnixNano,attributes:n.i(r),status:{code:O(t,e.Nn.status)===`error`?T:E}}}var A={name:e.En,serialize(t){let r=n.t(t).map(e=>({resource:{attributes:n.i(e.resource)},scopeSpans:n.n(e.records).map(e=>({scope:{name:e.name},spans:e.records.map(k)}))}));return{body:JSON.stringify({resourceSpans:r}),contentType:e.R}}};function j(e){return e===`otlp`?n.r:e===`ecs`?m:e}function M(e,n){let r=n=>e.records.length>0&&e.records.every(e=>t.t(e,`log.type`)===n);return n.metricsEndpoint!==``&&r(`metric`)?`metrics`:r(`span`)?`traces`:`logs`}function N(e,t){return e===`metrics`?t.metricsEndpoint:e===`traces`?t.tracesEndpoint:t.endpoint}var P={metrics:C,traces:A};function F(e,t,n,r){try{return(P[M(t,e)]??j(e.serializer)).serialize(t.records)}catch(e){n.report(`transport.serialize_failed`,r,{batchId:t.id},e);return}}Object.defineProperty(exports,"a",{enumerable:!0,get:function(){return A}}),Object.defineProperty(exports,"c",{enumerable:!0,get:function(){return i}}),Object.defineProperty(exports,"i",{enumerable:!0,get:function(){return j}}),Object.defineProperty(exports,"n",{enumerable:!0,get:function(){return N}}),Object.defineProperty(exports,"o",{enumerable:!0,get:function(){return C}}),Object.defineProperty(exports,"r",{enumerable:!0,get:function(){return F}}),Object.defineProperty(exports,"s",{enumerable:!0,get:function(){return r}}),Object.defineProperty(exports,"t",{enumerable:!0,get:function(){return M}});
3
- //# sourceMappingURL=select-CTk-K5mG.cjs.map
@@ -1 +0,0 @@
1
- {"version":3,"file":"select-CTk-K5mG.cjs","names":["MILLIS_PER_SECOND","ATTR_APP_NAMESPACE","NANOS_PATTERN","NANOS_PER_MILLI","ECS_VERSION","ECS_LEVEL_NAMES","RESOURCE_SERVICE_NAME","RESOURCE_SERVICE_VERSION","RESOURCE_DEPLOYMENT_ENVIRONMENT","RESOURCE_BROWSER_USER_AGENT","CONTENT_TYPE_NDJSON","METRIC_KEYS","toKeyValues","SERIALIZER_NAME_OTLP","groupByResource","TELEMETRY_SDK_NAME","TELEMETRY_SDK_VERSION","CONTENT_TYPE_JSON","ATTR_LOG_TYPE","SPAN_KEYS","toKeyValues","SERIALIZER_NAME_OTLP","groupByResource","groupByScope","CONTENT_TYPE_JSON","otlpSerializer","attributeOf","require_constants","require_batch","require_otlp","TransportError","message","cause","kind","status","retryAfterMs","maxBytes","parseRetryAfter","header","seconds","date","ERROR_FIELDS","MAPPED_KEYS","toMillis","timeUnixNano","toLabelValue","value","pushLabel","existing","labels","key","flattenLabel","scalar","seen","item","name","entry","toLabels","source","errorOf","fields","field","attributes","unmapped","ecsSerializer","records","millis","record","logger","DELTA","numberOf","isNumbers","pointAttributes","keys","out","histogramOf","count","bounds","buckets","min","numberPointOf","pointOf","start","values","metricOf","points","data","point","otlpMetricsSerializer","resourceMetrics","entries","group","type","named","unit","found","SPAN_KIND","STATUS_ERROR","STATUS_UNSET","FIELD_KEYS","stringOf","spanOf","parent","linkTraceId","linkSpanId","otlpTracesSerializer","resourceSpans","scope","serializerFor","choice","batchKind","only","batch","config","endpointFor","SIGNAL_SERIALIZERS","serializeBatch","error","diagnostics"],"sources":["../src/transport/errors.ts","../src/transport/serializers/ecs.ts","../src/transport/serializers/otlp-metrics.ts","../src/transport/serializers/otlp-traces.ts","../src/transport/serializers/select.ts"],"sourcesContent":["// src/transport/errors.ts\n//\n// Classifies HTTP transport failures and parses the Retry-After header.\n\nimport { MILLIS_PER_SECOND } from \"../constants\";\n\n/**\n * The failure kind decides whether the engine retries, backs off or drops. Transient, offline\n * and timeout failures are retried with backoff. A throttled failure waits for the server's\n * delay, and a too_large failure splits the batch. A permanent failure is dropped, because the\n * server will never accept that batch.\n */\nexport type TransportFailureKind =\n \"transient\" | \"throttled\" | \"too_large\" | \"permanent\" | \"timeout\" | \"offline\";\n\n/** A failed transport attempt, with its failure kind and metadata. */\nexport class TransportError extends Error {\n /**\n * @param kind Failure classification.\n * @param message Error description.\n * @param status Optional HTTP response status code.\n * @param retryAfterMs Delay requested by the server in milliseconds.\n * @param maxBytes Maximum payload bytes suggested by a 413 response.\n * @param cause Error that caused this failure.\n */\n constructor(\n public readonly kind: TransportFailureKind,\n message: string,\n public readonly status?: number,\n public readonly retryAfterMs?: number,\n public readonly maxBytes?: number,\n cause?: unknown,\n ) {\n super(message, cause === undefined ? undefined : { cause });\n this.name = \"TransportError\";\n }\n}\n\n/**\n * Parses an HTTP Retry-After value into a delay in milliseconds. The value\n * can be a number of seconds or an HTTP date. A date in the past gives a negative delay,\n * which is clamped to zero.\n * @param header Raw Retry-After header string or null.\n * @returns Non-negative delay in milliseconds, or undefined if invalid or missing.\n */\nexport function parseRetryAfter(header: string | null): number | undefined {\n if (!header) {\n return undefined;\n }\n\n const seconds = Number(header);\n if (Number.isFinite(seconds)) {\n return Math.max(0, seconds * MILLIS_PER_SECOND);\n }\n\n const date = Date.parse(header);\n return Number.isNaN(date) ? undefined : Math.max(0, date - Date.now());\n}\n","// src/transport/serializers/ecs.ts\n//\n// Serializes log batches as Elastic Common Schema (ECS) newline-delimited JSON.\n\nimport {\n ATTR_APP_NAMESPACE,\n ATTR_LOG_TYPE,\n ATTR_PAGE_URL,\n ATTR_URL_FULL,\n CONTENT_TYPE_NDJSON,\n ECS_LEVEL_NAMES,\n ECS_VERSION,\n LOG_TYPE_METRIC,\n NANOS_PATTERN,\n NANOS_PER_MILLI,\n RESOURCE_BROWSER_USER_AGENT,\n RESOURCE_DEPLOYMENT_ENVIRONMENT,\n RESOURCE_SERVICE_NAME,\n RESOURCE_SERVICE_VERSION,\n SERIALIZER_NAME_ECS,\n} from \"../../constants\";\nimport type { LogRecord } from \"../../models/log-record\";\nimport type { LogSerializer, SerializedBatch } from \"../../models/serializer\";\n\n/** The ECS field for each error attribute. */\nconst ERROR_FIELDS = {\n \"error.type\": \"type\",\n \"error.message\": \"message\",\n \"error.stack_trace\": \"stack_trace\",\n} as const;\n\n/** Attribute keys whose string value moves to an ECS field, and so leaves labels. */\nconst MAPPED_KEYS = new Set<string>([ATTR_APP_NAMESPACE, ...Object.keys(ERROR_FIELDS)]);\n\n/**\n * Converts a nanosecond epoch string to epoch milliseconds. A record from the bus has only\n * passed a shape check, and BigInt throws a SyntaxError on a non-numeric string. That error\n * would lose the whole batch, not just one record.\n * @param timeUnixNano Nanosecond epoch as decimal digits.\n * @returns Epoch milliseconds, or the current time when the input isn't numeric.\n */\nfunction toMillis(timeUnixNano: string): number {\n if (!NANOS_PATTERN.test(timeUnixNano)) {\n return Date.now();\n }\n\n return Number(BigInt(timeUnixNano) / NANOS_PER_MILLI);\n}\n\n/** Elasticsearch maps these value types under `labels` without a dynamic mapping conflict. */\ntype LabelValue = string | number | boolean;\n\n/**\n * Converts a value to its label form.\n * @param value Raw attribute or resource value.\n * @returns Scalar label value, or null when the value has no scalar form.\n */\nfunction toLabelValue(value: unknown): LabelValue | null {\n if (typeof value === \"string\" || typeof value === \"number\" || typeof value === \"boolean\") {\n return value;\n }\n\n // JSON.stringify throws on a BigInt, and that error would lose the whole batch.\n if (typeof value === \"bigint\") {\n return value.toString();\n }\n\n return null;\n}\n\n/**\n * Writes one label, folding a repeated key into an array. Elasticsearch reads\n * a repeated leaf as one multi-valued field, and an array of objects maps the same way.\n * @param labels Label map being built.\n * @param key Dotted label key.\n * @param value Scalar label value.\n */\nfunction pushLabel(labels: Record<string, unknown>, key: string, value: LabelValue): void {\n const existing = labels[key];\n\n if (existing === undefined) {\n labels[key] = value;\n return;\n }\n\n if (Array.isArray(existing)) {\n (existing as LabelValue[]).push(value);\n return;\n }\n\n labels[key] = [existing, value];\n}\n\n/**\n * Flattens one value into dotted label keys. ECS `labels` is a flat map, and a\n * nested object under it causes an Elasticsearch dynamic mapping conflict.\n * @param labels Label map being built.\n * @param key Dotted key for this value.\n * @param value Value to flatten.\n * @param seen Active ancestor objects. Stops infinite recursion on a cycle.\n */\nfunction flattenLabel(\n labels: Record<string, unknown>,\n key: string,\n value: unknown,\n seen: WeakSet<object>,\n): void {\n const scalar = toLabelValue(value);\n\n if (scalar !== null) {\n pushLabel(labels, key, scalar);\n return;\n }\n\n // A forwarded record has only passed a shape check, so its attributes can contain a cycle.\n if (typeof value !== \"object\" || value === null || seen.has(value)) {\n return;\n }\n\n seen.add(value);\n\n if (Array.isArray(value)) {\n for (const item of value as unknown[]) {\n flattenLabel(labels, key, item, seen);\n }\n } else {\n for (const [name, entry] of Object.entries(value)) {\n flattenLabel(labels, `${key}.${name}`, entry, seen);\n }\n }\n\n // Remove the object on unwind, otherwise a repeated sibling reads as a cycle.\n seen.delete(value);\n}\n\n/**\n * Flattens an attribute or resource map into ECS labels.\n * @param source Attribute or resource map.\n * @returns Flat label map keyed by dotted path.\n */\nfunction toLabels(source: Record<string, unknown>): Record<string, unknown> {\n // Use a null prototype, so an attribute named `__proto__` becomes a key and not a prototype.\n const labels: Record<string, unknown> = Object.create(null) as Record<string, unknown>;\n const seen = new WeakSet();\n\n for (const [key, value] of Object.entries(source)) {\n flattenLabel(labels, key, value, seen);\n }\n\n return labels;\n}\n\n/**\n * Builds the ECS error field from the error attributes.\n * @param attributes Record attributes.\n * @returns The field, or undefined for a record without a string error attribute.\n */\nfunction errorOf(attributes: Record<string, unknown>): Record<string, string> | undefined {\n const fields: [string, string][] = [];\n\n for (const [key, field] of Object.entries(ERROR_FIELDS)) {\n const value = attributes[key];\n if (typeof value === \"string\") {\n fields.push([field, value]);\n }\n }\n\n return fields.length > 0 ? Object.fromEntries(fields) : undefined;\n}\n\n/**\n * Removes the attributes that have an ECS field. A label copy of a stack trace would double\n * the size.\n * @param attributes Record attributes.\n * @returns The attributes that go to labels.\n */\nfunction unmapped(attributes: Record<string, unknown>): Record<string, unknown> {\n return Object.fromEntries(\n Object.entries(attributes).filter(\n ([key, value]) => !(MAPPED_KEYS.has(key) && typeof value === \"string\"),\n ),\n );\n}\n\n/** Writes log records as Elastic Common Schema (ECS) NDJSON documents. */\nexport const ecsSerializer: LogSerializer = {\n /** The format name. */\n name: SERIALIZER_NAME_ECS,\n\n /**\n * Serializes log records into newline-delimited ECS JSON documents.\n * @param records Records to serialize.\n * @returns Serialized NDJSON batch payload.\n */\n serialize(records: LogRecord[]): SerializedBatch {\n const lines = records.map((record) => {\n const millis = toMillis(record.timeUnixNano);\n\n const { attributes } = record;\n const logger = attributes[ATTR_APP_NAMESPACE];\n\n // JSON.stringify leaves out an undefined field.\n return JSON.stringify({\n \"@timestamp\": new Date(millis).toISOString(),\n message: record.body,\n ecs: { version: ECS_VERSION },\n log: {\n level: ECS_LEVEL_NAMES[record.severityText] ?? record.severityText.toLowerCase(),\n logger: typeof logger === \"string\" ? logger : undefined,\n },\n event: { kind: attributes[ATTR_LOG_TYPE] === LOG_TYPE_METRIC ? \"metric\" : \"event\" },\n error: errorOf(attributes),\n trace: { id: record.traceId },\n span: { id: record.spanId },\n service: {\n name: record.resource[RESOURCE_SERVICE_NAME],\n version: record.resource[RESOURCE_SERVICE_VERSION],\n environment: record.resource[RESOURCE_DEPLOYMENT_ENVIRONMENT],\n },\n user_agent: { original: record.resource[RESOURCE_BROWSER_USER_AGENT] },\n // A captured network event's request URL takes precedence over the page URL.\n url: {\n full: attributes[ATTR_URL_FULL] ?? attributes[ATTR_PAGE_URL],\n },\n // Spread the attributes last, so a record attribute overrides a resource key with the\n // same name.\n labels: { ...toLabels(record.resource), ...toLabels(unmapped(attributes)) },\n });\n });\n\n return { body: `${lines.join(\"\\n\")}\\n`, contentType: CONTENT_TYPE_NDJSON };\n },\n};\n","// src/transport/serializers/otlp-metrics.ts\n//\n// Serializes metric records as an OTLP/JSON ExportMetricsServiceRequest. The transport only\n// uses it for a batch of metric records when metricsEndpoint is set.\n\nimport {\n CONTENT_TYPE_JSON,\n METRIC_KEYS,\n SERIALIZER_NAME_OTLP,\n TELEMETRY_SDK_NAME,\n TELEMETRY_SDK_VERSION,\n} from \"../../constants\";\nimport type { LogRecord } from \"../../models/log-record\";\nimport type { LogSerializer, SerializedBatch } from \"../../models/serializer\";\nimport { groupByResource, toKeyValues } from \"./otlp\";\n\n/** OTLP AggregationTemporality DELTA. Each point holds the change since the previous point. */\nconst DELTA = 1;\n\n/** The OTLP field for each metric type. Anything that isn't a counter or a histogram is a gauge. */\ntype MetricField = \"sum\" | \"histogram\" | \"gauge\";\n\n/** One OTLP data point. */\ntype DataPoint = Record<string, unknown>;\n\n/** Data points of one metric name, type and unit. */\ninterface MetricEntry {\n /** Metric name. */\n name: string;\n /** Unit of the values. */\n unit: string;\n /** OTLP field of the type. */\n field: MetricField;\n /** Data points. */\n points: DataPoint[];\n}\n\n/**\n * Reads a finite number attribute.\n * @param record Metric record.\n * @param key Attribute key.\n * @returns The number, or undefined.\n */\nfunction numberOf(record: LogRecord, key: string): number | undefined {\n const value: unknown = record.attributes[key];\n return typeof value === \"number\" && Number.isFinite(value) ? value : undefined;\n}\n\n/**\n * Checks whether a value is a list of finite numbers.\n * @param value Attribute value.\n * @returns True for a list of finite numbers.\n */\nfunction isNumbers(value: unknown): value is number[] {\n return (\n Array.isArray(value) &&\n value.every((item: unknown) => typeof item === \"number\" && Number.isFinite(item))\n );\n}\n\n/**\n * Reads the point attributes that the app passed in its call. The record's context attributes\n * stay out, because a session id on every point would create a new series for every session.\n * @param record Metric record.\n * @returns The string, number and boolean attributes that `metric.attribute_keys` names.\n */\nfunction pointAttributes(record: LogRecord): Record<string, unknown> {\n const keys: unknown = record.attributes[METRIC_KEYS.attributeKeys];\n const out: Record<string, unknown> = {};\n\n if (!Array.isArray(keys)) {\n return out;\n }\n\n for (const key of keys as unknown[]) {\n // A key from the app's call can have the same name as a metric field, and that field\n // holds the library's value.\n const named = typeof key === \"string\" && !key.startsWith(\"metric.\");\n const value: unknown = named ? record.attributes[key] : undefined;\n if (typeof value === \"string\" || typeof value === \"number\" || typeof value === \"boolean\") {\n out[key as string] = value;\n }\n }\n\n return out;\n}\n\n/**\n * Builds a point's histogram fields.\n * @param record Metric record.\n * @returns The fields, or null for a point that a record limit cut short.\n */\nfunction histogramOf(record: LogRecord): DataPoint | null {\n const count = numberOf(record, METRIC_KEYS.count);\n\n // A logMetric histogram holds one value, so it has one bucket and no boundaries.\n if (count === undefined) {\n const value = numberOf(record, \"metric.value\");\n return value === undefined\n ? null\n : {\n count: \"1\",\n sum: value < 0 ? undefined : value,\n min: value,\n max: value,\n bucketCounts: [\"1\"],\n explicitBounds: [],\n };\n }\n\n const bounds: unknown = record.attributes[METRIC_KEYS.bounds];\n const buckets: unknown = record.attributes[METRIC_KEYS.buckets];\n\n // The library always builds complete lists, but a record from elsewhere can have lists that\n // don't line up, and a point built from those would report bogus buckets.\n if (!isNumbers(bounds) || !isNumbers(buckets) || buckets.length !== bounds.length + 1) {\n return null;\n }\n\n // Per OTLP, a histogram with a negative value sets no sum, because a backend reads the sum\n // as a total.\n const min = numberOf(record, METRIC_KEYS.min);\n\n return {\n count: String(count),\n sum: min !== undefined && min < 0 ? undefined : numberOf(record, METRIC_KEYS.sum),\n min,\n max: numberOf(record, METRIC_KEYS.max),\n // OTLP JSON encodes an int64 as a decimal string.\n bucketCounts: buckets.map(String),\n explicitBounds: bounds,\n };\n}\n\n/**\n * Builds the value field of a sum or gauge point.\n * @param record Metric record.\n * @returns The field, or null for a record without a valid value.\n */\nfunction numberPointOf(record: LogRecord): DataPoint | null {\n const value = numberOf(record, \"metric.value\");\n return value === undefined ? null : { asDouble: value };\n}\n\n/**\n * Builds one OTLP data point.\n * @param record Metric record.\n * @param field OTLP field of the type.\n * @returns The point, or null for a record without a valid value.\n */\nfunction pointOf(record: LogRecord, field: MetricField): DataPoint | null {\n const start: unknown = record.attributes[METRIC_KEYS.start];\n const values = field === \"histogram\" ? histogramOf(record) : numberPointOf(record);\n\n if (values === null) {\n return null;\n }\n\n return {\n attributes: toKeyValues(pointAttributes(record)),\n // A logMetric record has no interval, so its point starts and ends at its own time.\n startTimeUnixNano: typeof start === \"string\" ? start : record.timeUnixNano,\n timeUnixNano: record.timeUnixNano,\n ...values,\n };\n}\n\n/**\n * Builds the OTLP metric of an entry.\n * @param entry Data points of one name, type and unit.\n * @returns The OTLP metric.\n */\nfunction metricOf({ name, unit, field, points }: MetricEntry): Record<string, unknown> {\n if (field === \"gauge\") {\n return { name, unit, gauge: { dataPoints: points } };\n }\n\n const data: Record<string, unknown> = { aggregationTemporality: DELTA, dataPoints: points };\n\n // A logMetric counter can hold a negative value. A monotonic sum must not decrease.\n if (field === \"sum\") {\n data.isMonotonic = points.every((point) => (point.asDouble as number) >= 0);\n }\n\n return { name, unit, [field]: data };\n}\n\n/** Writes metric records as an OTLP/JSON ExportMetricsServiceRequest. */\nexport const otlpMetricsSerializer: LogSerializer = {\n /** The format name. */\n name: SERIALIZER_NAME_OTLP,\n\n /**\n * Groups the records by resource, then by metric name, type and unit. Drops any record\n * without a valid value.\n * @param records Metric records to serialize.\n * @returns Serialized JSON payload.\n */\n serialize(records: LogRecord[]): SerializedBatch {\n const resourceMetrics = groupByResource(records).map((group) => {\n const entries = new Map<string, MetricEntry>();\n\n for (const record of group.records) {\n const type: unknown = record.attributes[\"metric.type\"];\n const field: MetricField =\n type === \"counter\" ? \"sum\" : type === \"histogram\" ? \"histogram\" : \"gauge\";\n const point = pointOf(record, field);\n\n if (point === null) {\n continue;\n }\n\n const named: unknown = record.attributes[\"metric.name\"];\n const unit: unknown = record.attributes[\"metric.unit\"];\n const entry: MetricEntry = {\n name: typeof named === \"string\" ? named : record.body,\n unit: typeof unit === \"string\" ? unit : \"\",\n field,\n points: [],\n };\n const key = JSON.stringify([entry.field, entry.name, entry.unit]);\n const found = entries.get(key) ?? entry;\n\n found.points.push(point);\n entries.set(key, found);\n }\n\n return {\n resource: { attributes: toKeyValues(group.resource) },\n scopeMetrics: [\n {\n scope: { name: TELEMETRY_SDK_NAME, version: TELEMETRY_SDK_VERSION },\n metrics: [...entries.values()].map(metricOf),\n },\n ],\n };\n });\n\n return {\n body: JSON.stringify({ resourceMetrics }),\n contentType: CONTENT_TYPE_JSON,\n };\n },\n};\n","// src/transport/serializers/otlp-traces.ts\n//\n// Serializes span records as an OTLP/JSON ExportTraceServiceRequest. The transport\n// uses it for a batch of span records.\n\nimport { ATTR_LOG_TYPE, CONTENT_TYPE_JSON, SERIALIZER_NAME_OTLP, SPAN_KEYS } from \"../../constants\";\nimport type { LogRecord } from \"../../models/log-record\";\nimport type { LogSerializer, SerializedBatch } from \"../../models/serializer\";\nimport { groupByResource, groupByScope, toKeyValues } from \"./otlp\";\n\n/** The OTLP SpanKind for each of the library's span kinds. */\nconst SPAN_KIND = { internal: 1, client: 3 } as const;\n\n/** OTLP StatusCode ERROR. */\nconst STATUS_ERROR = 2;\n\n/** OTLP StatusCode UNSET. */\nconst STATUS_UNSET = 0;\n\n/** Attribute keys that hold span fields, and so aren't span attributes. */\nconst FIELD_KEYS = new Set<string>([ATTR_LOG_TYPE, ...Object.values(SPAN_KEYS)]);\n\n/**\n * Reads a string attribute.\n * @param record Span record.\n * @param key Attribute key.\n * @returns The string, or undefined.\n */\nfunction stringOf(record: LogRecord, key: string): string | undefined {\n const value: unknown = record.attributes[key];\n return typeof value === \"string\" ? value : undefined;\n}\n\n/**\n * Builds one OTLP span. A record that lost a time field starts and ends at its record time.\n * @param record Span record.\n * @returns The OTLP span.\n */\nfunction spanOf(record: LogRecord): Record<string, unknown> {\n const attributes = Object.fromEntries(\n Object.entries(record.attributes).filter(([key]) => !FIELD_KEYS.has(key)),\n );\n const parent = stringOf(record, SPAN_KEYS.parentId);\n const linkTraceId = stringOf(record, SPAN_KEYS.linkTraceId);\n const linkSpanId = stringOf(record, SPAN_KEYS.linkSpanId);\n\n return {\n traceId: record.traceId,\n spanId: record.spanId,\n // A root span has no parent, so leave the field out.\n ...(parent ? { parentSpanId: parent } : {}),\n ...(linkTraceId && linkSpanId\n ? {\n links: [{ traceId: linkTraceId, spanId: linkSpanId }],\n }\n : {}),\n name: record.body,\n kind: stringOf(record, SPAN_KEYS.kind) === \"client\" ? SPAN_KIND.client : SPAN_KIND.internal,\n startTimeUnixNano: stringOf(record, SPAN_KEYS.start) ?? record.timeUnixNano,\n endTimeUnixNano: stringOf(record, SPAN_KEYS.end) ?? record.timeUnixNano,\n attributes: toKeyValues(attributes),\n status: {\n code: stringOf(record, SPAN_KEYS.status) === \"error\" ? STATUS_ERROR : STATUS_UNSET,\n },\n };\n}\n\n/** Writes span records as an OTLP/JSON ExportTraceServiceRequest. */\nexport const otlpTracesSerializer: LogSerializer = {\n /** The format name. */\n name: SERIALIZER_NAME_OTLP,\n\n /**\n * Groups the records by resource.\n * @param records Span records to serialize.\n * @returns Serialized JSON payload.\n */\n serialize(records: LogRecord[]): SerializedBatch {\n const resourceSpans = groupByResource(records).map((group) => ({\n resource: { attributes: toKeyValues(group.resource) },\n scopeSpans: groupByScope(group.records).map((scope) => ({\n scope: { name: scope.name },\n spans: scope.records.map(spanOf),\n })),\n }));\n\n return {\n body: JSON.stringify({ resourceSpans }),\n contentType: CONTENT_TYPE_JSON,\n };\n },\n};\n","// src/transport/serializers/select.ts\n//\n// Maps the serializer option to an implementation. Only transport code imports this module,\n// and config.ts keeps just the name, so the main chunk contains no serializer.\n\nimport { ATTR_LOG_TYPE } from \"../../constants\";\nimport type { Diagnostics } from \"../../core/diagnostics\";\nimport { attributeOf, type LogBatch } from \"../../models/batch\";\nimport type { BatchKind, ResolvedConfig, SerializerChoice } from \"../../models/config\";\nimport type { LogSerializer, SerializedBatch } from \"../../models/serializer\";\nimport { ecsSerializer } from \"./ecs\";\nimport { otlpSerializer } from \"./otlp\";\nimport { otlpMetricsSerializer } from \"./otlp-metrics\";\nimport { otlpTracesSerializer } from \"./otlp-traces\";\n\n/**\n * Returns the implementation for a resolved serializer option.\n * @param choice Serializer name, or a custom implementation.\n * @returns Serializer implementation.\n */\nexport function serializerFor(choice: SerializerChoice): LogSerializer {\n if (choice === \"otlp\") {\n return otlpSerializer;\n }\n\n if (choice === \"ecs\") {\n return ecsSerializer;\n }\n\n return choice;\n}\n\n/**\n * Returns the kind of a batch. Only a batch of metric records goes to metricsEndpoint. A batch\n * of span records is always \"traces\" and must not go to endpoint as log records. A stored\n * record can be corrupt, and then it is neither a metric nor a span.\n * @param batch Batch to test.\n * @param config Active configuration.\n * @returns \"metrics\" with metricsEndpoint set and only metric records, \"traces\" for only span\n * records, else \"logs\".\n */\nexport function batchKind(batch: LogBatch, config: ResolvedConfig): BatchKind {\n const only = (type: string): boolean =>\n batch.records.length > 0 &&\n batch.records.every((record) => attributeOf(record, ATTR_LOG_TYPE) === type);\n\n if (config.metricsEndpoint !== \"\" && only(\"metric\")) {\n return \"metrics\";\n }\n\n return only(\"span\") ? \"traces\" : \"logs\";\n}\n\n/**\n * Returns the endpoint for a batch kind.\n * @param kind Kind of the batch.\n * @param config Active configuration.\n * @returns metricsEndpoint for a metrics batch, tracesEndpoint for a traces batch, else\n * endpoint. \"\" means the batch has no destination.\n */\nexport function endpointFor(kind: BatchKind, config: ResolvedConfig): string | null {\n if (kind === \"metrics\") {\n return config.metricsEndpoint;\n }\n\n return kind === \"traces\" ? config.tracesEndpoint : config.endpoint;\n}\n\n/** Serializers for the batch kinds that don't use the configured serializer. */\nconst SIGNAL_SERIALIZERS: Partial<Record<BatchKind, LogSerializer>> = {\n metrics: otlpMetricsSerializer,\n traces: otlpTracesSerializer,\n};\n\n/**\n * Serializes a batch. Reports a serializer that throws, and the caller then drops the batch.\n * A metrics batch gets the OTLP metrics format, and a traces batch the OTLP traces format.\n * @param config Active configuration.\n * @param batch Batch to serialize.\n * @param diagnostics Diagnostics reporter.\n * @param message ASD-STE100 sentence for the report.\n * @returns The serialized batch, or undefined if the serializer threw.\n */\nexport function serializeBatch(\n config: ResolvedConfig,\n batch: LogBatch,\n diagnostics: Diagnostics,\n message: string,\n): SerializedBatch | undefined {\n try {\n const serializer =\n SIGNAL_SERIALIZERS[batchKind(batch, config)] ?? serializerFor(config.serializer);\n return serializer.serialize(batch.records);\n } catch (error) {\n diagnostics.report(\"transport.serialize_failed\", message, { batchId: batch.id }, error);\n return undefined;\n }\n}\n"],"mappings":"A,+GAgBA,IAAa8B,EAAb,cAAoC,KAAM,CAUtB,KAEA,OACA,aACA,SALlB,YACE,EACA,EACA,EACA,EACA,EACA,EACA,CACA,MAAMC,EAASC,IAAU,IAAA,GAAY,IAAA,GAAY,CAAE,OAAM,CAAC,EAP1C,KAAA,KAAAC,EAEA,KAAA,OAAAC,EACA,KAAA,aAAAC,EACA,KAAA,SAAAC,EAIhB,KAAK,KAAO,gBACd,CACF,EASA,SAAgBC,EAAgB,EAA2C,CACzE,GAAI,CAACC,EACH,OAGF,IAAMC,EAAU,OAAOD,CAAM,EAC7B,GAAI,OAAO,SAASC,CAAO,EACzB,OAAO,KAAK,IAAI,EAAGA,EAAUvC,EAAAA,EAAiB,EAGhD,IAAMwC,EAAO,KAAK,MAAMF,CAAM,EAC9B,OAAO,OAAO,MAAME,CAAI,EAAI,IAAA,GAAY,KAAK,IAAI,EAAGA,EAAO,KAAK,IAAI,CAAC,CACvE,CChCA,IAAMC,EAAe,CACnB,aAAc,OACd,gBAAiB,UACjB,oBAAqB,aACvB,EAGMC,EAAc,IAAI,IAAY,CAACzC,EAAAA,EAAoB,GAAG,OAAO,KAAKwC,CAAY,CAAC,CAAC,EAStF,SAASE,EAAS,EAA8B,CAK9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