@utk09/ui-observability 1.0.0 → 1.2.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 (298) hide show
  1. package/CHANGELOG.md +111 -219
  2. package/README.md +24 -26
  3. package/dist/{batch-CXmPmTse.js → batch-120Kc9jr.js} +3 -3
  4. package/dist/{batch-CXmPmTse.js.map → batch-120Kc9jr.js.map} +1 -1
  5. package/dist/{batch-mmPigCpi.cjs → batch-C3uNp5kU.cjs} +2 -2
  6. package/dist/{batch-mmPigCpi.cjs.map → batch-C3uNp5kU.cjs.map} +1 -1
  7. package/dist/bus/bus.d.cts +31 -2
  8. package/dist/bus/bus.d.ts +31 -2
  9. package/dist/bus-Dj8IEVcC.cjs +2 -0
  10. package/dist/bus-Dj8IEVcC.cjs.map +1 -0
  11. package/dist/{bus-C39wspFV.js → bus-DyNafxZN.js} +127 -104
  12. package/dist/bus-DyNafxZN.js.map +1 -0
  13. package/dist/capture/errors.d.cts +10 -0
  14. package/dist/capture/errors.d.ts +10 -0
  15. package/dist/capture/interactions.d.cts +35 -3
  16. package/dist/capture/interactions.d.ts +35 -3
  17. package/dist/capture/observed-windows.d.cts +51 -0
  18. package/dist/capture/observed-windows.d.ts +51 -0
  19. package/dist/capture/replay.d.cts +1 -1
  20. package/dist/capture/replay.d.ts +1 -1
  21. package/dist/capture/types.d.cts +5 -0
  22. package/dist/capture/types.d.ts +5 -0
  23. package/dist/capture/web-vitals.d.cts +1 -0
  24. package/dist/capture/web-vitals.d.ts +1 -0
  25. package/dist/{compression-tVtXwVjX.js → compression-BWkDWY3v.js} +2 -2
  26. package/dist/{compression-tVtXwVjX.js.map → compression-BWkDWY3v.js.map} +1 -1
  27. package/dist/{compression-CvED_Jel.cjs → compression-CEVe7NPX.cjs} +2 -2
  28. package/dist/{compression-CvED_Jel.cjs.map → compression-CEVe7NPX.cjs.map} +1 -1
  29. package/dist/config-C0PtemvC.cjs +2 -0
  30. package/dist/config-C0PtemvC.cjs.map +1 -0
  31. package/dist/config-DK1Zf7jn.js +556 -0
  32. package/dist/config-DK1Zf7jn.js.map +1 -0
  33. package/dist/{console-BGgGnjSi.js → console-CAyCQOpm.js} +5 -5
  34. package/dist/{console-BGgGnjSi.js.map → console-CAyCQOpm.js.map} +1 -1
  35. package/dist/{console-CSZ5_Vx5.cjs → console-Dk6GH4yj.cjs} +2 -2
  36. package/dist/{console-CSZ5_Vx5.cjs.map → console-Dk6GH4yj.cjs.map} +1 -1
  37. package/dist/{constants-CUyd9cTZ.js → constants-CEHN6KuY.js} +46 -25
  38. package/dist/constants-CEHN6KuY.js.map +1 -0
  39. package/dist/constants-NtiQDWL_.cjs +2 -0
  40. package/dist/constants-NtiQDWL_.cjs.map +1 -0
  41. package/dist/constants.d.cts +23 -0
  42. package/dist/constants.d.ts +23 -0
  43. package/dist/core/config.d.cts +9 -3
  44. package/dist/core/config.d.ts +9 -3
  45. package/dist/core/diagnostics.d.cts +1 -1
  46. package/dist/core/diagnostics.d.ts +1 -1
  47. package/dist/core/pipeline.d.cts +11 -0
  48. package/dist/core/pipeline.d.ts +11 -0
  49. package/dist/core/record.d.cts +2 -2
  50. package/dist/core/record.d.ts +2 -2
  51. package/dist/core/rotation.d.cts +26 -2
  52. package/dist/core/rotation.d.ts +26 -2
  53. package/dist/core/runtime.d.cts +9 -0
  54. package/dist/core/runtime.d.ts +9 -0
  55. package/dist/core/sender.d.cts +3 -2
  56. package/dist/core/sender.d.ts +3 -2
  57. package/dist/{debug-bundle-BXIlwDKM.cjs → debug-bundle-DMzUfiQc.cjs} +2 -2
  58. package/dist/{debug-bundle-BXIlwDKM.cjs.map → debug-bundle-DMzUfiQc.cjs.map} +1 -1
  59. package/dist/{debug-bundle-CRpYV_ui.js → debug-bundle-w78W46zr.js} +4 -4
  60. package/dist/{debug-bundle-CRpYV_ui.js.map → debug-bundle-w78W46zr.js.map} +1 -1
  61. package/dist/doctor.cjs +1 -1
  62. package/dist/doctor.js +36 -36
  63. package/dist/doctor.js.map +1 -1
  64. package/dist/errors-07pmZ7VY.cjs +3 -0
  65. package/dist/errors-07pmZ7VY.cjs.map +1 -0
  66. package/dist/{errors-BE_EZV7Q.js → errors-C-LYbqyB.js} +27 -24
  67. package/dist/errors-C-LYbqyB.js.map +1 -0
  68. package/dist/{factory-CTi0Is3F.js → factory-BHYrcSaU.js} +39 -28
  69. package/dist/factory-BHYrcSaU.js.map +1 -0
  70. package/dist/factory-DsaNdcXp.cjs +2 -0
  71. package/dist/factory-DsaNdcXp.cjs.map +1 -0
  72. package/dist/{identity-DdhKgrpk.js → identity-Byh3gCdT.js} +35 -24
  73. package/dist/identity-Byh3gCdT.js.map +1 -0
  74. package/dist/identity-BzAzdQyv.cjs +2 -0
  75. package/dist/identity-BzAzdQyv.cjs.map +1 -0
  76. package/dist/index.cjs +1 -1
  77. package/dist/index.cjs.map +1 -1
  78. package/dist/index.d.cts +1 -0
  79. package/dist/index.d.ts +1 -0
  80. package/dist/index.js +453 -417
  81. package/dist/index.js.map +1 -1
  82. package/dist/{indexeddb-storage-GHdl0t8A.js → indexeddb-storage-BYywz-v6.js} +17 -17
  83. package/dist/{indexeddb-storage-GHdl0t8A.js.map → indexeddb-storage-BYywz-v6.js.map} +1 -1
  84. package/dist/{indexeddb-storage-CL9uqBCy.cjs → indexeddb-storage-BfqGkLFe.cjs} +2 -2
  85. package/dist/{indexeddb-storage-CL9uqBCy.cjs.map → indexeddb-storage-BfqGkLFe.cjs.map} +1 -1
  86. package/dist/interactions-BXzEel4F.cjs +2 -0
  87. package/dist/interactions-BXzEel4F.cjs.map +1 -0
  88. package/dist/interactions-DdKPMWIN.js +207 -0
  89. package/dist/interactions-DdKPMWIN.js.map +1 -0
  90. package/dist/{journey-B4Adltjm.cjs → journey-BUmsrgaw.cjs} +2 -2
  91. package/dist/{journey-B4Adltjm.cjs.map → journey-BUmsrgaw.cjs.map} +1 -1
  92. package/dist/{journey-D2_sia57.js → journey-Nu655gEO.js} +14 -14
  93. package/dist/{journey-D2_sia57.js.map → journey-Nu655gEO.js.map} +1 -1
  94. package/dist/{library-console-CPW6bvZH.cjs → library-console-DdIlzzph.cjs} +2 -2
  95. package/dist/{library-console-CPW6bvZH.cjs.map → library-console-DdIlzzph.cjs.map} +1 -1
  96. package/dist/{library-console-Btrzt814.js → library-console-amePMnP8.js} +2 -2
  97. package/dist/{library-console-Btrzt814.js.map → library-console-amePMnP8.js.map} +1 -1
  98. package/dist/{library-request-BJ9PLRaD.js → library-request-Cv7C05jf.js} +2 -2
  99. package/dist/{library-request-BJ9PLRaD.js.map → library-request-Cv7C05jf.js.map} +1 -1
  100. package/dist/{library-request-D7OvTxZV.cjs → library-request-DO3Ec7KE.cjs} +2 -2
  101. package/dist/{library-request-D7OvTxZV.cjs.map → library-request-DO3Ec7KE.cjs.map} +1 -1
  102. package/dist/{lifecycle-IaAm1mOC.cjs → lifecycle-B5yfH5is.cjs} +2 -2
  103. package/dist/{lifecycle-IaAm1mOC.cjs.map → lifecycle-B5yfH5is.cjs.map} +1 -1
  104. package/dist/{lifecycle-22CUCrc9.js → lifecycle-CMHz2Zbs.js} +2 -2
  105. package/dist/{lifecycle-22CUCrc9.js.map → lifecycle-CMHz2Zbs.js.map} +1 -1
  106. package/dist/{log-record-BNiLfqtL.js → log-record-B_nSqxoe.js} +2 -2
  107. package/dist/{log-record-BNiLfqtL.js.map → log-record-B_nSqxoe.js.map} +1 -1
  108. package/dist/{log-record-CkivuiEl.cjs → log-record-Bdywwg0k.cjs} +2 -2
  109. package/dist/{log-record-CkivuiEl.cjs.map → log-record-Bdywwg0k.cjs.map} +1 -1
  110. package/dist/{long-frames-DNFaRnC3.js → long-frames-6NGl1-uN.js} +3 -3
  111. package/dist/{long-frames-DNFaRnC3.js.map → long-frames-6NGl1-uN.js.map} +1 -1
  112. package/dist/{long-frames-BUUbXd-B.cjs → long-frames-D9DfSWqv.cjs} +2 -2
  113. package/dist/{long-frames-BUUbXd-B.cjs.map → long-frames-D9DfSWqv.cjs.map} +1 -1
  114. package/dist/models/bus.d.cts +6 -1
  115. package/dist/models/bus.d.ts +6 -1
  116. package/dist/models/config.d.cts +27 -11
  117. package/dist/models/config.d.ts +27 -11
  118. package/dist/models/serializer.d.cts +3 -1
  119. package/dist/models/serializer.d.ts +3 -1
  120. package/dist/{network-CGMLQ-mA.cjs → network-BNHBI0Fc.cjs} +2 -2
  121. package/dist/{network-CGMLQ-mA.cjs.map → network-BNHBI0Fc.cjs.map} +1 -1
  122. package/dist/{network-on2zZT6H.js → network-Cc3tSB7e.js} +5 -5
  123. package/dist/{network-on2zZT6H.js.map → network-Cc3tSB7e.js.map} +1 -1
  124. package/dist/observed-windows-8JtCsIr1.js +64 -0
  125. package/dist/observed-windows-8JtCsIr1.js.map +1 -0
  126. package/dist/observed-windows-BlE25nrn.cjs +2 -0
  127. package/dist/observed-windows-BlE25nrn.cjs.map +1 -0
  128. package/dist/openfin-Bxelt0yg.js.map +1 -1
  129. package/dist/openfin-DtH2f7zX.cjs.map +1 -1
  130. package/dist/{otlp-DimfrRor.js → otlp-Btix3EBa.js} +7 -7
  131. package/dist/{otlp-DimfrRor.js.map → otlp-Btix3EBa.js.map} +1 -1
  132. package/dist/{otlp-BENHf3g9.cjs → otlp-CFSW-Dno.cjs} +2 -2
  133. package/dist/{otlp-BENHf3g9.cjs.map → otlp-CFSW-Dno.cjs.map} +1 -1
  134. package/dist/patch-DlcKzIi-.cjs +2 -0
  135. package/dist/patch-DlcKzIi-.cjs.map +1 -0
  136. package/dist/patch-Sr1wKg7W.js +9 -0
  137. package/dist/patch-Sr1wKg7W.js.map +1 -0
  138. package/dist/platform-BZjp9wp1.cjs +2 -0
  139. package/dist/platform-BZjp9wp1.cjs.map +1 -0
  140. package/dist/platform-Dba6R3Hp.js +75 -0
  141. package/dist/platform-Dba6R3Hp.js.map +1 -0
  142. package/dist/{profiler-BAZoh7A4.js → profiler-DNKcqu09.js} +60 -60
  143. package/dist/{profiler-BAZoh7A4.js.map → profiler-DNKcqu09.js.map} +1 -1
  144. package/dist/{profiler-D4tJpDRc.cjs → profiler-DpoPi1hH.cjs} +2 -2
  145. package/dist/{profiler-D4tJpDRc.cjs.map → profiler-DpoPi1hH.cjs.map} +1 -1
  146. package/dist/{profiler-frames-C4xr7KfH.cjs → profiler-frames-C9zJNd8_.cjs} +2 -2
  147. package/dist/{profiler-frames-C4xr7KfH.cjs.map → profiler-frames-C9zJNd8_.cjs.map} +1 -1
  148. package/dist/{profiler-frames-cJMx9wNM.js → profiler-frames-CGXZeZ_3.js} +16 -16
  149. package/dist/{profiler-frames-cJMx9wNM.js.map → profiler-frames-CGXZeZ_3.js.map} +1 -1
  150. package/dist/{remote-rules-Dz9MRAsB.js → remote-rules-DNK96vLa.js} +25 -25
  151. package/dist/{remote-rules-Dz9MRAsB.js.map → remote-rules-DNK96vLa.js.map} +1 -1
  152. package/dist/{remote-rules-_tY0zj5o.cjs → remote-rules-DuMFRlit.cjs} +2 -2
  153. package/dist/{remote-rules-_tY0zj5o.cjs.map → remote-rules-DuMFRlit.cjs.map} +1 -1
  154. package/dist/replay-Cab-lSit.cjs +2 -0
  155. package/dist/replay-Cab-lSit.cjs.map +1 -0
  156. package/dist/{replay-Ds-ANH34.js → replay-Dy6OiaOZ.js} +104 -77
  157. package/dist/replay-Dy6OiaOZ.js.map +1 -0
  158. package/dist/{reports-BDSe4dFH.cjs → reports-CGK9YQch.cjs} +2 -2
  159. package/dist/{reports-BDSe4dFH.cjs.map → reports-CGK9YQch.cjs.map} +1 -1
  160. package/dist/{reports-C-thq-bk.js → reports-CX57-S9s.js} +3 -3
  161. package/dist/{reports-C-thq-bk.js.map → reports-CX57-S9s.js.map} +1 -1
  162. package/dist/{resource-timing-eUl2dNgC.js → resource-timing-CWVDCbrY.js} +4 -4
  163. package/dist/{resource-timing-eUl2dNgC.js.map → resource-timing-CWVDCbrY.js.map} +1 -1
  164. package/dist/{resource-timing-C576gFIQ.cjs → resource-timing-DalulXiR.cjs} +2 -2
  165. package/dist/{resource-timing-C576gFIQ.cjs.map → resource-timing-DalulXiR.cjs.map} +1 -1
  166. package/dist/response-body-Cpz5__4g.cjs +3 -0
  167. package/dist/response-body-Cpz5__4g.cjs.map +1 -0
  168. package/dist/{response-body-eoSQpLiH.js → response-body-yi92Rpvo.js} +109 -109
  169. package/dist/response-body-yi92Rpvo.js.map +1 -0
  170. package/dist/{rotation-Cwct4ckk.js → rotation-ChBbNDE2.js} +27 -28
  171. package/dist/rotation-ChBbNDE2.js.map +1 -0
  172. package/dist/rotation-fTnNJcfH.cjs +2 -0
  173. package/dist/rotation-fTnNJcfH.cjs.map +1 -0
  174. package/dist/{sampling-BlrI8jor.js → sampling-DZTOD28D.js} +16 -16
  175. package/dist/{sampling-BlrI8jor.js.map → sampling-DZTOD28D.js.map} +1 -1
  176. package/dist/{sampling-mXt4dstx.cjs → sampling-wAVJIZXp.cjs} +2 -2
  177. package/dist/{sampling-mXt4dstx.cjs.map → sampling-wAVJIZXp.cjs.map} +1 -1
  178. package/dist/{sanitize-Ba0KqU06.js → sanitize-B2GKlSFp.js} +2 -2
  179. package/dist/{sanitize-Ba0KqU06.js.map → sanitize-B2GKlSFp.js.map} +1 -1
  180. package/dist/{sanitize-DQyiI_KY.cjs → sanitize-BZdhoghq.cjs} +2 -2
  181. package/dist/{sanitize-DQyiI_KY.cjs.map → sanitize-BZdhoghq.cjs.map} +1 -1
  182. package/dist/{sender-Dv8rAmpV.js → sender-BRSpc7R8.js} +192 -178
  183. package/dist/sender-BRSpc7R8.js.map +1 -0
  184. package/dist/sender-CFu98DAB.cjs +2 -0
  185. package/dist/sender-CFu98DAB.cjs.map +1 -0
  186. package/dist/storage/emergency-queue.d.cts +3 -1
  187. package/dist/storage/emergency-queue.d.ts +3 -1
  188. package/dist/storage/stored-context.d.cts +3 -2
  189. package/dist/storage/stored-context.d.ts +3 -2
  190. package/dist/stored-context-CPLlzgpm.cjs +2 -0
  191. package/dist/stored-context-CPLlzgpm.cjs.map +1 -0
  192. package/dist/{stored-context-B2EzVuYm.js → stored-context-df1dEnht.js} +12 -10
  193. package/dist/stored-context-df1dEnht.js.map +1 -0
  194. package/dist/{storm-DjKetLKZ.js → storm-U3_ek1nA.js} +2 -2
  195. package/dist/{storm-DjKetLKZ.js.map → storm-U3_ek1nA.js.map} +1 -1
  196. package/dist/{storm-C-zYSdDX.cjs → storm-qiE_AMC7.cjs} +2 -2
  197. package/dist/{storm-C-zYSdDX.cjs.map → storm-qiE_AMC7.cjs.map} +1 -1
  198. package/dist/transport/exit-flush.d.cts +23 -0
  199. package/dist/transport/exit-flush.d.ts +23 -0
  200. package/dist/transport/http-transport.d.cts +3 -2
  201. package/dist/transport/http-transport.d.ts +3 -2
  202. package/dist/transport/retry-engine.d.cts +11 -3
  203. package/dist/transport/retry-engine.d.ts +11 -3
  204. package/dist/types-BAerHgCq.js.map +1 -1
  205. package/dist/types-C7WNpnG1.cjs.map +1 -1
  206. package/dist/{unclean-exit-DQD1cT7c.js → unclean-exit-Bj6gYHeL.js} +2 -2
  207. package/dist/{unclean-exit-DQD1cT7c.js.map → unclean-exit-Bj6gYHeL.js.map} +1 -1
  208. package/dist/{unclean-exit-py99ApzT.cjs → unclean-exit-CuBh-ee5.cjs} +2 -2
  209. package/dist/{unclean-exit-py99ApzT.cjs.map → unclean-exit-CuBh-ee5.cjs.map} +1 -1
  210. package/dist/{user-timing-D6XTmpuM.cjs → user-timing-BWqzYF2Q.cjs} +2 -2
  211. package/dist/{user-timing-D6XTmpuM.cjs.map → user-timing-BWqzYF2Q.cjs.map} +1 -1
  212. package/dist/{user-timing-BePqb1uN.js → user-timing-Duz0d-OA.js} +2 -2
  213. package/dist/{user-timing-BePqb1uN.js.map → user-timing-Duz0d-OA.js.map} +1 -1
  214. package/dist/utils/identity.d.cts +5 -0
  215. package/dist/utils/identity.d.ts +5 -0
  216. package/dist/utils/lock.d.cts +3 -2
  217. package/dist/utils/lock.d.ts +3 -2
  218. package/dist/utils/openfin.d.cts +18 -6
  219. package/dist/utils/openfin.d.ts +18 -6
  220. package/dist/utils/patch.d.cts +1 -1
  221. package/dist/utils/patch.d.ts +1 -1
  222. package/dist/utils/platform.d.cts +6 -0
  223. package/dist/utils/platform.d.ts +6 -0
  224. package/dist/{web-socket-DSHgDiZ6.js → web-socket-CE_9Q22z.js} +5 -5
  225. package/dist/{web-socket-DSHgDiZ6.js.map → web-socket-CE_9Q22z.js.map} +1 -1
  226. package/dist/{web-socket-CoIUBM3C.cjs → web-socket-sm3rD-A_.cjs} +2 -2
  227. package/dist/{web-socket-CoIUBM3C.cjs.map → web-socket-sm3rD-A_.cjs.map} +1 -1
  228. package/dist/{web-vitals-4pWACwaR.js → web-vitals-CGwXGF-M.js} +4 -4
  229. package/dist/web-vitals-CGwXGF-M.js.map +1 -0
  230. package/dist/web-vitals-Df4Wsfx9.cjs +2 -0
  231. package/dist/web-vitals-Df4Wsfx9.cjs.map +1 -0
  232. package/dist/{worker-protocol-QbvqNazn.cjs → worker-protocol-D5VnCdWY.cjs} +2 -2
  233. package/dist/{worker-protocol-QbvqNazn.cjs.map → worker-protocol-D5VnCdWY.cjs.map} +1 -1
  234. package/dist/{worker-protocol-x074Rpet.js → worker-protocol-h4-tRWqy.js} +6 -6
  235. package/dist/{worker-protocol-x074Rpet.js.map → worker-protocol-h4-tRWqy.js.map} +1 -1
  236. package/dist/{worker-server-CFe4nvos.cjs → worker-server-CF1yatXq.cjs} +2 -2
  237. package/dist/{worker-server-CFe4nvos.cjs.map → worker-server-CF1yatXq.cjs.map} +1 -1
  238. package/dist/worker-server-FYfKHQhJ.js +94 -0
  239. package/dist/{worker-server-iUVSjH8L.js.map → worker-server-FYfKHQhJ.js.map} +1 -1
  240. package/dist/worker-transport-COgY4RX8.cjs +2 -0
  241. package/dist/worker-transport-COgY4RX8.cjs.map +1 -0
  242. package/dist/{worker-transport-Dy1KMA7t.js → worker-transport-jzX1IusG.js} +49 -45
  243. package/dist/worker-transport-jzX1IusG.js.map +1 -0
  244. package/llms.txt +14 -12
  245. package/package.json +13 -5
  246. package/dist/bus-C39wspFV.js.map +0 -1
  247. package/dist/bus-_EaOVPGq.cjs +0 -2
  248. package/dist/bus-_EaOVPGq.cjs.map +0 -1
  249. package/dist/config-DUs7uHHt.cjs +0 -2
  250. package/dist/config-DUs7uHHt.cjs.map +0 -1
  251. package/dist/config-SgQcCP1_.js +0 -560
  252. package/dist/config-SgQcCP1_.js.map +0 -1
  253. package/dist/constants-CUyd9cTZ.js.map +0 -1
  254. package/dist/constants-CqdJhTxH.cjs +0 -2
  255. package/dist/constants-CqdJhTxH.cjs.map +0 -1
  256. package/dist/errors-BE_EZV7Q.js.map +0 -1
  257. package/dist/errors-CNPbesMs.cjs +0 -3
  258. package/dist/errors-CNPbesMs.cjs.map +0 -1
  259. package/dist/factory-CTi0Is3F.js.map +0 -1
  260. package/dist/factory-hRrH32v5.cjs +0 -2
  261. package/dist/factory-hRrH32v5.cjs.map +0 -1
  262. package/dist/identity-DdhKgrpk.js.map +0 -1
  263. package/dist/identity-DlWRIuwy.cjs +0 -2
  264. package/dist/identity-DlWRIuwy.cjs.map +0 -1
  265. package/dist/interactions-CUkzK8sR.cjs +0 -2
  266. package/dist/interactions-CUkzK8sR.cjs.map +0 -1
  267. package/dist/interactions-DiFvCosX.js +0 -111
  268. package/dist/interactions-DiFvCosX.js.map +0 -1
  269. package/dist/patch-BX8KrPCT.cjs +0 -2
  270. package/dist/patch-BX8KrPCT.cjs.map +0 -1
  271. package/dist/patch-UdPz1ea8.js +0 -8
  272. package/dist/patch-UdPz1ea8.js.map +0 -1
  273. package/dist/platform-BaaFIPCU.js +0 -62
  274. package/dist/platform-BaaFIPCU.js.map +0 -1
  275. package/dist/platform-CfA3-7sJ.cjs +0 -2
  276. package/dist/platform-CfA3-7sJ.cjs.map +0 -1
  277. package/dist/replay-B3gFXIZd.cjs +0 -2
  278. package/dist/replay-B3gFXIZd.cjs.map +0 -1
  279. package/dist/replay-Ds-ANH34.js.map +0 -1
  280. package/dist/response-body-YdNl-HkR.cjs +0 -3
  281. package/dist/response-body-YdNl-HkR.cjs.map +0 -1
  282. package/dist/response-body-eoSQpLiH.js.map +0 -1
  283. package/dist/rotation-Cwct4ckk.js.map +0 -1
  284. package/dist/rotation-D4qUAHAu.cjs +0 -2
  285. package/dist/rotation-D4qUAHAu.cjs.map +0 -1
  286. package/dist/sender-BdRuNVhF.cjs +0 -2
  287. package/dist/sender-BdRuNVhF.cjs.map +0 -1
  288. package/dist/sender-Dv8rAmpV.js.map +0 -1
  289. package/dist/stored-context-B2EzVuYm.js.map +0 -1
  290. package/dist/stored-context-CXt7eHZL.cjs +0 -2
  291. package/dist/stored-context-CXt7eHZL.cjs.map +0 -1
  292. package/dist/web-vitals-4pWACwaR.js.map +0 -1
  293. package/dist/web-vitals-__X7t4pj.cjs +0 -2
  294. package/dist/web-vitals-__X7t4pj.cjs.map +0 -1
  295. package/dist/worker-server-iUVSjH8L.js +0 -94
  296. package/dist/worker-transport-CRAX-09c.cjs +0 -2
  297. package/dist/worker-transport-CRAX-09c.cjs.map +0 -1
  298. package/dist/worker-transport-Dy1KMA7t.js.map +0 -1
