pcm-agents 0.6.11 → 0.6.13

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 (292) hide show
  1. package/dist/cjs/error-event-J_ZWIqWF.js +33 -0
  2. package/dist/cjs/error-event-J_ZWIqWF.js.map +1 -0
  3. package/dist/cjs/{index-CvEfNyEj.js → index-CRlt8Nv6.js} +53 -3
  4. package/dist/cjs/index-CRlt8Nv6.js.map +1 -0
  5. package/dist/cjs/index-WNdOTXnX.js +11068 -0
  6. package/dist/cjs/index-WNdOTXnX.js.map +1 -0
  7. package/dist/cjs/index.cjs.js +2 -2
  8. package/dist/cjs/loader.cjs.js +3 -5
  9. package/dist/cjs/loader.cjs.js.map +1 -1
  10. package/dist/cjs/message.service-DGUsA-FY.js +135 -0
  11. package/dist/cjs/message.service-DGUsA-FY.js.map +1 -0
  12. package/dist/cjs/{pcm-1zhanshi-mnms-modal_17.cjs.entry.js → pcm-1zhanshi-mnms-modal_21.cjs.entry.js} +3276 -216
  13. package/dist/cjs/pcm-1zhanshi-mnms-modal_21.cjs.entry.js.map +1 -0
  14. package/dist/cjs/pcm-agents.cjs.js +4 -6
  15. package/dist/cjs/pcm-agents.cjs.js.map +1 -1
  16. package/dist/cjs/pcm-message.cjs.entry.js +3 -3
  17. package/dist/cjs/pcm-message.cjs.entry.js.map +1 -1
  18. package/dist/cjs/pcm-message.entry.cjs.js.map +1 -1
  19. package/dist/cjs/pcm-mnms-video-modal.cjs.entry.js +8 -8
  20. package/dist/cjs/pcm-mnms-video-modal.cjs.entry.js.map +1 -1
  21. package/dist/cjs/pcm-mnms-video-modal.entry.cjs.js.map +1 -1
  22. package/dist/cjs/pcm-mnms-zp-modal.cjs.entry.js +29 -86
  23. package/dist/cjs/pcm-mnms-zp-modal.cjs.entry.js.map +1 -1
  24. package/dist/cjs/pcm-mnms-zp-modal.entry.cjs.js.map +1 -1
  25. package/dist/cjs/{sentry-reporter-BWFtw_aT.js → sentry-reporter-tpI4WdkE.js} +12 -40
  26. package/dist/cjs/sentry-reporter-tpI4WdkE.js.map +1 -0
  27. package/dist/collection/collection-manifest.json +5 -1
  28. package/dist/collection/components/pcm-1zhanshi-mnms-modal/pcm-1zhanshi-mnms-modal.js.map +1 -1
  29. package/dist/collection/components/pcm-app-chat-modal/pcm-app-chat-modal.css +986 -986
  30. package/dist/collection/components/pcm-app-chat-modal/pcm-app-chat-modal.js +7 -9
  31. package/dist/collection/components/pcm-app-chat-modal/pcm-app-chat-modal.js.map +1 -1
  32. package/dist/collection/components/pcm-button/pcm-button.css +199 -199
  33. package/dist/collection/components/pcm-button/pcm-button.js +6 -6
  34. package/dist/collection/components/pcm-button/pcm-button.js.map +1 -1
  35. package/dist/collection/components/pcm-card/pcm-card.css +259 -259
  36. package/dist/collection/components/pcm-card/pcm-card.js +1 -1
  37. package/dist/collection/components/pcm-card/pcm-card.js.map +1 -1
  38. package/dist/collection/components/pcm-chat-message/pcm-chat-message.css +554 -554
  39. package/dist/collection/components/pcm-chat-message/pcm-chat-message.js +3 -3
  40. package/dist/collection/components/pcm-chat-message/pcm-chat-message.js.map +1 -1
  41. package/dist/collection/components/pcm-drawer/pcm-drawer.css +102 -102
  42. package/dist/collection/components/pcm-drawer/pcm-drawer.js +1 -1
  43. package/dist/collection/components/pcm-drawer/pcm-drawer.js.map +1 -1
  44. package/dist/collection/components/pcm-hr-chat-modal/pcm-hr-chat-modal.css +854 -854
  45. package/dist/collection/components/pcm-hr-chat-modal/pcm-hr-chat-modal.js +5 -7
  46. package/dist/collection/components/pcm-hr-chat-modal/pcm-hr-chat-modal.js.map +1 -1
  47. package/dist/collection/components/pcm-htws-modal/pcm-htws-modal.css +95 -95
  48. package/dist/collection/components/pcm-htws-modal/pcm-htws-modal.js +1 -1
  49. package/dist/collection/components/pcm-htws-modal/pcm-htws-modal.js.map +1 -1
  50. package/dist/collection/components/pcm-hyzj-modal/pcm-hyzj-modal.js +2 -2
  51. package/dist/collection/components/pcm-hyzj-modal/pcm-hyzj-modal.js.map +1 -1
  52. package/dist/collection/components/pcm-jd-modal/pcm-jd-modal.css +312 -312
  53. package/dist/collection/components/pcm-jd-modal/pcm-jd-modal.js +1 -1
  54. package/dist/collection/components/pcm-jd-modal/pcm-jd-modal.js.map +1 -1
  55. package/dist/collection/components/pcm-jlpp-modal/pcm-jlpp-modal.js +2 -2
  56. package/dist/collection/components/pcm-jlpp-modal/pcm-jlpp-modal.js.map +1 -1
  57. package/dist/collection/components/pcm-message/pcm-message.css +64 -64
  58. package/dist/collection/components/pcm-message/pcm-message.js +2 -2
  59. package/dist/collection/components/pcm-message/pcm-message.js.map +1 -1
  60. package/dist/collection/components/pcm-mnct-modal/pcm-mnct-modal.css +1 -1
  61. package/dist/collection/components/pcm-mnct-modal/pcm-mnct-modal.js +2 -2
  62. package/dist/collection/components/pcm-mnct-modal/pcm-mnct-modal.js.map +1 -1
  63. package/dist/collection/components/pcm-mnms-modal/pcm-mnms-modal.js +67 -84
  64. package/dist/collection/components/pcm-mnms-modal/pcm-mnms-modal.js.map +1 -1
  65. package/dist/collection/components/pcm-mnms-video-modal/pcm-mnms-video-modal.js +2 -2
  66. package/dist/collection/components/pcm-mnms-video-modal/pcm-mnms-video-modal.js.map +1 -1
  67. package/dist/collection/components/pcm-mnms-zp-modal/pcm-mnms-zp-modal.js +67 -84
  68. package/dist/collection/components/pcm-mnms-zp-modal/pcm-mnms-zp-modal.js.map +1 -1
  69. package/dist/collection/components/pcm-mobile-input-btn/pcm-mobile-input-btn.css +140 -0
  70. package/dist/collection/components/pcm-mobile-input-btn/pcm-mobile-input-btn.js +307 -0
  71. package/dist/collection/components/pcm-mobile-input-btn/pcm-mobile-input-btn.js.map +1 -0
  72. package/dist/collection/components/pcm-mobile-input-btn/uploadNumberSDK.js +25 -0
  73. package/dist/collection/components/pcm-mobile-input-btn/uploadNumberSDK.js.map +1 -0
  74. package/dist/collection/components/pcm-mobile-upload-btn/pcm-mobile-upload-btn.css +127 -0
  75. package/dist/collection/components/pcm-mobile-upload-btn/pcm-mobile-upload-btn.js +350 -0
  76. package/dist/collection/components/pcm-mobile-upload-btn/pcm-mobile-upload-btn.js.map +1 -0
  77. package/dist/collection/components/pcm-mobile-upload-btn/uploadNumberSDK.js +25 -0
  78. package/dist/collection/components/pcm-mobile-upload-btn/uploadNumberSDK.js.map +1 -0
  79. package/dist/collection/components/pcm-msbg-modal/pcm-msbg-modal.js +2 -2
  80. package/dist/collection/components/pcm-msbg-modal/pcm-msbg-modal.js.map +1 -1
  81. package/dist/collection/components/pcm-qgqjl-modal/pcm-qgqjl-modal.css +1 -1
  82. package/dist/collection/components/pcm-qgqjl-modal/pcm-qgqjl-modal.js +2 -2
  83. package/dist/collection/components/pcm-qgqjl-modal/pcm-qgqjl-modal.js.map +1 -1
  84. package/dist/collection/components/pcm-time-count-down/pcm-time-count-down.css +0 -0
  85. package/dist/collection/components/pcm-time-count-down/pcm-time-count-down.js +106 -0
  86. package/dist/collection/components/pcm-time-count-down/pcm-time-count-down.js.map +1 -0
  87. package/dist/collection/components/pcm-upload/pcm-upload.css +0 -0
  88. package/dist/collection/components/pcm-upload/pcm-upload.js +408 -0
  89. package/dist/collection/components/pcm-upload/pcm-upload.js.map +1 -0
  90. package/dist/collection/components/pcm-zsk-chat-modal/pcm-zsk-chat-modal.css +969 -969
  91. package/dist/collection/components/pcm-zsk-chat-modal/pcm-zsk-chat-modal.js +3 -5
  92. package/dist/collection/components/pcm-zsk-chat-modal/pcm-zsk-chat-modal.js.map +1 -1
  93. package/dist/collection/components/pcm-zygh-modal/pcm-zygh-modal.css +68 -68
  94. package/dist/collection/components/pcm-zygh-modal/pcm-zygh-modal.js +4 -4
  95. package/dist/collection/components/pcm-zygh-modal/pcm-zygh-modal.js.map +1 -1
  96. package/dist/collection/global/global.css +401 -398
  97. package/dist/collection/global/markdown.css +1233 -1233
  98. package/dist/collection/global/message.js.map +1 -1
  99. package/dist/collection/index.js.map +1 -1
  100. package/dist/collection/interfaces/chat.js.map +1 -1
  101. package/dist/collection/interfaces/events.js.map +1 -1
  102. package/dist/collection/services/message.service.js.map +1 -1
  103. package/dist/collection/utils/env.js +3 -0
  104. package/dist/collection/utils/env.js.map +1 -1
  105. package/dist/collection/utils/error-event.js.map +1 -1
  106. package/dist/collection/utils/init.js.map +1 -1
  107. package/dist/collection/utils/sentry-reporter.js.map +1 -1
  108. package/dist/collection/utils/utils.js +48 -24
  109. package/dist/collection/utils/utils.js.map +1 -1
  110. package/dist/components/index.js +3 -5482
  111. package/dist/components/index.js.map +1 -1
  112. package/dist/components/{p-AYWZDCn8.js → p-B0WOTw9J.js} +51 -4
  113. package/dist/components/p-B0WOTw9J.js.map +1 -0
  114. package/dist/components/{p-DUQ46MUh.js → p-BGXbWUJg.js} +3 -3
  115. package/dist/components/{p-DUQ46MUh.js.map → p-BGXbWUJg.js.map} +1 -1
  116. package/dist/{esm/sentry-reporter-BFBS363a.js → components/p-BW3r6Lrf.js} +5 -32
  117. package/dist/components/p-BW3r6Lrf.js.map +1 -0
  118. package/dist/{esm/app-globals-Chti62re.js → components/p-BdiUKin5.js} +9619 -4296
  119. package/dist/components/p-BdiUKin5.js.map +1 -0
  120. package/dist/components/{p-FjtoYPVY.js → p-BywzltXy.js} +10 -9
  121. package/dist/components/p-BywzltXy.js.map +1 -0
  122. package/dist/components/p-C2OsjtRx.js +208 -0
  123. package/dist/components/p-C2OsjtRx.js.map +1 -0
  124. package/dist/components/{p-D2Z8casl.js → p-CuIvbaWY.js} +5 -5
  125. package/dist/components/p-CuIvbaWY.js.map +1 -0
  126. package/dist/components/p-D0ZMoyH8.js +251 -0
  127. package/dist/components/p-D0ZMoyH8.js.map +1 -0
  128. package/dist/components/{p-CjbFHLT7.js → p-De3VHEUn.js} +7 -71
  129. package/dist/components/p-De3VHEUn.js.map +1 -0
  130. package/dist/components/p-Dv8qvK0w.js +2646 -0
  131. package/dist/components/p-Dv8qvK0w.js.map +1 -0
  132. package/dist/components/p-RD3mwuBX.js +226 -0
  133. package/dist/components/p-RD3mwuBX.js.map +1 -0
  134. package/dist/components/p-njngFX_n.js +80 -0
  135. package/dist/components/p-njngFX_n.js.map +1 -0
  136. package/dist/components/pcm-1zhanshi-mnms-modal.js +7 -7
  137. package/dist/components/pcm-1zhanshi-mnms-modal.js.map +1 -1
  138. package/dist/components/pcm-app-chat-modal.js +1 -1
  139. package/dist/components/pcm-button.js +2 -2
  140. package/dist/components/pcm-button.js.map +1 -1
  141. package/dist/components/pcm-card.js +3 -3
  142. package/dist/components/pcm-card.js.map +1 -1
  143. package/dist/components/pcm-chat-message.js +1 -1
  144. package/dist/components/pcm-drawer.js +1 -1
  145. package/dist/components/pcm-hr-chat-modal.js +5 -4
  146. package/dist/components/pcm-hr-chat-modal.js.map +1 -1
  147. package/dist/components/pcm-htws-modal.js +8 -7
  148. package/dist/components/pcm-htws-modal.js.map +1 -1
  149. package/dist/components/pcm-hyzj-modal.js +8 -7
  150. package/dist/components/pcm-hyzj-modal.js.map +1 -1
  151. package/dist/components/pcm-jd-modal.js +8 -7
  152. package/dist/components/pcm-jd-modal.js.map +1 -1
  153. package/dist/components/pcm-jlpp-modal.js +8 -7
  154. package/dist/components/pcm-jlpp-modal.js.map +1 -1
  155. package/dist/components/pcm-message.js +3 -3
  156. package/dist/components/pcm-message.js.map +1 -1
  157. package/dist/components/pcm-mnct-modal.js +8 -7
  158. package/dist/components/pcm-mnct-modal.js.map +1 -1
  159. package/dist/components/pcm-mnms-modal.js +60 -90
  160. package/dist/components/pcm-mnms-modal.js.map +1 -1
  161. package/dist/components/pcm-mnms-video-modal.js +8 -7
  162. package/dist/components/pcm-mnms-video-modal.js.map +1 -1
  163. package/dist/components/pcm-mnms-zp-modal.js +60 -90
  164. package/dist/components/pcm-mnms-zp-modal.js.map +1 -1
  165. package/dist/components/pcm-mobile-input-btn.d.ts +11 -0
  166. package/dist/components/pcm-mobile-input-btn.js +9 -0
  167. package/dist/components/pcm-mobile-input-btn.js.map +1 -0
  168. package/dist/components/pcm-mobile-upload-btn.d.ts +11 -0
  169. package/dist/components/pcm-mobile-upload-btn.js +9 -0
  170. package/dist/components/pcm-mobile-upload-btn.js.map +1 -0
  171. package/dist/components/pcm-msbg-modal.js +8 -7
  172. package/dist/components/pcm-msbg-modal.js.map +1 -1
  173. package/dist/components/pcm-qgqjl-modal.js +8 -7
  174. package/dist/components/pcm-qgqjl-modal.js.map +1 -1
  175. package/dist/components/pcm-time-count-down.d.ts +11 -0
  176. package/dist/components/pcm-time-count-down.js +9 -0
  177. package/dist/components/pcm-time-count-down.js.map +1 -0
  178. package/dist/components/pcm-upload.d.ts +11 -0
  179. package/dist/components/pcm-upload.js +9 -0
  180. package/dist/components/pcm-upload.js.map +1 -0
  181. package/dist/components/pcm-zsk-chat-modal.js +4 -4
  182. package/dist/components/pcm-zsk-chat-modal.js.map +1 -1
  183. package/dist/components/pcm-zygh-modal.js +8 -7
  184. package/dist/components/pcm-zygh-modal.js.map +1 -1
  185. package/dist/esm/error-event-C0FYX2-Z.js +31 -0
  186. package/dist/esm/error-event-C0FYX2-Z.js.map +1 -0
  187. package/dist/esm/{index-GyOE8SlD.js → index-BnNqOUZf.js} +51 -4
  188. package/dist/esm/index-BnNqOUZf.js.map +1 -0
  189. package/dist/esm/index-BuVfV0zo.js +11035 -0
  190. package/dist/esm/index-BuVfV0zo.js.map +1 -0
  191. package/dist/esm/index.js +2 -2
  192. package/dist/esm/loader.js +3 -5
  193. package/dist/esm/loader.js.map +1 -1
  194. package/dist/esm/message.service-DXVhHj6-.js +133 -0
  195. package/dist/esm/message.service-DXVhHj6-.js.map +1 -0
  196. package/dist/esm/{pcm-1zhanshi-mnms-modal_17.entry.js → pcm-1zhanshi-mnms-modal_21.entry.js} +3225 -169
  197. package/dist/esm/pcm-1zhanshi-mnms-modal_21.entry.js.map +1 -0
  198. package/dist/esm/pcm-agents.js +4 -6
  199. package/dist/esm/pcm-agents.js.map +1 -1
  200. package/dist/esm/pcm-message.entry.js +3 -3
  201. package/dist/esm/pcm-message.entry.js.map +1 -1
  202. package/dist/esm/pcm-mnms-video-modal.entry.js +5 -5
  203. package/dist/esm/pcm-mnms-video-modal.entry.js.map +1 -1
  204. package/dist/esm/pcm-mnms-zp-modal.entry.js +28 -85
  205. package/dist/esm/pcm-mnms-zp-modal.entry.js.map +1 -1
  206. package/dist/esm/sentry-reporter-CYzy4_8O.js +70 -0
  207. package/dist/esm/sentry-reporter-CYzy4_8O.js.map +1 -0
  208. package/dist/pcm-agents/index.esm.js +1 -1
  209. package/dist/pcm-agents/loader.esm.js.map +1 -1
  210. package/dist/pcm-agents/p-18a06873.entry.js +2 -0
  211. package/dist/pcm-agents/p-18a06873.entry.js.map +1 -0
  212. package/dist/pcm-agents/p-47e2e1d0.entry.js +2 -0
  213. package/dist/pcm-agents/p-47e2e1d0.entry.js.map +1 -0
  214. package/dist/pcm-agents/{p-3608c0c6.entry.js → p-7a582f00.entry.js} +2 -2
  215. package/dist/pcm-agents/p-7a582f00.entry.js.map +1 -0
  216. package/dist/pcm-agents/p-BhFnI70g.js +2 -0
  217. package/dist/pcm-agents/p-BhFnI70g.js.map +1 -0
  218. package/dist/pcm-agents/p-BuVfV0zo.js +3 -0
  219. package/dist/pcm-agents/p-BuVfV0zo.js.map +1 -0
  220. package/dist/pcm-agents/p-C0FYX2-Z.js +2 -0
  221. package/dist/pcm-agents/p-C0FYX2-Z.js.map +1 -0
  222. package/dist/pcm-agents/p-DXVhHj6-.js +2 -0
  223. package/dist/pcm-agents/p-DXVhHj6-.js.map +1 -0
  224. package/dist/pcm-agents/p-DkeaAFic.js +2 -0
  225. package/dist/pcm-agents/p-DkeaAFic.js.map +1 -0
  226. package/dist/pcm-agents/p-f5f96853.entry.js +245 -0
  227. package/dist/pcm-agents/p-f5f96853.entry.js.map +1 -0
  228. package/dist/pcm-agents/pcm-agents.esm.js +1 -1
  229. package/dist/pcm-agents/pcm-agents.esm.js.map +1 -1
  230. package/dist/pcm-agents/pcm-message.entry.esm.js.map +1 -1
  231. package/dist/pcm-agents/pcm-mnms-video-modal.entry.esm.js.map +1 -1
  232. package/dist/pcm-agents/pcm-mnms-zp-modal.entry.esm.js.map +1 -1
  233. package/dist/store/auth.store.js.map +1 -1
  234. package/dist/store/config.store.js.map +1 -1
  235. package/dist/types/components/pcm-mnms-modal/pcm-mnms-modal.d.ts +9 -4
  236. package/dist/types/components/pcm-mnms-zp-modal/pcm-mnms-zp-modal.d.ts +9 -4
  237. package/dist/types/components/pcm-mobile-input-btn/pcm-mobile-input-btn.d.ts +36 -0
  238. package/dist/types/components/pcm-mobile-input-btn/uploadNumberSDK.d.ts +9 -0
  239. package/dist/types/components/pcm-mobile-upload-btn/pcm-mobile-upload-btn.d.ts +44 -0
  240. package/dist/types/components/pcm-mobile-upload-btn/uploadNumberSDK.d.ts +9 -0
  241. package/dist/types/components/pcm-time-count-down/pcm-time-count-down.d.ts +15 -0
  242. package/dist/types/components/pcm-upload/pcm-upload.d.ts +54 -0
  243. package/dist/types/components/pcm-upload/type.d.ts +4 -0
  244. package/dist/types/components.d.ts +798 -30
  245. package/dist/types/stencil-public-runtime.d.ts +1 -1
  246. package/dist/types/utils/env.d.ts +2 -0
  247. package/dist/types/utils/utils.d.ts +30 -12
  248. package/package.json +70 -69
  249. package/dist/cjs/app-globals-BIO4q6tX.js +0 -5487
  250. package/dist/cjs/app-globals-BIO4q6tX.js.map +0 -1
  251. package/dist/cjs/exports-Dc-pQh4A.js +0 -4087
  252. package/dist/cjs/exports-Dc-pQh4A.js.map +0 -1
  253. package/dist/cjs/index-C_qhED9Z.js +0 -1538
  254. package/dist/cjs/index-C_qhED9Z.js.map +0 -1
  255. package/dist/cjs/index-CvEfNyEj.js.map +0 -1
  256. package/dist/cjs/pcm-1zhanshi-mnms-modal_17.cjs.entry.js.map +0 -1
  257. package/dist/cjs/sentry-reporter-BWFtw_aT.js.map +0 -1
  258. package/dist/components/p-75J0r72D.js +0 -4017
  259. package/dist/components/p-75J0r72D.js.map +0 -1
  260. package/dist/components/p-AYWZDCn8.js.map +0 -1
  261. package/dist/components/p-CR7WLzmM.js +0 -1303
  262. package/dist/components/p-CR7WLzmM.js.map +0 -1
  263. package/dist/components/p-CjbFHLT7.js.map +0 -1
  264. package/dist/components/p-D2Z8casl.js.map +0 -1
  265. package/dist/components/p-FjtoYPVY.js.map +0 -1
  266. package/dist/esm/app-globals-Chti62re.js.map +0 -1
  267. package/dist/esm/exports-Bs-zO1WZ.js +0 -4017
  268. package/dist/esm/exports-Bs-zO1WZ.js.map +0 -1
  269. package/dist/esm/index-Bq0K-WqZ.js +0 -1528
  270. package/dist/esm/index-Bq0K-WqZ.js.map +0 -1
  271. package/dist/esm/index-GyOE8SlD.js.map +0 -1
  272. package/dist/esm/pcm-1zhanshi-mnms-modal_17.entry.js.map +0 -1
  273. package/dist/esm/sentry-reporter-BFBS363a.js.map +0 -1
  274. package/dist/pcm-agents/p-2Gpw8rvH.js +0 -2
  275. package/dist/pcm-agents/p-2Gpw8rvH.js.map +0 -1
  276. package/dist/pcm-agents/p-3608c0c6.entry.js.map +0 -1
  277. package/dist/pcm-agents/p-60d7a0b0.entry.js +0 -2
  278. package/dist/pcm-agents/p-60d7a0b0.entry.js.map +0 -1
  279. package/dist/pcm-agents/p-9e6efc2d.entry.js +0 -2
  280. package/dist/pcm-agents/p-9e6efc2d.entry.js.map +0 -1
  281. package/dist/pcm-agents/p-BUV0S8Cc.js +0 -2
  282. package/dist/pcm-agents/p-BUV0S8Cc.js.map +0 -1
  283. package/dist/pcm-agents/p-Bq0K-WqZ.js +0 -3
  284. package/dist/pcm-agents/p-Bq0K-WqZ.js.map +0 -1
  285. package/dist/pcm-agents/p-Bs-zO1WZ.js +0 -2
  286. package/dist/pcm-agents/p-Bs-zO1WZ.js.map +0 -1
  287. package/dist/pcm-agents/p-CeRTfvY9.js +0 -2
  288. package/dist/pcm-agents/p-CeRTfvY9.js.map +0 -1
  289. package/dist/pcm-agents/p-e6c87a78.entry.js +0 -2
  290. package/dist/pcm-agents/p-e6c87a78.entry.js.map +0 -1
  291. /package/dist/types/{code/agents-sdk → Users/debugksir/Documents/pcm/sdk}/packages/pcm-agents/.stencil/store/auth.store.d.ts +0 -0
  292. /package/dist/types/{code/agents-sdk → Users/debugksir/Documents/pcm/sdk}/packages/pcm-agents/.stencil/store/config.store.d.ts +0 -0