package/dist/doctor.js CHANGED
@@ -1,21 +1,21 @@
1
- import { V as e, Vn as t, dt as n, ft as r, ht as i, lt as a, mt as o, nn as s, pn as c, pt as l, rn as u, tt as d, ut as f, z as p } from "./constants-CUyd9cTZ.js";
2
- import { t as m } from "./compression-tVtXwVjX.js";
3
- import { r as h } from "./otlp-DimfrRor.js";
1
+ import { Gn as e, V as t, _n as n, an as r, dt as i, ft as a, gt as o, ht as s, mt as c, nt as l, on as u, pt as d, ut as f, z as p } from "./constants-CEHN6KuY.js";
2
+ import { t as m } from "./compression-BWkDWY3v.js";
3
+ import { r as h } from "./otlp-Btix3EBa.js";
4
4
  // src/doctor.ts
5
5
  var g = 1e4, _ = 0, v = 1, y = 2, b = "Usage: uiobs doctor <url> --origin <origin> [--replay] [--credentials include] [--header \"Name: value\"]. An origin has no path and no trailing slash. With --replay, the URL is a replay endpoint. With --credentials include, a * in a CORS header fails.", x = "--header", S = "--replay", C = "--credentials", w = "include", T = 5e6, ee = 5, E = "uiobs-doctor", te = /^([\w!#$%&'*+.^`|~-]+): *([\x20-\x7e]+)$/, ne = "<hidden>", D = "Access-Control-Expose-Headers", O = "Access-Control-Allow-Origin", k = "Access-Control-Allow-Headers", A = "Access-Control-Allow-Credentials", j = "A browser refuses * with credentials: \"include\".", M = "A browser does not read * as a wildcard with credentials: \"include\".", re = "A browser never lets * cover authorization.", ie = "Add --credentials include to check that case.", N = [
6
- r,
7
- n,
8
- f,
9
- a
10
- ].map((e) => e.toLowerCase()), ae = [...N, "origin"], P = [i, l].map((e) => e.toLowerCase()), F = "authorization", I = [o.toLowerCase()], oe = [...I, ...P];
6
+ d,
7
+ a,
8
+ i,
9
+ f
10
+ ].map((e) => e.toLowerCase()), ae = [...N, "origin"], P = [o, c].map((e) => e.toLowerCase()), F = "authorization", I = [s.toLowerCase()], oe = [...I, ...P];
11
11
  function se() {
12
- let e = crypto.randomUUID().replaceAll("-", "");
12
+ let t = crypto.randomUUID().replaceAll("-", "");
13
13
  return {
14
14
  timeUnixNano: `${String(Date.now())}000000`,
15
- traceId: e,
16
- spanId: e.slice(0, 16),
15
+ traceId: t,
16
+ spanId: t.slice(0, 16),
17
17
  traceFlags: 1,
18
- severityNumber: t.INFO,
18
+ severityNumber: e.INFO,
19
19
  severityText: "INFO",
20
20
  body: "uiobs doctor test record",
21
21
  attributes: {},
@@ -101,38 +101,38 @@ function Y(e, t) {
101
101
  return `${k} must include ${n.join(", ")}.${r}${i}`;
102
102
  })];
103
103
  }