@@ -1,4017 +0,0 @@
1
- /**
2
- * This serves as a build time flag that will be true by default, but false in non-debug builds or if users replace `__SENTRY_DEBUG__` in their generated code.
3
- *
4
- * ATTENTION: This constant must never cross package boundaries (i.e. be exported) to guarantee that it can be used for tree shaking.
5
- */
6
- const DEBUG_BUILD = (typeof __SENTRY_DEBUG__ === 'undefined' || __SENTRY_DEBUG__);
7
-
8
- // This is a magic string replaced by rollup
9
-
10
- const SDK_VERSION = "9.22.0" ;
11
-
12
- /** Internal global with common properties and Sentry extensions */
13
-
14
- /** Get's the global object for the current JavaScript runtime */
15
- const GLOBAL_OBJ = globalThis ;
16
-
17
- /**
18
- * An object that contains globally accessible properties and maintains a scope stack.
19
- * @hidden
20
- */
21
-
22
- /**
23
- * Returns the global shim registry.
24
- *
25
- * FIXME: This function is problematic, because despite always returning a valid Carrier,
26
- * it has an optional `__SENTRY__` property, which then in turn requires us to always perform an unnecessary check
27
- * at the call-site. We always access the carrier through this function, so we can guarantee that `__SENTRY__` is there.
28
- **/
29
- function getMainCarrier() {
30
- // This ensures a Sentry carrier exists
31
- getSentryCarrier(GLOBAL_OBJ);
32
- return GLOBAL_OBJ;
33
- }
34
-
35
- /** Will either get the existing sentry carrier, or create a new one. */
36
- function getSentryCarrier(carrier) {
37
- const __SENTRY__ = (carrier.__SENTRY__ = carrier.__SENTRY__ || {});
38
-
39
- // For now: First SDK that sets the .version property wins
40
- __SENTRY__.version = __SENTRY__.version || SDK_VERSION;
41
-
42
- // Intentionally populating and returning the version of "this" SDK instance
43
- // rather than what's set in .version so that "this" SDK always gets its carrier
44
- return (__SENTRY__[SDK_VERSION] = __SENTRY__[SDK_VERSION] || {});
45
- }
46
-
47
- /**
48
- * Returns a global singleton contained in the global `__SENTRY__[]` object.
49
- *
50
- * If the singleton doesn't already exist in `__SENTRY__`, it will be created using the given factory
51
- * function and added to the `__SENTRY__` object.
52
- *
53
- * @param name name of the global singleton on __SENTRY__
54
- * @param creator creator Factory function to create the singleton if it doesn't already exist on `__SENTRY__`
55
- * @param obj (Optional) The global object on which to look for `__SENTRY__`, if not `GLOBAL_OBJ`'s return value
56
- * @returns the singleton
57
- */
58
- function getGlobalSingleton(
59
- name,
60
- creator,
61
- obj = GLOBAL_OBJ,
62
- ) {
63
- const __SENTRY__ = (obj.__SENTRY__ = obj.__SENTRY__ || {});
64
- const carrier = (__SENTRY__[SDK_VERSION] = __SENTRY__[SDK_VERSION] || {});
65
- // Note: We do not want to set `carrier.version` here, as this may be called before any `init` is called, e.g. for the default scopes
66
- return carrier[name] || (carrier[name] = creator());
67
- }
68
-
69
- // eslint-disable-next-line @typescript-eslint/unbound-method
70
- const objectToString = Object.prototype.toString;
71
-
72
- /**
73
- * Checks whether given value's type is one of a few Error or Error-like
74
- * {@link isError}.
75
- *
76
- * @param wat A value to be checked.
77
- * @returns A boolean representing the result.
78
- */
79
- function isError(wat) {
80
- switch (objectToString.call(wat)) {
81
- case '[object Error]':
82
- case '[object Exception]':
83
- case '[object DOMException]':
84
- case '[object WebAssembly.Exception]':
85
- return true;
86
- default:
87
- return isInstanceOf(wat, Error);
88
- }
89
- }
90
- /**
91
- * Checks whether given value is an instance of the given built-in class.
92
- *
93
- * @param wat The value to be checked
94
- * @param className
95
- * @returns A boolean representing the result.
96
- */
97
- function isBuiltin(wat, className) {
98
- return objectToString.call(wat) === `[object ${className}]`;
99
- }
100
-
101
- /**
102
- * Checks whether given value's type is ErrorEvent
103
- * {@link isErrorEvent}.
104
- *
105
- * @param wat A value to be checked.
106
- * @returns A boolean representing the result.
107
- */
108
- function isErrorEvent(wat) {
109
- return isBuiltin(wat, 'ErrorEvent');
110
- }
111
-
112
- /**
113
- * Checks whether given value's type is DOMError
114
- * {@link isDOMError}.
115
- *
116
- * @param wat A value to be checked.
117
- * @returns A boolean representing the result.
118
- */
119
- function isDOMError(wat) {
120
- return isBuiltin(wat, 'DOMError');
121
- }
122
-
123
- /**
124
- * Checks whether given value's type is DOMException
125
- * {@link isDOMException}.
126
- *
127
- * @param wat A value to be checked.
128
- * @returns A boolean representing the result.
129
- */
130
- function isDOMException(wat) {
131
- return isBuiltin(wat, 'DOMException');
132
- }
133
-
134
- /**
135
- * Checks whether given value's type is a string
136
- * {@link isString}.
137
- *
138
- * @param wat A value to be checked.
139
- * @returns A boolean representing the result.
140
- */
141
- function isString(wat) {
142
- return isBuiltin(wat, 'String');
143
- }
144
-
145
- /**
146
- * Checks whether given string is parameterized
147
- * {@link isParameterizedString}.
148
- *
149
- * @param wat A value to be checked.
150
- * @returns A boolean representing the result.
151
- */
152
- function isParameterizedString(wat) {
153
- return (
154
- typeof wat === 'object' &&
155
- wat !== null &&
156
- '__sentry_template_string__' in wat &&
157
- '__sentry_template_values__' in wat
158
- );
159
- }
160
-
161
- /**
162
- * Checks whether given value is a primitive (undefined, null, number, boolean, string, bigint, symbol)
163
- * {@link isPrimitive}.
164
- *
165
- * @param wat A value to be checked.
166
- * @returns A boolean representing the result.
167
- */
168
- function isPrimitive(wat) {
169
- return wat === null || isParameterizedString(wat) || (typeof wat !== 'object' && typeof wat !== 'function');
170
- }
171
-
172
- /**
173
- * Checks whether given value's type is an object literal, or a class instance.
174
- * {@link isPlainObject}.
175
- *
176
- * @param wat A value to be checked.
177
- * @returns A boolean representing the result.
178
- */
179
- function isPlainObject(wat) {
180
- return isBuiltin(wat, 'Object');
181
- }
182
-
183
- /**
184
- * Checks whether given value's type is an Event instance
185
- * {@link isEvent}.
186
- *
187
- * @param wat A value to be checked.
188
- * @returns A boolean representing the result.
189
- */
190
- function isEvent(wat) {
191
- return typeof Event !== 'undefined' && isInstanceOf(wat, Event);
192
- }
193
-
194
- /**
195
- * Checks whether given value's type is an Element instance
196
- * {@link isElement}.
197
- *
198
- * @param wat A value to be checked.
199
- * @returns A boolean representing the result.
200
- */
201
- function isElement(wat) {
202
- return typeof Element !== 'undefined' && isInstanceOf(wat, Element);
203
- }
204
-
205
- /**
206
- * Checks whether given value's type is an regexp
207
- * {@link isRegExp}.
208
- *
209
- * @param wat A value to be checked.
210
- * @returns A boolean representing the result.
211
- */
212
- function isRegExp(wat) {
213
- return isBuiltin(wat, 'RegExp');
214
- }
215
-
216
- /**
217
- * Checks whether given value has a then function.
218
- * @param wat A value to be checked.
219
- */
220
- function isThenable(wat) {
221
- // eslint-disable-next-line @typescript-eslint/no-unsafe-member-access
222
- return Boolean(wat?.then && typeof wat.then === 'function');
223
- }
224
-
225
- /**
226
- * Checks whether given value's type is a SyntheticEvent
227
- * {@link isSyntheticEvent}.
228
- *
229
- * @param wat A value to be checked.
230
- * @returns A boolean representing the result.
231
- */
232
- function isSyntheticEvent(wat) {
233
- return isPlainObject(wat) && 'nativeEvent' in wat && 'preventDefault' in wat && 'stopPropagation' in wat;
234
- }
235
-
236
- /**
237
- * Checks whether given value's type is an instance of provided constructor.
238
- * {@link isInstanceOf}.
239
- *
240
- * @param wat A value to be checked.
241
- * @param base A constructor to be used in a check.
242
- * @returns A boolean representing the result.
243
- */
244
- function isInstanceOf(wat, base) {
245
- try {
246
- return wat instanceof base;
247
- } catch (_e) {
248
- return false;
249
- }
250
- }
251
-
252
- /**
253
- * Checks whether given value's type is a Vue ViewModel.
254
- *
255
- * @param wat A value to be checked.
256
- * @returns A boolean representing the result.
257
- */
258
- function isVueViewModel(wat) {
259
- // Not using Object.prototype.toString because in Vue 3 it would read the instance's Symbol(Symbol.toStringTag) property.
260
- return !!(typeof wat === 'object' && wat !== null && ((wat ).__isVue || (wat )._isVue));
261
- }
262
-
263
- /**
264
- * Checks whether the given parameter is a Standard Web API Request instance.
265
- *
266
- * Returns false if Request is not available in the current runtime.
267
- */
268
- function isRequest(request) {
269
- return typeof Request !== 'undefined' && isInstanceOf(request, Request);
270
- }
271
-
272
- const WINDOW = GLOBAL_OBJ ;
273
-
274
- const DEFAULT_MAX_STRING_LENGTH = 80;
275
-
276
- /**
277
- * Given a child DOM element, returns a query-selector statement describing that
278
- * and its ancestors
279
- * e.g. [HTMLElement] => body > div > input#foo.btn[name=baz]
280
- * @returns generated DOM path
281
- */
282
- function htmlTreeAsString(
283
- elem,
284
- options = {},
285
- ) {
286
- if (!elem) {
287
- return '<unknown>';
288
- }
289
-
290
- // try/catch both:
291
- // - accessing event.target (see getsentry/raven-js#838, #768)
292
- // - `htmlTreeAsString` because it's complex, and just accessing the DOM incorrectly
293
- // - can throw an exception in some circumstances.
294
- try {
295
- let currentElem = elem ;
296
- const MAX_TRAVERSE_HEIGHT = 5;
297
- const out = [];
298
- let height = 0;
299
- let len = 0;
300
- const separator = ' > ';
301
- const sepLength = separator.length;
302
- let nextStr;
303
- const keyAttrs = Array.isArray(options) ? options : options.keyAttrs;
304
- const maxStringLength = (!Array.isArray(options) && options.maxStringLength) || DEFAULT_MAX_STRING_LENGTH;
305
-
306
- while (currentElem && height++ < MAX_TRAVERSE_HEIGHT) {
307
- nextStr = _htmlElementAsString(currentElem, keyAttrs);
308
- // bail out if
309
- // - nextStr is the 'html' element
310
- // - the length of the string that would be created exceeds maxStringLength
311
- // (ignore this limit if we are on the first iteration)
312
- if (nextStr === 'html' || (height > 1 && len + out.length * sepLength + nextStr.length >= maxStringLength)) {
313
- break;
314
- }
315
-
316
- out.push(nextStr);
317
-
318
- len += nextStr.length;
319
- currentElem = currentElem.parentNode;
320
- }
321
-
322
- return out.reverse().join(separator);
323
- } catch (_oO) {
324
- return '<unknown>';
325
- }
326
- }
327
-
328
- /**
329
- * Returns a simple, query-selector representation of a DOM element
330
- * e.g. [HTMLElement] => input#foo.btn[name=baz]
331
- * @returns generated DOM path
332
- */
333
- function _htmlElementAsString(el, keyAttrs) {
334
- const elem = el
335
-
336
- ;
337
-
338
- const out = [];
339
-
340
- if (!elem?.tagName) {
341
- return '';
342
- }
343
-
344
- // @ts-expect-error WINDOW has HTMLElement
345
- if (WINDOW.HTMLElement) {
346
- // If using the component name annotation plugin, this value may be available on the DOM node
347
- if (elem instanceof HTMLElement && elem.dataset) {
348
- if (elem.dataset['sentryComponent']) {
349
- return elem.dataset['sentryComponent'];
350
- }
351
- if (elem.dataset['sentryElement']) {
352
- return elem.dataset['sentryElement'];
353
- }
354
- }
355
- }
356
-
357
- out.push(elem.tagName.toLowerCase());
358
-
359
- // Pairs of attribute keys defined in `serializeAttribute` and their values on element.
360
- const keyAttrPairs = keyAttrs?.length
361
- ? keyAttrs.filter(keyAttr => elem.getAttribute(keyAttr)).map(keyAttr => [keyAttr, elem.getAttribute(keyAttr)])
362
- : null;
363
-
364
- if (keyAttrPairs?.length) {
365
- keyAttrPairs.forEach(keyAttrPair => {
366
- out.push(`[${keyAttrPair[0]}="${keyAttrPair[1]}"]`);
367
- });
368
- } else {
369
- if (elem.id) {
370
- out.push(`#${elem.id}`);
371
- }
372
-
373
- const className = elem.className;
374
- if (className && isString(className)) {
375
- const classes = className.split(/\s+/);
376
- for (const c of classes) {
377
- out.push(`.${c}`);
378
- }
379
- }
380
- }
381
- const allowedAttrs = ['aria-label', 'type', 'name', 'title', 'alt'];
382
- for (const k of allowedAttrs) {
383
- const attr = elem.getAttribute(k);
384
- if (attr) {
385
- out.push(`[${k}="${attr}"]`);
386
- }
387
- }
388
-
389
- return out.join('');
390
- }
391
-
392
- /**
393
- * A safe form of location.href
394
- */
395
- function getLocationHref() {
396
- try {
397
- return WINDOW.document.location.href;
398
- } catch (oO) {
399
- return '';
400
- }
401
- }
402
-
403
- /**
404
- * Given a DOM element, traverses up the tree until it finds the first ancestor node
405
- * that has the `data-sentry-component` or `data-sentry-element` attribute with `data-sentry-component` taking
406
- * precedence. This attribute is added at build-time by projects that have the component name annotation plugin installed.
407
- *
408
- * @returns a string representation of the component for the provided DOM element, or `null` if not found
409
- */
410
- function getComponentName(elem) {
411
- // @ts-expect-error WINDOW has HTMLElement
412
- if (!WINDOW.HTMLElement) {
413
- return null;
414
- }
415
-
416
- let currentElem = elem ;
417
- const MAX_TRAVERSE_HEIGHT = 5;
418
- for (let i = 0; i < MAX_TRAVERSE_HEIGHT; i++) {
419
- if (!currentElem) {
420
- return null;
421
- }
422
-
423
- if (currentElem instanceof HTMLElement) {
424
- if (currentElem.dataset['sentryComponent']) {
425
- return currentElem.dataset['sentryComponent'];
426
- }
427
- if (currentElem.dataset['sentryElement']) {
428
- return currentElem.dataset['sentryElement'];
429
- }
430
- }
431
-
432
- currentElem = currentElem.parentNode;
433
- }
434
-
435
- return null;
436
- }
437
-
438
- /** Prefix for logging strings */
439
- const PREFIX = 'Sentry Logger ';
440
-
441
- const CONSOLE_LEVELS = [
442
- 'debug',
443
- 'info',
444
- 'warn',
445
- 'error',
446
- 'log',
447
- 'assert',
448
- 'trace',
449
- ] ;
450
-
451
- /** This may be mutated by the console instrumentation. */
452
- const originalConsoleMethods
453
-
454
- = {};
455
-
456
- /** A Sentry Logger instance. */
457
-
458
- /**
459
- * Temporarily disable sentry console instrumentations.
460
- *
461
- * @param callback The function to run against the original `console` messages
462
- * @returns The results of the callback
463
- */
464
- function consoleSandbox(callback) {
465
- if (!('console' in GLOBAL_OBJ)) {
466
- return callback();
467
- }
468
-
469
- const console = GLOBAL_OBJ.console ;
470
- const wrappedFuncs = {};
471
-
472
- const wrappedLevels = Object.keys(originalConsoleMethods) ;
473
-
474
- // Restore all wrapped console methods
475
- wrappedLevels.forEach(level => {
476
- const originalConsoleMethod = originalConsoleMethods[level] ;
477
- wrappedFuncs[level] = console[level] ;
478
- console[level] = originalConsoleMethod;
479
- });
480
-
481
- try {
482
- return callback();
483
- } finally {
484
- // Revert restoration to wrapped state
485
- wrappedLevels.forEach(level => {
486
- console[level] = wrappedFuncs[level] ;
487
- });
488
- }
489
- }
490
-
491
- function makeLogger() {
492
- let enabled = false;
493
- const logger = {
494
- enable: () => {
495
- enabled = true;
496
- },
497
- disable: () => {
498
- enabled = false;
499
- },
500
- isEnabled: () => enabled,
501
- };
502
-
503
- if (DEBUG_BUILD) {
504
- CONSOLE_LEVELS.forEach(name => {
505
- logger[name] = (...args) => {
506
- if (enabled) {
507
- consoleSandbox(() => {
508
- GLOBAL_OBJ.console[name](`${PREFIX}[${name}]:`, ...args);
509
- });
510
- }
511
- };
512
- });
513
- } else {
514
- CONSOLE_LEVELS.forEach(name => {
515
- logger[name] = () => undefined;
516
- });
517
- }
518
-
519
- return logger ;
520
- }
521
-
522
- /**
523
- * This is a logger singleton which either logs things or no-ops if logging is not enabled.
524
- * The logger is a singleton on the carrier, to ensure that a consistent logger is used throughout the SDK.
525
- */
526
- const logger = getGlobalSingleton('logger', makeLogger);
527
-
528
- /**
529
- * Truncates given string to the maximum characters count
530
- *
531
- * @param str An object that contains serializable values
532
- * @param max Maximum number of characters in truncated string (0 = unlimited)
533
- * @returns string Encoded
534
- */
535
- function truncate(str, max = 0) {
536
- if (typeof str !== 'string' || max === 0) {
537
- return str;
538
- }
539
- return str.length <= max ? str : `${str.slice(0, max)}...`;
540
- }
541
-
542
- /**
543
- * Join values in array
544
- * @param input array of values to be joined together
545
- * @param delimiter string to be placed in-between values
546
- * @returns Joined values
547
- */
548
- function safeJoin(input, delimiter) {
549
- if (!Array.isArray(input)) {
550
- return '';
551
- }
552
-
553
- const output = [];
554
- // eslint-disable-next-line @typescript-eslint/prefer-for-of
555
- for (let i = 0; i < input.length; i++) {
556
- const value = input[i];
557
- try {
558
- // This is a hack to fix a Vue3-specific bug that causes an infinite loop of
559
- // console warnings. This happens when a Vue template is rendered with
560
- // an undeclared variable, which we try to stringify, ultimately causing
561
- // Vue to issue another warning which repeats indefinitely.
562
- // see: https://github.com/getsentry/sentry-javascript/pull/8981
563
- if (isVueViewModel(value)) {
564
- output.push('[VueViewModel]');
565
- } else {
566
- output.push(String(value));
567
- }
568
- } catch (e) {
569
- output.push('[value cannot be serialized]');
570
- }
571
- }
572
-
573
- return output.join(delimiter);
574
- }
575
-
576
- /**
577
- * Checks if the given value matches a regex or string
578
- *
579
- * @param value The string to test
580
- * @param pattern Either a regex or a string against which `value` will be matched
581
- * @param requireExactStringMatch If true, `value` must match `pattern` exactly. If false, `value` will match
582
- * `pattern` if it contains `pattern`. Only applies to string-type patterns.
583
- */
584
- function isMatchingPattern(
585
- value,
586
- pattern,
587
- requireExactStringMatch = false,
588
- ) {
589
- if (!isString(value)) {
590
- return false;
591
- }
592
-
593
- if (isRegExp(pattern)) {
594
- return pattern.test(value);
595
- }
596
- if (isString(pattern)) {
597
- return requireExactStringMatch ? value === pattern : value.includes(pattern);
598
- }
599
-
600
- return false;
601
- }
602
-
603
- /**
604
- * Test the given string against an array of strings and regexes. By default, string matching is done on a
605
- * substring-inclusion basis rather than a strict equality basis
606
- *
607
- * @param testString The string to test
608
- * @param patterns The patterns against which to test the string
609
- * @param requireExactStringMatch If true, `testString` must match one of the given string patterns exactly in order to
610
- * count. If false, `testString` will match a string pattern if it contains that pattern.
611
- * @returns
612
- */
613
- function stringMatchesSomePattern(
614
- testString,
615
- patterns = [],
616
- requireExactStringMatch = false,
617
- ) {
618
- return patterns.some(pattern => isMatchingPattern(testString, pattern, requireExactStringMatch));
619
- }
620
-
621
- /**
622
- * Replace a method in an object with a wrapped version of itself.
623
- *
624
- * If the method on the passed object is not a function, the wrapper will not be applied.
625
- *
626
- * @param source An object that contains a method to be wrapped.
627
- * @param name The name of the method to be wrapped.
628
- * @param replacementFactory A higher-order function that takes the original version of the given method and returns a
629
- * wrapped version. Note: The function returned by `replacementFactory` needs to be a non-arrow function, in order to
630
- * preserve the correct value of `this`, and the original method must be called using `origMethod.call(this, <other
631
- * args>)` or `origMethod.apply(this, [<other args>])` (rather than being called directly), again to preserve `this`.
632
- * @returns void
633
- */
634
- function fill(source, name, replacementFactory) {
635
- if (!(name in source)) {
636
- return;
637
- }
638
-
639
- // explicitly casting to unknown because we don't know the type of the method initially at all
640
- const original = source[name] ;
641
-
642
- if (typeof original !== 'function') {
643
- return;
644
- }
645
-
646
- const wrapped = replacementFactory(original) ;
647
-
648
- // Make sure it's a function first, as we need to attach an empty prototype for `defineProperties` to work
649
- // otherwise it'll throw "TypeError: Object.defineProperties called on non-object"
650
- if (typeof wrapped === 'function') {
651
- markFunctionWrapped(wrapped, original);
652
- }
653
-
654
- try {
655
- source[name] = wrapped;
656
- } catch {
657
- DEBUG_BUILD && logger.log(`Failed to replace method "${name}" in object`, source);
658
- }
659
- }
660
-
661
- /**
662
- * Defines a non-enumerable property on the given object.
663
- *
664
- * @param obj The object on which to set the property
665
- * @param name The name of the property to be set
666
- * @param value The value to which to set the property
667
- */
668
- function addNonEnumerableProperty(obj, name, value) {
669
- try {
670
- Object.defineProperty(obj, name, {
671
- // enumerable: false, // the default, so we can save on bundle size by not explicitly setting it
672
- value: value,
673
- writable: true,
674
- configurable: true,
675
- });
676
- } catch (o_O) {
677
- DEBUG_BUILD && logger.log(`Failed to add non-enumerable property "${name}" to object`, obj);
678
- }
679
- }
680
-
681
- /**
682
- * Remembers the original function on the wrapped function and
683
- * patches up the prototype.
684
- *
685
- * @param wrapped the wrapper function
686
- * @param original the original function that gets wrapped
687
- */
688
- function markFunctionWrapped(wrapped, original) {
689
- try {
690
- const proto = original.prototype || {};
691
- wrapped.prototype = original.prototype = proto;
692
- addNonEnumerableProperty(wrapped, '__sentry_original__', original);
693
- } catch (o_O) {} // eslint-disable-line no-empty
694
- }
695
-
696
- /**
697
- * This extracts the original function if available. See
698
- * `markFunctionWrapped` for more information.
699
- *
700
- * @param func the function to unwrap
701
- * @returns the unwrapped version of the function if available.
702
- */
703
- // eslint-disable-next-line @typescript-eslint/ban-types
704
- function getOriginalFunction(func) {
705
- return func.__sentry_original__;
706
- }
707
-
708
- /**
709
- * Transforms any `Error` or `Event` into a plain object with all of their enumerable properties, and some of their
710
- * non-enumerable properties attached.
711
- *
712
- * @param value Initial source that we have to transform in order for it to be usable by the serializer
713
- * @returns An Event or Error turned into an object - or the value argument itself, when value is neither an Event nor
714
- * an Error.
715
- */
716
- function convertToPlainObject(value)
717
-
718
- {
719
- if (isError(value)) {
720
- return {
721
- message: value.message,
722
- name: value.name,
723
- stack: value.stack,
724
- ...getOwnProperties(value),
725
- };
726
- } else if (isEvent(value)) {
727
- const newObj
728
-
729
- = {
730
- type: value.type,
731
- target: serializeEventTarget(value.target),
732
- currentTarget: serializeEventTarget(value.currentTarget),
733
- ...getOwnProperties(value),
734
- };
735
-
736
- if (typeof CustomEvent !== 'undefined' && isInstanceOf(value, CustomEvent)) {
737
- newObj.detail = value.detail;
738
- }
739
-
740
- return newObj;
741
- } else {
742
- return value;
743
- }
744
- }
745
-
746
- /** Creates a string representation of the target of an `Event` object */
747
- function serializeEventTarget(target) {
748
- try {
749
- return isElement(target) ? htmlTreeAsString(target) : Object.prototype.toString.call(target);
750
- } catch (_oO) {
751
- return '<unknown>';
752
- }
753
- }
754
-
755
- /** Filters out all but an object's own properties */
756
- function getOwnProperties(obj) {
757
- if (typeof obj === 'object' && obj !== null) {
758
- const extractedProps = {};
759
- for (const property in obj) {
760
- if (Object.prototype.hasOwnProperty.call(obj, property)) {
761
- extractedProps[property] = (obj )[property];
762
- }
763
- }
764
- return extractedProps;
765
- } else {
766
- return {};
767
- }
768
- }
769
-
770
- /**
771
- * Given any captured exception, extract its keys and create a sorted
772
- * and truncated list that will be used inside the event message.
773
- * eg. `Non-error exception captured with keys: foo, bar, baz`
774
- */
775
- function extractExceptionKeysForMessage(exception, maxLength = 40) {
776
- const keys = Object.keys(convertToPlainObject(exception));
777
- keys.sort();
778
-
779
- const firstKey = keys[0];
780
-
781
- if (!firstKey) {
782
- return '[object has no keys]';
783
- }
784
-
785
- if (firstKey.length >= maxLength) {
786
- return truncate(firstKey, maxLength);
787
- }
788
-
789
- for (let includedKeys = keys.length; includedKeys > 0; includedKeys--) {
790
- const serialized = keys.slice(0, includedKeys).join(', ');
791
- if (serialized.length > maxLength) {
792
- continue;
793
- }
794
- if (includedKeys === keys.length) {
795
- return serialized;
796
- }
797
- return truncate(serialized, maxLength);
798
- }
799
-
800
- return '';
801
- }
802
-
803
- function getCrypto() {
804
- const gbl = GLOBAL_OBJ ;
805
- return gbl.crypto || gbl.msCrypto;
806
- }
807
-
808
- /**
809
- * UUID4 generator
810
- * @param crypto Object that provides the crypto API.
811
- * @returns string Generated UUID4.
812
- */
813
- function uuid4(crypto = getCrypto()) {
814
- let getRandomByte = () => Math.random() * 16;
815
- try {
816
- if (crypto?.randomUUID) {
817
- return crypto.randomUUID().replace(/-/g, '');
818
- }
819
- if (crypto?.getRandomValues) {
820
- getRandomByte = () => {
821
- // crypto.getRandomValues might return undefined instead of the typed array
822
- // in old Chromium versions (e.g. 23.0.1235.0 (151422))
823
- // However, `typedArray` is still filled in-place.
824
- // @see https://developer.mozilla.org/en-US/docs/Web/API/Crypto/getRandomValues#typedarray
825
- const typedArray = new Uint8Array(1);
826
- crypto.getRandomValues(typedArray);
827
- // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
828
- return typedArray[0];
829
- };
830
- }
831
- } catch (_) {
832
- // some runtimes can crash invoking crypto
833
- // https://github.com/getsentry/sentry-javascript/issues/8935
834
- }
835
-
836
- // http://stackoverflow.com/questions/105034/how-to-create-a-guid-uuid-in-javascript/2117523#2117523
837
- // Concatenating the following numbers as strings results in '10000000100040008000100000000000'
838
- return (([1e7] ) + 1e3 + 4e3 + 8e3 + 1e11).replace(/[018]/g, c =>
839
- // eslint-disable-next-line no-bitwise
840
- ((c ) ^ ((getRandomByte() & 15) >> ((c ) / 4))).toString(16),
841
- );
842
- }
843
-
844
- function getFirstException(event) {
845
- return event.exception?.values?.[0];
846
- }
847
-
848
- /**
849
- * Extracts either message or type+value from an event that can be used for user-facing logs
850
- * @returns event's description
851
- */
852
- function getEventDescription(event) {
853
- const { message, event_id: eventId } = event;
854
- if (message) {
855
- return message;
856
- }
857
-
858
- const firstException = getFirstException(event);
859
- if (firstException) {
860
- if (firstException.type && firstException.value) {
861
- return `${firstException.type}: ${firstException.value}`;
862
- }
863
- return firstException.type || firstException.value || eventId || '<unknown>';
864
- }
865
- return eventId || '<unknown>';
866
- }
867
-
868
- /**
869
- * Adds exception values, type and value to an synthetic Exception.
870
- * @param event The event to modify.
871
- * @param value Value of the exception.
872
- * @param type Type of the exception.
873
- * @hidden
874
- */
875
- function addExceptionTypeValue(event, value, type) {
876
- const exception = (event.exception = event.exception || {});
877
- const values = (exception.values = exception.values || []);
878
- const firstException = (values[0] = values[0] || {});
879
- if (!firstException.value) {
880
- firstException.value = value || '';
881
- }
882
- if (!firstException.type) {
883
- firstException.type = 'Error';
884
- }
885
- }
886
-
887
- /**
888
- * Adds exception mechanism data to a given event. Uses defaults if the second parameter is not passed.
889
- *
890
- * @param event The event to modify.
891
- * @param newMechanism Mechanism data to add to the event.
892
- * @hidden
893
- */
894
- function addExceptionMechanism(event, newMechanism) {
895
- const firstException = getFirstException(event);
896
- if (!firstException) {
897
- return;
898
- }
899
-
900
- const defaultMechanism = { type: 'generic', handled: true };
901
- const currentMechanism = firstException.mechanism;
902
- firstException.mechanism = { ...defaultMechanism, ...currentMechanism, ...newMechanism };
903
-
904
- if (newMechanism && 'data' in newMechanism) {
905
- const mergedData = { ...currentMechanism?.data, ...newMechanism.data };
906
- firstException.mechanism.data = mergedData;
907
- }
908
- }
909
-
910
- /**
911
- * Checks whether or not we've already captured the given exception (note: not an identical exception - the very object
912
- * in question), and marks it captured if not.
913
- *
914
- * This is useful because it's possible for an error to get captured by more than one mechanism. After we intercept and
915
- * record an error, we rethrow it (assuming we've intercepted it before it's reached the top-level global handlers), so
916
- * that we don't interfere with whatever effects the error might have had were the SDK not there. At that point, because
917
- * the error has been rethrown, it's possible for it to bubble up to some other code we've instrumented. If it's not
918
- * caught after that, it will bubble all the way up to the global handlers (which of course we also instrument). This
919
- * function helps us ensure that even if we encounter the same error more than once, we only record it the first time we
920
- * see it.
921
- *
922
- * Note: It will ignore primitives (always return `false` and not mark them as seen), as properties can't be set on
923
- * them. {@link: Object.objectify} can be used on exceptions to convert any that are primitives into their equivalent
924
- * object wrapper forms so that this check will always work. However, because we need to flag the exact object which
925
- * will get rethrown, and because that rethrowing happens outside of the event processing pipeline, the objectification
926
- * must be done before the exception captured.
927
- *
928
- * @param A thrown exception to check or flag as having been seen
929
- * @returns `true` if the exception has already been captured, `false` if not (with the side effect of marking it seen)
930
- */
931
- function checkOrSetAlreadyCaught(exception) {
932
- if (isAlreadyCaptured(exception)) {
933
- return true;
934
- }
935
-
936
- try {
937
- // set it this way rather than by assignment so that it's not ennumerable and therefore isn't recorded by the
938
- // `ExtraErrorData` integration
939
- addNonEnumerableProperty(exception , '__sentry_captured__', true);
940
- } catch (err) {
941
- // `exception` is a primitive, so we can't mark it seen
942
- }
943
-
944
- return false;
945
- }
946
-
947
- function isAlreadyCaptured(exception) {
948
- try {
949
- return (exception ).__sentry_captured__;
950
- } catch {} // eslint-disable-line no-empty
951
- }
952
-
953
- const ONE_SECOND_IN_MS = 1000;
954
-
955
- /**
956
- * A partial definition of the [Performance Web API]{@link https://developer.mozilla.org/en-US/docs/Web/API/Performance}
957
- * for accessing a high-resolution monotonic clock.
958
- */
959
-
960
- /**
961
- * Returns a timestamp in seconds since the UNIX epoch using the Date API.
962
- */
963
- function dateTimestampInSeconds() {
964
- return Date.now() / ONE_SECOND_IN_MS;
965
- }
966
-
967
- /**
968
- * Returns a wrapper around the native Performance API browser implementation, or undefined for browsers that do not
969
- * support the API.
970
- *
971
- * Wrapping the native API works around differences in behavior from different browsers.
972
- */
973
- function createUnixTimestampInSecondsFunc() {
974
- const { performance } = GLOBAL_OBJ ;
975
- if (!performance?.now) {
976
- return dateTimestampInSeconds;
977
- }
978
-
979
- // Some browser and environments don't have a timeOrigin, so we fallback to
980
- // using Date.now() to compute the starting time.
981
- const approxStartingTimeOrigin = Date.now() - performance.now();
982
- const timeOrigin = performance.timeOrigin == undefined ? approxStartingTimeOrigin : performance.timeOrigin;
983
-
984
- // performance.now() is a monotonic clock, which means it starts at 0 when the process begins. To get the current
985
- // wall clock time (actual UNIX timestamp), we need to add the starting time origin and the current time elapsed.
986
- //
987
- // TODO: This does not account for the case where the monotonic clock that powers performance.now() drifts from the
988
- // wall clock time, which causes the returned timestamp to be inaccurate. We should investigate how to detect and
989
- // correct for this.
990
- // See: https://github.com/getsentry/sentry-javascript/issues/2590
991
- // See: https://github.com/mdn/content/issues/4713
992
- // See: https://dev.to/noamr/when-a-millisecond-is-not-a-millisecond-3h6
993
- return () => {
994
- return (timeOrigin + performance.now()) / ONE_SECOND_IN_MS;
995
- };
996
- }
997
-
998
- /**
999
- * Returns a timestamp in seconds since the UNIX epoch using either the Performance or Date APIs, depending on the
1000
- * availability of the Performance API.
1001
- *
1002
- * BUG: Note that because of how browsers implement the Performance API, the clock might stop when the computer is
1003
- * asleep. This creates a skew between `dateTimestampInSeconds` and `timestampInSeconds`. The
1004
- * skew can grow to arbitrary amounts like days, weeks or months.
1005
- * See https://github.com/getsentry/sentry-javascript/issues/2590.
1006
- */
1007
- const timestampInSeconds = createUnixTimestampInSecondsFunc();
1008
-
1009
- /**
1010
- * Creates a new `Session` object by setting certain default parameters. If optional @param context
1011
- * is passed, the passed properties are applied to the session object.
1012
- *
1013
- * @param context (optional) additional properties to be applied to the returned session object
1014
- *
1015
- * @returns a new `Session` object
1016
- */
1017
- function makeSession(context) {
1018
- // Both timestamp and started are in seconds since the UNIX epoch.
1019
- const startingTime = timestampInSeconds();
1020
-
1021
- const session = {
1022
- sid: uuid4(),
1023
- init: true,
1024
- timestamp: startingTime,
1025
- started: startingTime,
1026
- duration: 0,
1027
- status: 'ok',
1028
- errors: 0,
1029
- ignoreDuration: false,
1030
- toJSON: () => sessionToJSON(session),
1031
- };
1032
-
1033
- if (context) {
1034
- updateSession(session, context);
1035
- }
1036
-
1037
- return session;
1038
- }
1039
-
1040
- /**
1041
- * Updates a session object with the properties passed in the context.
1042
- *
1043
- * Note that this function mutates the passed object and returns void.
1044
- * (Had to do this instead of returning a new and updated session because closing and sending a session
1045
- * makes an update to the session after it was passed to the sending logic.
1046
- * @see Client.captureSession )
1047
- *
1048
- * @param session the `Session` to update
1049
- * @param context the `SessionContext` holding the properties that should be updated in @param session
1050
- */
1051
- // eslint-disable-next-line complexity
1052
- function updateSession(session, context = {}) {
1053
- if (context.user) {
1054
- if (!session.ipAddress && context.user.ip_address) {
1055
- session.ipAddress = context.user.ip_address;
1056
- }
1057
-
1058
- if (!session.did && !context.did) {
1059
- session.did = context.user.id || context.user.email || context.user.username;
1060
- }
1061
- }
1062
-
1063
- session.timestamp = context.timestamp || timestampInSeconds();
1064
-
1065
- if (context.abnormal_mechanism) {
1066
- session.abnormal_mechanism = context.abnormal_mechanism;
1067
- }
1068
-
1069
- if (context.ignoreDuration) {
1070
- session.ignoreDuration = context.ignoreDuration;
1071
- }
1072
- if (context.sid) {
1073
- // Good enough uuid validation. — Kamil
1074
- session.sid = context.sid.length === 32 ? context.sid : uuid4();
1075
- }
1076
- if (context.init !== undefined) {
1077
- session.init = context.init;
1078
- }
1079
- if (!session.did && context.did) {
1080
- session.did = `${context.did}`;
1081
- }
1082
- if (typeof context.started === 'number') {
1083
- session.started = context.started;
1084
- }
1085
- if (session.ignoreDuration) {
1086
- session.duration = undefined;
1087
- } else if (typeof context.duration === 'number') {
1088
- session.duration = context.duration;
1089
- } else {
1090
- const duration = session.timestamp - session.started;
1091
- session.duration = duration >= 0 ? duration : 0;
1092
- }
1093
- if (context.release) {
1094
- session.release = context.release;
1095
- }
1096
- if (context.environment) {
1097
- session.environment = context.environment;
1098
- }
1099
- if (!session.ipAddress && context.ipAddress) {
1100
- session.ipAddress = context.ipAddress;
1101
- }
1102
- if (!session.userAgent && context.userAgent) {
1103
- session.userAgent = context.userAgent;
1104
- }
1105
- if (typeof context.errors === 'number') {
1106
- session.errors = context.errors;
1107
- }
1108
- if (context.status) {
1109
- session.status = context.status;
1110
- }
1111
- }
1112
-
1113
- /**
1114
- * Closes a session by setting its status and updating the session object with it.
1115
- * Internally calls `updateSession` to update the passed session object.
1116
- *
1117
- * Note that this function mutates the passed session (@see updateSession for explanation).
1118
- *
1119
- * @param session the `Session` object to be closed
1120
- * @param status the `SessionStatus` with which the session was closed. If you don't pass a status,
1121
- * this function will keep the previously set status, unless it was `'ok'` in which case
1122
- * it is changed to `'exited'`.
1123
- */
1124
- function closeSession(session, status) {
1125
- let context = {};
1126
- if (session.status === 'ok') {
1127
- context = { status: 'exited' };
1128
- }
1129
-
1130
- updateSession(session, context);
1131
- }
1132
-
1133
- /**
1134
- * Serializes a passed session object to a JSON object with a slightly different structure.
1135
- * This is necessary because the Sentry backend requires a slightly different schema of a session
1136
- * than the one the JS SDKs use internally.
1137
- *
1138
- * @param session the session to be converted
1139
- *
1140
- * @returns a JSON object of the passed session
1141
- */
1142
- function sessionToJSON(session) {
1143
- return {
1144
- sid: `${session.sid}`,
1145
- init: session.init,
1146
- // Make sure that sec is converted to ms for date constructor
1147
- started: new Date(session.started * 1000).toISOString(),
1148
- timestamp: new Date(session.timestamp * 1000).toISOString(),
1149
- status: session.status,
1150
- errors: session.errors,
1151
- did: typeof session.did === 'number' || typeof session.did === 'string' ? `${session.did}` : undefined,
1152
- duration: session.duration,
1153
- abnormal_mechanism: session.abnormal_mechanism,
1154
- attrs: {
1155
- release: session.release,
1156
- environment: session.environment,
1157
- ip_address: session.ipAddress,
1158
- user_agent: session.userAgent,
1159
- },
1160
- };
1161
- }
1162
-
1163
- /**
1164
- * Shallow merge two objects.
1165
- * Does not mutate the passed in objects.
1166
- * Undefined/empty values in the merge object will overwrite existing values.
1167
- *
1168
- * By default, this merges 2 levels deep.
1169
- */
1170
- function merge(initialObj, mergeObj, levels = 2) {
1171
- // If the merge value is not an object, or we have no merge levels left,
1172
- // we just set the value to the merge value
1173
- if (!mergeObj || typeof mergeObj !== 'object' || levels <= 0) {
1174
- return mergeObj;
1175
- }
1176
-
1177
- // If the merge object is an empty object, and the initial object is not undefined, we return the initial object
1178
- if (initialObj && Object.keys(mergeObj).length === 0) {
1179
- return initialObj;
1180
- }
1181
-
1182
- // Clone object
1183
- const output = { ...initialObj };
1184
-
1185
- // Merge values into output, resursively
1186
- for (const key in mergeObj) {
1187
- if (Object.prototype.hasOwnProperty.call(mergeObj, key)) {
1188
- output[key] = merge(output[key], mergeObj[key], levels - 1);
1189
- }
1190
- }
1191
-
1192
- return output;
1193
- }
1194
-
1195
- const SCOPE_SPAN_FIELD = '_sentrySpan';
1196
-
1197
- /**
1198
- * Set the active span for a given scope.
1199
- * NOTE: This should NOT be used directly, but is only used internally by the trace methods.
1200
- */
1201
- function _setSpanForScope(scope, span) {
1202
- if (span) {
1203
- addNonEnumerableProperty(scope , SCOPE_SPAN_FIELD, span);
1204
- } else {
1205
- // eslint-disable-next-line @typescript-eslint/no-dynamic-delete
1206
- delete (scope )[SCOPE_SPAN_FIELD];
1207
- }
1208
- }
1209
-
1210
- /**
1211
- * Get the active span for a given scope.
1212
- * NOTE: This should NOT be used directly, but is only used internally by the trace methods.
1213
- */
1214
- function _getSpanForScope(scope) {
1215
- return scope[SCOPE_SPAN_FIELD];
1216
- }
1217
-
1218
- /**
1219
- * Generate a random, valid trace ID.
1220
- */
1221
- function generateTraceId() {
1222
- return uuid4();
1223
- }
1224
-
1225
- /**
1226
- * Generate a random, valid span ID.
1227
- */
1228
- function generateSpanId() {
1229
- return uuid4().substring(16);
1230
- }
1231
-
1232
- /**
1233
- * Default value for maximum number of breadcrumbs added to an event.
1234
- */
1235
- const DEFAULT_MAX_BREADCRUMBS = 100;
1236
-
1237
- /**
1238
- * A context to be used for capturing an event.
1239
- * This can either be a Scope, or a partial ScopeContext,
1240
- * or a callback that receives the current scope and returns a new scope to use.
1241
- */
1242
-
1243
- /**
1244
- * Holds additional event information.
1245
- */
1246
- class Scope {
1247
- /** Flag if notifying is happening. */
1248
-
1249
- /** Callback for client to receive scope changes. */
1250
-
1251
- /** Callback list that will be called during event processing. */
1252
-
1253
- /** Array of breadcrumbs. */
1254
-
1255
- /** User */
1256
-
1257
- /** Tags */
1258
-
1259
- /** Extra */
1260
-
1261
- /** Contexts */
1262
-
1263
- /** Attachments */
1264
-
1265
- /** Propagation Context for distributed tracing */
1266
-
1267
- /**
1268
- * A place to stash data which is needed at some point in the SDK's event processing pipeline but which shouldn't get
1269
- * sent to Sentry
1270
- */
1271
-
1272
- /** Fingerprint */
1273
-
1274
- /** Severity */
1275
-
1276
- /**
1277
- * Transaction Name
1278
- *
1279
- * IMPORTANT: The transaction name on the scope has nothing to do with root spans/transaction objects.
1280
- * It's purpose is to assign a transaction to the scope that's added to non-transaction events.
1281
- */
1282
-
1283
- /** Session */
1284
-
1285
- /** The client on this scope */
1286
-
1287
- /** Contains the last event id of a captured event. */
1288
-
1289
- // NOTE: Any field which gets added here should get added not only to the constructor but also to the `clone` method.
1290
-
1291
- constructor() {
1292
- this._notifyingListeners = false;
1293
- this._scopeListeners = [];
1294
- this._eventProcessors = [];
1295
- this._breadcrumbs = [];
1296
- this._attachments = [];
1297
- this._user = {};
1298
- this._tags = {};
1299
- this._extra = {};
1300
- this._contexts = {};
1301
- this._sdkProcessingMetadata = {};
1302
- this._propagationContext = {
1303
- traceId: generateTraceId(),
1304
- sampleRand: Math.random(),
1305
- };
1306
- }
1307
-
1308
- /**
1309
- * Clone all data from this scope into a new scope.
1310
- */
1311
- clone() {
1312
- const newScope = new Scope();
1313
- newScope._breadcrumbs = [...this._breadcrumbs];
1314
- newScope._tags = { ...this._tags };
1315
- newScope._extra = { ...this._extra };
1316
- newScope._contexts = { ...this._contexts };
1317
- if (this._contexts.flags) {
1318
- // We need to copy the `values` array so insertions on a cloned scope
1319
- // won't affect the original array.
1320
- newScope._contexts.flags = {
1321
- values: [...this._contexts.flags.values],
1322
- };
1323
- }
1324
-
1325
- newScope._user = this._user;
1326
- newScope._level = this._level;
1327
- newScope._session = this._session;
1328
- newScope._transactionName = this._transactionName;
1329
- newScope._fingerprint = this._fingerprint;
1330
- newScope._eventProcessors = [...this._eventProcessors];
1331
- newScope._attachments = [...this._attachments];
1332
- newScope._sdkProcessingMetadata = { ...this._sdkProcessingMetadata };
1333
- newScope._propagationContext = { ...this._propagationContext };
1334
- newScope._client = this._client;
1335
- newScope._lastEventId = this._lastEventId;
1336
-
1337
- _setSpanForScope(newScope, _getSpanForScope(this));
1338
-
1339
- return newScope;
1340
- }
1341
-
1342
- /**
1343
- * Update the client assigned to this scope.
1344
- * Note that not every scope will have a client assigned - isolation scopes & the global scope will generally not have a client,
1345
- * as well as manually created scopes.
1346
- */
1347
- setClient(client) {
1348
- this._client = client;
1349
- }
1350
-
1351
- /**
1352
- * Set the ID of the last captured error event.
1353
- * This is generally only captured on the isolation scope.
1354
- */
1355
- setLastEventId(lastEventId) {
1356
- this._lastEventId = lastEventId;
1357
- }
1358
-
1359
- /**
1360
- * Get the client assigned to this scope.
1361
- */
1362
- getClient() {
1363
- return this._client ;
1364
- }
1365
-
1366
- /**
1367
- * Get the ID of the last captured error event.
1368
- * This is generally only available on the isolation scope.
1369
- */
1370
- lastEventId() {
1371
- return this._lastEventId;
1372
- }
1373
-
1374
- /**
1375
- * @inheritDoc
1376
- */
1377
- addScopeListener(callback) {
1378
- this._scopeListeners.push(callback);
1379
- }
1380
-
1381
- /**
1382
- * Add an event processor that will be called before an event is sent.
1383
- */
1384
- addEventProcessor(callback) {
1385
- this._eventProcessors.push(callback);
1386
- return this;
1387
- }
1388
-
1389
- /**
1390
- * Set the user for this scope.
1391
- * Set to `null` to unset the user.
1392
- */
1393
- setUser(user) {
1394
- // If null is passed we want to unset everything, but still define keys,
1395
- // so that later down in the pipeline any existing values are cleared.
1396
- this._user = user || {
1397
- email: undefined,
1398
- id: undefined,
1399
- ip_address: undefined,
1400
- username: undefined,
1401
- };
1402
-
1403
- if (this._session) {
1404
- updateSession(this._session, { user });
1405
- }
1406
-
1407
- this._notifyScopeListeners();
1408
- return this;
1409
- }
1410
-
1411
- /**
1412
- * Get the user from this scope.
1413
- */
1414
- getUser() {
1415
- return this._user;
1416
- }
1417
-
1418
- /**
1419
- * Set an object that will be merged into existing tags on the scope,
1420
- * and will be sent as tags data with the event.
1421
- */
1422
- setTags(tags) {
1423
- this._tags = {
1424
- ...this._tags,
1425
- ...tags,
1426
- };
1427
- this._notifyScopeListeners();
1428
- return this;
1429
- }
1430
-
1431
- /**
1432
- * Set a single tag that will be sent as tags data with the event.
1433
- */
1434
- setTag(key, value) {
1435
- this._tags = { ...this._tags, [key]: value };
1436
- this._notifyScopeListeners();
1437
- return this;
1438
- }
1439
-
1440
- /**
1441
- * Set an object that will be merged into existing extra on the scope,
1442
- * and will be sent as extra data with the event.
1443
- */
1444
- setExtras(extras) {
1445
- this._extra = {
1446
- ...this._extra,
1447
- ...extras,
1448
- };
1449
- this._notifyScopeListeners();
1450
- return this;
1451
- }
1452
-
1453
- /**
1454
- * Set a single key:value extra entry that will be sent as extra data with the event.
1455
- */
1456
- setExtra(key, extra) {
1457
- this._extra = { ...this._extra, [key]: extra };
1458
- this._notifyScopeListeners();
1459
- return this;
1460
- }
1461
-
1462
- /**
1463
- * Sets the fingerprint on the scope to send with the events.
1464
- * @param {string[]} fingerprint Fingerprint to group events in Sentry.
1465
- */
1466
- setFingerprint(fingerprint) {
1467
- this._fingerprint = fingerprint;
1468
- this._notifyScopeListeners();
1469
- return this;
1470
- }
1471
-
1472
- /**
1473
- * Sets the level on the scope for future events.
1474
- */
1475
- setLevel(level) {
1476
- this._level = level;
1477
- this._notifyScopeListeners();
1478
- return this;
1479
- }
1480
-
1481
- /**
1482
- * Sets the transaction name on the scope so that the name of e.g. taken server route or
1483
- * the page location is attached to future events.
1484
- *
1485
- * IMPORTANT: Calling this function does NOT change the name of the currently active
1486
- * root span. If you want to change the name of the active root span, use
1487
- * `Sentry.updateSpanName(rootSpan, 'new name')` instead.
1488
- *
1489
- * By default, the SDK updates the scope's transaction name automatically on sensible
1490
- * occasions, such as a page navigation or when handling a new request on the server.
1491
- */
1492
- setTransactionName(name) {
1493
- this._transactionName = name;
1494
- this._notifyScopeListeners();
1495
- return this;
1496
- }
1497
-
1498
- /**
1499
- * Sets context data with the given name.
1500
- * Data passed as context will be normalized. You can also pass `null` to unset the context.
1501
- * Note that context data will not be merged - calling `setContext` will overwrite an existing context with the same key.
1502
- */
1503
- setContext(key, context) {
1504
- if (context === null) {
1505
- // eslint-disable-next-line @typescript-eslint/no-dynamic-delete
1506
- delete this._contexts[key];
1507
- } else {
1508
- this._contexts[key] = context;
1509
- }
1510
-
1511
- this._notifyScopeListeners();
1512
- return this;
1513
- }
1514
-
1515
- /**
1516
- * Set the session for the scope.
1517
- */
1518
- setSession(session) {
1519
- if (!session) {
1520
- delete this._session;
1521
- } else {
1522
- this._session = session;
1523
- }
1524
- this._notifyScopeListeners();
1525
- return this;
1526
- }
1527
-
1528
- /**
1529
- * Get the session from the scope.
1530
- */
1531
- getSession() {
1532
- return this._session;
1533
- }
1534
-
1535
- /**
1536
- * Updates the scope with provided data. Can work in three variations:
1537
- * - plain object containing updatable attributes
1538
- * - Scope instance that'll extract the attributes from
1539
- * - callback function that'll receive the current scope as an argument and allow for modifications
1540
- */
1541
- update(captureContext) {
1542
- if (!captureContext) {
1543
- return this;
1544
- }
1545
-
1546
- const scopeToMerge = typeof captureContext === 'function' ? captureContext(this) : captureContext;
1547
-
1548
- const scopeInstance =
1549
- scopeToMerge instanceof Scope
1550
- ? scopeToMerge.getScopeData()
1551
- : isPlainObject(scopeToMerge)
1552
- ? (captureContext )
1553
- : undefined;
1554
-
1555
- const { tags, extra, user, contexts, level, fingerprint = [], propagationContext } = scopeInstance || {};
1556
-
1557
- this._tags = { ...this._tags, ...tags };
1558
- this._extra = { ...this._extra, ...extra };
1559
- this._contexts = { ...this._contexts, ...contexts };
1560
-
1561
- if (user && Object.keys(user).length) {
1562
- this._user = user;
1563
- }
1564
-
1565
- if (level) {
1566
- this._level = level;
1567
- }
1568
-
1569
- if (fingerprint.length) {
1570
- this._fingerprint = fingerprint;
1571
- }
1572
-
1573
- if (propagationContext) {
1574
- this._propagationContext = propagationContext;
1575
- }
1576
-
1577
- return this;
1578
- }
1579
-
1580
- /**
1581
- * Clears the current scope and resets its properties.
1582
- * Note: The client will not be cleared.
1583
- */
1584
- clear() {
1585
- // client is not cleared here on purpose!
1586
- this._breadcrumbs = [];
1587
- this._tags = {};
1588
- this._extra = {};
1589
- this._user = {};
1590
- this._contexts = {};
1591
- this._level = undefined;
1592
- this._transactionName = undefined;
1593
- this._fingerprint = undefined;
1594
- this._session = undefined;
1595
- _setSpanForScope(this, undefined);
1596
- this._attachments = [];
1597
- this.setPropagationContext({ traceId: generateTraceId(), sampleRand: Math.random() });
1598
-
1599
- this._notifyScopeListeners();
1600
- return this;
1601
- }
1602
-
1603
- /**
1604
- * Adds a breadcrumb to the scope.
1605
- * By default, the last 100 breadcrumbs are kept.
1606
- */
1607
- addBreadcrumb(breadcrumb, maxBreadcrumbs) {
1608
- const maxCrumbs = typeof maxBreadcrumbs === 'number' ? maxBreadcrumbs : DEFAULT_MAX_BREADCRUMBS;
1609
-
1610
- // No data has been changed, so don't notify scope listeners
1611
- if (maxCrumbs <= 0) {
1612
- return this;
1613
- }
1614
-
1615
- const mergedBreadcrumb = {
1616
- timestamp: dateTimestampInSeconds(),
1617
- ...breadcrumb,
1618
- // Breadcrumb messages can theoretically be infinitely large and they're held in memory so we truncate them not to leak (too much) memory
1619
- message: breadcrumb.message ? truncate(breadcrumb.message, 2048) : breadcrumb.message,
1620
- };
1621
-
1622
- this._breadcrumbs.push(mergedBreadcrumb);
1623
- if (this._breadcrumbs.length > maxCrumbs) {
1624
- this._breadcrumbs = this._breadcrumbs.slice(-maxCrumbs);
1625
- this._client?.recordDroppedEvent('buffer_overflow', 'log_item');
1626
- }
1627
-
1628
- this._notifyScopeListeners();
1629
-
1630
- return this;
1631
- }
1632
-
1633
- /**
1634
- * Get the last breadcrumb of the scope.
1635
- */
1636
- getLastBreadcrumb() {
1637
- return this._breadcrumbs[this._breadcrumbs.length - 1];
1638
- }
1639
-
1640
- /**
1641
- * Clear all breadcrumbs from the scope.
1642
- */
1643
- clearBreadcrumbs() {
1644
- this._breadcrumbs = [];
1645
- this._notifyScopeListeners();
1646
- return this;
1647
- }
1648
-
1649
- /**
1650
- * Add an attachment to the scope.
1651
- */
1652
- addAttachment(attachment) {
1653
- this._attachments.push(attachment);
1654
- return this;
1655
- }
1656
-
1657
- /**
1658
- * Clear all attachments from the scope.
1659
- */
1660
- clearAttachments() {
1661
- this._attachments = [];
1662
- return this;
1663
- }
1664
-
1665
- /**
1666
- * Get the data of this scope, which should be applied to an event during processing.
1667
- */
1668
- getScopeData() {
1669
- return {
1670
- breadcrumbs: this._breadcrumbs,
1671
- attachments: this._attachments,
1672
- contexts: this._contexts,
1673
- tags: this._tags,
1674
- extra: this._extra,
1675
- user: this._user,
1676
- level: this._level,
1677
- fingerprint: this._fingerprint || [],
1678
- eventProcessors: this._eventProcessors,
1679
- propagationContext: this._propagationContext,
1680
- sdkProcessingMetadata: this._sdkProcessingMetadata,
1681
- transactionName: this._transactionName,
1682
- span: _getSpanForScope(this),
1683
- };
1684
- }
1685
-
1686
- /**
1687
- * Add data which will be accessible during event processing but won't get sent to Sentry.
1688
- */
1689
- setSDKProcessingMetadata(newData) {
1690
- this._sdkProcessingMetadata = merge(this._sdkProcessingMetadata, newData, 2);
1691
- return this;
1692
- }
1693
-
1694
- /**
1695
- * Add propagation context to the scope, used for distributed tracing
1696
- */
1697
- setPropagationContext(context) {
1698
- this._propagationContext = context;
1699
- return this;
1700
- }
1701
-
1702
- /**
1703
- * Get propagation context from the scope, used for distributed tracing
1704
- */
1705
- getPropagationContext() {
1706
- return this._propagationContext;
1707
- }
1708
-
1709
- /**
1710
- * Capture an exception for this scope.
1711
- *
1712
- * @returns {string} The id of the captured Sentry event.
1713
- */
1714
- captureException(exception, hint) {
1715
- const eventId = hint?.event_id || uuid4();
1716
-
1717
- if (!this._client) {
1718
- logger.warn('No client configured on scope - will not capture exception!');
1719
- return eventId;
1720
- }
1721
-
1722
- const syntheticException = new Error('Sentry syntheticException');
1723
-
1724
- this._client.captureException(
1725
- exception,
1726
- {
1727
- originalException: exception,
1728
- syntheticException,
1729
- ...hint,
1730
- event_id: eventId,
1731
- },
1732
- this,
1733
- );
1734
-
1735
- return eventId;
1736
- }
1737
-
1738
- /**
1739
- * Capture a message for this scope.
1740
- *
1741
- * @returns {string} The id of the captured message.
1742
- */
1743
- captureMessage(message, level, hint) {
1744
- const eventId = hint?.event_id || uuid4();
1745
-
1746
- if (!this._client) {
1747
- logger.warn('No client configured on scope - will not capture message!');
1748
- return eventId;
1749
- }
1750
-
1751
- const syntheticException = new Error(message);
1752
-
1753
- this._client.captureMessage(
1754
- message,
1755
- level,
1756
- {
1757
- originalException: message,
1758
- syntheticException,
1759
- ...hint,
1760
- event_id: eventId,
1761
- },
1762
- this,
1763
- );
1764
-
1765
- return eventId;
1766
- }
1767
-
1768
- /**
1769
- * Capture a Sentry event for this scope.
1770
- *
1771
- * @returns {string} The id of the captured event.
1772
- */
1773
- captureEvent(event, hint) {
1774
- const eventId = hint?.event_id || uuid4();
1775
-
1776
- if (!this._client) {
1777
- logger.warn('No client configured on scope - will not capture event!');
1778
- return eventId;
1779
- }
1780
-
1781
- this._client.captureEvent(event, { ...hint, event_id: eventId }, this);
1782
-
1783
- return eventId;
1784
- }
1785
-
1786
- /**
1787
- * This will be called on every set call.
1788
- */
1789
- _notifyScopeListeners() {
1790
- // We need this check for this._notifyingListeners to be able to work on scope during updates
1791
- // If this check is not here we'll produce endless recursion when something is done with the scope
1792
- // during the callback.
1793
- if (!this._notifyingListeners) {
1794
- this._notifyingListeners = true;
1795
- this._scopeListeners.forEach(callback => {
1796
- callback(this);
1797
- });
1798
- this._notifyingListeners = false;
1799
- }
1800
- }
1801
- }
1802
-
1803
- /** Get the default current scope. */
1804
- function getDefaultCurrentScope() {
1805
- return getGlobalSingleton('defaultCurrentScope', () => new Scope());
1806
- }
1807
-
1808
- /** Get the default isolation scope. */
1809
- function getDefaultIsolationScope() {
1810
- return getGlobalSingleton('defaultIsolationScope', () => new Scope());
1811
- }
1812
-
1813
- /**
1814
- * This is an object that holds a stack of scopes.
1815
- */
1816
- class AsyncContextStack {
1817
-
1818
- constructor(scope, isolationScope) {
1819
- let assignedScope;
1820
- if (!scope) {
1821
- assignedScope = new Scope();
1822
- } else {
1823
- assignedScope = scope;
1824
- }
1825
-
1826
- let assignedIsolationScope;
1827
- if (!isolationScope) {
1828
- assignedIsolationScope = new Scope();
1829
- } else {
1830
- assignedIsolationScope = isolationScope;
1831
- }
1832
-
1833
- // scope stack for domains or the process
1834
- this._stack = [{ scope: assignedScope }];
1835
- this._isolationScope = assignedIsolationScope;
1836
- }
1837
-
1838
- /**
1839
- * Fork a scope for the stack.
1840
- */
1841
- withScope(callback) {
1842
- const scope = this._pushScope();
1843
-
1844
- let maybePromiseResult;
1845
- try {
1846
- maybePromiseResult = callback(scope);
1847
- } catch (e) {
1848
- this._popScope();
1849
- throw e;
1850
- }
1851
-
1852
- if (isThenable(maybePromiseResult)) {
1853
- // @ts-expect-error - isThenable returns the wrong type
1854
- return maybePromiseResult.then(
1855
- res => {
1856
- this._popScope();
1857
- return res;
1858
- },
1859
- e => {
1860
- this._popScope();
1861
- throw e;
1862
- },
1863
- );
1864
- }
1865
-
1866
- this._popScope();
1867
- return maybePromiseResult;
1868
- }
1869
-
1870
- /**
1871
- * Get the client of the stack.
1872
- */
1873
- getClient() {
1874
- return this.getStackTop().client ;
1875
- }
1876
-
1877
- /**
1878
- * Returns the scope of the top stack.
1879
- */
1880
- getScope() {
1881
- return this.getStackTop().scope;
1882
- }
1883
-
1884
- /**
1885
- * Get the isolation scope for the stack.
1886
- */
1887
- getIsolationScope() {
1888
- return this._isolationScope;
1889
- }
1890
-
1891
- /**
1892
- * Returns the topmost scope layer in the order domain > local > process.
1893
- */
1894
- getStackTop() {
1895
- return this._stack[this._stack.length - 1] ;
1896
- }
1897
-
1898
- /**
1899
- * Push a scope to the stack.
1900
- */
1901
- _pushScope() {
1902
- // We want to clone the content of prev scope
1903
- const scope = this.getScope().clone();
1904
- this._stack.push({
1905
- client: this.getClient(),
1906
- scope,
1907
- });
1908
- return scope;
1909
- }
1910
-
1911
- /**
1912
- * Pop a scope from the stack.
1913
- */
1914
- _popScope() {
1915
- if (this._stack.length <= 1) return false;
1916
- return !!this._stack.pop();
1917
- }
1918
- }
1919
-
1920
- /**
1921
- * Get the global async context stack.
1922
- * This will be removed during the v8 cycle and is only here to make migration easier.
1923
- */
1924
- function getAsyncContextStack() {
1925
- const registry = getMainCarrier();
1926
- const sentry = getSentryCarrier(registry);
1927
-
1928
- return (sentry.stack = sentry.stack || new AsyncContextStack(getDefaultCurrentScope(), getDefaultIsolationScope()));
1929
- }
1930
-
1931
- function withScope$1(callback) {
1932
- return getAsyncContextStack().withScope(callback);
1933
- }
1934
-
1935
- function withSetScope(scope, callback) {
1936
- const stack = getAsyncContextStack() ;
1937
- return stack.withScope(() => {
1938
- stack.getStackTop().scope = scope;
1939
- return callback(scope);
1940
- });
1941
- }
1942
-
1943
- function withIsolationScope(callback) {
1944
- return getAsyncContextStack().withScope(() => {
1945
- return callback(getAsyncContextStack().getIsolationScope());
1946
- });
1947
- }
1948
-
1949
- /**
1950
- * Get the stack-based async context strategy.
1951
- */
1952
- function getStackAsyncContextStrategy() {
1953
- return {
1954
- withIsolationScope,
1955
- withScope: withScope$1,
1956
- withSetScope,
1957
- withSetIsolationScope: (_isolationScope, callback) => {
1958
- return withIsolationScope(callback);
1959
- },
1960
- getCurrentScope: () => getAsyncContextStack().getScope(),
1961
- getIsolationScope: () => getAsyncContextStack().getIsolationScope(),
1962
- };
1963
- }
1964
-
1965
- /**
1966
- * Get the current async context strategy.
1967
- * If none has been setup, the default will be used.
1968
- */
1969
- function getAsyncContextStrategy(carrier) {
1970
- const sentry = getSentryCarrier(carrier);
1971
-
1972
- if (sentry.acs) {
1973
- return sentry.acs;
1974
- }
1975
-
1976
- // Otherwise, use the default one (stack)
1977
- return getStackAsyncContextStrategy();
1978
- }
1979
-
1980
- /**
1981
- * Get the currently active scope.
1982
- */
1983
- function getCurrentScope() {
1984
- const carrier = getMainCarrier();
1985
- const acs = getAsyncContextStrategy(carrier);
1986
- return acs.getCurrentScope();
1987
- }
1988
-
1989
- /**
1990
- * Get the currently active isolation scope.
1991
- * The isolation scope is active for the current execution context.
1992
- */
1993
- function getIsolationScope() {
1994
- const carrier = getMainCarrier();
1995
- const acs = getAsyncContextStrategy(carrier);
1996
- return acs.getIsolationScope();
1997
- }
1998
-
1999
- /**
2000
- * Get the global scope.
2001
- * This scope is applied to _all_ events.
2002
- */
2003
- function getGlobalScope() {
2004
- return getGlobalSingleton('globalScope', () => new Scope());
2005
- }
2006
-
2007
- /**
2008
- * Creates a new scope with and executes the given operation within.
2009
- * The scope is automatically removed once the operation
2010
- * finishes or throws.
2011
- */
2012
-
2013
- /**
2014
- * Either creates a new active scope, or sets the given scope as active scope in the given callback.
2015
- */
2016
- function withScope(
2017
- ...rest
2018
- ) {
2019
- const carrier = getMainCarrier();
2020
- const acs = getAsyncContextStrategy(carrier);
2021
-
2022
- // If a scope is defined, we want to make this the active scope instead of the default one
2023
- if (rest.length === 2) {
2024
- const [scope, callback] = rest;
2025
-
2026
- if (!scope) {
2027
- return acs.withScope(callback);
2028
- }
2029
-
2030
- return acs.withSetScope(scope, callback);
2031
- }
2032
-
2033
- return acs.withScope(rest[0]);
2034
- }
2035
-
2036
- /**
2037
- * Get the currently active client.
2038
- */
2039
- function getClient() {
2040
- return getCurrentScope().getClient();
2041
- }
2042
-
2043
- /**
2044
- * Get a trace context for the given scope.
2045
- */
2046
- function getTraceContextFromScope(scope) {
2047
- const propagationContext = scope.getPropagationContext();
2048
-
2049
- const { traceId, parentSpanId, propagationSpanId } = propagationContext;
2050
-
2051
- const traceContext = {
2052
- trace_id: traceId,
2053
- span_id: propagationSpanId || generateSpanId(),
2054
- };
2055
-
2056
- if (parentSpanId) {
2057
- traceContext.parent_span_id = parentSpanId;
2058
- }
2059
-
2060
- return traceContext;
2061
- }
2062
-
2063
- /**
2064
- * Use this attribute to represent the source of a span.
2065
- * Should be one of: custom, url, route, view, component, task, unknown
2066
- *
2067
- */
2068
- const SEMANTIC_ATTRIBUTE_SENTRY_SOURCE = 'sentry.source';
2069
-
2070
- /**
2071
- * Attributes that holds the sample rate that was locally applied to a span.
2072
- * If this attribute is not defined, it means that the span inherited a sampling decision.
2073
- *
2074
- * NOTE: Is only defined on root spans.
2075
- */
2076
- const SEMANTIC_ATTRIBUTE_SENTRY_SAMPLE_RATE = 'sentry.sample_rate';
2077
-
2078
- /**
2079
- * Attribute holding the sample rate of the previous trace.
2080
- * This is used to sample consistently across subsequent traces in the browser SDK.
2081
- *
2082
- * Note: Only defined on root spans, if opted into consistent sampling
2083
- */
2084
- const SEMANTIC_ATTRIBUTE_SENTRY_PREVIOUS_TRACE_SAMPLE_RATE = 'sentry.previous_trace_sample_rate';
2085
-
2086
- /**
2087
- * Use this attribute to represent the operation of a span.
2088
- */
2089
- const SEMANTIC_ATTRIBUTE_SENTRY_OP = 'sentry.op';
2090
-
2091
- /**
2092
- * Use this attribute to represent the origin of a span.
2093
- */
2094
- const SEMANTIC_ATTRIBUTE_SENTRY_ORIGIN = 'sentry.origin';
2095
-
2096
- /**
2097
- * The id of the profile that this span occurred in.
2098
- */
2099
- const SEMANTIC_ATTRIBUTE_PROFILE_ID = 'sentry.profile_id';
2100
-
2101
- const SEMANTIC_ATTRIBUTE_EXCLUSIVE_TIME = 'sentry.exclusive_time';
2102
-
2103
- const SPAN_STATUS_UNSET = 0;
2104
- const SPAN_STATUS_OK = 1;
2105
-
2106
- const SCOPE_ON_START_SPAN_FIELD = '_sentryScope';
2107
- const ISOLATION_SCOPE_ON_START_SPAN_FIELD = '_sentryIsolationScope';
2108
-
2109
- /**
2110
- * Grabs the scope and isolation scope off a span that were active when the span was started.
2111
- */
2112
- function getCapturedScopesOnSpan(span) {
2113
- return {
2114
- scope: (span )[SCOPE_ON_START_SPAN_FIELD],
2115
- isolationScope: (span )[ISOLATION_SCOPE_ON_START_SPAN_FIELD],
2116
- };
2117
- }
2118
-
2119
- const SENTRY_BAGGAGE_KEY_PREFIX = 'sentry-';
2120
-
2121
- const SENTRY_BAGGAGE_KEY_PREFIX_REGEX = /^sentry-/;
2122
-
2123
- /**
2124
- * Takes a baggage header and turns it into Dynamic Sampling Context, by extracting all the "sentry-" prefixed values
2125
- * from it.
2126
- *
2127
- * @param baggageHeader A very bread definition of a baggage header as it might appear in various frameworks.
2128
- * @returns The Dynamic Sampling Context that was found on `baggageHeader`, if there was any, `undefined` otherwise.
2129
- */
2130
- function baggageHeaderToDynamicSamplingContext(
2131
- // Very liberal definition of what any incoming header might look like
2132
- baggageHeader,
2133
- ) {
2134
- const baggageObject = parseBaggageHeader(baggageHeader);
2135
-
2136
- if (!baggageObject) {
2137
- return undefined;
2138
- }
2139
-
2140
- // Read all "sentry-" prefixed values out of the baggage object and put it onto a dynamic sampling context object.
2141
- const dynamicSamplingContext = Object.entries(baggageObject).reduce((acc, [key, value]) => {
2142
- if (key.match(SENTRY_BAGGAGE_KEY_PREFIX_REGEX)) {
2143
- const nonPrefixedKey = key.slice(SENTRY_BAGGAGE_KEY_PREFIX.length);
2144
- acc[nonPrefixedKey] = value;
2145
- }
2146
- return acc;
2147
- }, {});
2148
-
2149
- // Only return a dynamic sampling context object if there are keys in it.
2150
- // A keyless object means there were no sentry values on the header, which means that there is no DSC.
2151
- if (Object.keys(dynamicSamplingContext).length > 0) {
2152
- return dynamicSamplingContext ;
2153
- } else {
2154
- return undefined;
2155
- }
2156
- }
2157
-
2158
- /**
2159
- * Take a baggage header and parse it into an object.
2160
- */
2161
- function parseBaggageHeader(
2162
- baggageHeader,
2163
- ) {
2164
- if (!baggageHeader || (!isString(baggageHeader) && !Array.isArray(baggageHeader))) {
2165
- return undefined;
2166
- }
2167
-
2168
- if (Array.isArray(baggageHeader)) {
2169
- // Combine all baggage headers into one object containing the baggage values so we can later read the Sentry-DSC-values from it
2170
- return baggageHeader.reduce((acc, curr) => {
2171
- const currBaggageObject = baggageHeaderToObject(curr);
2172
- Object.entries(currBaggageObject).forEach(([key, value]) => {
2173
- acc[key] = value;
2174
- });
2175
- return acc;
2176
- }, {});
2177
- }
2178
-
2179
- return baggageHeaderToObject(baggageHeader);
2180
- }
2181
-
2182
- /**
2183
- * Will parse a baggage header, which is a simple key-value map, into a flat object.
2184
- *
2185
- * @param baggageHeader The baggage header to parse.
2186
- * @returns a flat object containing all the key-value pairs from `baggageHeader`.
2187
- */
2188
- function baggageHeaderToObject(baggageHeader) {
2189
- return baggageHeader
2190
- .split(',')
2191
- .map(baggageEntry =>
2192
- baggageEntry.split('=').map(keyOrValue => {
2193
- try {
2194
- return decodeURIComponent(keyOrValue.trim());
2195
- } catch {
2196
- // We ignore errors here, e.g. if the value cannot be URL decoded.
2197
- // This will then be skipped in the next step
2198
- return;
2199
- }
2200
- }),
2201
- )
2202
- .reduce((acc, [key, value]) => {
2203
- if (key && value) {
2204
- acc[key] = value;
2205
- }
2206
- return acc;
2207
- }, {});
2208
- }
2209
-
2210
- const TRACE_FLAG_SAMPLED = 0x1;
2211
-
2212
- let hasShownSpanDropWarning = false;
2213
-
2214
- /**
2215
- * Convert a span to a trace context, which can be sent as the `trace` context in a non-transaction event.
2216
- */
2217
- function spanToTraceContext(span) {
2218
- const { spanId, traceId: trace_id, isRemote } = span.spanContext();
2219
-
2220
- // If the span is remote, we use a random/virtual span as span_id to the trace context,
2221
- // and the remote span as parent_span_id
2222
- const parent_span_id = isRemote ? spanId : spanToJSON(span).parent_span_id;
2223
- const scope = getCapturedScopesOnSpan(span).scope;
2224
-
2225
- const span_id = isRemote ? scope?.getPropagationContext().propagationSpanId || generateSpanId() : spanId;
2226
-
2227
- return {
2228
- parent_span_id,
2229
- span_id,
2230
- trace_id,
2231
- };
2232
- }
2233
-
2234
- /**
2235
- * Converts the span links array to a flattened version to be sent within an envelope.
2236
- *
2237
- * If the links array is empty, it returns `undefined` so the empty value can be dropped before it's sent.
2238
- */
2239
- function convertSpanLinksForEnvelope(links) {
2240
- if (links && links.length > 0) {
2241
- return links.map(({ context: { spanId, traceId, traceFlags, ...restContext }, attributes }) => ({
2242
- span_id: spanId,
2243
- trace_id: traceId,
2244
- sampled: traceFlags === TRACE_FLAG_SAMPLED,
2245
- attributes,
2246
- ...restContext,
2247
- }));
2248
- } else {
2249
- return undefined;
2250
- }
2251
- }
2252
-
2253
- /**
2254
- * Convert a span time input into a timestamp in seconds.
2255
- */
2256
- function spanTimeInputToSeconds(input) {
2257
- if (typeof input === 'number') {
2258
- return ensureTimestampInSeconds(input);
2259
- }
2260
-
2261
- if (Array.isArray(input)) {
2262
- // See {@link HrTime} for the array-based time format
2263
- return input[0] + input[1] / 1e9;
2264
- }
2265
-
2266
- if (input instanceof Date) {
2267
- return ensureTimestampInSeconds(input.getTime());
2268
- }
2269
-
2270
- return timestampInSeconds();
2271
- }
2272
-
2273
- /**
2274
- * Converts a timestamp to second, if it was in milliseconds, or keeps it as second.
2275
- */
2276
- function ensureTimestampInSeconds(timestamp) {
2277
- const isMs = timestamp > 9999999999;
2278
- return isMs ? timestamp / 1000 : timestamp;
2279
- }
2280
-
2281
- /**
2282
- * Convert a span to a JSON representation.
2283
- */
2284
- // Note: Because of this, we currently have a circular type dependency (which we opted out of in package.json).
2285
- // This is not avoidable as we need `spanToJSON` in `spanUtils.ts`, which in turn is needed by `span.ts` for backwards compatibility.
2286
- // And `spanToJSON` needs the Span class from `span.ts` to check here.
2287
- function spanToJSON(span) {
2288
- if (spanIsSentrySpan(span)) {
2289
- return span.getSpanJSON();
2290
- }
2291
-
2292
- const { spanId: span_id, traceId: trace_id } = span.spanContext();
2293
-
2294
- // Handle a span from @opentelemetry/sdk-base-trace's `Span` class
2295
- if (spanIsOpenTelemetrySdkTraceBaseSpan(span)) {
2296
- const { attributes, startTime, name, endTime, status, links } = span;
2297
-
2298
- // In preparation for the next major of OpenTelemetry, we want to support
2299
- // looking up the parent span id according to the new API
2300
- // In OTel v1, the parent span id is accessed as `parentSpanId`
2301
- // In OTel v2, the parent span id is accessed as `spanId` on the `parentSpanContext`
2302
- const parentSpanId =
2303
- 'parentSpanId' in span
2304
- ? span.parentSpanId
2305
- : 'parentSpanContext' in span
2306
- ? (span.parentSpanContext )?.spanId
2307
- : undefined;
2308
-
2309
- return {
2310
- span_id,
2311
- trace_id,
2312
- data: attributes,
2313
- description: name,
2314
- parent_span_id: parentSpanId,
2315
- start_timestamp: spanTimeInputToSeconds(startTime),
2316
- // This is [0,0] by default in OTEL, in which case we want to interpret this as no end time
2317
- timestamp: spanTimeInputToSeconds(endTime) || undefined,
2318
- status: getStatusMessage(status),
2319
- op: attributes[SEMANTIC_ATTRIBUTE_SENTRY_OP],
2320
- origin: attributes[SEMANTIC_ATTRIBUTE_SENTRY_ORIGIN] ,
2321
- links: convertSpanLinksForEnvelope(links),
2322
- };
2323
- }
2324
-
2325
- // Finally, at least we have `spanContext()`....
2326
- // This should not actually happen in reality, but we need to handle it for type safety.
2327
- return {
2328
- span_id,
2329
- trace_id,
2330
- start_timestamp: 0,
2331
- data: {},
2332
- };
2333
- }
2334
-
2335
- function spanIsOpenTelemetrySdkTraceBaseSpan(span) {
2336
- const castSpan = span ;
2337
- return !!castSpan.attributes && !!castSpan.startTime && !!castSpan.name && !!castSpan.endTime && !!castSpan.status;
2338
- }
2339
-
2340
- /** Exported only for tests. */
2341
-
2342
- /**
2343
- * Sadly, due to circular dependency checks we cannot actually import the Span class here and check for instanceof.
2344
- * :( So instead we approximate this by checking if it has the `getSpanJSON` method.
2345
- */
2346
- function spanIsSentrySpan(span) {
2347
- return typeof (span ).getSpanJSON === 'function';
2348
- }
2349
-
2350
- /**
2351
- * Returns true if a span is sampled.
2352
- * In most cases, you should just use `span.isRecording()` instead.
2353
- * However, this has a slightly different semantic, as it also returns false if the span is finished.
2354
- * So in the case where this distinction is important, use this method.
2355
- */
2356
- function spanIsSampled(span) {
2357
- // We align our trace flags with the ones OpenTelemetry use
2358
- // So we also check for sampled the same way they do.
2359
- const { traceFlags } = span.spanContext();
2360
- return traceFlags === TRACE_FLAG_SAMPLED;
2361
- }
2362
-
2363
- /** Get the status message to use for a JSON representation of a span. */
2364
- function getStatusMessage(status) {
2365
- if (!status || status.code === SPAN_STATUS_UNSET) {
2366
- return undefined;
2367
- }
2368
-
2369
- if (status.code === SPAN_STATUS_OK) {
2370
- return 'ok';
2371
- }
2372
-
2373
- return status.message || 'unknown_error';
2374
- }
2375
- const ROOT_SPAN_FIELD = '_sentryRootSpan';
2376
-
2377
- /**
2378
- * Returns the root span of a given span.
2379
- */
2380
- function getRootSpan(span) {
2381
- return span[ROOT_SPAN_FIELD] || span;
2382
- }
2383
-
2384
- /**
2385
- * Logs a warning once if `beforeSendSpan` is used to drop spans.
2386
- */
2387
- function showSpanDropWarning() {
2388
- if (!hasShownSpanDropWarning) {
2389
- consoleSandbox(() => {
2390
- // eslint-disable-next-line no-console
2391
- console.warn(
2392
- '[Sentry] Returning null from `beforeSendSpan` is disallowed. To drop certain spans, configure the respective integrations directly.',
2393
- );
2394
- });
2395
- hasShownSpanDropWarning = true;
2396
- }
2397
- }
2398
-
2399
- const STACKTRACE_FRAME_LIMIT = 50;
2400
- const UNKNOWN_FUNCTION = '?';
2401
- // Used to sanitize webpack (error: *) wrapped stack errors
2402
- const WEBPACK_ERROR_REGEXP = /\(error: (.*)\)/;
2403
- const STRIP_FRAME_REGEXP = /captureMessage|captureException/;
2404
-
2405
- /**
2406
- * Creates a stack parser with the supplied line parsers
2407
- *
2408
- * StackFrames are returned in the correct order for Sentry Exception
2409
- * frames and with Sentry SDK internal frames removed from the top and bottom
2410
- *
2411
- */
2412
- function createStackParser(...parsers) {
2413
- const sortedParsers = parsers.sort((a, b) => a[0] - b[0]).map(p => p[1]);
2414
-
2415
- return (stack, skipFirstLines = 0, framesToPop = 0) => {
2416
- const frames = [];
2417
- const lines = stack.split('\n');
2418
-
2419
- for (let i = skipFirstLines; i < lines.length; i++) {
2420
- const line = lines[i] ;
2421
- // Ignore lines over 1kb as they are unlikely to be stack frames.
2422
- // Many of the regular expressions use backtracking which results in run time that increases exponentially with
2423
- // input size. Huge strings can result in hangs/Denial of Service:
2424
- // https://github.com/getsentry/sentry-javascript/issues/2286
2425
- if (line.length > 1024) {
2426
- continue;
2427
- }
2428
-
2429
- // https://github.com/getsentry/sentry-javascript/issues/5459
2430
- // Remove webpack (error: *) wrappers
2431
- const cleanedLine = WEBPACK_ERROR_REGEXP.test(line) ? line.replace(WEBPACK_ERROR_REGEXP, '$1') : line;
2432
-
2433
- // https://github.com/getsentry/sentry-javascript/issues/7813
2434
- // Skip Error: lines
2435
- if (cleanedLine.match(/\S*Error: /)) {
2436
- continue;
2437
- }
2438
-
2439
- for (const parser of sortedParsers) {
2440
- const frame = parser(cleanedLine);
2441
-
2442
- if (frame) {
2443
- frames.push(frame);
2444
- break;
2445
- }
2446
- }
2447
-
2448
- if (frames.length >= STACKTRACE_FRAME_LIMIT + framesToPop) {
2449
- break;
2450
- }
2451
- }
2452
-
2453
- return stripSentryFramesAndReverse(frames.slice(framesToPop));
2454
- };
2455
- }
2456
-
2457
- /**
2458
- * Gets a stack parser implementation from Options.stackParser
2459
- * @see Options
2460
- *
2461
- * If options contains an array of line parsers, it is converted into a parser
2462
- */
2463
- function stackParserFromStackParserOptions(stackParser) {
2464
- if (Array.isArray(stackParser)) {
2465
- return createStackParser(...stackParser);
2466
- }
2467
- return stackParser;
2468
- }
2469
-
2470
- /**
2471
- * Removes Sentry frames from the top and bottom of the stack if present and enforces a limit of max number of frames.
2472
- * Assumes stack input is ordered from top to bottom and returns the reverse representation so call site of the
2473
- * function that caused the crash is the last frame in the array.
2474
- * @hidden
2475
- */
2476
- function stripSentryFramesAndReverse(stack) {
2477
- if (!stack.length) {
2478
- return [];
2479
- }
2480
-
2481
- const localStack = Array.from(stack);
2482
-
2483
- // If stack starts with one of our API calls, remove it (starts, meaning it's the top of the stack - aka last call)
2484
- if (/sentryWrapped/.test(getLastStackFrame(localStack).function || '')) {
2485
- localStack.pop();
2486
- }
2487
-
2488
- // Reversing in the middle of the procedure allows us to just pop the values off the stack
2489
- localStack.reverse();
2490
-
2491
- // If stack ends with one of our internal API calls, remove it (ends, meaning it's the bottom of the stack - aka top-most call)
2492
- if (STRIP_FRAME_REGEXP.test(getLastStackFrame(localStack).function || '')) {
2493
- localStack.pop();
2494
-
2495
- // When using synthetic events, we will have a 2 levels deep stack, as `new Error('Sentry syntheticException')`
2496
- // is produced within the scope itself, making it:
2497
- //
2498
- // Sentry.captureException()
2499
- // scope.captureException()
2500
- //
2501
- // instead of just the top `Sentry` call itself.
2502
- // This forces us to possibly strip an additional frame in the exact same was as above.
2503
- if (STRIP_FRAME_REGEXP.test(getLastStackFrame(localStack).function || '')) {
2504
- localStack.pop();
2505
- }
2506
- }
2507
-
2508
- return localStack.slice(0, STACKTRACE_FRAME_LIMIT).map(frame => ({
2509
- ...frame,
2510
- filename: frame.filename || getLastStackFrame(localStack).filename,
2511
- function: frame.function || UNKNOWN_FUNCTION,
2512
- }));
2513
- }
2514
-
2515
- function getLastStackFrame(arr) {
2516
- return arr[arr.length - 1] || {};
2517
- }
2518
-
2519
- const defaultFunctionName = '<anonymous>';
2520
-
2521
- /**
2522
- * Safely extract function name from itself
2523
- */
2524
- function getFunctionName(fn) {
2525
- try {
2526
- if (!fn || typeof fn !== 'function') {
2527
- return defaultFunctionName;
2528
- }
2529
- return fn.name || defaultFunctionName;
2530
- } catch (e) {
2531
- // Just accessing custom props in some Selenium environments
2532
- // can cause a "Permission denied" exception (see raven-js#495).
2533
- return defaultFunctionName;
2534
- }
2535
- }
2536
-
2537
- /**
2538
- * Get's stack frames from an event without needing to check for undefined properties.
2539
- */
2540
- function getFramesFromEvent(event) {
2541
- const exception = event.exception;
2542
-
2543
- if (exception) {
2544
- const frames = [];
2545
- try {
2546
- // @ts-expect-error Object could be undefined
2547
- exception.values.forEach(value => {
2548
- // @ts-expect-error Value could be undefined
2549
- if (value.stacktrace.frames) {
2550
- // @ts-expect-error Value could be undefined
2551
- frames.push(...value.stacktrace.frames);
2552
- }
2553
- });
2554
- return frames;
2555
- } catch (_oO) {
2556
- return undefined;
2557
- }
2558
- }
2559
- return undefined;
2560
- }
2561
-
2562
- // Treeshakable guard to remove all code related to tracing
2563
-
2564
- /**
2565
- * Determines if span recording is currently enabled.
2566
- *
2567
- * Spans are recorded when at least one of `tracesSampleRate` and `tracesSampler`
2568
- * is defined in the SDK config. This function does not make any assumption about
2569
- * sampling decisions, it only checks if the SDK is configured to record spans.
2570
- *
2571
- * Important: This function only determines if span recording is enabled. Trace
2572
- * continuation and propagation is separately controlled and not covered by this function.
2573
- * If this function returns `false`, traces can still be propagated (which is what
2574
- * we refer to by "Tracing without Performance")
2575
- * @see https://develop.sentry.dev/sdk/telemetry/traces/tracing-without-performance/
2576
- *
2577
- * @param maybeOptions An SDK options object to be passed to this function.
2578
- * If this option is not provided, the function will use the current client's options.
2579
- */
2580
- function hasSpansEnabled(
2581
- maybeOptions,
2582
- ) {
2583
- if (typeof __SENTRY_TRACING__ === 'boolean' && !__SENTRY_TRACING__) {
2584
- return false;
2585
- }
2586
-
2587
- const options = maybeOptions || getClient()?.getOptions();
2588
- return (
2589
- !!options &&
2590
- // Note: This check is `!= null`, meaning "nullish". `0` is not "nullish", `undefined` and `null` are. (This comment was brought to you by 15 minutes of questioning life)
2591
- (options.tracesSampleRate != null || !!options.tracesSampler)
2592
- );
2593
- }
2594
-
2595
- const DEFAULT_ENVIRONMENT = 'production';
2596
-
2597
- /** Regular expression used to extract org ID from a DSN host. */
2598
- const ORG_ID_REGEX = /^o(\d+)\./;
2599
-
2600
- /** Regular expression used to parse a Dsn. */
2601
- const DSN_REGEX = /^(?:(\w+):)\/\/(?:(\w+)(?::(\w+)?)?@)([\w.-]+)(?::(\d+))?\/(.+)/;
2602
-
2603
- function isValidProtocol(protocol) {
2604
- return protocol === 'http' || protocol === 'https';
2605
- }
2606
-
2607
- /**
2608
- * Renders the string representation of this Dsn.
2609
- *
2610
- * By default, this will render the public representation without the password
2611
- * component. To get the deprecated private representation, set `withPassword`
2612
- * to true.
2613
- *
2614
- * @param withPassword When set to true, the password will be included.
2615
- */
2616
- function dsnToString(dsn, withPassword = false) {
2617
- const { host, path, pass, port, projectId, protocol, publicKey } = dsn;
2618
- return (
2619
- `${protocol}://${publicKey}${withPassword && pass ? `:${pass}` : ''}` +
2620
- `@${host}${port ? `:${port}` : ''}/${path ? `${path}/` : path}${projectId}`
2621
- );
2622
- }
2623
-
2624
- /**
2625
- * Parses a Dsn from a given string.
2626
- *
2627
- * @param str A Dsn as string
2628
- * @returns Dsn as DsnComponents or undefined if @param str is not a valid DSN string
2629
- */
2630
- function dsnFromString(str) {
2631
- const match = DSN_REGEX.exec(str);
2632
-
2633
- if (!match) {
2634
- // This should be logged to the console
2635
- consoleSandbox(() => {
2636
- // eslint-disable-next-line no-console
2637
- console.error(`Invalid Sentry Dsn: ${str}`);
2638
- });
2639
- return undefined;
2640
- }
2641
-
2642
- const [protocol, publicKey, pass = '', host = '', port = '', lastPath = ''] = match.slice(1);
2643
- let path = '';
2644
- let projectId = lastPath;
2645
-
2646
- const split = projectId.split('/');
2647
- if (split.length > 1) {
2648
- path = split.slice(0, -1).join('/');
2649
- projectId = split.pop() ;
2650
- }
2651
-
2652
- if (projectId) {
2653
- const projectMatch = projectId.match(/^\d+/);
2654
- if (projectMatch) {
2655
- projectId = projectMatch[0];
2656
- }
2657
- }
2658
-
2659
- return dsnFromComponents({ host, pass, path, projectId, port, protocol: protocol , publicKey });
2660
- }
2661
-
2662
- function dsnFromComponents(components) {
2663
- return {
2664
- protocol: components.protocol,
2665
- publicKey: components.publicKey || '',
2666
- pass: components.pass || '',
2667
- host: components.host,
2668
- port: components.port || '',
2669
- path: components.path || '',
2670
- projectId: components.projectId,
2671
- };
2672
- }
2673
-
2674
- function validateDsn(dsn) {
2675
- if (!DEBUG_BUILD) {
2676
- return true;
2677
- }
2678
-
2679
- const { port, projectId, protocol } = dsn;
2680
-
2681
- const requiredComponents = ['protocol', 'publicKey', 'host', 'projectId'];
2682
- const hasMissingRequiredComponent = requiredComponents.find(component => {
2683
- if (!dsn[component]) {
2684
- logger.error(`Invalid Sentry Dsn: ${component} missing`);
2685
- return true;
2686
- }
2687
- return false;
2688
- });
2689
-
2690
- if (hasMissingRequiredComponent) {
2691
- return false;
2692
- }
2693
-
2694
- if (!projectId.match(/^\d+$/)) {
2695
- logger.error(`Invalid Sentry Dsn: Invalid projectId ${projectId}`);
2696
- return false;
2697
- }
2698
-
2699
- if (!isValidProtocol(protocol)) {
2700
- logger.error(`Invalid Sentry Dsn: Invalid protocol ${protocol}`);
2701
- return false;
2702
- }
2703
-
2704
- if (port && isNaN(parseInt(port, 10))) {
2705
- logger.error(`Invalid Sentry Dsn: Invalid port ${port}`);
2706
- return false;
2707
- }
2708
-
2709
- return true;
2710
- }
2711
-
2712
- /**
2713
- * Extract the org ID from a DSN host.
2714
- *
2715
- * @param host The host from a DSN
2716
- * @returns The org ID if found, undefined otherwise
2717
- */
2718
- function extractOrgIdFromDsnHost(host) {
2719
- const match = host.match(ORG_ID_REGEX);
2720
-
2721
- return match?.[1];
2722
- }
2723
-
2724
- /**
2725
- * Creates a valid Sentry Dsn object, identifying a Sentry instance and project.
2726
- * @returns a valid DsnComponents object or `undefined` if @param from is an invalid DSN source
2727
- */
2728
- function makeDsn(from) {
2729
- const components = typeof from === 'string' ? dsnFromString(from) : dsnFromComponents(from);
2730
- if (!components || !validateDsn(components)) {
2731
- return undefined;
2732
- }
2733
- return components;
2734
- }
2735
-
2736
- /**
2737
- * If you change this value, also update the terser plugin config to
2738
- * avoid minification of the object property!
2739
- */
2740
- const FROZEN_DSC_FIELD = '_frozenDsc';
2741
-
2742
- /**
2743
- * Creates a dynamic sampling context from a client.
2744
- *
2745
- * Dispatches the `createDsc` lifecycle hook as a side effect.
2746
- */
2747
- function getDynamicSamplingContextFromClient(trace_id, client) {
2748
- const options = client.getOptions();
2749
-
2750
- const { publicKey: public_key, host } = client.getDsn() || {};
2751
-
2752
- let org_id;
2753
- if (options.orgId) {
2754
- org_id = String(options.orgId);
2755
- } else if (host) {
2756
- org_id = extractOrgIdFromDsnHost(host);
2757
- }
2758
-
2759
- // Instead of conditionally adding non-undefined values, we add them and then remove them if needed
2760
- // otherwise, the order of baggage entries changes, which "breaks" a bunch of tests etc.
2761
- const dsc = {
2762
- environment: options.environment || DEFAULT_ENVIRONMENT,
2763
- release: options.release,
2764
- public_key,
2765
- trace_id,
2766
- org_id,
2767
- };
2768
-
2769
- client.emit('createDsc', dsc);
2770
-
2771
- return dsc;
2772
- }
2773
-
2774
- /**
2775
- * Get the dynamic sampling context for the currently active scopes.
2776
- */
2777
- function getDynamicSamplingContextFromScope(client, scope) {
2778
- const propagationContext = scope.getPropagationContext();
2779
- return propagationContext.dsc || getDynamicSamplingContextFromClient(propagationContext.traceId, client);
2780
- }
2781
-
2782
- /**
2783
- * Creates a dynamic sampling context from a span (and client and scope)
2784
- *
2785
- * @param span the span from which a few values like the root span name and sample rate are extracted.
2786
- *
2787
- * @returns a dynamic sampling context
2788
- */
2789
- function getDynamicSamplingContextFromSpan(span) {
2790
- const client = getClient();
2791
- if (!client) {
2792
- return {};
2793
- }
2794
-
2795
- const rootSpan = getRootSpan(span);
2796
- const rootSpanJson = spanToJSON(rootSpan);
2797
- const rootSpanAttributes = rootSpanJson.data;
2798
- const traceState = rootSpan.spanContext().traceState;
2799
-
2800
- // The span sample rate that was locally applied to the root span should also always be applied to the DSC, even if the DSC is frozen.
2801
- // This is so that the downstream traces/services can use parentSampleRate in their `tracesSampler` to make consistent sampling decisions across the entire trace.
2802
- const rootSpanSampleRate =
2803
- traceState?.get('sentry.sample_rate') ??
2804
- rootSpanAttributes[SEMANTIC_ATTRIBUTE_SENTRY_SAMPLE_RATE] ??
2805
- rootSpanAttributes[SEMANTIC_ATTRIBUTE_SENTRY_PREVIOUS_TRACE_SAMPLE_RATE];
2806
-
2807
- function applyLocalSampleRateToDsc(dsc) {
2808
- if (typeof rootSpanSampleRate === 'number' || typeof rootSpanSampleRate === 'string') {
2809
- dsc.sample_rate = `${rootSpanSampleRate}`;
2810
- }
2811
- return dsc;
2812
- }
2813
-
2814
- // For core implementation, we freeze the DSC onto the span as a non-enumerable property
2815
- const frozenDsc = (rootSpan )[FROZEN_DSC_FIELD];
2816
- if (frozenDsc) {
2817
- return applyLocalSampleRateToDsc(frozenDsc);
2818
- }
2819
-
2820
- // For OpenTelemetry, we freeze the DSC on the trace state
2821
- const traceStateDsc = traceState?.get('sentry.dsc');
2822
-
2823
- // If the span has a DSC, we want it to take precedence
2824
- const dscOnTraceState = traceStateDsc && baggageHeaderToDynamicSamplingContext(traceStateDsc);
2825
-
2826
- if (dscOnTraceState) {
2827
- return applyLocalSampleRateToDsc(dscOnTraceState);
2828
- }
2829
-
2830
- // Else, we generate it from the span
2831
- const dsc = getDynamicSamplingContextFromClient(span.spanContext().traceId, client);
2832
-
2833
- // We don't want to have a transaction name in the DSC if the source is "url" because URLs might contain PII
2834
- const source = rootSpanAttributes[SEMANTIC_ATTRIBUTE_SENTRY_SOURCE];
2835
-
2836
- // after JSON conversion, txn.name becomes jsonSpan.description
2837
- const name = rootSpanJson.description;
2838
- if (source !== 'url' && name) {
2839
- dsc.transaction = name;
2840
- }
2841
-
2842
- // How can we even land here with hasSpansEnabled() returning false?
2843
- // Otel creates a Non-recording span in Tracing Without Performance mode when handling incoming requests
2844
- // So we end up with an active span that is not sampled (neither positively nor negatively)
2845
- if (hasSpansEnabled()) {
2846
- dsc.sampled = String(spanIsSampled(rootSpan));
2847
- dsc.sample_rand =
2848
- // In OTEL we store the sample rand on the trace state because we cannot access scopes for NonRecordingSpans
2849
- // The Sentry OTEL SpanSampler takes care of writing the sample rand on the root span
2850
- traceState?.get('sentry.sample_rand') ??
2851
- // On all other platforms we can actually get the scopes from a root span (we use this as a fallback)
2852
- getCapturedScopesOnSpan(rootSpan).scope?.getPropagationContext().sampleRand.toString();
2853
- }
2854
-
2855
- applyLocalSampleRateToDsc(dsc);
2856
-
2857
- client.emit('createDsc', dsc, rootSpan);
2858
-
2859
- return dsc;
2860
- }
2861
-
2862
- /**
2863
- * Recursively normalizes the given object.
2864
- *
2865
- * - Creates a copy to prevent original input mutation
2866
- * - Skips non-enumerable properties
2867
- * - When stringifying, calls `toJSON` if implemented
2868
- * - Removes circular references
2869
- * - Translates non-serializable values (`undefined`/`NaN`/functions) to serializable format
2870
- * - Translates known global objects/classes to a string representations
2871
- * - Takes care of `Error` object serialization
2872
- * - Optionally limits depth of final output
2873
- * - Optionally limits number of properties/elements included in any single object/array
2874
- *
2875
- * @param input The object to be normalized.
2876
- * @param depth The max depth to which to normalize the object. (Anything deeper stringified whole.)
2877
- * @param maxProperties The max number of elements or properties to be included in any single array or
2878
- * object in the normalized output.
2879
- * @returns A normalized version of the object, or `"**non-serializable**"` if any errors are thrown during normalization.
2880
- */
2881
- // eslint-disable-next-line @typescript-eslint/no-explicit-any
2882
- function normalize(input, depth = 100, maxProperties = +Infinity) {
2883
- try {
2884
- // since we're at the outermost level, we don't provide a key
2885
- return visit('', input, depth, maxProperties);
2886
- } catch (err) {
2887
- return { ERROR: `**non-serializable** (${err})` };
2888
- }
2889
- }
2890
-
2891
- /** JSDoc */
2892
- function normalizeToSize(
2893
- // eslint-disable-next-line @typescript-eslint/no-explicit-any
2894
- object,
2895
- // Default Node.js REPL depth
2896
- depth = 3,
2897
- // 100kB, as 200kB is max payload size, so half sounds reasonable
2898
- maxSize = 100 * 1024,
2899
- ) {
2900
- const normalized = normalize(object, depth);
2901
-
2902
- if (jsonSize(normalized) > maxSize) {
2903
- return normalizeToSize(object, depth - 1, maxSize);
2904
- }
2905
-
2906
- return normalized ;
2907
- }
2908
-
2909
- /**
2910
- * Visits a node to perform normalization on it
2911
- *
2912
- * @param key The key corresponding to the given node
2913
- * @param value The node to be visited
2914
- * @param depth Optional number indicating the maximum recursion depth
2915
- * @param maxProperties Optional maximum number of properties/elements included in any single object/array
2916
- * @param memo Optional Memo class handling decycling
2917
- */
2918
- function visit(
2919
- key,
2920
- value,
2921
- depth = +Infinity,
2922
- maxProperties = +Infinity,
2923
- memo = memoBuilder(),
2924
- ) {
2925
- const [memoize, unmemoize] = memo;
2926
-
2927
- // Get the simple cases out of the way first
2928
- if (
2929
- value == null || // this matches null and undefined -> eqeq not eqeqeq
2930
- ['boolean', 'string'].includes(typeof value) ||
2931
- (typeof value === 'number' && Number.isFinite(value))
2932
- ) {
2933
- return value ;
2934
- }
2935
-
2936
- const stringified = stringifyValue(key, value);
2937
-
2938
- // Anything we could potentially dig into more (objects or arrays) will have come back as `"[object XXXX]"`.
2939
- // Everything else will have already been serialized, so if we don't see that pattern, we're done.
2940
- if (!stringified.startsWith('[object ')) {
2941
- return stringified;
2942
- }
2943
-
2944
- // From here on, we can assert that `value` is either an object or an array.
2945
-
2946
- // Do not normalize objects that we know have already been normalized. As a general rule, the
2947
- // "__sentry_skip_normalization__" property should only be used sparingly and only should only be set on objects that
2948
- // have already been normalized.
2949
- if ((value )['__sentry_skip_normalization__']) {
2950
- return value ;
2951
- }
2952
-
2953
- // We can set `__sentry_override_normalization_depth__` on an object to ensure that from there
2954
- // We keep a certain amount of depth.
2955
- // This should be used sparingly, e.g. we use it for the redux integration to ensure we get a certain amount of state.
2956
- const remainingDepth =
2957
- typeof (value )['__sentry_override_normalization_depth__'] === 'number'
2958
- ? ((value )['__sentry_override_normalization_depth__'] )
2959
- : depth;
2960
-
2961
- // We're also done if we've reached the max depth
2962
- if (remainingDepth === 0) {
2963
- // At this point we know `serialized` is a string of the form `"[object XXXX]"`. Clean it up so it's just `"[XXXX]"`.
2964
- return stringified.replace('object ', '');
2965
- }
2966
-
2967
- // If we've already visited this branch, bail out, as it's circular reference. If not, note that we're seeing it now.
2968
- if (memoize(value)) {
2969
- return '[Circular ~]';
2970
- }
2971
-
2972
- // If the value has a `toJSON` method, we call it to extract more information
2973
- const valueWithToJSON = value ;
2974
- if (valueWithToJSON && typeof valueWithToJSON.toJSON === 'function') {
2975
- try {
2976
- const jsonValue = valueWithToJSON.toJSON();
2977
- // We need to normalize the return value of `.toJSON()` in case it has circular references
2978
- return visit('', jsonValue, remainingDepth - 1, maxProperties, memo);
2979
- } catch (err) {
2980
- // pass (The built-in `toJSON` failed, but we can still try to do it ourselves)
2981
- }
2982
- }
2983
-
2984
- // At this point we know we either have an object or an array, we haven't seen it before, and we're going to recurse
2985
- // because we haven't yet reached the max depth. Create an accumulator to hold the results of visiting each
2986
- // property/entry, and keep track of the number of items we add to it.
2987
- const normalized = (Array.isArray(value) ? [] : {}) ;
2988
- let numAdded = 0;
2989
-
2990
- // Before we begin, convert`Error` and`Event` instances into plain objects, since some of each of their relevant
2991
- // properties are non-enumerable and otherwise would get missed.
2992
- const visitable = convertToPlainObject(value );
2993
-
2994
- for (const visitKey in visitable) {
2995
- // Avoid iterating over fields in the prototype if they've somehow been exposed to enumeration.
2996
- if (!Object.prototype.hasOwnProperty.call(visitable, visitKey)) {
2997
- continue;
2998
- }
2999
-
3000
- if (numAdded >= maxProperties) {
3001
- normalized[visitKey] = '[MaxProperties ~]';
3002
- break;
3003
- }
3004
-
3005
- // Recursively visit all the child nodes
3006
- const visitValue = visitable[visitKey];
3007
- normalized[visitKey] = visit(visitKey, visitValue, remainingDepth - 1, maxProperties, memo);
3008
-
3009
- numAdded++;
3010
- }
3011
-
3012
- // Once we've visited all the branches, remove the parent from memo storage
3013
- unmemoize(value);
3014
-
3015
- // Return accumulated values
3016
- return normalized;
3017
- }
3018
-
3019
- /* eslint-disable complexity */
3020
- /**
3021
- * Stringify the given value. Handles various known special values and types.
3022
- *
3023
- * Not meant to be used on simple primitives which already have a string representation, as it will, for example, turn
3024
- * the number 1231 into "[Object Number]", nor on `null`, as it will throw.
3025
- *
3026
- * @param value The value to stringify
3027
- * @returns A stringified representation of the given value
3028
- */
3029
- function stringifyValue(
3030
- key,
3031
- // this type is a tiny bit of a cheat, since this function does handle NaN (which is technically a number), but for
3032
- // our internal use, it'll do
3033
- value,
3034
- ) {
3035
- try {
3036
- if (key === 'domain' && value && typeof value === 'object' && (value )._events) {
3037
- return '[Domain]';
3038
- }
3039
-
3040
- if (key === 'domainEmitter') {
3041
- return '[DomainEmitter]';
3042
- }
3043
-
3044
- // It's safe to use `global`, `window`, and `document` here in this manner, as we are asserting using `typeof` first
3045
- // which won't throw if they are not present.
3046
-
3047
- if (typeof global !== 'undefined' && value === global) {
3048
- return '[Global]';
3049
- }
3050
-
3051
- // eslint-disable-next-line no-restricted-globals
3052
- if (typeof window !== 'undefined' && value === window) {
3053
- return '[Window]';
3054
- }
3055
-
3056
- // eslint-disable-next-line no-restricted-globals
3057
- if (typeof document !== 'undefined' && value === document) {
3058
- return '[Document]';
3059
- }
3060
-
3061
- if (isVueViewModel(value)) {
3062
- return '[VueViewModel]';
3063
- }
3064
-
3065
- // React's SyntheticEvent thingy
3066
- if (isSyntheticEvent(value)) {
3067
- return '[SyntheticEvent]';
3068
- }
3069
-
3070
- if (typeof value === 'number' && !Number.isFinite(value)) {
3071
- return `[${value}]`;
3072
- }
3073
-
3074
- if (typeof value === 'function') {
3075
- return `[Function: ${getFunctionName(value)}]`;
3076
- }
3077
-
3078
- if (typeof value === 'symbol') {
3079
- return `[${String(value)}]`;
3080
- }
3081
-
3082
- // stringified BigInts are indistinguishable from regular numbers, so we need to label them to avoid confusion
3083
- if (typeof value === 'bigint') {
3084
- return `[BigInt: ${String(value)}]`;
3085
- }
3086
-
3087
- // Now that we've knocked out all the special cases and the primitives, all we have left are objects. Simply casting
3088
- // them to strings means that instances of classes which haven't defined their `toStringTag` will just come out as
3089
- // `"[object Object]"`. If we instead look at the constructor's name (which is the same as the name of the class),
3090
- // we can make sure that only plain objects come out that way.
3091
- const objName = getConstructorName(value);
3092
-
3093
- // Handle HTML Elements
3094
- if (/^HTML(\w*)Element$/.test(objName)) {
3095
- return `[HTMLElement: ${objName}]`;
3096
- }
3097
-
3098
- return `[object ${objName}]`;
3099
- } catch (err) {
3100
- return `**non-serializable** (${err})`;
3101
- }
3102
- }
3103
- /* eslint-enable complexity */
3104
-
3105
- function getConstructorName(value) {
3106
- const prototype = Object.getPrototypeOf(value);
3107
-
3108
- return prototype?.constructor ? prototype.constructor.name : 'null prototype';
3109
- }
3110
-
3111
- /** Calculates bytes size of input string */
3112
- function utf8Length(value) {
3113
- // eslint-disable-next-line no-bitwise
3114
- return ~-encodeURI(value).split(/%..|./).length;
3115
- }
3116
-
3117
- /** Calculates bytes size of input object */
3118
- // eslint-disable-next-line @typescript-eslint/no-explicit-any
3119
- function jsonSize(value) {
3120
- return utf8Length(JSON.stringify(value));
3121
- }
3122
-
3123
- /**
3124
- * Helper to decycle json objects
3125
- */
3126
- function memoBuilder() {
3127
- const inner = new WeakSet();
3128
- function memoize(obj) {
3129
- if (inner.has(obj)) {
3130
- return true;
3131
- }
3132
- inner.add(obj);
3133
- return false;
3134
- }
3135
-
3136
- function unmemoize(obj) {
3137
- inner.delete(obj);
3138
- }
3139
- return [memoize, unmemoize];
3140
- }
3141
-
3142
- /* eslint-disable @typescript-eslint/no-explicit-any */
3143
-
3144
- /** SyncPromise internal states */
3145
- var States; (function (States) {
3146
- /** Pending */
3147
- const PENDING = 0; States[States["PENDING"] = PENDING] = "PENDING";
3148
- /** Resolved / OK */
3149
- const RESOLVED = 1; States[States["RESOLVED"] = RESOLVED] = "RESOLVED";
3150
- /** Rejected / Error */
3151
- const REJECTED = 2; States[States["REJECTED"] = REJECTED] = "REJECTED";
3152
- })(States || (States = {}));
3153
-
3154
- // Overloads so we can call resolvedSyncPromise without arguments and generic argument
3155
-
3156
- /**
3157
- * Creates a resolved sync promise.
3158
- *
3159
- * @param value the value to resolve the promise with
3160
- * @returns the resolved sync promise
3161
- */
3162
- function resolvedSyncPromise(value) {
3163
- return new SyncPromise(resolve => {
3164
- resolve(value);
3165
- });
3166
- }
3167
-
3168
- /**
3169
- * Creates a rejected sync promise.
3170
- *
3171
- * @param value the value to reject the promise with
3172
- * @returns the rejected sync promise
3173
- */
3174
- function rejectedSyncPromise(reason) {
3175
- return new SyncPromise((_, reject) => {
3176
- reject(reason);
3177
- });
3178
- }
3179
-
3180
- /**
3181
- * Thenable class that behaves like a Promise and follows it's interface
3182
- * but is not async internally
3183
- */
3184
- class SyncPromise {
3185
-
3186
- constructor(executor) {
3187
- this._state = States.PENDING;
3188
- this._handlers = [];
3189
-
3190
- this._runExecutor(executor);
3191
- }
3192
-
3193
- /** @inheritdoc */
3194
- then(
3195
- onfulfilled,
3196
- onrejected,
3197
- ) {
3198
- return new SyncPromise((resolve, reject) => {
3199
- this._handlers.push([
3200
- false,
3201
- result => {
3202
- if (!onfulfilled) {
3203
- // TODO: ¯\_(ツ)_/¯
3204
- // TODO: FIXME
3205
- resolve(result );
3206
- } else {
3207
- try {
3208
- resolve(onfulfilled(result));
3209
- } catch (e) {
3210
- reject(e);
3211
- }
3212
- }
3213
- },
3214
- reason => {
3215
- if (!onrejected) {
3216
- reject(reason);
3217
- } else {
3218
- try {
3219
- resolve(onrejected(reason));
3220
- } catch (e) {
3221
- reject(e);
3222
- }
3223
- }
3224
- },
3225
- ]);
3226
- this._executeHandlers();
3227
- });
3228
- }
3229
-
3230
- /** @inheritdoc */
3231
- catch(
3232
- onrejected,
3233
- ) {
3234
- return this.then(val => val, onrejected);
3235
- }
3236
-
3237
- /** @inheritdoc */
3238
- finally(onfinally) {
3239
- return new SyncPromise((resolve, reject) => {
3240
- let val;
3241
- let isRejected;
3242
-
3243
- return this.then(
3244
- value => {
3245
- isRejected = false;
3246
- val = value;
3247
- if (onfinally) {
3248
- onfinally();
3249
- }
3250
- },
3251
- reason => {
3252
- isRejected = true;
3253
- val = reason;
3254
- if (onfinally) {
3255
- onfinally();
3256
- }
3257
- },
3258
- ).then(() => {
3259
- if (isRejected) {
3260
- reject(val);
3261
- return;
3262
- }
3263
-
3264
- resolve(val );
3265
- });
3266
- });
3267
- }
3268
-
3269
- /** Excute the resolve/reject handlers. */
3270
- _executeHandlers() {
3271
- if (this._state === States.PENDING) {
3272
- return;
3273
- }
3274
-
3275
- const cachedHandlers = this._handlers.slice();
3276
- this._handlers = [];
3277
-
3278
- cachedHandlers.forEach(handler => {
3279
- if (handler[0]) {
3280
- return;
3281
- }
3282
-
3283
- if (this._state === States.RESOLVED) {
3284
- handler[1](this._value );
3285
- }
3286
-
3287
- if (this._state === States.REJECTED) {
3288
- handler[2](this._value);
3289
- }
3290
-
3291
- handler[0] = true;
3292
- });
3293
- }
3294
-
3295
- /** Run the executor for the SyncPromise. */
3296
- _runExecutor(executor) {
3297
- const setResult = (state, value) => {
3298
- if (this._state !== States.PENDING) {
3299
- return;
3300
- }
3301
-
3302
- if (isThenable(value)) {
3303
- void (value ).then(resolve, reject);
3304
- return;
3305
- }
3306
-
3307
- this._state = state;
3308
- this._value = value;
3309
-
3310
- this._executeHandlers();
3311
- };
3312
-
3313
- const resolve = (value) => {
3314
- setResult(States.RESOLVED, value);
3315
- };
3316
-
3317
- const reject = (reason) => {
3318
- setResult(States.REJECTED, reason);
3319
- };
3320
-
3321
- try {
3322
- executor(resolve, reject);
3323
- } catch (e) {
3324
- reject(e);
3325
- }
3326
- }
3327
- }
3328
-
3329
- /**
3330
- * Process an array of event processors, returning the processed event (or `null` if the event was dropped).
3331
- */
3332
- function notifyEventProcessors(
3333
- processors,
3334
- event,
3335
- hint,
3336
- index = 0,
3337
- ) {
3338
- return new SyncPromise((resolve, reject) => {
3339
- const processor = processors[index];
3340
- if (event === null || typeof processor !== 'function') {
3341
- resolve(event);
3342
- } else {
3343
- const result = processor({ ...event }, hint) ;
3344
-
3345
- DEBUG_BUILD && processor.id && result === null && logger.log(`Event processor "${processor.id}" dropped event`);
3346
-
3347
- if (isThenable(result)) {
3348
- void result
3349
- .then(final => notifyEventProcessors(processors, final, hint, index + 1).then(resolve))
3350
- .then(null, reject);
3351
- } else {
3352
- void notifyEventProcessors(processors, result, hint, index + 1)
3353
- .then(resolve)
3354
- .then(null, reject);
3355
- }
3356
- }
3357
- });
3358
- }
3359
-
3360
- let parsedStackResults;
3361
- let lastKeysCount;
3362
- let cachedFilenameDebugIds;
3363
-
3364
- /**
3365
- * Returns a map of filenames to debug identifiers.
3366
- */
3367
- function getFilenameToDebugIdMap(stackParser) {
3368
- const debugIdMap = GLOBAL_OBJ._sentryDebugIds;
3369
- if (!debugIdMap) {
3370
- return {};
3371
- }
3372
-
3373
- const debugIdKeys = Object.keys(debugIdMap);
3374
-
3375
- // If the count of registered globals hasn't changed since the last call, we
3376
- // can just return the cached result.
3377
- if (cachedFilenameDebugIds && debugIdKeys.length === lastKeysCount) {
3378
- return cachedFilenameDebugIds;
3379
- }
3380
-
3381
- lastKeysCount = debugIdKeys.length;
3382
-
3383
- // Build a map of filename -> debug_id.
3384
- cachedFilenameDebugIds = debugIdKeys.reduce((acc, stackKey) => {
3385
- if (!parsedStackResults) {
3386
- parsedStackResults = {};
3387
- }
3388
-
3389
- const result = parsedStackResults[stackKey];
3390
-
3391
- if (result) {
3392
- acc[result[0]] = result[1];
3393
- } else {
3394
- const parsedStack = stackParser(stackKey);
3395
-
3396
- for (let i = parsedStack.length - 1; i >= 0; i--) {
3397
- const stackFrame = parsedStack[i];
3398
- const filename = stackFrame?.filename;
3399
- const debugId = debugIdMap[stackKey];
3400
-
3401
- if (filename && debugId) {
3402
- acc[filename] = debugId;
3403
- parsedStackResults[stackKey] = [filename, debugId];
3404
- break;
3405
- }
3406
- }
3407
- }
3408
-
3409
- return acc;
3410
- }, {});
3411
-
3412
- return cachedFilenameDebugIds;
3413
- }
3414
-
3415
- /**
3416
- * Applies data from the scope to the event and runs all event processors on it.
3417
- */
3418
- function applyScopeDataToEvent(event, data) {
3419
- const { fingerprint, span, breadcrumbs, sdkProcessingMetadata } = data;
3420
-
3421
- // Apply general data
3422
- applyDataToEvent(event, data);
3423
-
3424
- // We want to set the trace context for normal events only if there isn't already
3425
- // a trace context on the event. There is a product feature in place where we link
3426
- // errors with transaction and it relies on that.
3427
- if (span) {
3428
- applySpanToEvent(event, span);
3429
- }
3430
-
3431
- applyFingerprintToEvent(event, fingerprint);
3432
- applyBreadcrumbsToEvent(event, breadcrumbs);
3433
- applySdkMetadataToEvent(event, sdkProcessingMetadata);
3434
- }
3435
-
3436
- /** Merge data of two scopes together. */
3437
- function mergeScopeData(data, mergeData) {
3438
- const {
3439
- extra,
3440
- tags,
3441
- user,
3442
- contexts,
3443
- level,
3444
- sdkProcessingMetadata,
3445
- breadcrumbs,
3446
- fingerprint,
3447
- eventProcessors,
3448
- attachments,
3449
- propagationContext,
3450
- transactionName,
3451
- span,
3452
- } = mergeData;
3453
-
3454
- mergeAndOverwriteScopeData(data, 'extra', extra);
3455
- mergeAndOverwriteScopeData(data, 'tags', tags);
3456
- mergeAndOverwriteScopeData(data, 'user', user);
3457
- mergeAndOverwriteScopeData(data, 'contexts', contexts);
3458
-
3459
- data.sdkProcessingMetadata = merge(data.sdkProcessingMetadata, sdkProcessingMetadata, 2);
3460
-
3461
- if (level) {
3462
- data.level = level;
3463
- }
3464
-
3465
- if (transactionName) {
3466
- data.transactionName = transactionName;
3467
- }
3468
-
3469
- if (span) {
3470
- data.span = span;
3471
- }
3472
-
3473
- if (breadcrumbs.length) {
3474
- data.breadcrumbs = [...data.breadcrumbs, ...breadcrumbs];
3475
- }
3476
-
3477
- if (fingerprint.length) {
3478
- data.fingerprint = [...data.fingerprint, ...fingerprint];
3479
- }
3480
-
3481
- if (eventProcessors.length) {
3482
- data.eventProcessors = [...data.eventProcessors, ...eventProcessors];
3483
- }
3484
-
3485
- if (attachments.length) {
3486
- data.attachments = [...data.attachments, ...attachments];
3487
- }
3488
-
3489
- data.propagationContext = { ...data.propagationContext, ...propagationContext };
3490
- }
3491
-
3492
- /**
3493
- * Merges certain scope data. Undefined values will overwrite any existing values.
3494
- * Exported only for tests.
3495
- */
3496
- function mergeAndOverwriteScopeData
3497
-
3498
- (data, prop, mergeVal) {
3499
- data[prop] = merge(data[prop], mergeVal, 1);
3500
- }
3501
-
3502
- function applyDataToEvent(event, data) {
3503
- const { extra, tags, user, contexts, level, transactionName } = data;
3504
-
3505
- if (Object.keys(extra).length) {
3506
- event.extra = { ...extra, ...event.extra };
3507
- }
3508
-
3509
- if (Object.keys(tags).length) {
3510
- event.tags = { ...tags, ...event.tags };
3511
- }
3512
-
3513
- if (Object.keys(user).length) {
3514
- event.user = { ...user, ...event.user };
3515
- }
3516
-
3517
- if (Object.keys(contexts).length) {
3518
- event.contexts = { ...contexts, ...event.contexts };
3519
- }
3520
-
3521
- if (level) {
3522
- event.level = level;
3523
- }
3524
-
3525
- // transaction events get their `transaction` from the root span name
3526
- if (transactionName && event.type !== 'transaction') {
3527
- event.transaction = transactionName;
3528
- }
3529
- }
3530
-
3531
- function applyBreadcrumbsToEvent(event, breadcrumbs) {
3532
- const mergedBreadcrumbs = [...(event.breadcrumbs || []), ...breadcrumbs];
3533
- event.breadcrumbs = mergedBreadcrumbs.length ? mergedBreadcrumbs : undefined;
3534
- }
3535
-
3536
- function applySdkMetadataToEvent(event, sdkProcessingMetadata) {
3537
- event.sdkProcessingMetadata = {
3538
- ...event.sdkProcessingMetadata,
3539
- ...sdkProcessingMetadata,
3540
- };
3541
- }
3542
-
3543
- function applySpanToEvent(event, span) {
3544
- event.contexts = {
3545
- trace: spanToTraceContext(span),
3546
- ...event.contexts,
3547
- };
3548
-
3549
- event.sdkProcessingMetadata = {
3550
- dynamicSamplingContext: getDynamicSamplingContextFromSpan(span),
3551
- ...event.sdkProcessingMetadata,
3552
- };
3553
-
3554
- const rootSpan = getRootSpan(span);
3555
- const transactionName = spanToJSON(rootSpan).description;
3556
- if (transactionName && !event.transaction && event.type === 'transaction') {
3557
- event.transaction = transactionName;
3558
- }
3559
- }
3560
-
3561
- /**
3562
- * Applies fingerprint from the scope to the event if there's one,
3563
- * uses message if there's one instead or get rid of empty fingerprint
3564
- */
3565
- function applyFingerprintToEvent(event, fingerprint) {
3566
- // Make sure it's an array first and we actually have something in place
3567
- event.fingerprint = event.fingerprint
3568
- ? Array.isArray(event.fingerprint)
3569
- ? event.fingerprint
3570
- : [event.fingerprint]
3571
- : [];
3572
-
3573
- // If we have something on the scope, then merge it with event
3574
- if (fingerprint) {
3575
- event.fingerprint = event.fingerprint.concat(fingerprint);
3576
- }
3577
-
3578
- // If we have no data at all, remove empty array default
3579
- if (!event.fingerprint.length) {
3580
- delete event.fingerprint;
3581
- }
3582
- }
3583
-
3584
- /**
3585
- * This type makes sure that we get either a CaptureContext, OR an EventHint.
3586
- * It does not allow mixing them, which could lead to unexpected outcomes, e.g. this is disallowed:
3587
- * { user: { id: '123' }, mechanism: { handled: false } }
3588
- */
3589
-
3590
- /**
3591
- * Adds common information to events.
3592
- *
3593
- * The information includes release and environment from `options`,
3594
- * breadcrumbs and context (extra, tags and user) from the scope.
3595
- *
3596
- * Information that is already present in the event is never overwritten. For
3597
- * nested objects, such as the context, keys are merged.
3598
- *
3599
- * @param event The original event.
3600
- * @param hint May contain additional information about the original exception.
3601
- * @param scope A scope containing event metadata.
3602
- * @returns A new event with more information.
3603
- * @hidden
3604
- */
3605
- function prepareEvent(
3606
- options,
3607
- event,
3608
- hint,
3609
- scope,
3610
- client,
3611
- isolationScope,
3612
- ) {
3613
- const { normalizeDepth = 3, normalizeMaxBreadth = 1000 } = options;
3614
- const prepared = {
3615
- ...event,
3616
- event_id: event.event_id || hint.event_id || uuid4(),
3617
- timestamp: event.timestamp || dateTimestampInSeconds(),
3618
- };
3619
- const integrations = hint.integrations || options.integrations.map(i => i.name);
3620
-
3621
- applyClientOptions(prepared, options);
3622
- applyIntegrationsMetadata(prepared, integrations);
3623
-
3624
- if (client) {
3625
- client.emit('applyFrameMetadata', event);
3626
- }
3627
-
3628
- // Only put debug IDs onto frames for error events.
3629
- if (event.type === undefined) {
3630
- applyDebugIds(prepared, options.stackParser);
3631
- }
3632
-
3633
- // If we have scope given to us, use it as the base for further modifications.
3634
- // This allows us to prevent unnecessary copying of data if `captureContext` is not provided.
3635
- const finalScope = getFinalScope(scope, hint.captureContext);
3636
-
3637
- if (hint.mechanism) {
3638
- addExceptionMechanism(prepared, hint.mechanism);
3639
- }
3640
-
3641
- const clientEventProcessors = client ? client.getEventProcessors() : [];
3642
-
3643
- // This should be the last thing called, since we want that
3644
- // {@link Scope.addEventProcessor} gets the finished prepared event.
3645
- // Merge scope data together
3646
- const data = getGlobalScope().getScopeData();
3647
-
3648
- if (isolationScope) {
3649
- const isolationData = isolationScope.getScopeData();
3650
- mergeScopeData(data, isolationData);
3651
- }
3652
-
3653
- if (finalScope) {
3654
- const finalScopeData = finalScope.getScopeData();
3655
- mergeScopeData(data, finalScopeData);
3656
- }
3657
-
3658
- const attachments = [...(hint.attachments || []), ...data.attachments];
3659
- if (attachments.length) {
3660
- hint.attachments = attachments;
3661
- }
3662
-
3663
- applyScopeDataToEvent(prepared, data);
3664
-
3665
- const eventProcessors = [
3666
- ...clientEventProcessors,
3667
- // Run scope event processors _after_ all other processors
3668
- ...data.eventProcessors,
3669
- ];
3670
-
3671
- const result = notifyEventProcessors(eventProcessors, prepared, hint);
3672
-
3673
- return result.then(evt => {
3674
- if (evt) {
3675
- // We apply the debug_meta field only after all event processors have ran, so that if any event processors modified
3676
- // file names (e.g.the RewriteFrames integration) the filename -> debug ID relationship isn't destroyed.
3677
- // This should not cause any PII issues, since we're only moving data that is already on the event and not adding
3678
- // any new data
3679
- applyDebugMeta(evt);
3680
- }
3681
-
3682
- if (typeof normalizeDepth === 'number' && normalizeDepth > 0) {
3683
- return normalizeEvent(evt, normalizeDepth, normalizeMaxBreadth);
3684
- }
3685
- return evt;
3686
- });
3687
- }
3688
-
3689
- /**
3690
- * Enhances event using the client configuration.
3691
- * It takes care of all "static" values like environment, release and `dist`,
3692
- * as well as truncating overly long values.
3693
- *
3694
- * Only exported for tests.
3695
- *
3696
- * @param event event instance to be enhanced
3697
- */
3698
- function applyClientOptions(event, options) {
3699
- const { environment, release, dist, maxValueLength = 250 } = options;
3700
-
3701
- // empty strings do not make sense for environment, release, and dist
3702
- // so we handle them the same as if they were not provided
3703
- event.environment = event.environment || environment || DEFAULT_ENVIRONMENT;
3704
-
3705
- if (!event.release && release) {
3706
- event.release = release;
3707
- }
3708
-
3709
- if (!event.dist && dist) {
3710
- event.dist = dist;
3711
- }
3712
-
3713
- const request = event.request;
3714
- if (request?.url) {
3715
- request.url = truncate(request.url, maxValueLength);
3716
- }
3717
- }
3718
-
3719
- /**
3720
- * Puts debug IDs into the stack frames of an error event.
3721
- */
3722
- function applyDebugIds(event, stackParser) {
3723
- // Build a map of filename -> debug_id
3724
- const filenameDebugIdMap = getFilenameToDebugIdMap(stackParser);
3725
-
3726
- event.exception?.values?.forEach(exception => {
3727
- exception.stacktrace?.frames?.forEach(frame => {
3728
- if (frame.filename) {
3729
- frame.debug_id = filenameDebugIdMap[frame.filename];
3730
- }
3731
- });
3732
- });
3733
- }
3734
-
3735
- /**
3736
- * Moves debug IDs from the stack frames of an error event into the debug_meta field.
3737
- */
3738
- function applyDebugMeta(event) {
3739
- // Extract debug IDs and filenames from the stack frames on the event.
3740
- const filenameDebugIdMap = {};
3741
- event.exception?.values?.forEach(exception => {
3742
- exception.stacktrace?.frames?.forEach(frame => {
3743
- if (frame.debug_id) {
3744
- if (frame.abs_path) {
3745
- filenameDebugIdMap[frame.abs_path] = frame.debug_id;
3746
- } else if (frame.filename) {
3747
- filenameDebugIdMap[frame.filename] = frame.debug_id;
3748
- }
3749
- delete frame.debug_id;
3750
- }
3751
- });
3752
- });
3753
-
3754
- if (Object.keys(filenameDebugIdMap).length === 0) {
3755
- return;
3756
- }
3757
-
3758
- // Fill debug_meta information
3759
- event.debug_meta = event.debug_meta || {};
3760
- event.debug_meta.images = event.debug_meta.images || [];
3761
- const images = event.debug_meta.images;
3762
- Object.entries(filenameDebugIdMap).forEach(([filename, debug_id]) => {
3763
- images.push({
3764
- type: 'sourcemap',
3765
- code_file: filename,
3766
- debug_id,
3767
- });
3768
- });
3769
- }
3770
-
3771
- /**
3772
- * This function adds all used integrations to the SDK info in the event.
3773
- * @param event The event that will be filled with all integrations.
3774
- */
3775
- function applyIntegrationsMetadata(event, integrationNames) {
3776
- if (integrationNames.length > 0) {
3777
- event.sdk = event.sdk || {};
3778
- event.sdk.integrations = [...(event.sdk.integrations || []), ...integrationNames];
3779
- }
3780
- }
3781
-
3782
- /**
3783
- * Applies `normalize` function on necessary `Event` attributes to make them safe for serialization.
3784
- * Normalized keys:
3785
- * - `breadcrumbs.data`
3786
- * - `user`
3787
- * - `contexts`
3788
- * - `extra`
3789
- * @param event Event
3790
- * @returns Normalized event
3791
- */
3792
- function normalizeEvent(event, depth, maxBreadth) {
3793
- if (!event) {
3794
- return null;
3795
- }
3796
-
3797
- const normalized = {
3798
- ...event,
3799
- ...(event.breadcrumbs && {
3800
- breadcrumbs: event.breadcrumbs.map(b => ({
3801
- ...b,
3802
- ...(b.data && {
3803
- data: normalize(b.data, depth, maxBreadth),
3804
- }),
3805
- })),
3806
- }),
3807
- ...(event.user && {
3808
- user: normalize(event.user, depth, maxBreadth),
3809
- }),
3810
- ...(event.contexts && {
3811
- contexts: normalize(event.contexts, depth, maxBreadth),
3812
- }),
3813
- ...(event.extra && {
3814
- extra: normalize(event.extra, depth, maxBreadth),
3815
- }),
3816
- };
3817
-
3818
- // event.contexts.trace stores information about a Transaction. Similarly,
3819
- // event.spans[] stores information about child Spans. Given that a
3820
- // Transaction is conceptually a Span, normalization should apply to both
3821
- // Transactions and Spans consistently.
3822
- // For now the decision is to skip normalization of Transactions and Spans,
3823
- // so this block overwrites the normalized event to add back the original
3824
- // Transaction information prior to normalization.
3825
- if (event.contexts?.trace && normalized.contexts) {
3826
- normalized.contexts.trace = event.contexts.trace;
3827
-
3828
- // event.contexts.trace.data may contain circular/dangerous data so we need to normalize it
3829
- if (event.contexts.trace.data) {
3830
- normalized.contexts.trace.data = normalize(event.contexts.trace.data, depth, maxBreadth);
3831
- }
3832
- }
3833
-
3834
- // event.spans[].data may contain circular/dangerous data so we need to normalize it
3835
- if (event.spans) {
3836
- normalized.spans = event.spans.map(span => {
3837
- return {
3838
- ...span,
3839
- ...(span.data && {
3840
- data: normalize(span.data, depth, maxBreadth),
3841
- }),
3842
- };
3843
- });
3844
- }
3845
-
3846
- // event.contexts.flags (FeatureFlagContext) stores context for our feature
3847
- // flag integrations. It has a greater nesting depth than our other typed
3848
- // Contexts, so we re-normalize with a fixed depth of 3 here. We do not want
3849
- // to skip this in case of conflicting, user-provided context.
3850
- if (event.contexts?.flags && normalized.contexts) {
3851
- normalized.contexts.flags = normalize(event.contexts.flags, 3, maxBreadth);
3852
- }
3853
-
3854
- return normalized;
3855
- }
3856
-
3857
- function getFinalScope(scope, captureContext) {
3858
- if (!captureContext) {
3859
- return scope;
3860
- }
3861
-
3862
- const finalScope = scope ? scope.clone() : new Scope();
3863
- finalScope.update(captureContext);
3864
- return finalScope;
3865
- }
3866
-
3867
- /**
3868
- * Parse either an `EventHint` directly, or convert a `CaptureContext` to an `EventHint`.
3869
- * This is used to allow to update method signatures that used to accept a `CaptureContext` but should now accept an `EventHint`.
3870
- */
3871
- function parseEventHintOrCaptureContext(
3872
- hint,
3873
- ) {
3874
- {
3875
- return undefined;
3876
- }
3877
- }
3878
-
3879
- /**
3880
- * Captures an exception event and sends it to Sentry.
3881
- *
3882
- * @param exception The exception to capture.
3883
- * @param hint Optional additional data to attach to the Sentry event.
3884
- * @returns the id of the captured Sentry event.
3885
- */
3886
- function captureException(exception, hint) {
3887
- return getCurrentScope().captureException(exception, parseEventHintOrCaptureContext());
3888
- }
3889
-
3890
- /**
3891
- * Captures a message event and sends it to Sentry.
3892
- *
3893
- * @param message The message to send to Sentry.
3894
- * @param captureContext Define the level of the message or pass in additional data to attach to the message.
3895
- * @returns the id of the captured message.
3896
- */
3897
- function captureMessage(message, captureContext) {
3898
- // This is necessary to provide explicit scopes upgrade, without changing the original
3899
- // arity of the `captureMessage(message, level)` method.
3900
- const level = undefined;
3901
- const context = { captureContext } ;
3902
- return getCurrentScope().captureMessage(message, level, context);
3903
- }
3904
-
3905
- /**
3906
- * Captures a manually created event and sends it to Sentry.
3907
- *
3908
- * @param event The event to send to Sentry.
3909
- * @param hint Optional additional data to attach to the Sentry event.
3910
- * @returns the id of the captured event.
3911
- */
3912
- function captureEvent(event, hint) {
3913
- return getCurrentScope().captureEvent(event, hint);
3914
- }
3915
-
3916
- /**
3917
- * Sets context data with the given name.
3918
- * @param name of the context
3919
- * @param context Any kind of data. This data will be normalized.
3920
- */
3921
- function setContext(name, context) {
3922
- getIsolationScope().setContext(name, context);
3923
- }
3924
-
3925
- /**
3926
- * Updates user context information for future events.
3927
- *
3928
- * @param user User context object to be set in the current context. Pass `null` to unset the user.
3929
- */
3930
- function setUser(user) {
3931
- getIsolationScope().setUser(user);
3932
- }
3933
-
3934
- /**
3935
- * Start a session on the current isolation scope.
3936
- *
3937
- * @param context (optional) additional properties to be applied to the returned session object
3938
- *
3939
- * @returns the new active session
3940
- */
3941
- function startSession(context) {
3942
- const isolationScope = getIsolationScope();
3943
- const currentScope = getCurrentScope();
3944
-
3945
- // Will fetch userAgent if called from browser sdk
3946
- const { userAgent } = GLOBAL_OBJ.navigator || {};
3947
-
3948
- const session = makeSession({
3949
- user: currentScope.getUser() || isolationScope.getUser(),
3950
- ...(userAgent && { userAgent }),
3951
- ...context,
3952
- });
3953
-
3954
- // End existing session if there's one
3955
- const currentSession = isolationScope.getSession();
3956
- if (currentSession?.status === 'ok') {
3957
- updateSession(currentSession, { status: 'exited' });
3958
- }
3959
-
3960
- endSession();
3961
-
3962
- // Afterwards we set the new session on the scope
3963
- isolationScope.setSession(session);
3964
-
3965
- return session;
3966
- }
3967
-
3968
- /**
3969
- * End the session on the current isolation scope.
3970
- */
3971
- function endSession() {
3972
- const isolationScope = getIsolationScope();
3973
- const currentScope = getCurrentScope();
3974
-
3975
- const session = currentScope.getSession() || isolationScope.getSession();
3976
- if (session) {
3977
- closeSession(session);
3978
- }
3979
- _sendSessionUpdate();
3980
-
3981
- // the session is over; take it off of the scope
3982
- isolationScope.setSession();
3983
- }
3984
-
3985
- /**
3986
- * Sends the current Session on the scope
3987
- */
3988
- function _sendSessionUpdate() {
3989
- const isolationScope = getIsolationScope();
3990
- const client = getClient();
3991
- const session = isolationScope.getSession();
3992
- if (session && client) {
3993
- client.captureSession(session);
3994
- }
3995
- }
3996
-
3997
- /**
3998
- * Sends the current session on the scope to Sentry
3999
- *
4000
- * @param end If set the session will be marked as exited and removed from the scope.
4001
- * Defaults to `false`.
4002
- */
4003
- function captureSession(end = false) {
4004
- // both send the update and pull the session from the scope
4005
- if (end) {
4006
- endSession();
4007
- return;
4008
- }
4009
-
4010
- // only send the update
4011
- _sendSessionUpdate();
4012
- }
4013
-
4014
- export { isErrorEvent as $, showSpanDropWarning as A, merge as B, isThenable as C, DEBUG_BUILD as D, isPlainObject as E, consoleSandbox as F, GLOBAL_OBJ as G, SDK_VERSION as H, getClient as I, getOriginalFunction as J, getEventDescription as K, stringMatchesSomePattern as L, isInstanceOf as M, CONSOLE_LEVELS as N, fill as O, originalConsoleMethods as P, getFramesFromEvent as Q, timestampInSeconds as R, SEMANTIC_ATTRIBUTE_EXCLUSIVE_TIME as S, isError as T, addNonEnumerableProperty as U, isRequest as V, getLocationHref as W, markFunctionWrapped as X, withScope as Y, addExceptionTypeValue as Z, addExceptionMechanism as _, setContext as a, isDOMError as a0, isDOMException as a1, isEvent as a2, normalizeToSize as a3, extractExceptionKeysForMessage as a4, isString as a5, createStackParser as a6, UNKNOWN_FUNCTION as a7, htmlTreeAsString as a8, safeJoin as a9, getComponentName as aa, startSession as ab, captureSession as ac, captureEvent as ad, stackParserFromStackParserOptions as ae, captureMessage as b, captureException as c, dsnToString as d, getSentryCarrier as e, SEMANTIC_ATTRIBUTE_PROFILE_ID as f, getFunctionName as g, dateTimestampInSeconds as h, checkOrSetAlreadyCaught as i, isPrimitive as j, updateSession as k, logger as l, makeDsn as m, normalize as n, DEFAULT_ENVIRONMENT as o, SyncPromise as p, prepareEvent as q, resolvedSyncPromise as r, setUser as s, getTraceContextFromScope as t, uuid4 as u, getDynamicSamplingContextFromScope as v, getCurrentScope as w, getIsolationScope as x, rejectedSyncPromise as y, isParameterizedString as z };
4015
- //# sourceMappingURL=exports-Bs-zO1WZ.js.map
4016
-
4017
- //# sourceMappingURL=exports-Bs-zO1WZ.js.map