104
- function X({ url: e, origin: t, custom: n }, i, o) {
105
- return (s, c, l, u = {}) => L(e, {
104
+ function X({ url: e, origin: t, custom: n }, r, a) {
105
+ return (o, s, c, l = {}) => L(e, {
106
106
  method: "POST",
107
107
  headers: {
108
108
  ...n,
109
109
  Origin: t,
110
- [r]: i,
111
- [f]: s,
112
- [a]: String(c),
113
- ...u
110
+ [d]: r,
111
+ [i]: o,
112
+ [f]: String(s),
113
+ ...l
114
114
  },
115
- body: l
116
- }, o);
115
+ body: c
116
+ }, a);
117
117
  }
118
- async function Z(e, t, r) {
119
- let i = await m(r);
120
- return i ? e(t, 0, i, { [n]: d }) : "This Node version has no CompressionStream.";
118
+ async function Z(e, t, n) {
119
+ let r = await m(n);
120
+ return r ? e(t, 0, r, { [a]: l }) : "This Node version has no CompressionStream.";
121
121
  }
122
- async function Q(t, n, i = {}, a = !1) {
123
- let o = H(t, n, i, a), c = U(o), l = await J(o), { body: d, contentType: f } = h.serialize([se()]), p = X(o, f), m = crypto.randomUUID(), g = await p(m, 0, d), _ = await p(m, 1, d), v = await Z(p, crypto.randomUUID(), d), y = new URL(t);
124
- y.searchParams.set(s, crypto.randomUUID()), y.searchParams.set(u, "pagehide");
122
+ async function Q(e, n, i = {}, a = !1) {
123
+ let o = H(e, n, i, a), s = U(o), c = await J(o), { body: l, contentType: f } = h.serialize([se()]), p = X(o, f), m = crypto.randomUUID(), g = await p(m, 0, l), _ = await p(m, 1, l), v = await Z(p, crypto.randomUUID(), l), y = new URL(e);
124
+ y.searchParams.set(r, crypto.randomUUID()), y.searchParams.set(u, "pagehide");
125
125
  let b = o.requestHeaders.length > N.length ? void 0 : await L(y.toString(), {
126
126
  method: "POST",
127
127
  headers: {
128
128
  Origin: n,
129
- [r]: e
129
+ [d]: t
130
130
  },
131
- body: d
131
+ body: l
132
132
  }), x = typeof g == "string" ? [] : z(g, D, P, !o.credentials), S = x.length > 0 ? ` Optional headers stay hidden: ${x.join(", ")}.` : "", C = G(q(g, D, oe), o, M);
133
133
  return [
134
- ...Y(l, o),
135
- V("test batch", g, `The server accepted a test batch.${G(W(g) === "*", o)}`, B, c),
134
+ ...Y(c, o),
135
+ V("test batch", g, `The server accepted a test batch.${G(W(g) === "*", o)}`, B, s),
136
136
  V("exposed headers", g, `The server exposes Retry-After.${S}${C}`, (e) => z(e, D, I, !o.credentials).length === 0 ? void 0 : `${D} must include retry-after.${K(e, D, o)}`),
137
137
  V("gzip", v, "The server accepted a gzip batch.", B),
138
138
  V("deduplication", _, "The server accepted a repeated batch id. A client cannot see if it stored the batch again.", B),
@@ -143,9 +143,9 @@ async function Q(t, n, i = {}, a = !1) {
143
143
  } : V("beacon", b, "The server accepted a text/plain batch.", ce, B)
144
144
  ];
145
145
  }
146
- async function $(e, t, n = {}, r = !1) {
147
- let i = H(e, t, n, r), a = U(i), o = await J(i), s = crypto.randomUUID(), l = {
148
- "replay.id": s,
146
+ async function $(e, t, r = {}, i = !1) {
147
+ let a = H(e, t, r, i), o = U(a), s = await J(a), c = crypto.randomUUID(), l = {
148
+ "replay.id": c,
149
149
  "session.id": crypto.randomUUID(),
150
150
  "tab.id": crypto.randomUUID(),
151
151
  "service.name": E
@@ -164,10 +164,10 @@ async function $(e, t, n = {}, r = !1) {
164
164
  bytes: JSON.stringify(n).length,
165
165
  events: n
166
166
  });
167
- }, d = (e) => `${s}-${String(e)}`, f = X(i, p), m = u(0, "uiobs doctor test event"), h = await f(d(0), 0, m), g = await f(d(0), 1, m), _ = await Z(f, d(1), u(1, "uiobs doctor gzip event")), v = await X(i, p, c)(d(2), 0, u(2, "x".repeat(T)));
167
+ }, d = (e) => `${c}-${String(e)}`, f = X(a, p), m = u(0, "uiobs doctor test event"), h = await f(d(0), 0, m), g = await f(d(0), 1, m), _ = await Z(f, d(1), u(1, "uiobs doctor gzip event")), v = await X(a, p, n)(d(2), 0, u(2, "x".repeat(T)));
168
168
  return [
169
- ...Y(o, i),
170
- V("test segment", h, `The server accepted a test segment.${G(W(h) === "*", i)}`, B, a),
169
+ ...Y(s, a),
170
+ V("test segment", h, `The server accepted a test segment.${G(W(h) === "*", a)}`, B, o),
171
171
  V("gzip", _, "The server accepted a gzip segment.", B),
172
172
  V("large segment", v, `The server accepted a segment of ${String(T)} bytes without gzip.`, (e) => e.ok ? void 0 : `The server returned ${String(e.status)} for a segment of ${String(T)} bytes. The first segment of an upload has a full snapshot of the page. Raise the body limit of the server.`),
173
173
  V("deduplication", g, "The server accepted a repeated batch id. A client cannot see if it stored the segment again.", B)
@@ -1 +1 @@
1
- {"version":3,"file":"doctor.js","names":["LIBRARY_TIMEOUT_MS","CONTENT_TYPE_TEXT_PLAIN","SEVERITY_NUMBER","HEADER_CONTENT_ENCODING","HEADER_CONTENT_TYPE","HEADER_SAMPLING","HEADER_ATTEMPT","HEADER_RETRY_AFTER","QUERY_PARAM_BATCH_ID","REQUEST_TIMEOUT_MS$1","HEADER_DATE","QUERY_PARAM_EXIT_REASON","ENCODING_GZIP","HEADER_BATCH_ID","CONTENT_TYPE_JSON","gzip","otlpSerializer","REQUEST_TIMEOUT_MS","EXIT_PASS","EXIT_FAIL","EXIT_USAGE","USAGE","HEADER_FLAG","REPLAY_FLAG","CREDENTIALS_FLAG","CREDENTIALS_INCLUDE","LARGE_EVENT_CHARS","CUSTOM_EVENT","DOCTOR_NAME","HEADER_PATTERN","HIDDEN","EXPOSE_HEADERS","ALLOW_ORIGIN","ALLOW_HEADERS","ALLOW_CREDENTIALS","STAR_REFUSED","STAR_PLAIN","STAR_AUTHORIZATION","STAR_HINT","REQUEST_HEADERS","name","RESERVED_HEADERS","OPTIONAL_EXPOSED","NON_WILDCARD_HEADER","REQUIRED_EXPOSED","WANTED_EXPOSED","testRecord","traceId","request","url","init","timeoutMs","error","reason","valuesOf","response","value","absent","values","star","wildcard","wanted","statusProblem","mediaTypeProblem","judge","tests","problem","answer","test","found","passed","targetOf","customNames","custom","originTest","allowed","credentials","origin","allowsCredentials","allowedOrigin","starNote","earnedByStar","starWhy","coveredByStar","sendPreflight","requestHeaders","preflightResults","originNote","preflight","target","headersNote","missing","why","authorization","poster","contentType","id","attempt","extra","payload","postZipped","compressed","body","post","runDoctor","originProblem","batchId","first","repeated","zipped","beaconUrl","beacon","hidden","hiddenNote","exposedNote","runReplayDoctor","replayId","head","segment","events","text","idOf","sequence","small","large","parseOptions","pairs","index","args","match","isHttpUrl","username","password","SHOWN_WORDS","shownArgument","arg","pathname","isOrigin","main","command","flag","rest","replay","options","print","results","headers","pass","rule","detail"],"sources":["../src/doctor.ts"],"sourcesContent":["// src/doctor.ts\n//\n// Checks an ingest server, or a replay endpoint, against its contract in docs/ingest-server.md.\n// The `uiobs doctor` command calls main(). Only web APIs are used here, and the browser build\n// replaces every \"node:\" import.\n\nimport {\n CONTENT_TYPE_JSON,\n CONTENT_TYPE_TEXT_PLAIN,\n ENCODING_GZIP,\n HEADER_ATTEMPT,\n HEADER_BATCH_ID,\n HEADER_CONTENT_ENCODING,\n HEADER_CONTENT_TYPE,\n HEADER_DATE,\n HEADER_RETRY_AFTER,\n HEADER_SAMPLING,\n HTTP_UNSUPPORTED_MEDIA_TYPE,\n QUERY_PARAM_BATCH_ID,\n QUERY_PARAM_EXIT_REASON,\n REQUEST_TIMEOUT_MS as LIBRARY_TIMEOUT_MS,\n SEVERITY_NUMBER,\n} from \"./constants\";\nimport type { LogRecord } from \"./models/log-record\";\nimport { gzip } from \"./transport/compression\";\nimport { otlpSerializer } from \"./transport/serializers/otlp\";\n\n/** How long to wait for one answer, in milliseconds. */\nconst REQUEST_TIMEOUT_MS = 10000;\n\n/** Exit code when every rule passes. */\nconst EXIT_PASS = 0;\n\n/** Exit code when a rule fails. */\nconst EXIT_FAIL = 1;\n\n/** Exit code for a wrong command. */\nconst EXIT_USAGE = 2;\n\n/** Printed for a wrong command. */\nconst USAGE =\n 'Usage: uiobs doctor <url> --origin <origin> [--replay] [--credentials include] [--header \"Name: value\"]. An origin has no path and no trailing slash. With --replay, the URL is a replay endpoint. With --credentials include, a * in a CORS header fails.';\n\n/** Adds a request header, e.g. an Authorization header. */\nconst HEADER_FLAG = \"--header\";\n\n/** Says that the URL is a replay endpoint, so the tool sends segments instead of batches. */\nconst REPLAY_FLAG = \"--replay\";\n\n/** Says that the app sets `credentials: \"include\"`, so a browser refuses a * in a CORS header. */\nconst CREDENTIALS_FLAG = \"--credentials\";\n\n/** The only value of CREDENTIALS_FLAG. */\nconst CREDENTIALS_INCLUDE = \"include\";\n\n/**\n * Size of the event in the large test segment, in characters. The first segment of a real\n * upload holds a full snapshot, and one of a page with 35,000 table cells measured 4.7 MB.\n */\nconst LARGE_EVENT_CHARS = 5_000_000;\n\n/** The recorder's custom event type. A player skips a custom event it doesn't know. */\nconst CUSTOM_EVENT = 5;\n\n/** Marks everything the tool stores, so an operator can find and delete it. */\nconst DOCTOR_NAME = \"uiobs-doctor\";\n\n/** A header name, a colon, then a value of printable ASCII. */\nconst HEADER_PATTERN = /^([\\w!#$%&'*+.^`|~-]+): *([\\x20-\\x7e]+)$/;\n\n/** Printed in place of any argument that might contain a secret. */\nconst HIDDEN = \"<hidden>\";\n\n/** Response header that lists the headers a page can read. */\nconst EXPOSE_HEADERS = \"Access-Control-Expose-Headers\";\n\n/** Response header that names the origin that may read the answer. */\nconst ALLOW_ORIGIN = \"Access-Control-Allow-Origin\";\n\n/** Response header of a preflight that lists the request headers the server accepts. */\nconst ALLOW_HEADERS = \"Access-Control-Allow-Headers\";\n\n/** Response header that lets a browser send and read an answer with credentials. */\nconst ALLOW_CREDENTIALS = \"Access-Control-Allow-Credentials\";\n\n/** Why a * in Access-Control-Allow-Origin fails with credentials. */\nconst STAR_REFUSED = 'A browser refuses * with credentials: \"include\".';\n\n/** Why a * in a list of header names fails with credentials. */\nconst STAR_PLAIN = 'A browser does not read * as a wildcard with credentials: \"include\".';\n\n/** Why a * in Access-Control-Allow-Headers fails for Authorization, with or without credentials. */\nconst STAR_AUTHORIZATION = \"A browser never lets * cover authorization.\";\n\n/** Ends the note of a PASS line that only a * earned, so the run without credentials says so. */\nconst STAR_HINT = \"Add --credentials include to check that case.\";\n\n/** The library's request headers. The server must allow every one of them. */\nconst REQUEST_HEADERS = [\n HEADER_CONTENT_TYPE,\n HEADER_CONTENT_ENCODING,\n HEADER_BATCH_ID,\n HEADER_ATTEMPT,\n].map((name) => name.toLowerCase());\n\n/** Headers the tool sets itself. A custom header can't reuse one of these names. */\nconst RESERVED_HEADERS = [...REQUEST_HEADERS, \"origin\"];\n\n/** Response headers that only an optional feature reads. */\nconst OPTIONAL_EXPOSED = [HEADER_SAMPLING, HEADER_DATE].map((name) => name.toLowerCase());\n\n/** The one request header that a * in Access-Control-Allow-Headers never covers. */\nconst NON_WILDCARD_HEADER = \"authorization\";\n\n/** The response header that the library can't work without when it is hidden. */\nconst REQUIRED_EXPOSED = [HEADER_RETRY_AFTER.toLowerCase()];\n\n/** Every response header that the library reads. */\nconst WANTED_EXPOSED = [...REQUIRED_EXPOSED, ...OPTIONAL_EXPOSED];\n\n/** The result of one ingest contract rule. */\nexport interface DoctorResult {\n /** Rule name. */\n rule: string;\n /** True when the server meets the rule. */\n pass: boolean;\n /** Why the rule passed or failed. */\n detail: string;\n}\n\n/** An HTTP answer, or the text of a failed request. */\ntype Answer = Response | string;\n\n/** Returns a description of the problem, or undefined when the answer passes the test. */\ntype AnswerTest = (response: Response) => string | undefined;\n\n/** Builds the test record. The server stores it like any other record. */\nfunction testRecord(): LogRecord {\n const traceId = crypto.randomUUID().replaceAll(\"-\", \"\");\n\n return {\n timeUnixNano: `${String(Date.now())}000000`,\n traceId,\n spanId: traceId.slice(0, 16),\n traceFlags: 1,\n severityNumber: SEVERITY_NUMBER.INFO,\n severityText: \"INFO\",\n body: \"uiobs doctor test record\",\n attributes: {},\n resource: { \"service.name\": DOCTOR_NAME },\n };\n}\n\n/** Sends one request. A failure shows up in the result line, as the tool has no diagnostics. */\nasync function request(\n url: string,\n init: RequestInit,\n timeoutMs = REQUEST_TIMEOUT_MS,\n): Promise<Answer> {\n try {\n // A browser refuses a preflight that redirects, and a redirect can also name another host.\n return await fetch(url, {\n ...init,\n redirect: \"manual\",\n signal: AbortSignal.timeout(timeoutMs),\n });\n } catch (error) {\n // Node only says \"fetch failed\". The cause holds the real reason, for example ECONNREFUSED.\n const reason: unknown =\n error instanceof Error ? ((error as Error & { cause?: unknown }).cause ?? error) : error;\n\n return `The request failed. ${reason instanceof Error ? reason.message : String(reason)}`;\n }\n}\n\n/** Returns the lowercase values of a comma-separated response header. */\nfunction valuesOf(response: Response, name: string): string[] {\n return (response.headers.get(name) ?? \"\")\n .toLowerCase()\n .split(\",\")\n .map((value) => value.trim());\n}\n\n/**\n * Returns the wanted values a comma-separated header leaves out. With wildcard, a * covers them\n * all but Authorization, which the Fetch standard never lets a * cover. A run with credentials\n * passes false, because a browser reads * as a plain name then.\n */\nfunction absent(\n response: Response,\n name: string,\n wanted: readonly string[],\n wildcard: boolean,\n): string[] {\n const values = valuesOf(response, name);\n const star = wildcard && values.includes(\"*\");\n\n return wanted.filter(\n (value) => !values.includes(value) && !(star && value !== NON_WILDCARD_HEADER),\n );\n}\n\n/** Checks an answer's status. */\nconst statusProblem: AnswerTest = (response) =>\n response.ok ? undefined : `The server returned ${String(response.status)}.`;\n\n/**\n * Names the collector case for a 415 answer to the beacon batch, because the bare status doesn't\n * say that only the exit batches are lost or how to fix it.\n */\nconst mediaTypeProblem: AnswerTest = (response) =>\n response.status === HTTP_UNSUPPORTED_MEDIA_TYPE\n ? `The server returned ${String(response.status)} to a text/plain batch, as a stock OpenTelemetry Collector does. The library loses the exit batches of a page on another origin. Set headers in the app, or put a same-origin proxy in front of the server.`\n : undefined;\n\n/** Builds the result for one rule. The first problem found becomes the detail. */\nfunction judge(rule: string, answer: Answer, passed: string, ...tests: AnswerTest[]): DoctorResult {\n const problem =\n typeof answer === \"string\"\n ? answer\n : tests.map((test) => test(answer)).find((found) => found !== undefined);\n\n return { rule, pass: problem === undefined, detail: problem ?? passed };\n}\n\n/** One endpoint under test: where it is, who calls it and with which headers. */\ninterface Target {\n /** Endpoint URL. */\n url: string;\n /** The app's origin. */\n origin: string;\n /** The app's headers for each POST, e.g. an Authorization header. */\n custom: Readonly<Record<string, string>>;\n /** Lowercase names of every header a POST carries. The preflight asks for them. */\n requestHeaders: string[];\n /** True with `--credentials include`. A browser then refuses a * in a CORS header. */\n credentials: boolean;\n}\n\n/** Sends one POST the way the library does. Extra headers go on top. */\ntype Post = (\n id: string,\n attempt: number,\n payload: BodyInit,\n extra?: Record<string, string>,\n) => Promise<Answer>;\n\n/** Builds the target for one run. */\nfunction targetOf(\n url: string,\n origin: string,\n custom: Readonly<Record<string, string>>,\n credentials: boolean,\n): Target {\n const customNames = Object.keys(custom).map((name) => name.toLowerCase());\n\n return {\n url,\n origin,\n custom,\n requestHeaders: [...REQUEST_HEADERS, ...customNames],\n credentials,\n };\n}\n\n/** Builds the test that an answer lets the app's origin read it. */\nfunction originTest({ origin, credentials }: Target): AnswerTest {\n return (response) => {\n const allowed = response.headers.get(ALLOW_ORIGIN);\n\n if (allowed === \"*\" && credentials) {\n return `${ALLOW_ORIGIN} is *. ${STAR_REFUSED} It must be ${origin}.`;\n }\n\n if (allowed !== origin && allowed !== \"*\") {\n return `${ALLOW_ORIGIN} is ${String(allowed)}. It must allow ${origin}.`;\n }\n\n // A browser rejects a credentialed answer without this header. The library then sees a\n // network error and sends the batch again.\n return credentials ? allowsCredentials(response) : undefined;\n };\n}\n\n/** Checks that an answer lets the browser send and read credentials. */\nconst allowsCredentials: AnswerTest = (response) => {\n const allowed = response.headers.get(ALLOW_CREDENTIALS);\n\n return allowed === \"true\"\n ? undefined\n : `${ALLOW_CREDENTIALS} is ${String(allowed)}. It must be true with credentials: \"include\".`;\n};\n\n/** Returns the origin an answer allows, or null for a failed request or a missing header. */\nfunction allowedOrigin(answer: Answer): string | null {\n return typeof answer === \"string\" ? null : answer.headers.get(ALLOW_ORIGIN);\n}\n\n/**\n * Returns the note for a PASS that only a * earned. With credentials the rule fails on that *,\n * so the note is for the run without them.\n */\nfunction starNote(earnedByStar: boolean, { credentials }: Target, reason = STAR_REFUSED): string {\n return earnedByStar && !credentials ? ` ${reason} ${STAR_HINT}` : \"\";\n}\n\n/** Returns the reason that a * doesn't help a list of header names with credentials, or \"\". */\nfunction starWhy(response: Response, name: string, { credentials }: Target): string {\n return credentials && valuesOf(response, name).includes(\"*\") ? ` ${STAR_PLAIN}` : \"\";\n}\n\n/** True when a list of header names passes only because of its *: it has one and misses a name. */\nfunction coveredByStar(answer: Answer, name: string, wanted: readonly string[]): boolean {\n return (\n typeof answer !== \"string\" &&\n valuesOf(answer, name).includes(\"*\") &&\n absent(answer, name, wanted, false).length > 0\n );\n}\n\n/** Sends the preflight a browser sends before the library's POST. */\nfunction sendPreflight({ url, origin, requestHeaders }: Target): Promise<Answer> {\n return request(url, {\n method: \"OPTIONS\",\n headers: {\n Origin: origin,\n \"Access-Control-Request-Method\": \"POST\",\n \"Access-Control-Request-Headers\": requestHeaders.join(\", \"),\n },\n });\n}\n\n/** Builds the two results every preflight gives. */\nfunction preflightResults(preflight: Answer, target: Target): DoctorResult[] {\n const originNote = starNote(allowedOrigin(preflight) === \"*\", target);\n const headersByStar = coveredByStar(preflight, ALLOW_HEADERS, target.requestHeaders);\n const headersNote = starNote(headersByStar, target, STAR_PLAIN);\n\n return [\n judge(\n \"preflight\",\n preflight,\n `The server permits POST from this origin.${originNote}`,\n statusProblem,\n originTest(target),\n ),\n judge(\n \"allowed headers\",\n preflight,\n `The server allows each request header of the library.${headersNote}`,\n (response) => {\n const missing = absent(response, ALLOW_HEADERS, target.requestHeaders, !target.credentials);\n if (missing.length === 0) {\n return undefined;\n }\n\n const why = starWhy(response, ALLOW_HEADERS, target);\n const authorization =\n missing.includes(NON_WILDCARD_HEADER) && valuesOf(response, ALLOW_HEADERS).includes(\"*\")\n ? ` ${STAR_AUTHORIZATION}`\n : \"\";\n\n return `${ALLOW_HEADERS} must include ${missing.join(\", \")}.${why}${authorization}`;\n },\n ),\n ];\n}\n\n/** Builds the POST function for one target and content type. */\nfunction poster({ url, origin, custom }: Target, contentType: string, timeoutMs?: number): Post {\n return (id, attempt, payload, extra = {}) =>\n request(\n url,\n {\n method: \"POST\",\n headers: {\n ...custom,\n Origin: origin,\n [HEADER_CONTENT_TYPE]: contentType,\n [HEADER_BATCH_ID]: id,\n [HEADER_ATTEMPT]: String(attempt),\n ...extra,\n },\n body: payload,\n },\n timeoutMs,\n );\n}\n\n/** Sends a body with gzip. Gives the text of the problem if this Node can't compress. */\nasync function postZipped(post: Post, id: string, body: string): Promise<Answer> {\n const compressed = await gzip(body);\n\n return compressed\n ? post(id, 0, compressed, { [HEADER_CONTENT_ENCODING]: ENCODING_GZIP })\n : \"This Node version has no CompressionStream.\";\n}\n\n/**\n * Runs each rule's requests one at a time. Two requests with the same batch id must not overlap.\n * @param url Ingest URL.\n * @param origin The app's origin.\n * @param custom The app's headers for each batch, e.g. an Authorization header.\n * @param credentials True when the app sets `credentials: \"include\"`. A * in a CORS header then\n * fails, and the preflight must allow credentials.\n * @returns One result per rule.\n */\nexport async function runDoctor(\n url: string,\n origin: string,\n custom: Readonly<Record<string, string>> = {},\n credentials = false,\n): Promise<DoctorResult[]> {\n const target = targetOf(url, origin, custom, credentials);\n const originProblem = originTest(target);\n const preflight = await sendPreflight(target);\n\n const { body, contentType } = otlpSerializer.serialize([testRecord()]);\n const post = poster(target, contentType);\n\n const batchId = crypto.randomUUID();\n const first = await post(batchId, 0, body);\n const repeated = await post(batchId, 1, body);\n const zipped = await postZipped(post, crypto.randomUUID(), body);\n\n // sendBeacon can't set headers, so the id and the reason go in the query, like the exit flush.\n const beaconUrl = new URL(url);\n beaconUrl.searchParams.set(QUERY_PARAM_BATCH_ID, crypto.randomUUID());\n beaconUrl.searchParams.set(QUERY_PARAM_EXIT_REASON, \"pagehide\");\n\n // With custom headers the library's exit flush uses a keepalive fetch instead of a beacon.\n const beacon =\n target.requestHeaders.length > REQUEST_HEADERS.length\n ? undefined\n : await request(beaconUrl.toString(), {\n method: \"POST\",\n headers: { Origin: origin, [HEADER_CONTENT_TYPE]: CONTENT_TYPE_TEXT_PLAIN },\n body,\n });\n\n const hidden =\n typeof first === \"string\"\n ? []\n : absent(first, EXPOSE_HEADERS, OPTIONAL_EXPOSED, !target.credentials);\n const hiddenNote =\n hidden.length > 0 ? ` Optional headers stay hidden: ${hidden.join(\", \")}.` : \"\";\n const exposedNote = starNote(\n coveredByStar(first, EXPOSE_HEADERS, WANTED_EXPOSED),\n target,\n STAR_PLAIN,\n );\n\n return [\n ...preflightResults(preflight, target),\n judge(\n \"test batch\",\n first,\n `The server accepted a test batch.${starNote(allowedOrigin(first) === \"*\", target)}`,\n statusProblem,\n originProblem,\n ),\n judge(\n \"exposed headers\",\n first,\n `The server exposes Retry-After.${hiddenNote}${exposedNote}`,\n (response) => {\n if (absent(response, EXPOSE_HEADERS, REQUIRED_EXPOSED, !target.credentials).length === 0) {\n return undefined;\n }\n\n const why = starWhy(response, EXPOSE_HEADERS, target);\n\n return `${EXPOSE_HEADERS} must include retry-after.${why}`;\n },\n ),\n judge(\"gzip\", zipped, \"The server accepted a gzip batch.\", statusProblem),\n judge(\n \"deduplication\",\n repeated,\n \"The server accepted a repeated batch id. A client cannot see if it stored the batch again.\",\n statusProblem,\n ),\n beacon === undefined\n ? {\n rule: \"beacon\",\n pass: true,\n detail: \"The library sends no beacon with custom headers. The tool sent no beacon.\",\n }\n : judge(\n \"beacon\",\n beacon,\n \"The server accepted a text/plain batch.\",\n mediaTypeProblem,\n statusProblem,\n ),\n ];\n}\n\n/**\n * Checks a replay endpoint the way runDoctor() checks an ingest server. A segment has its own\n * body and its own batch id form, and its first one can be several megabytes.\n * @param url Replay endpoint URL, the value of replay.endpoint.\n * @param origin The app's origin.\n * @param custom The app's replay.headers, e.g. an Authorization header.\n * @param credentials True when the app sets `credentials: \"include\"`. See runDoctor().\n * @returns One result per rule.\n */\nexport async function runReplayDoctor(\n url: string,\n origin: string,\n custom: Readonly<Record<string, string>> = {},\n credentials = false,\n): Promise<DoctorResult[]> {\n const target = targetOf(url, origin, custom, credentials);\n const originProblem = originTest(target);\n const preflight = await sendPreflight(target);\n\n const replayId = crypto.randomUUID();\n const head = {\n \"replay.id\": replayId,\n \"session.id\": crypto.randomUUID(),\n \"tab.id\": crypto.randomUUID(),\n \"service.name\": DOCTOR_NAME,\n };\n // The body the uploader sends: the ids, the sequence, the JSON length of the events, and the\n // events themselves.\n const segment = (sequence: number, text: string): string => {\n const events = [\n { type: CUSTOM_EVENT, timestamp: Date.now(), data: { tag: DOCTOR_NAME, payload: text } },\n ];\n\n return JSON.stringify({ ...head, sequence, bytes: JSON.stringify(events).length, events });\n };\n // The uploader's batch id is the replay id plus the sequence.\n const idOf = (sequence: number): string => `${replayId}-${String(sequence)}`;\n const post = poster(target, CONTENT_TYPE_JSON);\n const small = segment(0, \"uiobs doctor test event\");\n\n const first = await post(idOf(0), 0, small);\n const repeated = await post(idOf(0), 1, small);\n const zipped = await postZipped(post, idOf(1), segment(1, \"uiobs doctor gzip event\"));\n // No gzip here. That is the worst case: compression off, or a browser without\n // CompressionStream. The library gives a segment delivery.requestTimeoutMs, so the tool\n // waits for the default of that. A shorter wait would fail a slow link the library can use.\n const large = await poster(target, CONTENT_TYPE_JSON, LIBRARY_TIMEOUT_MS)(\n idOf(2),\n 0,\n segment(2, \"x\".repeat(LARGE_EVENT_CHARS)),\n );\n\n return [\n ...preflightResults(preflight, target),\n judge(\n \"test segment\",\n first,\n `The server accepted a test segment.${starNote(allowedOrigin(first) === \"*\", target)}`,\n statusProblem,\n originProblem,\n ),\n judge(\"gzip\", zipped, \"The server accepted a gzip segment.\", statusProblem),\n judge(\n \"large segment\",\n large,\n `The server accepted a segment of ${String(LARGE_EVENT_CHARS)} bytes without gzip.`,\n // The library drops a segment after a 413, so a low body limit loses every replay.\n (response) =>\n response.ok\n ? undefined\n : `The server returned ${String(response.status)} for a segment of ${String(LARGE_EVENT_CHARS)} bytes. The first segment of an upload has a full snapshot of the page. Raise the body limit of the server.`,\n ),\n judge(\n \"deduplication\",\n repeated,\n \"The server accepted a repeated batch id. A client cannot see if it stored the segment again.\",\n statusProblem,\n ),\n ];\n}\n\n/** The options after the origin and the replay flag. */\ninterface Options {\n /** The headers of the --header options. */\n headers: Record<string, string>;\n /** True with `--credentials include`. */\n credentials: boolean;\n}\n\n/**\n * Parses the options. Each one is a flag and its value: a \"Name: value\" argument for a header,\n * or `include` for the credentials.\n * @param args The arguments after the origin.\n * @returns The options, or undefined if an option is malformed.\n */\nfunction parseOptions(args: readonly string[]): Options | undefined {\n const pairs: [string, string][] = [];\n let credentials = false;\n\n for (let index = 0; index < args.length; index += 2) {\n if (args[index] === CREDENTIALS_FLAG && args[index + 1] === CREDENTIALS_INCLUDE) {\n credentials = true;\n continue;\n }\n\n // A flag without a value leaves undefined here, which exec() treats as text with no colon.\n const match = args[index] === HEADER_FLAG ? HEADER_PATTERN.exec(args[index + 1]) : null;\n\n if (!match || RESERVED_HEADERS.includes(match[1].toLowerCase())) {\n return undefined;\n }\n\n pairs.push([match[1], match[2]]);\n }\n\n return { headers: Object.fromEntries(pairs), credentials };\n}\n\n/** True for an HTTP URL without a user name or password. Result lines print the URL. */\nfunction isHttpUrl(value: string): boolean {\n if (!/^https?:\\/\\//i.test(value) || !URL.canParse(value)) {\n return false;\n }\n\n const { username, password } = new URL(value);\n return username === \"\" && password === \"\";\n}\n\n/** Command line words that are safe to print. */\nconst SHOWN_WORDS = [\n \"doctor\",\n \"--origin\",\n REPLAY_FLAG,\n HEADER_FLAG,\n CREDENTIALS_FLAG,\n CREDENTIALS_INCLUDE,\n];\n\n/**\n * Turns an argument into something safe to print in the usage message. An argument can be a\n * token, a URL can carry one in its query or user info, and the output may land in a shared log.\n * @param arg Command line argument.\n * @returns The word itself, a URL without query or user info, or a placeholder.\n */\nfunction shownArgument(arg: string): string {\n if (SHOWN_WORDS.includes(arg)) {\n return arg;\n }\n\n if (/^https?:\\/\\//i.test(arg) && URL.canParse(arg)) {\n const { origin, pathname } = new URL(arg);\n return `${origin}${pathname === \"/\" && !arg.endsWith(\"/\") ? \"\" : pathname}`;\n }\n\n return HIDDEN;\n}\n\n/** Checks for an exact browser origin. A path or a trailing slash doesn't match. */\nfunction isOrigin(value: string): boolean {\n return URL.canParse(value) && new URL(value).origin === value;\n}\n\n/**\n * Runs the command line tool.\n * @param args Arguments after the program name.\n * @param print Writes one line of output.\n * @returns The exit code.\n */\nexport async function main(\n args: readonly string[],\n print: (line: string) => void,\n): Promise<number> {\n const [command, url, flag, origin, ...rest] = args;\n // The replay flag comes right after the origin, before any other option.\n const replay = rest[0] === REPLAY_FLAG;\n const options = parseOptions(replay ? rest.slice(1) : rest);\n\n if (\n command !== \"doctor\" ||\n flag !== \"--origin\" ||\n !isHttpUrl(url) ||\n !isOrigin(origin) ||\n !options\n ) {\n print(USAGE);\n print(`Received: ${JSON.stringify(args.map(shownArgument))}`);\n return EXIT_USAGE;\n }\n\n const { headers, credentials } = options;\n const results = await (replay ? runReplayDoctor : runDoctor)(url, origin, headers, credentials);\n\n for (const { rule, pass, detail } of results) {\n print(`${pass ? \"PASS\" : \"FAIL\"} ${rule}: ${detail}`);\n }\n\n return results.every(({ pass }) => pass) ? EXIT_PASS : EXIT_FAIL;\n}\n"],"mappings":";;;;AA4BA,IAAMiB,IAAqB,KAGrBC,IAAY,GAGZC,IAAY,GAGZC,IAAa,GAGbC,IACJ,gQAGIC,IAAc,YAGdC,IAAc,YAGdC,IAAmB,iBAGnBC,IAAsB,WAMtBC,IAAoB,KAGpBC,KAAe,GAGfC,IAAc,gBAGdC,KAAiB,4CAGjBC,KAAS,YAGTC,IAAiB,iCAGjBC,IAAe,+BAGfC,IAAgB,gCAGhBC,IAAoB,oCAGpBC,IAAe,sDAGfC,IAAa,0EAGbC,KAAqB,+CAGrBC,KAAY,iDAGZC,IAAkB;CACtBnC;CACAD;CACAU;CACAP;AACF,CAAC,CAAC,KAAK,MAASkC,EAAK,YAAY,CAAC,GAG5BC,KAAmB,CAAC,GAAGF,GAAiB,QAAQ,GAGhDG,IAAmB,CAACrC,GAAiBK,CAAW,CAAC,CAAC,KAAK,MAAS8B,EAAK,YAAY,CAAC,GAGlFG,IAAsB,iBAGtBC,IAAmB,CAACrC,EAAmB,YAAY,CAAC,GAGpDsC,KAAiB,CAAC,GAAGD,GAAkB,GAAGF,CAAgB;AAmBhE,SAASI,KAAwB;CAC/B,I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S3B,IAAkBX,EAAA,CAAWvD,GAAK4B,GAAQqE,GAAStE,CAAW;CAE9F,KAAK,IAAM,EAAE,SAAM,SAAM,eAAYqE,GACnC,EAAM,GAAGE,IAAO,SAAS,OAAO,GAAGC,EAAK,IAAIC,GAAQ;CAGtD,OAAOJ,EAAQ,OAAO,EAAE,cAAWE,CAAI,IAAIjI,IAAYC;AACzD"}
1
+ {"version":3,"file":"doctor.js","names":["LIBRARY_TIMEOUT_MS","SEVERITY_NUMBER","CONTENT_TYPE_TEXT_PLAIN","REQUEST_TIMEOUT_MS$1","QUERY_PARAM_BATCH_ID","HEADER_BATCH_ID","HEADER_CONTENT_ENCODING","HEADER_SAMPLING","HEADER_RETRY_AFTER","HEADER_DATE","ENCODING_GZIP","QUERY_PARAM_EXIT_REASON","HEADER_CONTENT_TYPE","HEADER_ATTEMPT","CONTENT_TYPE_JSON","gzip","otlpSerializer","REQUEST_TIMEOUT_MS","EXIT_PASS","EXIT_FAIL","EXIT_USAGE","USAGE","HEADER_FLAG","REPLAY_FLAG","CREDENTIALS_FLAG","CREDENTIALS_INCLUDE","LARGE_EVENT_CHARS","CUSTOM_EVENT","DOCTOR_NAME","HEADER_PATTERN","HIDDEN","EXPOSE_HEADERS","ALLOW_ORIGIN","ALLOW_HEADERS","ALLOW_CREDENTIALS","STAR_REFUSED","STAR_PLAIN","STAR_AUTHORIZATION","STAR_HINT","REQUEST_HEADERS","name","RESERVED_HEADERS","OPTIONAL_EXPOSED","NON_WILDCARD_HEADER","REQUIRED_EXPOSED","WANTED_EXPOSED","testRecord","traceId","request","url","init","timeoutMs","error","reason","valuesOf","response","value","absent","values","star","wildcard","wanted","statusProblem","mediaTypeProblem","judge","tests","problem","answer","test","found","passed","targetOf","customNames","custom","originTest","allowed","credentials","origin","allowsCredentials","allowedOrigin","starNote","earnedByStar","starWhy","coveredByStar","sendPreflight","requestHeaders","preflightResults","originNote","preflight","target","headersNote","missing","why","authorization","poster","contentType","id","attempt","extra","payload","postZipped","compressed","body","post","runDoctor","originProblem","batchId","first","repeated","zipped","beaconUrl","beacon","hidden","hiddenNote","exposedNote","runReplayDoctor","replayId","head","segment","events","text","idOf","sequence","small","large","parseOptions","pairs","index","args","match","isHttpUrl","username","password","SHOWN_WORDS","shownArgument","arg","pathname","isOrigin","main","command","flag","rest","replay","options","print","results","headers","pass","rule","detail"],"sources":["../src/doctor.ts"],"sourcesContent":["// src/doctor.ts\n//\n// Checks an ingest server, or a replay endpoint, against its contract in docs/ingest-server.md.\n// The `uiobs doctor` command calls main(). Only web APIs are used here, and the browser build\n// replaces every \"node:\" import.\n\nimport {\n CONTENT_TYPE_JSON,\n CONTENT_TYPE_TEXT_PLAIN,\n ENCODING_GZIP,\n HEADER_ATTEMPT,\n HEADER_BATCH_ID,\n HEADER_CONTENT_ENCODING,\n HEADER_CONTENT_TYPE,\n HEADER_DATE,\n HEADER_RETRY_AFTER,\n HEADER_SAMPLING,\n HTTP_UNSUPPORTED_MEDIA_TYPE,\n QUERY_PARAM_BATCH_ID,\n QUERY_PARAM_EXIT_REASON,\n REQUEST_TIMEOUT_MS as LIBRARY_TIMEOUT_MS,\n SEVERITY_NUMBER,\n} from \"./constants\";\nimport type { LogRecord } from \"./models/log-record\";\nimport { gzip } from \"./transport/compression\";\nimport { otlpSerializer } from \"./transport/serializers/otlp\";\n\n/** How long to wait for one answer, in milliseconds. */\nconst REQUEST_TIMEOUT_MS = 10000;\n\n/** Exit code when every rule passes. */\nconst EXIT_PASS = 0;\n\n/** Exit code when a rule fails. */\nconst EXIT_FAIL = 1;\n\n/** Exit code for a wrong command. */\nconst EXIT_USAGE = 2;\n\n/** Printed for a wrong command. */\nconst USAGE =\n 'Usage: uiobs doctor <url> --origin <origin> [--replay] [--credentials include] [--header \"Name: value\"]. An origin has no path and no trailing slash. With --replay, the URL is a replay endpoint. With --credentials include, a * in a CORS header fails.';\n\n/** Adds a request header, e.g. an Authorization header. */\nconst HEADER_FLAG = \"--header\";\n\n/** Says that the URL is a replay endpoint, so the tool sends segments instead of batches. */\nconst REPLAY_FLAG = \"--replay\";\n\n/** Says that the app sets `credentials: \"include\"`, so a browser refuses a * in a CORS header. */\nconst CREDENTIALS_FLAG = \"--credentials\";\n\n/** The only value of CREDENTIALS_FLAG. */\nconst CREDENTIALS_INCLUDE = \"include\";\n\n/**\n * Size of the event in the large test segment, in characters. The first segment of a real\n * upload holds a full snapshot, and one of a page with 35,000 table cells measured 4.7 MB.\n */\nconst LARGE_EVENT_CHARS = 5_000_000;\n\n/** The recorder's custom event type. A player skips a custom event it doesn't know. */\nconst CUSTOM_EVENT = 5;\n\n/** Marks everything the tool stores, so an operator can find and delete it. */\nconst DOCTOR_NAME = \"uiobs-doctor\";\n\n/** A header name, a colon, then a value of printable ASCII. */\nconst HEADER_PATTERN = /^([\\w!#$%&'*+.^`|~-]+): *([\\x20-\\x7e]+)$/;\n\n/** Printed in place of any argument that might contain a secret. */\nconst HIDDEN = \"<hidden>\";\n\n/** Response header that lists the headers a page can read. */\nconst EXPOSE_HEADERS = \"Access-Control-Expose-Headers\";\n\n/** Response header that names the origin that may read the answer. */\nconst ALLOW_ORIGIN = \"Access-Control-Allow-Origin\";\n\n/** Response header of a preflight that lists the request headers the server accepts. */\nconst ALLOW_HEADERS = \"Access-Control-Allow-Headers\";\n\n/** Response header that lets a browser send and read an answer with credentials. */\nconst ALLOW_CREDENTIALS = \"Access-Control-Allow-Credentials\";\n\n/** Why a * in Access-Control-Allow-Origin fails with credentials. */\nconst STAR_REFUSED = 'A browser refuses * with credentials: \"include\".';\n\n/** Why a * in a list of header names fails with credentials. */\nconst STAR_PLAIN = 'A browser does not read * as a wildcard with credentials: \"include\".';\n\n/** Why a * in Access-Control-Allow-Headers fails for Authorization, with or without credentials. */\nconst STAR_AUTHORIZATION = \"A browser never lets * cover authorization.\";\n\n/** Ends the note of a PASS line that only a * earned, so the run without credentials says so. */\nconst STAR_HINT = \"Add --credentials include to check that case.\";\n\n/** The library's request headers. The server must allow every one of them. */\nconst REQUEST_HEADERS = [\n HEADER_CONTENT_TYPE,\n HEADER_CONTENT_ENCODING,\n HEADER_BATCH_ID,\n HEADER_ATTEMPT,\n].map((name) => name.toLowerCase());\n\n/** Headers the tool sets itself. A custom header can't reuse one of these names. */\nconst RESERVED_HEADERS = [...REQUEST_HEADERS, \"origin\"];\n\n/** Response headers that only an optional feature reads. */\nconst OPTIONAL_EXPOSED = [HEADER_SAMPLING, HEADER_DATE].map((name) => name.toLowerCase());\n\n/** The one request header that a * in Access-Control-Allow-Headers never covers. */\nconst NON_WILDCARD_HEADER = \"authorization\";\n\n/** The response header that the library can't work without when it is hidden. */\nconst REQUIRED_EXPOSED = [HEADER_RETRY_AFTER.toLowerCase()];\n\n/** Every response header that the library reads. */\nconst WANTED_EXPOSED = [...REQUIRED_EXPOSED, ...OPTIONAL_EXPOSED];\n\n/** The result of one ingest contract rule. */\nexport interface DoctorResult {\n /** Rule name. */\n rule: string;\n /** True when the server meets the rule. */\n pass: boolean;\n /** Why the rule passed or failed. */\n detail: string;\n}\n\n/** An HTTP answer, or the text of a failed request. */\ntype Answer = Response | string;\n\n/** Returns a description of the problem, or undefined when the answer passes the test. */\ntype AnswerTest = (response: Response) => string | undefined;\n\n/** Builds the test record. The server stores it like any other record. */\nfunction testRecord(): LogRecord {\n const traceId = crypto.randomUUID().replaceAll(\"-\", \"\");\n\n return {\n timeUnixNano: `${String(Date.now())}000000`,\n traceId,\n spanId: traceId.slice(0, 16),\n traceFlags: 1,\n severityNumber: SEVERITY_NUMBER.INFO,\n severityText: \"INFO\",\n body: \"uiobs doctor test record\",\n attributes: {},\n resource: { \"service.name\": DOCTOR_NAME },\n };\n}\n\n/** Sends one request. A failure shows up in the result line, as the tool has no diagnostics. */\nasync function request(\n url: string,\n init: RequestInit,\n timeoutMs = REQUEST_TIMEOUT_MS,\n): Promise<Answer> {\n try {\n // A browser refuses a preflight that redirects, and a redirect can also name another host.\n return await fetch(url, {\n ...init,\n redirect: \"manual\",\n signal: AbortSignal.timeout(timeoutMs),\n });\n } catch (error) {\n // Node only says \"fetch failed\". The cause holds the real reason, for example ECONNREFUSED.\n const reason: unknown =\n error instanceof Error ? ((error as Error & { cause?: unknown }).cause ?? error) : error;\n\n return `The request failed. ${reason instanceof Error ? reason.message : String(reason)}`;\n }\n}\n\n/** Returns the lowercase values of a comma-separated response header. */\nfunction valuesOf(response: Response, name: string): string[] {\n return (response.headers.get(name) ?? \"\")\n .toLowerCase()\n .split(\",\")\n .map((value) => value.trim());\n}\n\n/**\n * Returns the wanted values a comma-separated header leaves out. With wildcard, a * covers them\n * all but Authorization, which the Fetch standard never lets a * cover. A run with credentials\n * passes false, because a browser reads * as a plain name then.\n */\nfunction absent(\n response: Response,\n name: string,\n wanted: readonly string[],\n wildcard: boolean,\n): string[] {\n const values = valuesOf(response, name);\n const star = wildcard && values.includes(\"*\");\n\n return wanted.filter(\n (value) => !values.includes(value) && !(star && value !== NON_WILDCARD_HEADER),\n );\n}\n\n/** Checks an answer's status. */\nconst statusProblem: AnswerTest = (response) =>\n response.ok ? undefined : `The server returned ${String(response.status)}.`;\n\n/**\n * Names the collector case for a 415 answer to the beacon batch, because the bare status doesn't\n * say that only the exit batches are lost or how to fix it.\n */\nconst mediaTypeProblem: AnswerTest = (response) =>\n response.status === HTTP_UNSUPPORTED_MEDIA_TYPE\n ? `The server returned ${String(response.status)} to a text/plain batch, as a stock OpenTelemetry Collector does. The library loses the exit batches of a page on another origin. Set headers in the app, or put a same-origin proxy in front of the server.`\n : undefined;\n\n/** Builds the result for one rule. The first problem found becomes the detail. */\nfunction judge(rule: string, answer: Answer, passed: string, ...tests: AnswerTest[]): DoctorResult {\n const problem =\n typeof answer === \"string\"\n ? answer\n : tests.map((test) => test(answer)).find((found) => found !== undefined);\n\n return { rule, pass: problem === undefined, detail: problem ?? passed };\n}\n\n/** One endpoint under test: where it is, who calls it and with which headers. */\ninterface Target {\n /** Endpoint URL. */\n url: string;\n /** The app's origin. */\n origin: string;\n /** The app's headers for each POST, e.g. an Authorization header. */\n custom: Readonly<Record<string, string>>;\n /** Lowercase names of every header a POST carries. The preflight asks for them. */\n requestHeaders: string[];\n /** True with `--credentials include`. A browser then refuses a * in a CORS header. */\n credentials: boolean;\n}\n\n/** Sends one POST the way the library does. Extra headers go on top. */\ntype Post = (\n id: string,\n attempt: number,\n payload: BodyInit,\n extra?: Record<string, string>,\n) => Promise<Answer>;\n\n/** Builds the target for one run. */\nfunction targetOf(\n url: string,\n origin: string,\n custom: Readonly<Record<string, string>>,\n credentials: boolean,\n): Target {\n const customNames = Object.keys(custom).map((name) => name.toLowerCase());\n\n return {\n url,\n origin,\n custom,\n requestHeaders: [...REQUEST_HEADERS, ...customNames],\n credentials,\n };\n}\n\n/** Builds the test that an answer lets the app's origin read it. */\nfunction originTest({ origin, credentials }: Target): AnswerTest {\n return (response) => {\n const allowed = response.headers.get(ALLOW_ORIGIN);\n\n if (allowed === \"*\" && credentials) {\n return `${ALLOW_ORIGIN} is *. ${STAR_REFUSED} It must be ${origin}.`;\n }\n\n if (allowed !== origin && allowed !== \"*\") {\n return `${ALLOW_ORIGIN} is ${String(allowed)}. It must allow ${origin}.`;\n }\n\n // A browser rejects a credentialed answer without this header. The library then sees a\n // network error and sends the batch again.\n return credentials ? allowsCredentials(response) : undefined;\n };\n}\n\n/** Checks that an answer lets the browser send and read credentials. */\nconst allowsCredentials: AnswerTest = (response) => {\n const allowed = response.headers.get(ALLOW_CREDENTIALS);\n\n return allowed === \"true\"\n ? undefined\n : `${ALLOW_CREDENTIALS} is ${String(allowed)}. It must be true with credentials: \"include\".`;\n};\n\n/** Returns the origin an answer allows, or null for a failed request or a missing header. */\nfunction allowedOrigin(answer: Answer): string | null {\n return typeof answer === \"string\" ? null : answer.headers.get(ALLOW_ORIGIN);\n}\n\n/**\n * Returns the note for a PASS that only a * earned. With credentials the rule fails on that *,\n * so the note is for the run without them.\n */\nfunction starNote(earnedByStar: boolean, { credentials }: Target, reason = STAR_REFUSED): string {\n return earnedByStar && !credentials ? ` ${reason} ${STAR_HINT}` : \"\";\n}\n\n/** Returns the reason that a * doesn't help a list of header names with credentials, or \"\". */\nfunction starWhy(response: Response, name: string, { credentials }: Target): string {\n return credentials && valuesOf(response, name).includes(\"*\") ? ` ${STAR_PLAIN}` : \"\";\n}\n\n/** True when a list of header names passes only because of its *: it has one and misses a name. */\nfunction coveredByStar(answer: Answer, name: string, wanted: readonly string[]): boolean {\n return (\n typeof answer !== \"string\" &&\n valuesOf(answer, name).includes(\"*\") &&\n absent(answer, name, wanted, false).length > 0\n );\n}\n\n/** Sends the preflight a browser sends before the library's POST. */\nfunction sendPreflight({ url, origin, requestHeaders }: Target): Promise<Answer> {\n return request(url, {\n method: \"OPTIONS\",\n headers: {\n Origin: origin,\n \"Access-Control-Request-Method\": \"POST\",\n \"Access-Control-Request-Headers\": requestHeaders.join(\", \"),\n },\n });\n}\n\n/** Builds the two results every preflight gives. */\nfunction preflightResults(preflight: Answer, target: Target): DoctorResult[] {\n const originNote = starNote(allowedOrigin(preflight) === \"*\", target);\n const headersByStar = coveredByStar(preflight, ALLOW_HEADERS, target.requestHeaders);\n const headersNote = starNote(headersByStar, target, STAR_PLAIN);\n\n return [\n judge(\n \"preflight\",\n preflight,\n `The server permits POST from this origin.${originNote}`,\n statusProblem,\n originTest(target),\n ),\n judge(\n \"allowed headers\",\n preflight,\n `The server allows each request header of the library.${headersNote}`,\n (response) => {\n const missing = absent(response, ALLOW_HEADERS, target.requestHeaders, !target.credentials);\n if (missing.length === 0) {\n return undefined;\n }\n\n const why = starWhy(response, ALLOW_HEADERS, target);\n const authorization =\n missing.includes(NON_WILDCARD_HEADER) && valuesOf(response, ALLOW_HEADERS).includes(\"*\")\n ? ` ${STAR_AUTHORIZATION}`\n : \"\";\n\n return `${ALLOW_HEADERS} must include ${missing.join(\", \")}.${why}${authorization}`;\n },\n ),\n ];\n}\n\n/** Builds the POST function for one target and content type. */\nfunction poster({ url, origin, custom }: Target, contentType: string, timeoutMs?: number): Post {\n return (id, attempt, payload, extra = {}) =>\n request(\n url,\n {\n method: \"POST\",\n headers: {\n ...custom,\n Origin: origin,\n [HEADER_CONTENT_TYPE]: contentType,\n [HEADER_BATCH_ID]: id,\n [HEADER_ATTEMPT]: String(attempt),\n ...extra,\n },\n body: payload,\n },\n timeoutMs,\n );\n}\n\n/** Sends a body with gzip. Gives the text of the problem if this Node can't compress. */\nasync function postZipped(post: Post, id: string, body: string): Promise<Answer> {\n const compressed = await gzip(body);\n\n return compressed\n ? post(id, 0, compressed, { [HEADER_CONTENT_ENCODING]: ENCODING_GZIP })\n : \"This Node version has no CompressionStream.\";\n}\n\n/**\n * Runs each rule's requests one at a time. Two requests with the same batch id must not overlap.\n * @param url Ingest URL.\n * @param origin The app's origin.\n * @param custom The app's headers for each batch, e.g. an Authorization header.\n * @param credentials True when the app sets `credentials: \"include\"`. A * in a CORS header then\n * fails, and the preflight must allow credentials.\n * @returns One result per rule.\n */\nexport async function runDoctor(\n url: string,\n origin: string,\n custom: Readonly<Record<string, string>> = {},\n credentials = false,\n): Promise<DoctorResult[]> {\n const target = targetOf(url, origin, custom, credentials);\n const originProblem = originTest(target);\n const preflight = await sendPreflight(target);\n\n const { body, contentType } = otlpSerializer.serialize([testRecord()]);\n const post = poster(target, contentType);\n\n const batchId = crypto.randomUUID();\n const first = await post(batchId, 0, body);\n const repeated = await post(batchId, 1, body);\n const zipped = await postZipped(post, crypto.randomUUID(), body);\n\n // sendBeacon can't set headers, so the id and the reason go in the query, like the exit flush.\n const beaconUrl = new URL(url);\n beaconUrl.searchParams.set(QUERY_PARAM_BATCH_ID, crypto.randomUUID());\n beaconUrl.searchParams.set(QUERY_PARAM_EXIT_REASON, \"pagehide\");\n\n // With custom headers the library's exit flush uses a keepalive fetch instead of a beacon.\n const beacon =\n target.requestHeaders.length > REQUEST_HEADERS.length\n ? undefined\n : await request(beaconUrl.toString(), {\n method: \"POST\",\n headers: { Origin: origin, [HEADER_CONTENT_TYPE]: CONTENT_TYPE_TEXT_PLAIN },\n body,\n });\n\n const hidden =\n typeof first === \"string\"\n ? []\n : absent(first, EXPOSE_HEADERS, OPTIONAL_EXPOSED, !target.credentials);\n const hiddenNote =\n hidden.length > 0 ? ` Optional headers stay hidden: ${hidden.join(\", \")}.` : \"\";\n const exposedNote = starNote(\n coveredByStar(first, EXPOSE_HEADERS, WANTED_EXPOSED),\n target,\n STAR_PLAIN,\n );\n\n return [\n ...preflightResults(preflight, target),\n judge(\n \"test batch\",\n first,\n `The server accepted a test batch.${starNote(allowedOrigin(first) === \"*\", target)}`,\n statusProblem,\n originProblem,\n ),\n judge(\n \"exposed headers\",\n first,\n `The server exposes Retry-After.${hiddenNote}${exposedNote}`,\n (response) => {\n if (absent(response, EXPOSE_HEADERS, REQUIRED_EXPOSED, !target.credentials).length === 0) {\n return undefined;\n }\n\n const why = starWhy(response, EXPOSE_HEADERS, target);\n\n return `${EXPOSE_HEADERS} must include retry-after.${why}`;\n },\n ),\n judge(\"gzip\", zipped, \"The server accepted a gzip batch.\", statusProblem),\n judge(\n \"deduplication\",\n repeated,\n \"The server accepted a repeated batch id. A client cannot see if it stored the batch again.\",\n statusProblem,\n ),\n beacon === undefined\n ? {\n rule: \"beacon\",\n pass: true,\n detail: \"The library sends no beacon with custom headers. The tool sent no beacon.\",\n }\n : judge(\n \"beacon\",\n beacon,\n \"The server accepted a text/plain batch.\",\n mediaTypeProblem,\n statusProblem,\n ),\n ];\n}\n\n/**\n * Checks a replay endpoint the way runDoctor() checks an ingest server. A segment has its own\n * body and its own batch id form, and its first one can be several megabytes.\n * @param url Replay endpoint URL, the value of replay.endpoint.\n * @param origin The app's origin.\n * @param custom The app's replay.headers, e.g. an Authorization header.\n * @param credentials True when the app sets `credentials: \"include\"`. See runDoctor().\n * @returns One result per rule.\n */\nexport async function runReplayDoctor(\n url: string,\n origin: string,\n custom: Readonly<Record<string, string>> = {},\n credentials = false,\n): Promise<DoctorResult[]> {\n const target = targetOf(url, origin, custom, credentials);\n const originProblem = originTest(target);\n const preflight = await sendPreflight(target);\n\n const replayId = crypto.randomUUID();\n const head = {\n \"replay.id\": replayId,\n \"session.id\": crypto.randomUUID(),\n \"tab.id\": crypto.randomUUID(),\n \"service.name\": DOCTOR_NAME,\n };\n // The body the uploader sends: the ids, the sequence, the JSON length of the events, and the\n // events themselves.\n const segment = (sequence: number, text: string): string => {\n const events = [\n { type: CUSTOM_EVENT, timestamp: Date.now(), data: { tag: DOCTOR_NAME, payload: text } },\n ];\n\n return JSON.stringify({ ...head, sequence, bytes: JSON.stringify(events).length, events });\n };\n // The uploader's batch id is the replay id plus the sequence.\n const idOf = (sequence: number): string => `${replayId}-${String(sequence)}`;\n const post = poster(target, CONTENT_TYPE_JSON);\n const small = segment(0, \"uiobs doctor test event\");\n\n const first = await post(idOf(0), 0, small);\n const repeated = await post(idOf(0), 1, small);\n const zipped = await postZipped(post, idOf(1), segment(1, \"uiobs doctor gzip event\"));\n // No gzip here. That is the worst case: compression off, or a browser without\n // CompressionStream. The library gives a segment delivery.requestTimeoutMs, so the tool\n // waits for the default of that. A shorter wait would fail a slow link the library can use.\n const large = await poster(target, CONTENT_TYPE_JSON, LIBRARY_TIMEOUT_MS)(\n idOf(2),\n 0,\n segment(2, \"x\".repeat(LARGE_EVENT_CHARS)),\n );\n\n return [\n ...preflightResults(preflight, target),\n judge(\n \"test segment\",\n first,\n `The server accepted a test segment.${starNote(allowedOrigin(first) === \"*\", target)}`,\n statusProblem,\n originProblem,\n ),\n judge(\"gzip\", zipped, \"The server accepted a gzip segment.\", statusProblem),\n judge(\n \"large segment\",\n large,\n `The server accepted a segment of ${String(LARGE_EVENT_CHARS)} bytes without gzip.`,\n // The library drops a segment after a 413, so a low body limit loses every replay.\n (response) =>\n response.ok\n ? undefined\n : `The server returned ${String(response.status)} for a segment of ${String(LARGE_EVENT_CHARS)} bytes. The first segment of an upload has a full snapshot of the page. Raise the body limit of the server.`,\n ),\n judge(\n \"deduplication\",\n repeated,\n \"The server accepted a repeated batch id. A client cannot see if it stored the segment again.\",\n statusProblem,\n ),\n ];\n}\n\n/** The options after the origin and the replay flag. */\ninterface Options {\n /** The headers of the --header options. */\n headers: Record<string, string>;\n /** True with `--credentials include`. */\n credentials: boolean;\n}\n\n/**\n * Parses the options. Each one is a flag and its value: a \"Name: value\" argument for a header,\n * or `include` for the credentials.\n * @param args The arguments after the origin.\n * @returns The options, or undefined if an option is malformed.\n */\nfunction parseOptions(args: readonly string[]): Options | undefined {\n const pairs: [string, string][] = [];\n let credentials = false;\n\n for (let index = 0; index < args.length; index += 2) {\n if (args[index] === CREDENTIALS_FLAG && args[index + 1] === CREDENTIALS_INCLUDE) {\n credentials = true;\n continue;\n }\n\n // A flag without a value leaves undefined here, which exec() treats as text with no colon.\n const match = args[index] === HEADER_FLAG ? HEADER_PATTERN.exec(args[index + 1]) : null;\n\n if (!match || RESERVED_HEADERS.includes(match[1].toLowerCase())) {\n return undefined;\n }\n\n pairs.push([match[1], match[2]]);\n }\n\n return { headers: Object.fromEntries(pairs), credentials };\n}\n\n/** True for an HTTP URL without a user name or password. Result lines print the URL. */\nfunction isHttpUrl(value: string): boolean {\n if (!/^https?:\\/\\//i.test(value) || !URL.canParse(value)) {\n return false;\n }\n\n const { username, password } = new URL(value);\n return username === \"\" && password === \"\";\n}\n\n/** Command line words that are safe to print. */\nconst SHOWN_WORDS = [\n \"doctor\",\n \"--origin\",\n REPLAY_FLAG,\n HEADER_FLAG,\n CREDENTIALS_FLAG,\n CREDENTIALS_INCLUDE,\n];\n\n/**\n * Turns an argument into something safe to print in the usage message. An argument can be a\n * token, a URL can carry one in its query or user info, and the output may land in a shared log.\n * @param arg Command line argument.\n * @returns The word itself, a URL without query or user info, or a placeholder.\n */\nfunction shownArgument(arg: string): string {\n if (SHOWN_WORDS.includes(arg)) {\n return arg;\n }\n\n if (/^https?:\\/\\//i.test(arg) && URL.canParse(arg)) {\n const { origin, pathname } = new URL(arg);\n return `${origin}${pathname === \"/\" && !arg.endsWith(\"/\") ? \"\" : pathname}`;\n }\n\n return HIDDEN;\n}\n\n/** Checks for an exact browser origin. A path or a trailing slash doesn't match. */\nfunction isOrigin(value: string): boolean {\n return URL.canParse(value) && new URL(value).origin === value;\n}\n\n/**\n * Runs the command line tool.\n * @param args Arguments after the program name.\n * @param print Writes one line of output.\n * @returns The exit code.\n */\nexport async function main(\n args: readonly string[],\n print: (line: string) => void,\n): Promise<number> {\n const [command, url, flag, origin, ...rest] = args;\n // The replay flag comes right after the origin, before any other option.\n const replay = rest[0] === REPLAY_FLAG;\n const options = parseOptions(replay ? rest.slice(1) : rest);\n\n if (\n command !== \"doctor\" ||\n flag !== \"--origin\" ||\n !isHttpUrl(url) ||\n !isOrigin(origin) ||\n !options\n ) {\n print(USAGE);\n print(`Received: ${JSON.stringify(args.map(shownArgument))}`);\n return EXIT_USAGE;\n }\n\n const { headers, credentials } = options;\n const results = await (replay ? runReplayDoctor : runDoctor)(url, origin, headers, credentials);\n\n for (const { rule, pass, detail } of results) {\n print(`${pass ? \"PASS\" : \"FAIL\"} ${rule}: ${detail}`);\n }\n\n return results.every(({ pass }) => pass) ? EXIT_PASS : EXIT_FAIL;\n}\n"],"mappings":";;;;AA4BA,IAAMiB,IAAqB,KAGrBC,IAAY,GAGZC,IAAY,GAGZC,IAAa,GAGbC,IACJ,gQAGIC,IAAc,YAGdC,IAAc,YAGdC,IAAmB,iBAGnBC,IAAsB,WAMtBC,IAAoB,KAGpBC,KAAe,GAGfC,IAAc,gBAGdC,KAAiB,4CAGjBC,KAAS,YAGTC,IAAiB,iCAGjBC,IAAe,+BAGfC,IAAgB,gCAGhBC,IAAoB,oCAGpBC,IAAe,sDAGfC,IAAa,0EAGbC,KAAqB,+CAGrBC,KAAY,iDAGZC,IAAkB;CACtB3B;CACAN;CACAD;CACAQ;AACF,CAAC,CAAC,KAAK,MAAS2B,EAAK,YAAY,CAAC,GAG5BC,KAAmB,CAAC,GAAGF,GAAiB,QAAQ,GAGhDG,IAAmB,CAACnC,GAAiBE,CAAW,CAAC,CAAC,K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KAChB,CAACkE,GAID,OAFAC,EAAM3H,CAAK,GACX2H,EAAM,aAAa,KAAK,UAAUhB,EAAK,IAAIM,EAAa,CAAC,GAAG,GACrDlH;CAGT,IAAM,EAAE,YAAS,mBAAgB2H,GAC3BE,IAAU,OAAOH,IAAS3B,IAAkBX,EAAA,CAAWvD,GAAK4B,GAAQqE,GAAStE,CAAW;CAE9F,KAAK,IAAM,EAAE,SAAM,SAAM,eAAYqE,GACnC,EAAM,GAAGE,IAAO,SAAS,OAAO,GAAGC,EAAK,IAAIC,GAAQ;CAGtD,OAAOJ,EAAQ,OAAO,EAAE,cAAWE,CAAI,IAAIjI,IAAYC;AACzD"}
@@ -0,0 +1,3 @@
1
+ const e=require("./error-like-gGRx2s36.cjs"),t=require("./platform-BZjp9wp1.cjs"),n=require("./storm-qiE_AMC7.cjs"),r=require("./defineProperty-X1c4tIPD.cjs");function i(t){if(e.r(t)){let e=(t.stack??``).split(`
2
+ `)[1]??``;return{message:t.message,key:`${t.name}|${t.message}|${e}`}}let n=String(t);return{message:n,key:`${typeof t}|${n}|`}}var a=class{constructor(e){r.t(this,`ctx`,void 0),r.t(this,`name`,`errors`),r.t(this,`installed`,!1),r.t(this,`seen`,new Map),r.t(this,`window`,{start:0,count:0}),r.t(this,`onError`,e=>{this.ctx.diagnostics.guard(`capture.record_failed`,`The library could not record an error event.`,()=>{`message`in e?this.scriptError(e):this.failedResource(e.target)})}),r.t(this,`onRejection`,e=>{this.ctx.config.capture.rejections&&this.report(`unhandledrejection`,e.reason,{"error.type":`unhandledrejection`})}),this.ctx=e}install(){this.installed||typeof addEventListener>`u`||(this.installed=!0,addEventListener(`error`,this.onError,!0),addEventListener(`unhandledrejection`,this.onRejection))}uninstall(){this.installed&&(this.installed=!1,removeEventListener(`error`,this.onError,!0),removeEventListener(`unhandledrejection`,this.onRejection),this.seen.clear())}failedResource(e){let n=e;if(typeof n?.tagName!=`string`||!this.ctx.config.capture.resourceErrors)return;let r=n.tagName.toLowerCase(),i={"error.type":`resource`,"resource.tag":r},a=r,o=n.src??n.href;typeof o==`string`&&o!==``&&(a=t.a(o,this.ctx.config.capture.fullUrls,this.ctx.config.capture.urlTransform,this.ctx.diagnostics),i[`resource.url`]=a),this.ctx.breadcrumbs.push({t:Date.now(),category:`http`,message:`resource failed: ${a}`}),this.ctx.logger.warn(`resource failed to load`,i)}scriptError(e){if(!this.ctx.config.capture.errors)return;let n=e.message===``?`unknown error`:e.message,r=e.error??Error(n);this.report(`window.onerror`,r,{"error.source":t.a(e.filename,this.ctx.config.capture.fullUrls,this.ctx.config.capture.urlTransform,this.ctx.diagnostics),"error.line":e.lineno,"error.column":e.colno})}report(e,t,r){if(!n.t(this.window,this.ctx.config.captureLimits.errorsPerWindow,this.ctx.diagnostics,`errors`,this.ctx.config.captureLimits.windowMs))return;let a=Date.now(),{message:o,key:s}=this.ctx.diagnostics.guard(`capture.record_failed`,`The library could not read the error reason. It records the error without its message.`,()=>i(t))??{message:``,key:`${typeof t}||`},c=this.seen.get(s);if(c&&a-c.at<this.ctx.config.captureLimits.errorDedupeMs){c.count++,c.at=a;return}let l=c?c.count-1:0;if(this.seen.delete(s),this.seen.set(s,{at:a,count:1}),this.seen.size>200){let[e]=this.seen.keys();this.seen.delete(e)}let u=t===void 0?Error(o):t;this.ctx.logger.error(o===``?e:o,u,{...r,"error.captured_by":e,"error.suppressed_count":l})}};exports.ErrorCapture=a;
3
+ //# sourceMappingURL=errors-07pmZ7VY.cjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"errors-07pmZ7VY.cjs","names":["isErrorLike","recordedUrl","allowInWindow","require_error_like","require_platform","require_storm","require_defineProperty","signatureOf","value","frame","message","ErrorCapture","event","ctx","element","target","tag","attributes","label","source","fallback","errorEvent","error","now","previous","key","suppressed","oldest","reason","extra"],"sources":["../src/capture/errors.ts"],"sourcesContent":["// src/capture/errors.ts\n//\n// Captures uncaught errors, unhandled rejections and failed resource loads.\n\nimport { MAX_TRACKED_ERROR_SIGNATURES } from \"../constants\";\nimport { isErrorLike } from \"../utils/error-like\";\nimport { recordedUrl } from \"../utils/platform\";\nimport { allowInWindow, type StormWindow } from \"./storm\";\nimport type { Capture, CaptureContext } from \"./types\";\n\n/** Tracking metadata for a deduplicated error signature. */\ninterface SeenError {\n /** When the signature was last reported, in epoch milliseconds. */\n at: number;\n /** Occurrences recorded since the last report. */\n count: number;\n}\n\n/** A thrown value's message and deduplication key. */\ninterface Signature {\n /** The record's message. */\n message: string;\n /** Deduplication key. */\n key: string;\n}\n\n/**\n * Reads a thrown value's message and deduplication key.\n * Duck typing lets it read an error from another realm, which fails `instanceof Error`.\n * @param value Thrown value or rejection reason.\n * @returns The signature.\n * @throws When a getter or the value's text form throws. Call it inside a guard.\n */\nfunction signatureOf(value: unknown): Signature {\n if (isErrorLike(value)) {\n const frame = (value.stack ?? \"\").split(\"\\n\")[1] ?? \"\";\n return { message: value.message, key: `${value.name}|${value.message}|${frame}` };\n }\n\n const message = String(value);\n return { message, key: `${typeof value}|${message}|` };\n}\n\n/** Captures uncaught exceptions, unhandled promise rejections, and failed resource loads. */\nexport class ErrorCapture implements Capture {\n /** Capture module identifier. */\n readonly name = \"errors\";\n\n /** Prevents duplicate listener registration. */\n private installed = false;\n\n /** Recently reported error signatures in LRU order. */\n private readonly seen = new Map<string, SeenError>();\n\n /** This capture's own rate limit. Console noise has a separate window and can't use it. */\n private readonly window: StormWindow = { start: 0, count: 0 };\n\n /**\n * @param ctx Capture context: configuration, diagnostics, logger and breadcrumbs.\n */\n constructor(private readonly ctx: CaptureContext) {}\n\n /** Subscribes to global error and unhandledrejection events. */\n install(): void {\n if (this.installed || typeof addEventListener === \"undefined\") {\n return;\n }\n this.installed = true;\n\n // Resource load errors don't bubble, so listen in the capture phase.\n addEventListener(\"error\", this.onError, true);\n addEventListener(\"unhandledrejection\", this.onRejection);\n }\n\n /** Removes event listeners and clears tracked error signatures. */\n uninstall(): void {\n if (!this.installed) {\n return;\n }\n this.installed = false;\n\n removeEventListener(\"error\", this.onError, true);\n removeEventListener(\"unhandledrejection\", this.onRejection);\n this.seen.clear();\n }\n\n /** Routes resource load failures and uncaught script errors. */\n private readonly onError = (event: ErrorEvent | Event): void => {\n // The browser calls this listener, so a throw here would be a new uncaught error on the page.\n this.ctx.diagnostics.guard(\n \"capture.record_failed\",\n \"The library could not record an error event.\",\n () => {\n // A failed load fires a plain Event at its element. Only a script error carries the\n // ErrorEvent fields, so a plain Event at the window is neither.\n if (\"message\" in event) {\n this.scriptError(event);\n } else {\n this.failedResource(event.target);\n }\n },\n );\n };\n\n /**\n * Records a failed resource load.\n * @param target The event's target. The window and the document aren't resources.\n */\n private failedResource(target: EventTarget | null): void {\n const element = target as (Element & { src?: unknown; href?: unknown }) | null;\n if (typeof element?.tagName !== \"string\" || !this.ctx.config.capture.resourceErrors) {\n return;\n }\n\n const tag = element.tagName.toLowerCase();\n const attributes: Record<string, unknown> = { \"error.type\": \"resource\", \"resource.tag\": tag };\n // Without a URL, the breadcrumb names the tag.\n let label = tag;\n // An SVG href is an object and an object element has no src, so only a string URL goes in.\n // A cache buster is noise and a signed URL is a credential, so fullUrls decides on both.\n const source = element.src ?? element.href;\n if (typeof source === \"string\" && source !== \"\") {\n label = recordedUrl(\n source,\n this.ctx.config.capture.fullUrls,\n this.ctx.config.capture.urlTransform,\n this.ctx.diagnostics,\n );\n attributes[\"resource.url\"] = label;\n }\n\n this.ctx.breadcrumbs.push({\n t: Date.now(),\n category: \"http\",\n message: `resource failed: ${label}`,\n });\n this.ctx.logger.warn(\"resource failed to load\", attributes);\n }\n\n /**\n * Records an uncaught script error.\n * @param errorEvent The window's error event.\n */\n private scriptError(errorEvent: ErrorEvent): void {\n if (!this.ctx.config.capture.errors) {\n return;\n }\n\n const fallback = errorEvent.message === \"\" ? \"unknown error\" : errorEvent.message;\n const thrown: unknown = errorEvent.error;\n const error = thrown ?? new Error(fallback);\n\n this.report(\"window.onerror\", error, {\n // A signed script URL is a credential.\n \"error.source\": recordedUrl(\n errorEvent.filename,\n this.ctx.config.capture.fullUrls,\n this.ctx.config.capture.urlTransform,\n this.ctx.diagnostics,\n ),\n \"error.line\": errorEvent.lineno,\n \"error.column\": errorEvent.colno,\n });\n }\n\n /** Captures unhandled promise rejections. */\n private readonly onRejection = (event: PromiseRejectionEvent): void => {\n if (!this.ctx.config.capture.rejections) {\n return;\n }\n\n this.report(\"unhandledrejection\", event.reason, {\n \"error.type\": \"unhandledrejection\",\n });\n };\n\n /**\n * Rate limits, deduplicates and logs a captured error.\n * @param source Name of the capture event it came from.\n * @param error The caught error or thrown value.\n * @param extra Extra error attributes for the record.\n */\n private report(source: string, error: unknown, extra: Record<string, unknown>): void {\n if (\n !allowInWindow(\n this.window,\n this.ctx.config.captureLimits.errorsPerWindow,\n this.ctx.diagnostics,\n \"errors\",\n this.ctx.config.captureLimits.windowMs,\n )\n ) {\n return;\n }\n\n const now = Date.now();\n // A reason with no text form, for example a null-prototype object, gets an empty message,\n // and the record then uses the source as its message.\n const { message, key } = this.ctx.diagnostics.guard(\n \"capture.record_failed\",\n \"The library could not read the error reason. It records the error without its message.\",\n () => signatureOf(error),\n ) ?? { message: \"\", key: `${typeof error}||` };\n const previous = this.seen.get(key);\n\n if (previous && now - previous.at < this.ctx.config.captureLimits.errorDedupeMs) {\n previous.count++;\n previous.at = now;\n return;\n }\n\n // How many occurrences deduplication dropped since the last report. Without this count,\n // many errors look like a few.\n const suppressed = previous ? previous.count - 1 : 0;\n\n // Delete, then set, to move the key to the end of the map. That keeps the map in\n // least-recently-reported order, which the eviction below relies on.\n this.seen.delete(key);\n this.seen.set(key, { at: now, count: 1 });\n\n // A page can throw with a new message on every render, for example from a template literal\n // in a loop. Without this cap, the map grows until the document closes.\n if (this.seen.size > MAX_TRACKED_ERROR_SIGNATURES) {\n const [oldest] = this.seen.keys();\n this.seen.delete(oldest);\n }\n\n // Hand the logger the original value, so it converts the reason and keeps its data.\n // With no reason at all, the record still needs error.message and error.stack_trace.\n const reason = error === undefined ? new Error(message) : error;\n this.ctx.logger.error(message === \"\" ? source : message, reason, {\n ...extra,\n \"error.captured_by\": source,\n \"error.suppressed_count\": suppressed,\n });\n }\n}\n"],"mappings":"A,+JAiCA,SAASO,EAAY,EAA2B,CAC9C,GAAIP,EAAAA,EAAYQ,CAAK,EAAG,CACtB,IAAMC,GAASD,EAAM,OAAS,GAAA,CAAI,MAAM;CAAI,CAAC,CAAC,IAAM,GACpD,MAAO,CAAE,QAASA,EAAM,QAAS,IAAK,GAAGA,EAAM,KAAK,GAAGA,EAAM,QAAQ,GAAGC,GAAQ,CAClF,CAEA,IAAMC,EAAU,OAAOF,CAAK,EAC5B,MAAO,CAAE,UAAS,IAAK,GAAG,OAAOA,EAAM,GAAGE,EAAQ,EAAG,CACvD,CAGA,IAAaC,EAAb,KAA6C,CAgB3C,YAAY,EAAsC,CAArBL,EAAA,EAAA,KAAA,MAAA,IAAA,EAAA,EAd7BA,EAAA,EAAA,KAAA,OAAgB,QAAA,EAGhBA,EAAA,EAAA,KAAA,YAAoB,EAAA,EAGpBA,EAAA,EAAA,KAAA,OAAwB,IAAI,GAAuB,EAGnDA,EAAA,EAAA,KAAA,SAAuC,CAAE,MAAO,EAAG,MAAO,CAAE,CAAA,EAgC5DA,EAAA,EAAA,KAAA,UAA4B,GAAoC,CAE9D,KAAK,IAAI,YAAY,MACnB,wBACA,mDACM,CAGA,YAAaM,EACf,KAAK,YAAYA,CAAK,EAEtB,KAAK,eAAeA,EAAM,MAAM,CAEpC,CACF,CACF,CAAA,EAgEAN,EAAA,EAAA,KAAA,cAAgC,GAAuC,CAChE,KAAK,IAAI,OAAO,QAAQ,YAI7B,KAAK,OAAO,qBAAsBM,EAAM,OAAQ,CAC9C,aAAc,oBAChB,CAAC,CACH,CAAA,EAlH6B,KAAA,IAAAC,CAAsB,CAGnD,SAAgB,CACV,KAAK,WAAa,OAAO,iBAAqB,MAGlD,KAAK,UAAY,GAGjB,iBAAiB,QAAS,KAAK,QAAS,EAAI,EAC5C,iBAAiB,qB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,KAAK,IAAI,YACT,SACA,KAAK,IAAI,OAAO,cAAc,QAChC,EAEA,OAGF,IAAMqB,EAAM,KAAK,IAAI,EAGf,CAAE,UAAS,OAAQ,KAAK,IAAI,YAAY,MAC5C,wBACA,6FACMhB,EAAYe,CAAK,CACzB,GAAK,CAAE,QAAS,GAAI,IAAK,GAAG,OAAOA,EAAM,GAAI,EACvCE,EAAW,KAAK,KAAK,IAAIC,CAAG,EAElC,GAAID,GAAYD,EAAMC,EAAS,GAAK,KAAK,IAAI,OAAO,cAAc,cAAe,CAC/E,EAAS,QACT,EAAS,GAAKD,EACd,MACF,CAIA,IAAMG,EAAaF,EAAWA,EAAS,MAAQ,EAAI,EASnD,GALA,KAAK,KAAK,OAAOC,CAAG,EACpB,KAAK,KAAK,IAAIA,EAAK,CAAE,GAAIF,EAAK,MAAO,CAAE,CAAC,EAIpC,KAAK,KAAK,KAAA,IAAqC,CACjD,GAAM,CAACI,GAAU,KAAK,KAAK,KAAK,EAChC,KAAK,KAAK,OAAOA,CAAM,CACzB,CAIA,IAAMC,EAASN,IAAU,IAAA,GAAgB,MAAMZ,CAAO,EAAIY,EAC1D,KAAK,IAAI,OAAO,MAAMZ,IAAY,GAAKS,EAAST,EAASkB,EAAQ,CAC/D,GAAGC,EACH,oBAAqBV,EACrB,yBAA0BO,CAC5B,CAAC,CACH,CACF,E"}
@@ -1,6 +1,6 @@
1
1
  import { r as e } from "./error-like-B11pB4aL.js";
2
- import { i as t } from "./platform-BaaFIPCU.js";
3
- import { t as n } from "./storm-DjKetLKZ.js";
2
+ import { a as t } from "./platform-Dba6R3Hp.js";
3
+ import { t as n } from "./storm-U3_ek1nA.js";
4
4
  import { t as r } from "./defineProperty-s2S8BXUc.js";
5
5
  // src/capture/errors.ts
6
6
  function i(t) {
@@ -23,27 +23,8 @@ var a = class {
23
23
  start: 0,
24
24
  count: 0
25
25
  }), r(this, "onError", (e) => {
26
- let n = e.target, r = n?.src ?? n?.href ?? "";
27
- if (n !== null && n !== globalThis && r !== "") {
28
- if (!this.ctx.config.capture.resourceErrors) return;
29
- let e = t(r, this.ctx.config.capture.fullUrls, this.ctx.config.capture.urlTransform, this.ctx.diagnostics);
30
- this.ctx.breadcrumbs.push({
31
- t: Date.now(),
32
- category: "http",
33
- message: `resource failed: ${e}`
34
- }), this.ctx.logger.warn("resource failed to load", {
35
- "error.type": "resource",
36
- "resource.url": e,
37
- "resource.tag": n.tagName.toLowerCase()
38
- });
39
- return;
40
- }
41
- if (!this.ctx.config.capture.errors) return;
42
- let i = e, a = i.message === "" ? "unknown error" : i.message, o = i.error ?? Error(a);
43
- this.report("window.onerror", o, {
44
- "error.source": t(i.filename, this.ctx.config.capture.fullUrls, this.ctx.config.capture.urlTransform, this.ctx.diagnostics),
45
- "error.line": i.lineno,
46
- "error.column": i.colno
26
+ this.ctx.diagnostics.guard("capture.record_failed", "The library could not record an error event.", () => {
27
+ "message" in e ? this.scriptError(e) : this.failedResource(e.target);
47
28
  });
48
29
  }), r(this, "onRejection", (e) => {
49
30
  this.ctx.config.capture.rejections && this.report("unhandledrejection", e.reason, { "error.type": "unhandledrejection" });
@@ -55,6 +36,28 @@ var a = class {
55
36
  uninstall() {
56
37
  this.installed && (this.installed = !1, removeEventListener("error", this.onError, !0), removeEventListener("unhandledrejection", this.onRejection), this.seen.clear());
57
38
  }
39
+ failedResource(e) {
40
+ let n = e;
41
+ if (typeof n?.tagName != "string" || !this.ctx.config.capture.resourceErrors) return;
42
+ let r = n.tagName.toLowerCase(), i = {
43
+ "error.type": "resource",
44
+ "resource.tag": r
45
+ }, a = r, o = n.src ?? n.href;
46
+ typeof o == "string" && o !== "" && (a = t(o, this.ctx.config.capture.fullUrls, this.ctx.config.capture.urlTransform, this.ctx.diagnostics), i["resource.url"] = a), this.ctx.breadcrumbs.push({
47
+ t: Date.now(),
48
+ category: "http",
49
+ message: `resource failed: ${a}`
50
+ }), this.ctx.logger.warn("resource failed to load", i);
51
+ }
52
+ scriptError(e) {
53
+ if (!this.ctx.config.capture.errors) return;
54
+ let n = e.message === "" ? "unknown error" : e.message, r = e.error ?? Error(n);
55
+ this.report("window.onerror", r, {
56
+ "error.source": t(e.filename, this.ctx.config.capture.fullUrls, this.ctx.config.capture.urlTransform, this.ctx.diagnostics),
57
+ "error.line": e.lineno,
58
+ "error.column": e.colno
59
+ });
60
+ }
58
61
  report(e, t, r) {
59
62
  if (!n(this.window, this.ctx.config.captureLimits.errorsPerWindow, this.ctx.diagnostics, "errors", this.ctx.config.captureLimits.windowMs)) return;
60
63
  let a = Date.now(), { message: o, key: s } = this.ctx.diagnostics.guard("capture.record_failed", "The library could not read the error reason. It records the error without its message.", () => i(t)) ?? {
@@ -83,4 +86,4 @@ var a = class {
83
86
  };
84
87
  export { a as ErrorCapture };
85
88
 
86
- //# sourceMappingURL=errors-BE_EZV7Q.js.map
89
+ //# sourceMappingURL=errors-C-LYbqyB.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"errors-C-LYbqyB.js","names":["isErrorLike","recordedUrl","allowInWindow","_defineProperty","signatureOf","value","frame","message","ErrorCapture","event","ctx","element","target","tag","attributes","label","source","fallback","errorEvent","error","now","previous","key","suppressed","oldest","reason","extra"],"sources":["../src/capture/errors.ts"],"sourcesContent":["// src/capture/errors.ts\n//\n// Captures uncaught errors, unhandled rejections and failed resource loads.\n\nimport { MAX_TRACKED_ERROR_SIGNATURES } from \"../constants\";\nimport { isErrorLike } from \"../utils/error-like\";\nimport { recordedUrl } from \"../utils/platform\";\nimport { allowInWindow, type StormWindow } from \"./storm\";\nimport type { Capture, CaptureContext } from \"./types\";\n\n/** Tracking metadata for a deduplicated error signature. */\ninterface SeenError {\n /** When the signature was last reported, in epoch milliseconds. */\n at: number;\n /** Occurrences recorded since the last report. */\n count: number;\n}\n\n/** A thrown value's message and deduplication key. */\ninterface Signature {\n /** The record's message. */\n message: string;\n /** Deduplication key. */\n key: string;\n}\n\n/**\n * Reads a thrown value's message and deduplication key.\n * Duck typing lets it read an error from another realm, which fails `instanceof Error`.\n * @param value Thrown value or rejection reason.\n * @returns The signature.\n * @throws When a getter or the value's text form throws. Call it inside a guard.\n */\nfunction signatureOf(value: unknown): Signature {\n if (isErrorLike(value)) {\n const frame = (value.stack ?? \"\").split(\"\\n\")[1] ?? \"\";\n return { message: value.message, key: `${value.name}|${value.message}|${frame}` };\n }\n\n const message = String(value);\n return { message, key: `${typeof value}|${message}|` };\n}\n\n/** Captures uncaught exceptions, unhandled promise rejections, and failed resource loads. */\nexport class ErrorCapture implements Capture {\n /** Capture module identifier. */\n readonly name = \"errors\";\n\n /** Prevents duplicate listener registration. */\n private installed = false;\n\n /** Recently reported error signatures in LRU order. */\n private readonly seen = new Map<string, SeenError>();\n\n /** This capture's own rate limit. Console noise has a separate window and can't use it. */\n private readonly window: StormWindow = { start: 0, count: 0 };\n\n /**\n * @param ctx Capture context: configuration, diagnostics, logger and breadcrumbs.\n */\n constructor(private readonly ctx: CaptureContext) {}\n\n /** Subscribes to global error and unhandledrejection events. */\n install(): void {\n if (this.installed || typeof addEventListener === \"undefined\") {\n return;\n }\n this.installed = true;\n\n // Resource load errors don't bubble, so listen in the capture phase.\n addEventListener(\"error\", this.onError, true);\n addEventListener(\"unhandledrejection\", this.onRejection);\n }\n\n /** Removes event listeners and clears tracked error signatures. */\n uninstall(): void {\n if (!this.installed) {\n return;\n }\n this.installed = false;\n\n removeEventListener(\"error\", this.onError, true);\n removeEventListener(\"unhandledrejection\", this.onRejection);\n this.seen.clear();\n }\n\n /** Routes resource load failures and uncaught script errors. */\n private readonly onError = (event: ErrorEvent | Event): void => {\n // The browser calls this listener, so a throw here would be a new uncaught error on the page.\n this.ctx.diagnostics.guard(\n \"capture.record_failed\",\n \"The library could not record an error event.\",\n () => {\n // A failed load fires a plain Event at its element. Only a script error carries the\n // ErrorEvent fields, so a plain Event at the window is neither.\n if (\"message\" in event) {\n this.scriptError(event);\n } else {\n this.failedResource(event.target);\n }\n },\n );\n };\n\n /**\n * Records a failed resource load.\n * @param target The event's target. The window and the document aren't resources.\n */\n private failedResource(target: EventTarget | null): void {\n const element = target as (Element & { src?: unknown; href?: unknown }) | null;\n if (typeof element?.tagName !== \"string\" || !this.ctx.config.capture.resourceErrors) {\n return;\n }\n\n const tag = element.tagName.toLowerCase();\n const attributes: Record<string, unknown> = { \"error.type\": \"resource\", \"resource.tag\": tag };\n // Without a URL, the breadcrumb names the tag.\n let label = tag;\n // An SVG href is an object and an object element has no src, so only a string URL goes in.\n // A cache buster is noise and a signed URL is a credential, so fullUrls decides on both.\n const source = element.src ?? element.href;\n if (typeof source === \"string\" && source !== \"\") {\n label = recordedUrl(\n source,\n this.ctx.config.capture.fullUrls,\n this.ctx.config.capture.urlTransform,\n this.ctx.diagnostics,\n );\n attributes[\"resource.url\"] = label;\n }\n\n this.ctx.breadcrumbs.push({\n t: Date.now(),\n category: \"http\",\n message: `resource failed: ${label}`,\n });\n this.ctx.logger.warn(\"resource failed to load\", attributes);\n }\n\n /**\n * Records an uncaught script error.\n * @param errorEvent The window's error event.\n */\n private scriptError(errorEvent: ErrorEvent): void {\n if (!this.ctx.config.capture.errors) {\n return;\n }\n\n const fallback = errorEvent.message === \"\" ? \"unknown error\" : errorEvent.message;\n const thrown: unknown = errorEvent.error;\n const error = thrown ?? new Error(fallback);\n\n this.report(\"window.onerror\", error, {\n // A signed script URL is a credential.\n \"error.source\": recordedUrl(\n errorEvent.filename,\n this.ctx.config.capture.fullUrls,\n this.ctx.config.capture.urlTransform,\n this.ctx.diagnostics,\n ),\n \"error.line\": errorEvent.lineno,\n \"error.column\": errorEvent.colno,\n });\n }\n\n /** Captures unhandled promise rejections. */\n private readonly onRejection = (event: PromiseRejectionEvent): void => {\n if (!this.ctx.config.capture.rejections) {\n return;\n }\n\n this.report(\"unhandledrejection\", event.reason, {\n \"error.type\": \"unhandledrejection\",\n });\n };\n\n /**\n * Rate limits, deduplicates and logs a captured error.\n * @param source Name of the capture event it came from.\n * @param error The caught error or thrown value.\n * @param extra Extra error attributes for the record.\n */\n private report(source: string, error: unknown, extra: Record<string, unknown>): void {\n if (\n !allowInWindow(\n this.window,\n this.ctx.config.captureLimits.errorsPerWindow,\n this.ctx.diagnostics,\n \"errors\",\n this.ctx.config.captureLimits.windowMs,\n )\n ) {\n return;\n }\n\n const now = Date.now();\n // A reason with no text form, for example a null-prototype object, gets an empty message,\n // and the record then uses the source as its message.\n const { message, key } = this.ctx.diagnostics.guard(\n \"capture.record_failed\",\n \"The library could not read the error reason. It records the error without its message.\",\n () => signatureOf(error),\n ) ?? { message: \"\", key: `${typeof error}||` };\n const previous = this.seen.get(key);\n\n if (previous && now - previous.at < this.ctx.config.captureLimits.errorDedupeMs) {\n previous.count++;\n previous.at = now;\n return;\n }\n\n // How many occurrences deduplication dropped since the last report. Without this count,\n // many errors look like a few.\n const suppressed = previous ? previous.count - 1 : 0;\n\n // Delete, then set, to move the key to the end of the map. That keeps the map in\n // least-recently-reported order, which the eviction below relies on.\n this.seen.delete(key);\n this.seen.set(key, { at: now, count: 1 });\n\n // A page can throw with a new message on every render, for example from a template literal\n // in a loop. Without this cap, the map grows until the document closes.\n if (this.seen.size > MAX_TRACKED_ERROR_SIGNATURES) {\n const [oldest] = this.seen.keys();\n this.seen.delete(oldest);\n }\n\n // Hand the logger the original value, so it converts the reason and keeps its data.\n // With no reason at all, the record still needs error.message and error.stack_trace.\n const reason = error === undefined ? new Error(message) : error;\n this.ctx.logger.error(message === \"\" ? source : message, reason, {\n ...extra,\n \"error.captured_by\": source,\n \"error.suppressed_count\": suppressed,\n });\n }\n}\n"],"mappings":";;;;;AAiCA,SAASI,EAAY,GAA2B;CAC9C,IAAIJ,EAAYK,CAAK,GAAG;EACtB,IAAMC,KAASD,EAAM,SAAS,GAAA,CAAI,MAAM,IAAI,CAAC,CAAC,MAAM;EACpD,OAAO;GAAE,SAASA,EAAM;GAAS,KAAK,GAAGA,EAAM,KAAK,GAAGA,EAAM,QAAQ,GAAGC;EAAQ;CAClF;CAEA,IAAMC,IAAU,OAAOF,CAA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,IAAaF,IAAWA,EAAS,QAAQ,IAAI;EASnD,IALA,KAAK,KAAK,OAAOC,CAAG,GACpB,KAAK,KAAK,IAAIA,GAAK;GAAE,IAAIF;GAAK,OAAO;EAAE,CAAC,GAIpC,KAAK,KAAK,OAAA,KAAqC;GACjD,IAAM,CAACI,KAAU,KAAK,KAAK,KAAK;GAChC,KAAK,KAAK,OAAOA,CAAM;EACzB;EAIA,IAAMC,IAASN,MAAU,KAAA,IAAgB,MAAMZ,CAAO,IAAIY;EAC1D,KAAK,IAAI,OAAO,MAAMZ,MAAY,KAAKS,IAAST,GAASkB,GAAQ;GAC/D,GAAGC;GACH,qBAAqBV;GACrB,0BAA0BO;EAC5B,CAAC;CACH;AACF"}
@@ -1,6 +1,6 @@
1
- import { E as e, Jn as t, Un as n, Wn as r, Xn as i, Yn as a, et as o, qn as s } from "./constants-CUyd9cTZ.js";
1
+ import { $n as e, E as t, Jn as n, Qn as r, Zn as i, er as a, qn as o, tt as s } from "./constants-CEHN6KuY.js";
2
2
  import { t as c } from "./defineProperty-s2S8BXUc.js";
3
- import { i as l, n as u, r as d } from "./batch-CXmPmTse.js";
3
+ import { i as l, n as u, r as d } from "./batch-120Kc9jr.js";
4
4
  import { n as f } from "./deadline-C4ccAuk5.js";
5
5
  // src/models/storage.ts
6
6
  function p(e) {
@@ -55,9 +55,14 @@ var m = class {
55
55
  }
56
56
  };
57
57
  // src/utils/lock.ts
58
- function h(e, t, n, { skipIfBusy: r = !0 } = {}) {
58
+ async function h(e, t, n, { skipIfBusy: r = !0 } = {}) {
59
59
  let i = globalThis.navigator?.locks;
60
- return i?.request ? t.guardAsync("storage.degraded", `The library could not get the lock ${e}.`, () => i.request(e, { ifAvailable: r }, (e) => e ? n() : Promise.resolve(void 0))) : n();
60
+ if (!i?.request) return n();
61
+ try {
62
+ return await i.request(e, { ifAvailable: r }, (r) => r ? t.guardAsync("storage.degraded", `The work under the lock ${e} failed. The library skips this run.`, n) : Promise.resolve(void 0));
63
+ } catch (r) {
64
+ return t.report("storage.degraded", `The library could not get the lock ${e}. It runs the work without the lock.`, void 0, r), n();
65
+ }
61
66
  }
62
67
  function g(e, t) {
63
68
  return t ? `${e}:${encodeURIComponent(t)}` : e;
@@ -80,15 +85,15 @@ function y(e, t) {
80
85
  let n = t.guard("storage.degraded", "An emergency entry is not valid JSON. The library dropped it.", () => JSON.parse(e));
81
86
  return n === void 0 ? null : l(n) ? n : (t.report("storage.degraded", "An emergency entry is not a batch. The library dropped it."), null);
82
87
  }
83
- async function b(e, t, n, i) {
88
+ async function b(e, t, r, i) {
84
89
  let a = 0;
85
90
  for (let o of v(i, t)) {
86
91
  let i = t.guard("storage.unavailable", "The library could not read the emergency queue.", () => {
87
- let e = localStorage.getItem(o), r = e ? y(e, t) : null;
88
- return r && !n(r) ? null : (localStorage.removeItem(o), r);
92
+ let e = localStorage.getItem(o), n = e ? y(e, t) : null;
93
+ return n && !r(n) ? null : (localStorage.removeItem(o), n);
89
94
  });
90
95
  if (i) try {
91
- await f(e.save(i), r), a++;
96
+ await f(e.save(i), n), a++;
92
97
  } catch (e) {
93
98
  t.report("storage.degraded", "The library could not recover an emergency batch.", { key: o }, e);
94
99
  }
@@ -99,8 +104,8 @@ function x(e, t, n) {
99
104
  let r = w(e.persistenceNamespace), i = `writing the emergency queue, ${String(e.records.length)} records`, a = [], o = t.guard("storage.quota_exceeded", i, () => {
100
105
  let n = v(r, t);
101
106
  for (let e of n.slice(0, Math.max(0, n.length - 20 + 1))) {
102
- let n = y(String(localStorage.getItem(e)), t);
103
- n !== null && a.push(n), localStorage.removeItem(e);
107
+ let n = localStorage.getItem(e), r = n === null ? null : y(n, t);
108
+ r !== null && a.push(r), localStorage.removeItem(e);
104
109
  }
105
110
  return localStorage.setItem(_(r, e), JSON.stringify(e)), !0;
106
111
  });
@@ -116,16 +121,22 @@ async function S(e, t, n = () => !0, r = "") {
116
121
  return await h(g("ui-observability.emergency", r), t, () => b(e, t, n, w(r)), { skipIfBusy: !1 }) ?? 0;
117
122
  }
118
123
  function C(e, t, n = "", r = !1) {
119
- let i = w(n);
120
- t.guard("storage.unavailable", "The library could not clear the retired emergency queue.", () => {
124
+ let i = w(n), a = [];
125
+ return t.guard("storage.unavailable", "The library could not clear the retired emergency queue.", () => {
121
126
  for (let n of v(i, t)) {
127
+ if (r) {
128
+ localStorage.removeItem(n);
129
+ continue;
130
+ }
122
131
  let i = localStorage.getItem(n);
123
- i && (r || y(i, t)?.routingContextId === e) && localStorage.removeItem(n);
132
+ if (i === null) continue;
133
+ let o = y(i, t);
134
+ o?.routingContextId === e && (localStorage.removeItem(n), a.push(o));
124
135
  }
125
- });
136
+ }), a;
126
137
  }
127
138
  function w(e = "") {
128
- return e ? `ui-observability:namespaced:${encodeURIComponent(e)}:emergency:` : o;
139
+ return e ? `ui-observability:namespaced:${encodeURIComponent(e)}:emergency:` : s;
129
140
  }
130
141
  // src/storage/eviction.ts
131
142
  function T(e) {
@@ -164,8 +175,8 @@ function A(e, t) {
164
175
  return Number.isFinite(r) ? r : null;
165
176
  }
166
177
  var j = class {
167
- constructor(t, n, r, i = e) {
168
- c(this, "limits", void 0), c(this, "diagnostics", void 0), c(this, "onGap", void 0), c(this, "prefix", void 0), c(this, "name", s), this.limits = t, this.diagnostics = n, this.onGap = r, this.prefix = i;
178
+ constructor(e, n, r, a = t) {
179
+ c(this, "limits", void 0), c(this, "diagnostics", void 0), c(this, "onGap", void 0), c(this, "prefix", void 0), c(this, "name", i), this.limits = e, this.diagnostics = n, this.onGap = r, this.prefix = a;
169
180
  }
170
181
  save(e) {
171
182
  if (this.write(e, "localStorage refused a batch, evicting the oldest")) {
@@ -303,8 +314,8 @@ var j = class {
303
314
  return v(this.prefix, this.diagnostics);
304
315
  }
305
316
  }, M = class {
306
- constructor(e, n) {
307
- c(this, "limits", void 0), c(this, "onGap", void 0), c(this, "name", t), c(this, "batches", []), this.limits = e, this.onGap = n;
317
+ constructor(e, t) {
318
+ c(this, "limits", void 0), c(this, "onGap", void 0), c(this, "name", r), c(this, "batches", []), this.limits = e, this.onGap = t;
308
319
  }
309
320
  async save(e) {
310
321
  let t = this.batches.findIndex((t) => t.id === e.id);
@@ -357,15 +368,15 @@ var j = class {
357
368
  };
358
369
  // src/storage/factory.ts
359
370
  function N(e) {
360
- return e ? `${n}:${e}` : n;
371
+ return e ? `${o}:${e}` : o;
361
372
  }
362
- var P = (e) => ({
363
- name: a,
364
- save: (t) => (e?.({
373
+ var P = (t) => ({
374
+ name: e,
375
+ save: (e) => (t?.({
365
376
  batches: 1,
366
- records: t.records.length,
377
+ records: e.records.length,
367
378
  reason: "not_stored"
368
- }, [t]), Promise.resolve(!1)),
379
+ }, [e]), Promise.resolve(!1)),
369
380
  take: () => Promise.resolve([]),
370
381
  remove: () => Promise.resolve(),
371
382
  bumpAttempts: () => Promise.resolve(),
@@ -382,7 +393,7 @@ function F(e) {
382
393
  return e.guard("storage.unavailable", "The library could not read indexedDB.", () => globalThis.indexedDB != null) === !0;
383
394
  }
384
395
  function I(e) {
385
- return e.guard("storage.unavailable", "The library could not write a test key to localStorage.", () => (localStorage.setItem(i, "1"), localStorage.removeItem(i), !0)) === !0;
396
+ return e.guard("storage.unavailable", "The library could not write a test key to localStorage.", () => (localStorage.setItem(a, "1"), localStorage.removeItem(a), !0)) === !0;
386
397
  }
387
398
  async function L(e, t, n, r, i, a = "") {
388
399
  if (e === "none") return P(i);
@@ -390,7 +401,7 @@ async function L(e, t, n, r, i, a = "") {
390
401
  if (e === "indexeddb" || e === "auto") {
391
402
  if (F(r)) {
392
403
  let e = await r.guardAsync("storage.unavailable", "The library could not open IndexedDB.", async () => {
393
- let { IndexedDbStorage: e } = await import("./indexeddb-storage-GHdl0t8A.js"), a = new e(t, n, r, i);
404
+ let { IndexedDbStorage: e } = await import("./indexeddb-storage-BYywz-v6.js"), a = new e(t, n, r, i);
394
405
  return await a.open(), a;
395
406
  });
396
407
  if (e) return e;
@@ -401,4 +412,4 @@ async function L(e, t, n, r, i, a = "") {
401
412
  }
402
413
  export { E as a, S as c, h as d, m as f, k as i, x as l, N as n, T as o, p, O as r, C as s, L as t, g as u };
403
414
 
404
- //# sourceMappingURL=factory-CTi0Is3F.js.map
415
+ //# sourceMappingURL=factory-BHYrcSaU.js.map