@nathanclaire/edge-telemetry-sdk 3.0.0 → 5.0.1

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 (319) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +985 -185
  3. package/dist/appLifecycle-DS_fEclk.cjs +2 -0
  4. package/dist/appLifecycle-DS_fEclk.cjs.map +1 -0
  5. package/dist/appLifecycle-PffQ4vC1.js +24 -0
  6. package/dist/appLifecycle-PffQ4vC1.js.map +1 -0
  7. package/dist/autoTaps.native-By9I4Kr2.cjs +2 -0
  8. package/dist/autoTaps.native-By9I4Kr2.cjs.map +1 -0
  9. package/dist/autoTaps.native-DQCXevD7.js +66 -0
  10. package/dist/autoTaps.native-DQCXevD7.js.map +1 -0
  11. package/dist/crashHandler.web-6KvedEB-.cjs +2 -0
  12. package/dist/crashHandler.web-6KvedEB-.cjs.map +1 -0
  13. package/dist/crashHandler.web-BUlSXYoS.js +30 -0
  14. package/dist/crashHandler.web-BUlSXYoS.js.map +1 -0
  15. package/dist/crashHandlerNative.native-CFVQ5UcO.cjs +2 -0
  16. package/dist/crashHandlerNative.native-CFVQ5UcO.cjs.map +1 -0
  17. package/dist/crashHandlerNative.native-DsCRd-oN.js +39 -0
  18. package/dist/crashHandlerNative.native-DsCRd-oN.js.map +1 -0
  19. package/dist/deviceInfo.native-D5gNBG7m.cjs +2 -0
  20. package/dist/deviceInfo.native-D5gNBG7m.cjs.map +1 -0
  21. package/dist/deviceInfo.native-DiiHrnI3.js +53 -0
  22. package/dist/deviceInfo.native-DiiHrnI3.js.map +1 -0
  23. package/dist/deviceInfo.web-BHsjVveq.js +41 -0
  24. package/dist/deviceInfo.web-BHsjVveq.js.map +1 -0
  25. package/dist/deviceInfo.web-DGCUHAnv.cjs +2 -0
  26. package/dist/deviceInfo.web-DGCUHAnv.cjs.map +1 -0
  27. package/dist/deviceState.native-BEysbZ6O.js +58 -0
  28. package/dist/deviceState.native-BEysbZ6O.js.map +1 -0
  29. package/dist/deviceState.native-CrQMy11_.cjs +2 -0
  30. package/dist/deviceState.native-CrQMy11_.cjs.map +1 -0
  31. package/dist/deviceState.web-ByaQm9Ry.js +14 -0
  32. package/dist/deviceState.web-ByaQm9Ry.js.map +1 -0
  33. package/dist/deviceState.web-CSfUgHDU.cjs +2 -0
  34. package/dist/deviceState.web-CSfUgHDU.cjs.map +1 -0
  35. package/dist/frameTracker-9j0en6Zm.cjs +2 -0
  36. package/dist/frameTracker-9j0en6Zm.cjs.map +1 -0
  37. package/dist/frameTracker-BzXnxSkb.js +53 -0
  38. package/dist/frameTracker-BzXnxSkb.js.map +1 -0
  39. package/dist/httpAttributes-BWXOr4eP.js +70 -0
  40. package/dist/httpAttributes-BWXOr4eP.js.map +1 -0
  41. package/dist/httpAttributes-COY0_kiF.cjs +2 -0
  42. package/dist/httpAttributes-COY0_kiF.cjs.map +1 -0
  43. package/dist/index.native.cjs +1 -1
  44. package/dist/index.native.cjs.map +1 -1
  45. package/dist/index.native.d.ts +1 -1
  46. package/dist/index.native.js +173 -81
  47. package/dist/index.native.js.map +1 -1
  48. package/dist/index.web.cjs +1 -1
  49. package/dist/index.web.cjs.map +1 -1
  50. package/dist/index.web.d.ts +1 -1
  51. package/dist/index.web.js +107 -39
  52. package/dist/index.web.js.map +1 -1
  53. package/dist/interactionWeb.web-BWBjmovb.js +109 -0
  54. package/dist/interactionWeb.web-BWBjmovb.js.map +1 -0
  55. package/dist/interactionWeb.web-CKDJLD9r.cjs +2 -0
  56. package/dist/interactionWeb.web-CKDJLD9r.cjs.map +1 -0
  57. package/dist/interceptFetchWeb.web-DjSR_Rft.js +62 -0
  58. package/dist/interceptFetchWeb.web-DjSR_Rft.js.map +1 -0
  59. package/dist/interceptFetchWeb.web-ZHw6IQkU.cjs +2 -0
  60. package/dist/interceptFetchWeb.web-ZHw6IQkU.cjs.map +1 -0
  61. package/dist/interceptHttpNative.native-C5scIcgY.cjs +2 -0
  62. package/dist/interceptHttpNative.native-C5scIcgY.cjs.map +1 -0
  63. package/dist/interceptHttpNative.native-vF_Fksjk.js +18 -0
  64. package/dist/interceptHttpNative.native-vF_Fksjk.js.map +1 -0
  65. package/dist/loadingTime-Cj5Oh8lT.cjs +2 -0
  66. package/dist/loadingTime-Cj5Oh8lT.cjs.map +1 -0
  67. package/dist/loadingTime-DMc0zTY8.js +70 -0
  68. package/dist/loadingTime-DMc0zTY8.js.map +1 -0
  69. package/dist/memoryNative.native-CK3QFVjY.cjs +2 -0
  70. package/dist/memoryNative.native-CK3QFVjY.cjs.map +1 -0
  71. package/dist/memoryNative.native-DkA6f7id.js +54 -0
  72. package/dist/memoryNative.native-DkA6f7id.js.map +1 -0
  73. package/dist/nativeSender-Dt1HLaLi.js +37 -0
  74. package/dist/nativeSender-Dt1HLaLi.js.map +1 -0
  75. package/dist/nativeSender-hCgUa7Vz.cjs +2 -0
  76. package/dist/nativeSender-hCgUa7Vz.cjs.map +1 -0
  77. package/dist/navigationRef-CVIv0aIK.js +30 -0
  78. package/dist/navigationRef-CVIv0aIK.js.map +1 -0
  79. package/dist/navigationRef-CfIbeXX8.cjs +2 -0
  80. package/dist/navigationRef-CfIbeXX8.cjs.map +1 -0
  81. package/dist/navigationWeb.web-CRHpr5zl.js +51 -0
  82. package/dist/navigationWeb.web-CRHpr5zl.js.map +1 -0
  83. package/dist/navigationWeb.web-DwWjL80b.cjs +2 -0
  84. package/dist/navigationWeb.web-DwWjL80b.cjs.map +1 -0
  85. package/dist/{networkChange-CUO1hRLj.cjs → networkChange-2FGIQM-N.cjs} +2 -2
  86. package/dist/networkChange-2FGIQM-N.cjs.map +1 -0
  87. package/dist/{networkChange-D39hdSb0.js → networkChange-QA0893vW.js} +2 -2
  88. package/dist/networkChange-QA0893vW.js.map +1 -0
  89. package/dist/networkInfo.native-CcJ3JVRF.js +31 -0
  90. package/dist/networkInfo.native-CcJ3JVRF.js.map +1 -0
  91. package/dist/networkInfo.native-whB2wf6a.cjs +2 -0
  92. package/dist/networkInfo.native-whB2wf6a.cjs.map +1 -0
  93. package/dist/{networkInfo.web-twcNn_hc.js → networkInfo.web-CcUpXMUK.js} +4 -4
  94. package/dist/networkInfo.web-CcUpXMUK.js.map +1 -0
  95. package/dist/networkInfo.web-DfO-BUFx.cjs +2 -0
  96. package/dist/networkInfo.web-DfO-BUFx.cjs.map +1 -0
  97. package/dist/react-bqe7KPOf.cjs +4 -0
  98. package/dist/react-bqe7KPOf.cjs.map +1 -0
  99. package/dist/react-urNtDGTL.js +413 -0
  100. package/dist/react-urNtDGTL.js.map +1 -0
  101. package/dist/runtimeReady.native-CxFl1rQR.js +35 -0
  102. package/dist/runtimeReady.native-CxFl1rQR.js.map +1 -0
  103. package/dist/runtimeReady.native-zueSbsEv.cjs +2 -0
  104. package/dist/runtimeReady.native-zueSbsEv.cjs.map +1 -0
  105. package/dist/runtimeReady.web-JuE239Tg.js +25 -0
  106. package/dist/runtimeReady.web-JuE239Tg.js.map +1 -0
  107. package/dist/runtimeReady.web-vhAJFU61.cjs +2 -0
  108. package/dist/runtimeReady.web-vhAJFU61.cjs.map +1 -0
  109. package/dist/seedRuntimeReady-BlRdf3pR.js +10 -0
  110. package/dist/seedRuntimeReady-BlRdf3pR.js.map +1 -0
  111. package/dist/seedRuntimeReady-CbjqbWCd.cjs +2 -0
  112. package/dist/seedRuntimeReady-CbjqbWCd.cjs.map +1 -0
  113. package/dist/src/adapters/appLifecycle.d.ts +11 -4
  114. package/dist/src/adapters/batch.d.ts +46 -0
  115. package/dist/src/adapters/crashCapture.d.ts +42 -9
  116. package/dist/src/adapters/deviceState.d.ts +9 -0
  117. package/dist/src/adapters/failedEvents.d.ts +43 -0
  118. package/dist/src/adapters/frameAggregate.d.ts +19 -12
  119. package/dist/src/adapters/frameTracker.d.ts +30 -0
  120. package/dist/src/adapters/hangDetector.d.ts +41 -0
  121. package/dist/src/adapters/httpAttributes.d.ts +18 -0
  122. package/dist/src/adapters/loadingTime.d.ts +67 -0
  123. package/dist/src/adapters/manualSpans.d.ts +41 -0
  124. package/dist/src/adapters/native/autoTaps.native.d.ts +15 -0
  125. package/dist/src/adapters/native/deviceState.native.d.ts +15 -0
  126. package/dist/src/adapters/native/interceptHttpNative.native.d.ts +18 -0
  127. package/dist/src/adapters/native/memoryNative.native.d.ts +15 -11
  128. package/dist/src/adapters/native/networkInfo.native.d.ts +1 -1
  129. package/dist/src/adapters/native/runtimeReady.native.d.ts +17 -0
  130. package/dist/src/adapters/native/store.native.d.ts +10 -0
  131. package/dist/src/adapters/nativeSender.d.ts +2 -2
  132. package/dist/src/adapters/navigationRef.d.ts +29 -0
  133. package/dist/src/adapters/networkChange.d.ts +2 -2
  134. package/dist/src/adapters/seedRuntimeReady.d.ts +8 -0
  135. package/dist/src/adapters/traceHeader.d.ts +33 -0
  136. package/dist/src/adapters/traceManager.d.ts +144 -0
  137. package/dist/src/adapters/uiInteraction.d.ts +111 -0
  138. package/dist/src/adapters/viewManager.d.ts +177 -0
  139. package/dist/src/adapters/viewport.d.ts +15 -0
  140. package/dist/src/adapters/web/deviceState.web.d.ts +10 -0
  141. package/dist/src/adapters/web/interactionWeb.web.d.ts +36 -0
  142. package/dist/src/adapters/web/interceptFetchWeb.web.d.ts +3 -11
  143. package/dist/src/adapters/web/navigationWeb.web.d.ts +13 -7
  144. package/dist/src/adapters/web/runtimeReady.web.d.ts +5 -0
  145. package/dist/src/adapters/web/store.web.d.ts +12 -0
  146. package/dist/src/adapters/web/webVitals.web.d.ts +56 -0
  147. package/dist/src/adapters/webSender.d.ts +2 -2
  148. package/dist/src/adapters/webVitals.d.ts +25 -0
  149. package/dist/src/adapters/xhrIntercept.d.ts +55 -0
  150. package/dist/src/core/beforeSend.d.ts +20 -0
  151. package/dist/src/core/breadcrumbs.d.ts +10 -0
  152. package/dist/src/core/debug.d.ts +7 -0
  153. package/dist/src/core/memoryStore.d.ts +23 -0
  154. package/dist/src/core/store.d.ts +41 -0
  155. package/dist/src/core/telemetry.d.ts +422 -42
  156. package/dist/src/core/userProfile.d.ts +19 -0
  157. package/dist/src/core/utils/json.d.ts +7 -0
  158. package/dist/src/core/utils/uuid.d.ts +10 -1
  159. package/dist/src/createTelemetry.native.d.ts +10 -1
  160. package/dist/src/createTelemetry.web.d.ts +9 -1
  161. package/dist/src/golden.helper.d.ts +4 -0
  162. package/dist/src/index.base.d.ts +93 -3
  163. package/dist/src/index.native.d.ts +7 -27
  164. package/dist/src/index.web.d.ts +7 -23
  165. package/dist/src/react.d.ts +45 -0
  166. package/dist/src/telemetryNative.native.d.ts +79 -0
  167. package/dist/src/telemetryWeb.web.d.ts +59 -0
  168. package/dist/store.native-BbS76uWV.cjs +2 -0
  169. package/dist/store.native-BbS76uWV.cjs.map +1 -0
  170. package/dist/store.native-MlWyGgBp.js +32 -0
  171. package/dist/store.native-MlWyGgBp.js.map +1 -0
  172. package/dist/store.web-BzKaP57Z.cjs +2 -0
  173. package/dist/store.web-BzKaP57Z.cjs.map +1 -0
  174. package/dist/store.web-rhh0NOfs.js +31 -0
  175. package/dist/store.web-rhh0NOfs.js.map +1 -0
  176. package/dist/telemetry-60sfWkh0.js +1754 -0
  177. package/dist/telemetry-60sfWkh0.js.map +1 -0
  178. package/dist/telemetry-CW63glwb.cjs +2 -0
  179. package/dist/telemetry-CW63glwb.cjs.map +1 -0
  180. package/dist/uiInteraction-BIDOMcrL.js +109 -0
  181. package/dist/uiInteraction-BIDOMcrL.js.map +1 -0
  182. package/dist/uiInteraction-DxlwCVSn.cjs +2 -0
  183. package/dist/uiInteraction-DxlwCVSn.cjs.map +1 -0
  184. package/dist/viewport-9JcVIXYF.cjs +2 -0
  185. package/dist/viewport-9JcVIXYF.cjs.map +1 -0
  186. package/dist/viewport-GWTEBt2K.js +15 -0
  187. package/dist/viewport-GWTEBt2K.js.map +1 -0
  188. package/dist/web-vitals.attribution-DAvBvdng.cjs +2 -0
  189. package/dist/web-vitals.attribution-DAvBvdng.cjs.map +1 -0
  190. package/dist/web-vitals.attribution-DcoMtvlY.js +488 -0
  191. package/dist/web-vitals.attribution-DcoMtvlY.js.map +1 -0
  192. package/dist/webSender-DA087xb5.cjs +2 -0
  193. package/dist/webSender-DA087xb5.cjs.map +1 -0
  194. package/dist/webSender-g4rs5TIg.js +44 -0
  195. package/dist/webSender-g4rs5TIg.js.map +1 -0
  196. package/dist/webVitals.web-DRTDK6s5.js +100 -0
  197. package/dist/webVitals.web-DRTDK6s5.js.map +1 -0
  198. package/dist/webVitals.web-DvScDIjX.cjs +2 -0
  199. package/dist/webVitals.web-DvScDIjX.cjs.map +1 -0
  200. package/dist/xhrIntercept-9uAkQh3N.js +55 -0
  201. package/dist/xhrIntercept-9uAkQh3N.js.map +1 -0
  202. package/dist/xhrIntercept-xG1Yl5RI.cjs +2 -0
  203. package/dist/xhrIntercept-xG1Yl5RI.cjs.map +1 -0
  204. package/docs/migration-v4.md +190 -0
  205. package/docs/migration-v5.md +178 -0
  206. package/package.json +22 -6
  207. package/dist/appLifecycle-Cynw0kAv.js +0 -14
  208. package/dist/appLifecycle-Cynw0kAv.js.map +0 -1
  209. package/dist/appLifecycle-DvJIt7ym.cjs +0 -2
  210. package/dist/appLifecycle-DvJIt7ym.cjs.map +0 -1
  211. package/dist/batch-CLBFgYPC.cjs +0 -2
  212. package/dist/batch-CLBFgYPC.cjs.map +0 -1
  213. package/dist/batch-DLG_gtOm.js +0 -12
  214. package/dist/batch-DLG_gtOm.js.map +0 -1
  215. package/dist/crashCapture-BYTM4FLC.cjs +0 -2
  216. package/dist/crashCapture-BYTM4FLC.cjs.map +0 -1
  217. package/dist/crashCapture-D_rkkBVa.js +0 -31
  218. package/dist/crashCapture-D_rkkBVa.js.map +0 -1
  219. package/dist/crashHandler.web-BSxDpFTo.cjs +0 -2
  220. package/dist/crashHandler.web-BSxDpFTo.cjs.map +0 -1
  221. package/dist/crashHandler.web-D59bmhg9.js +0 -32
  222. package/dist/crashHandler.web-D59bmhg9.js.map +0 -1
  223. package/dist/crashHandlerNative.native-DeAFze4E.cjs +0 -2
  224. package/dist/crashHandlerNative.native-DeAFze4E.cjs.map +0 -1
  225. package/dist/crashHandlerNative.native-d7qJkzA6.js +0 -41
  226. package/dist/crashHandlerNative.native-d7qJkzA6.js.map +0 -1
  227. package/dist/debug-DsvQ9y3W.js +0 -68
  228. package/dist/debug-DsvQ9y3W.js.map +0 -1
  229. package/dist/debug-rnOOxFpN.cjs +0 -2
  230. package/dist/debug-rnOOxFpN.cjs.map +0 -1
  231. package/dist/deviceInfo.native-7hbRYixR.cjs +0 -2
  232. package/dist/deviceInfo.native-7hbRYixR.cjs.map +0 -1
  233. package/dist/deviceInfo.native-D2k0LDhI.js +0 -1171
  234. package/dist/deviceInfo.native-D2k0LDhI.js.map +0 -1
  235. package/dist/deviceInfo.web-ByNAlEJh.cjs +0 -2
  236. package/dist/deviceInfo.web-ByNAlEJh.cjs.map +0 -1
  237. package/dist/deviceInfo.web-DzQyEku6.js +0 -40
  238. package/dist/deviceInfo.web-DzQyEku6.js.map +0 -1
  239. package/dist/frameAggregate-C_HoVFcK.cjs +0 -2
  240. package/dist/frameAggregate-C_HoVFcK.cjs.map +0 -1
  241. package/dist/frameAggregate-Cwh1juw1.js +0 -17
  242. package/dist/frameAggregate-Cwh1juw1.js.map +0 -1
  243. package/dist/frameDropsNative.native-CP7zrXDf.js +0 -23
  244. package/dist/frameDropsNative.native-CP7zrXDf.js.map +0 -1
  245. package/dist/frameDropsNative.native-DKqEDqip.cjs +0 -2
  246. package/dist/frameDropsNative.native-DKqEDqip.cjs.map +0 -1
  247. package/dist/frameDropsWeb.web-C9Lt3Fuj.js +0 -22
  248. package/dist/frameDropsWeb.web-C9Lt3Fuj.js.map +0 -1
  249. package/dist/frameDropsWeb.web-azpwQCUz.cjs +0 -2
  250. package/dist/frameDropsWeb.web-azpwQCUz.cjs.map +0 -1
  251. package/dist/httpAttributes-BV50UKQU.js +0 -19
  252. package/dist/httpAttributes-BV50UKQU.js.map +0 -1
  253. package/dist/httpAttributes-xXOD9trQ.cjs +0 -2
  254. package/dist/httpAttributes-xXOD9trQ.cjs.map +0 -1
  255. package/dist/interaction-CH8yoY5-.js +0 -23
  256. package/dist/interaction-CH8yoY5-.js.map +0 -1
  257. package/dist/interaction-DcNFBW7a.cjs +0 -2
  258. package/dist/interaction-DcNFBW7a.cjs.map +0 -1
  259. package/dist/interceptFetchNative.native-VlhtMG-U.js +0 -49
  260. package/dist/interceptFetchNative.native-VlhtMG-U.js.map +0 -1
  261. package/dist/interceptFetchNative.native-jEAldH14.cjs +0 -2
  262. package/dist/interceptFetchNative.native-jEAldH14.cjs.map +0 -1
  263. package/dist/interceptFetchWeb.web-DFzZliik.cjs +0 -2
  264. package/dist/interceptFetchWeb.web-DFzZliik.cjs.map +0 -1
  265. package/dist/interceptFetchWeb.web-DfsMfoRP.js +0 -77
  266. package/dist/interceptFetchWeb.web-DfsMfoRP.js.map +0 -1
  267. package/dist/memoryNative.native-BWLh2S9L.js +0 -48
  268. package/dist/memoryNative.native-BWLh2S9L.js.map +0 -1
  269. package/dist/memoryNative.native-DCXSOd4Q.cjs +0 -2
  270. package/dist/memoryNative.native-DCXSOd4Q.cjs.map +0 -1
  271. package/dist/memoryWeb.web-B3YuV-cB.js +0 -48
  272. package/dist/memoryWeb.web-B3YuV-cB.js.map +0 -1
  273. package/dist/memoryWeb.web-CheXAcJn.cjs +0 -2
  274. package/dist/memoryWeb.web-CheXAcJn.cjs.map +0 -1
  275. package/dist/nativeSender-BE_mzw_S.js +0 -70
  276. package/dist/nativeSender-BE_mzw_S.js.map +0 -1
  277. package/dist/nativeSender-DyAUGY7c.cjs +0 -2
  278. package/dist/nativeSender-DyAUGY7c.cjs.map +0 -1
  279. package/dist/navigationNative.native-3tO5JxSd.cjs +0 -2
  280. package/dist/navigationNative.native-3tO5JxSd.cjs.map +0 -1
  281. package/dist/navigationNative.native-BUCGPQX2.js +0 -25
  282. package/dist/navigationNative.native-BUCGPQX2.js.map +0 -1
  283. package/dist/navigationTracker-B2GMwyKk.cjs +0 -2
  284. package/dist/navigationTracker-B2GMwyKk.cjs.map +0 -1
  285. package/dist/navigationTracker-Cts68dgG.js +0 -19
  286. package/dist/navigationTracker-Cts68dgG.js.map +0 -1
  287. package/dist/navigationWeb.web-B0necr5j.cjs +0 -2
  288. package/dist/navigationWeb.web-B0necr5j.cjs.map +0 -1
  289. package/dist/navigationWeb.web-CORzE_Id.js +0 -46
  290. package/dist/navigationWeb.web-CORzE_Id.js.map +0 -1
  291. package/dist/networkChange-CUO1hRLj.cjs.map +0 -1
  292. package/dist/networkChange-D39hdSb0.js.map +0 -1
  293. package/dist/networkInfo.native-BK5fpAOL.js +0 -343
  294. package/dist/networkInfo.native-BK5fpAOL.js.map +0 -1
  295. package/dist/networkInfo.native-cxuw93Uy.cjs +0 -2
  296. package/dist/networkInfo.native-cxuw93Uy.cjs.map +0 -1
  297. package/dist/networkInfo.web-DJmw1sNK.cjs +0 -2
  298. package/dist/networkInfo.web-DJmw1sNK.cjs.map +0 -1
  299. package/dist/networkInfo.web-twcNn_hc.js.map +0 -1
  300. package/dist/src/adapters/interaction.d.ts +0 -17
  301. package/dist/src/adapters/native/frameDropsNative.native.d.ts +0 -16
  302. package/dist/src/adapters/native/interceptFetchNative.native.d.ts +0 -23
  303. package/dist/src/adapters/native/navigationNative.native.d.ts +0 -12
  304. package/dist/src/adapters/navigationTracker.d.ts +0 -6
  305. package/dist/src/adapters/screenTiming.d.ts +0 -9
  306. package/dist/src/adapters/web/frameDropsWeb.web.d.ts +0 -16
  307. package/dist/src/adapters/web/memoryWeb.web.d.ts +0 -26
  308. package/dist/telemetry-Co4MYdwa.cjs +0 -2
  309. package/dist/telemetry-Co4MYdwa.cjs.map +0 -1
  310. package/dist/telemetry-KI0x4gzC.js +0 -389
  311. package/dist/telemetry-KI0x4gzC.js.map +0 -1
  312. package/dist/v4-BysszJq8.js +0 -31
  313. package/dist/v4-BysszJq8.js.map +0 -1
  314. package/dist/v4-CqdK_b8Y.cjs +0 -2
  315. package/dist/v4-CqdK_b8Y.cjs.map +0 -1
  316. package/dist/webSender-B27tmT1w.js +0 -42
  317. package/dist/webSender-B27tmT1w.js.map +0 -1
  318. package/dist/webSender-BWi4x1df.cjs +0 -2
  319. package/dist/webSender-BWi4x1df.cjs.map +0 -1
@@ -0,0 +1 @@
1
+ {"version":3,"file":"telemetry-CW63glwb.cjs","sources":["../src/adapters/batch.ts","../src/core/utils/uuid.ts","../src/adapters/viewManager.ts","../src/adapters/traceManager.ts","../src/adapters/hangDetector.ts","../src/adapters/failedEvents.ts","../src/core/utils/json.ts","../src/adapters/manualSpans.ts","../src/core/userProfile.ts","../src/core/breadcrumbs.ts","../src/core/beforeSend.ts","../src/core/telemetry.ts"],"sourcesContent":["import type { TelemetryEvent } from \"../core/telemetry\";\n\n/**\n * The catalogue's contract version this build speaks (#179, processor #29). Only the major gates\n * parsing; the minor follows the catalogue tag pinned in `catalogue.version`.\n */\nexport const CONTRACT_VERSION = \"4.3.0\";\n\n/**\n * Per-event identity copies the Context block stamps and the envelope lifts to its root\n * (processor #29). Tier A in `beforeSend` (`device.id` Tier B), so a hook cannot delete the\n * envelope out from under the batch. `sdk.platform` has no envelope slot: `sdk.name` +\n * `app.platform` carry it.\n */\nconst IDENTITY = [\"device.id\", \"app.name\", \"app.package_name\", \"app.version\", \"app.build_number\", \"sdk.version\", \"sdk.platform\"];\n\nconst identityOf = (e: TelemetryEvent) => JSON.stringify(IDENTITY.map(k => e.attributes?.[k]));\n\n/**\n * The 8-key 4.x envelope (`envelope.yaml`), shared by both senders so the web and native POST\n * bodies stay byte-identical. Identity comes from the rows themselves, so a batch persisted by\n * a prior launch replays under that launch's `app` block. Every row of one batch shares it:\n * the live queue has one identity per process, and `byIdentity()` splits a replayed one.\n */\nexport function buildBatch(events: TelemetryEvent[]): string {\n const a = events[0]?.attributes ?? {};\n return JSON.stringify({\n type: \"telemetry_batch\",\n contract_version: CONTRACT_VERSION,\n timestamp: new Date().toISOString(),\n batch_size: events.length,\n device_id: a[\"device.id\"],\n sdk: { name: \"react_native\", version: a[\"sdk.version\"] },\n app: {\n name: a[\"app.name\"],\n package_name: a[\"app.package_name\"],\n platform: a[\"device.platform\"],\n version: a[\"app.version\"],\n build_number: a[\"app.build_number\"],\n },\n events: events.map(e => {\n const attributes = { ...e.attributes };\n for (const k of IDENTITY) delete attributes[k];\n return { ...e, attributes };\n }),\n });\n}\n\n/** Rows grouped by identity, first-seen order — one envelope per group on replay. */\nexport function byIdentity(events: TelemetryEvent[]): TelemetryEvent[][] {\n const groups = new Map<string, TelemetryEvent[]>();\n for (const e of events) {\n const k = identityOf(e);\n groups.set(k, [...(groups.get(k) ?? []), e]);\n }\n return [...groups.values()];\n}\n\n/**\n * Replay a recovered queue, one POST per identity. On a failure the unsent rows go back to the\n * store — minus the failed group itself when it was rejected (§2.5: a 4xx is dropped, never kept).\n */\nexport async function replayGroups(\n stored: TelemetryEvent[],\n post: (events: TelemetryEvent[]) => Promise<void>,\n persist: (events: TelemetryEvent[]) => unknown,\n): Promise<void> {\n const groups = byIdentity(stored);\n for (let i = 0; i < groups.length; i++) {\n try {\n await post(groups[i]);\n } catch (err) {\n const rest = groups.slice(isRejected(err) ? i + 1 : i).flat();\n if (rest.length > 0) await persist(rest);\n throw err;\n }\n }\n}\n\n// Auth (processor #29): `X-API-Key` only. 4.x drops `Authorization: Bearer`.\nexport function buildHeaders(credential: string | undefined): Record<string, string> {\n return {\n \"Content-Type\": \"application/json\",\n ...(credential ? { \"X-API-Key\": credential } : {}),\n };\n}\n\n/**\n * A non-2xx the senders refuse to retry (§2.5): any 4xx, 429 included. `resetAt` is the epoch\n * ms `X-RateLimit-Reset` names, when the collector sent one. Core reads `status` by shape, so\n * a consumer's own sender can throw `{ status: 401 }` and get the same handling.\n */\nexport class HttpStatusError extends Error {\n constructor(public readonly status: number, public readonly resetAt?: number) {\n super(`Telemetry send failed: ${status}`);\n }\n}\n\n/** The status a send failed with, when it failed with one; `undefined` for network and the rest. */\nexport function statusOf(err: unknown): number | undefined {\n const s = (err as any)?.status;\n return typeof s === \"number\" ? s : undefined;\n}\n\n/** 4xx except 429: drop the batch — no retry, no persist (§2.5). */\nexport const isRejected = (err: unknown) => { const s = statusOf(err); return s !== undefined && s >= 400 && s < 500 && s !== 429; };\n\n/**\n * `X-RateLimit-Reset` as epoch ms. The header is read both ways in the wild — epoch seconds or\n * seconds-from-now — and the magnitude tells them apart: anything past 2001 is a timestamp.\n */\nfunction resetAtOf(headers: any, now = Date.now()): number | undefined {\n const raw = Number(headers?.get?.(\"x-ratelimit-reset\"));\n if (!Number.isFinite(raw) || raw < 0) return undefined;\n return raw > 1e9 ? raw * 1000 : now + raw * 1000;\n}\n\ntype PostResult = { ok: boolean; status: number; headers?: any };\n\n/**\n * Retry + backoff, shared by both senders so the §2.5 status table is one rule. 5xx and network\n * errors retry; a 4xx — 429 included — throws at once, because retrying a wrong credential three\n * times only delays the drop and retrying a 429 is the stampede the header exists to stop.\n */\nexport async function sendWithRetry(post: () => Promise<PostResult>, retryCount: number, backoffMs: (attempt: number) => number) {\n let lastError: unknown;\n for (let attempt = 1; attempt <= retryCount; attempt++) {\n try {\n const res = await post();\n if (res.ok) return;\n const err = new HttpStatusError(res.status, res.status === 429 ? resetAtOf(res.headers) : undefined);\n if (res.status >= 400 && res.status < 500) throw err;\n lastError = err;\n } catch (err) {\n if (statusOf(err) !== undefined && statusOf(err)! < 500) throw err;\n lastError = err;\n }\n if (attempt < retryCount) await new Promise(r => setTimeout(r, backoffMs(attempt)));\n }\n throw lastError;\n}\n\n// Placeholder host — always pass a real `endpoint`. The path is the collector's real one:\n// it terminates POST /telemetry (contract §11.1). Shared so the two senders cannot drift.\nexport const DEFAULT_ENDPOINT = \"https://your.telemetry.endpoint/telemetry\";\n","// Platform-agnostic id generator. The web/native split was byte-identical, so it's gone.\n\n/**\n * Wire-contract ids carry a 16-hex-char (64-bit) random segment (§3.3) — except W3C\n * `trace.id`, which is 32 (§6.1). The length is the caller's; the entropy source is not.\n *\n * Entropy is `crypto.getRandomValues`, not `Math.random()` (#91): `device.id` is now\n * persisted, so a collision is *permanent* — two handsets merge into one device row and\n * one rate-limit bucket forever — where a session collision was transient. RN has no\n * WebCrypto of its own; the native entry imports `react-native-get-random-values`\n * (already a dependency) to install it before the first id is minted.\n */\nexport function randomHex(length = 16): string {\n // Guarded, because the failure is otherwise a bare TypeError thrown from the Telemetry\n // constructor with nothing pointing at the cause. There is no Math.random() fallback on\n // purpose (#91): silently minting weak ids for a value that persists forever is worse\n // than refusing, and the fix is a reinstall, not a retry.\n if (typeof globalThis.crypto?.getRandomValues !== \"function\") {\n throw new Error(\n \"edge-telemetry: crypto.getRandomValues is unavailable, so no id can be minted. \" +\n \"On React Native this means react-native-get-random-values failed to load — \" +\n \"reinstall it and rebuild.\",\n );\n }\n const bytes = new Uint8Array(Math.ceil(length / 2));\n crypto.getRandomValues(bytes);\n let out = \"\";\n for (const b of bytes) out += b.toString(16).padStart(2, \"0\");\n return out.slice(0, length);\n}\n","// The View entity (§4.5, #96) — shared by both builds, because everything in it is\n// platform-agnostic bookkeeping. It owns three things:\n//\n// 1. `view.id` + `view.name`, denormalized onto the Context block of every event and\n// metric, so \"errors by screen\" and \"p95 by screen\" need no join.\n// 2. the `view` event emitted at exit, carrying dwell, the three counters and the\n// network-settle verdict from `loadingTime.ts` (#97).\n// 3. the name ladder, and the four lifetime boundaries.\n//\n// It never imports a platform API. The entries feed it: route changes via\n// `Telemetry.recordRouteChange`, background via `AppLifecycleEmitter`, session rotation\n// via `Telemetry.newSession`. Process death needs no feed — a new process opens a fresh\n// initial view, and the killed view's dwell is lost by design (no `view` event was emitted).\n\nimport { randomHex } from \"../core/utils/uuid\";\nimport { NetworkSettle } from \"./loadingTime\";\nimport type { TraceAttributes } from \"./traceManager\";\n\n/** §4.5.1's ladder. `none` is the literal `\"unknown\"` name, not an absent one. */\nexport type ViewNameSource = \"explicit\" | \"route\" | \"url\" | \"none\";\n/** §4.5's four `view.load_type` values — one per lifetime boundary that mints a successor. */\nexport type ViewLoadType = \"initial_load\" | \"route_change\" | \"resume\" | \"session_rotation\";\n\n/** Rank beats order (§4.5.1): explicit > route > url > none. */\nconst RANK: Record<ViewNameSource, number> = { none: 0, url: 1, route: 2, explicit: 3 };\n\n/** `view.name` before anything has named the view. A literal, never null (§4.5.1). */\nexport const UNKNOWN_VIEW_NAME = \"unknown\";\n\n/**\n * How many retired views `nameOf()` can still name (§3.1). Bounded because an unbounded\n * map is a leak on a long session; 16 because a span outliving that many boundaries is a\n * request §4.5.2's 30 s settle cap has already given up on.\n */\nexport const MAX_RETIRED_VIEW_NAMES = 16;\n\n/**\n * All ViewManager needs of core. Structural, so the manager stays unit-testable alone.\n * `trace` is optional for that reason and for that reason only — every real `Telemetry`\n * has one, and a view with no trace source simply carries no §6 keys.\n */\ntype Emitter = {\n log(name: string, data?: Record<string, any>): unknown;\n trace?: { viewSpan(entryAt: number): TraceAttributes };\n};\n\ntype View = {\n id: string;\n name: string;\n source: ViewNameSource;\n referrer: string;\n loadType: ViewLoadType;\n // Dwell is foreground-only (§4.5), so it banks on background and re-arms on foreground\n // rather than running off a single start timestamp.\n elapsed: number;\n resumedAt?: number; // undefined = the clock is paused (app backgrounded)\n errors: number;\n actions: number;\n // `view.request_count` and `view.loading_time` both live here — both count requests\n // *started* in this view, so one object owns both and they cannot disagree (§4.5.2).\n settle: NetworkSettle;\n // §6.3's Tier 1 keys, captured at view **entry**: a `view` row parents to the root that\n // was live when the screen opened, not the one live when the user left it. Held here\n // rather than read at exit precisely so the later root cannot claim it.\n span: TraceAttributes;\n /**\n * The route-level names this view has been bound to, per rung (#169). Rank-beats-order\n * holds only *within one route*: a route event naming a different route than the one\n * recorded here is a navigation, whatever rung the view's display name came from.\n */\n routes: Partial<Record<\"route\" | \"url\", string>>;\n /**\n * #171's screen-ready mark. `token` — only `initial_load` and route-change views can be\n * judged; a resume or rotation successor never can. `anchor` is what `view.ready_time`\n * measures from (entry, or process start for the initial view); unset means not judged.\n * `readyAt` is the first mark's T — first mark wins.\n */\n token: boolean;\n anchor?: number;\n readyAt?: number;\n};\n\n/** `view_{ms}_{16hex}` (§3.3). No platform suffix — a view never leaves its process. */\nfunction mintViewId(): string {\n return `view_${Date.now()}_${randomHex(16)}`;\n}\n\nexport class ViewManager {\n private view: View;\n /** Origin only, and only where there is one — omitted on native (§4.5). */\n private readonly host?: string;\n /** §4.6's aliveness subscribers. Empty on native and on a web build with no DOM. */\n private readonly activityListeners = new Set<() => void>();\n /** §5.1's boundary subscribers — the frame window, awaited before the successor mints. */\n private readonly boundaryListeners = new Set<(successorLoadType: ViewLoadType) => unknown>();\n /** Retired `view.id` → final `view.name`, for `nameOf()`. Bounded; oldest evicted. */\n private readonly retiredNames = new Map<string, string>();\n /**\n * `view.name`s this process has seen marked ready (#171). In memory only, never persisted:\n * `abandoned` is claimed only for a screen known to be instrumented, so an uninstrumented\n * screen never reads as abandoned. Its first visit per process can't be judged either.\n */\n private readonly markedNames = new Set<string>();\n\n constructor(private telemetry: Emitter) {\n // A capability check, not a platform branch: RN has no `location`, and a\n // white-label web bundle serving two banks needs the origin to tell them apart.\n this.host = typeof location !== \"undefined\" && location?.origin ? location.origin : undefined;\n // The initial view opens at SDK init, so `view.id` is never absent (§4.5).\n const now = Date.now();\n this.view = {\n id: mintViewId(), name: UNKNOWN_VIEW_NAME, source: \"none\",\n referrer: \"\", loadType: \"initial_load\",\n elapsed: 0, resumedAt: now, errors: 0, actions: 0,\n // The launch view is the one `load_type` that seeds from the platform's\n // runtime-ready marker: it is busy until the bundle has evaluated (§4.5.2).\n settle: new NetworkSettle(now, { awaitRuntimeReady: true }),\n // The launch root is live here — it is minted in the same `Telemetry` constructor,\n // just above this one — so the initial view is its child and a web hard load\n // reports `launch`, never `navigation` (§6.2).\n span: telemetry.trace?.viewSpan(now) ?? {},\n routes: {},\n // Anchored at process start by the entry (`anchorInitial`), never at SDK init:\n // one column, one anchor. Until then, and on a runtime with no marker, not judged.\n token: true,\n };\n }\n\n /**\n * The initial view's ready anchor — process start: web `performance.timeOrigin`, native\n * `rnStartupTiming.startTime` (#171). So its `view.ready_time` *is* cold-start-to-ready.\n * `undefined` (native Old Architecture) leaves the initial view unjudged.\n */\n anchorInitial(processStart: number | undefined): void {\n if (this.view.loadType === \"initial_load\") this.view.anchor = processStart;\n }\n\n /**\n * `markScreenReady()`'s bind (#171) — the caller stamped `at` synchronously and arrives here\n * a macrotask later, so a mount-effect mark lands on the view that mount belongs to. First\n * mark per view wins; a view with no token (a resume or rotation successor) ignores it.\n */\n markReady(at: number): void {\n const v = this.view;\n if (v.token && v.readyAt === undefined) v.readyAt = at;\n }\n\n /** The two keys the Context block carries on every row. Name resolves at log time. */\n get id(): string { return this.view.id; }\n get name(): string { return this.view.name; }\n\n /**\n * §3.1 — `view.name` for a **frozen** `view.id`. A span-carrying row pins itself to the\n * view live at span start, and its name is still resolved at log time, so an\n * `http.request` that outlives a route change reports the departing view's *current*\n * best name rather than a stale copy taken at send.\n *\n * ponytail: a bounded ring of retired names, not a full history. A span outliving\n * `MAX_RETIRED_VIEW_NAMES` boundaries is a request the settle cap (30 s) already gave up\n * on; it degrades to `\"unknown\"`, which is what a never-named view reports anyway.\n */\n nameOf(id: string): string {\n if (id === this.view.id) return this.view.name;\n return this.retiredNames.get(id) ?? UNKNOWN_VIEW_NAME;\n }\n\n /**\n * The name ladder (§4.5.1), and the only path that mints a view from a *name*.\n *\n * - a **higher** rung re-stamps the name and never changes `view.id` — that is what\n * \"rank beats order\" means, and it is why a route name arriving after a URL-derived\n * one upgrades the view in place instead of splitting it in two;\n * - a **lower** rung does not overwrite the name — **but a route change is always a\n * boundary** (#169, the v5 ladder ruling). Rank-beats-order applies only *within one\n * route*, the upgrade window where two rungs describe one navigation: a route or URL\n * event naming a different route than the one this view was bound to emits `view` and\n * mints a successor, so `screenStart()` can no longer pin a view across route changes;\n * - the **same** rung naming a different screen is a genuine navigation, so it ends the\n * view and mints a successor.\n *\n * Rungs 1 and 2 are handed through unnormalized: a host naming a screen \"Step 2 of 3\"\n * must not receive \"Step {id} of {id}\". The caller normalizes rung 3, not this method.\n */\n async navigate(name: string, source: ViewNameSource): Promise<void> {\n if (source === \"route\" || source === \"url\") {\n const bound = this.view.routes[source];\n if (bound !== undefined && bound !== name) { await this.exit(\"route_change\", name, source); return; }\n this.view.routes[source] = name;\n }\n const rank = RANK[source], current = RANK[this.view.source];\n if (rank < current) return;\n if (rank > current) { this.view.name = name; this.view.source = source; return; }\n if (name === this.view.name) return;\n await this.exit(\"route_change\", name, source);\n }\n\n /** `view.error_count` — `app.crash` rows sharing this `view.id`. A closed enumeration. */\n countError(): void { this.view.errors++; }\n\n /** `view.action_count` — interaction rows sharing this `view.id`. */\n countAction(): void { this.view.actions++; }\n\n /**\n * An HTTP request started (§4.5.2). Returns its completion callback, **bound to the view\n * that was live at start** — a request that finishes after a route change belongs to the\n * view it started in and does not hold the arriving one open. The collector's own POST\n * never reaches here; the interceptors filter it before calling.\n */\n requestStarted(now?: number): (endedAt?: number) => void {\n this.notifyActivity();\n return this.view.settle.requestStarted(now);\n }\n\n /**\n * §4.6's dead-click gate, in the two places this manager already sees: a request started\n * and a view minted (a route change, a resume, a session rotation). The web tracker adds\n * DOM mutation on top, which it can observe on its own; these two it cannot.\n *\n * Deliberately fires for the background and rotation boundaries too. Those are not\n * navigations the click caused, so counting them as aliveness **under-reports** dead\n * clicks — which is the direction §4.6 requires: `ui.dead` must never falsely accuse.\n *\n * @returns an unsubscribe, so a tracker that is torn down does not keep the manager alive.\n */\n onActivity(fn: () => void): () => void {\n this.activityListeners.add(fn);\n return () => { this.activityListeners.delete(fn); };\n }\n\n private notifyActivity(): void {\n for (const fn of this.activityListeners) fn();\n }\n\n /**\n * §5.1's view-boundary reset. A subscriber is **awaited inside `beginView`, before the\n * successor replaces the current view**, so anything it emits is stamped with the\n * departing `view.id`. That ordering is the whole feature: a fixed 10 s frame window\n * straddling a route change otherwise charges the departing screen's dropped frames to\n * the arriving one — backwards for the one query the metric exists to serve.\n *\n * ⚠ **It does not fire on the `session_rotation` boundary**, and that is deliberate.\n * `newSession()` installs the new `session.id` *before* minting the successor view, so a\n * row emitted there would carry the new `session.id` with the departing `view.id` — the\n * one thing §4.5's \"`view.id` never spans a `session.id`\" forbids. Emitting *before* the\n * rotation instead is worse: `logMetric` re-checks session expiry, `lastActivity` is\n * still stale at that point, and the emit would rotate the session a second time. The\n * accepted residue is a frame window that carries across a rotation — at most one\n * unflushed window, of a session that ended by idleness.\n *\n * The successor's load type is handed to the subscriber so it can tell the two firing\n * boundaries apart: `frame_render_time` wants both, while §5.3's running CLS/INP values\n * want **`\"resume\"` — the background boundary — only**. Emitting a page-load-scoped vital\n * at a soft navigation would ship a second row for the same page load and stamp it with\n * a `view.id` that is not the initial view's.\n *\n * @returns an unsubscribe, so a torn-down subscriber does not keep the manager alive.\n */\n onBoundary(fn: (successorLoadType: ViewLoadType) => unknown): () => void {\n this.boundaryListeners.add(fn);\n return () => { this.boundaryListeners.delete(fn); };\n }\n\n /**\n * The platform's runtime-ready marker — `loadEventEnd` on web,\n * `performance.rnStartupTiming` on native — or `undefined` where the platform has none.\n *\n * Forwarded to whatever view is current, which is safe because a view that was never gated\n * *ignores* the seed — enforced in `NetworkSettle`, not assumed here. On web the `load`\n * event routinely arrives after the first route change, and flooring that view's settle at\n * the page's load time would charge the launch's cost to a route change.\n */\n seedRuntimeReady(at?: number): void {\n this.view.settle.seedRuntimeReady(at);\n }\n\n /**\n * Emit the `view` event for the current view. Its `view.name` is authoritative and its\n * `view.name_source` reports the *final* rung; the Context-block copy on rows emitted\n * early in the view may still carry a lower rung's name (§4.5.1).\n *\n * `view.loading_time` is **omitted when null**, following this contract's general\n * absent-means-the-SDK-had-nothing discipline (§4.11 names `navigation.from_screen` as the\n * only explicit wire null). `view.loading_time_outcome` always ships: it is what tells the\n * three null causes apart, and reading p75-of-settled beside %-capped is the whole point.\n */\n async endView(cause: ViewLoadType = \"session_rotation\"): Promise<void> {\n const v = this.view;\n const { loadingTime, outcome } = v.settle.resolve();\n // #171. `ready` ⇔ `view.ready_time` present. `abandoned` only when the user left by\n // route change or rotation — **background is not judged**, never a false accusation —\n // and only for a screen this process has seen marked. Otherwise neither key: the screen\n // is simply not instrumented.\n let ready: Record<string, string | number> = {};\n if (v.token && v.anchor !== undefined) {\n if (v.readyAt !== undefined) {\n this.markedNames.add(v.name);\n ready = { \"view.ready_time\": Math.max(0, v.readyAt - v.anchor), \"view.ready_outcome\": \"ready\" };\n } else if (cause !== \"resume\" && this.markedNames.has(v.name)) {\n ready = { \"view.ready_outcome\": \"abandoned\" };\n }\n }\n await this.telemetry.log(\"view\", {\n // A **point span** (§6.3): `span.start_time` from view entry and never\n // `span.duration_ms`. View dwell is `view.time_spent`, not span width — a width\n // here would stretch every tap-that-navigates envelope across the whole visit.\n ...v.span,\n ...(this.host ? { \"view.host\": this.host } : {}),\n \"view.referrer\": v.referrer,\n \"view.load_type\": v.loadType,\n \"view.name_source\": v.source,\n \"view.time_spent\": this.timeSpent(),\n ...(loadingTime === null ? {} : { \"view.loading_time\": loadingTime }),\n \"view.loading_time_outcome\": outcome,\n \"view.error_count\": v.errors,\n \"view.action_count\": v.actions,\n \"view.request_count\": v.settle.requestCount,\n ...ready,\n });\n // #179 — `screen.load` (catalogue navigation.yaml), for the views a load can be judged on:\n // the launch view and route changes. `reported` when the host marked it ready, else\n // `inferred` from the network settle — so an inferred number is never read as measured.\n if (v.loadType !== \"initial_load\" && v.loadType !== \"route_change\") return;\n const reported = typeof ready[\"view.ready_time\"] === \"number\";\n const settled = reported ? ready[\"view.ready_time\"] : loadingTime;\n await this.telemetry.log(\"screen.load\", {\n \"screen.name\": v.name,\n \"screen.load.source\": reported ? \"reported\" : \"inferred\",\n \"screen.load.outcome\": reported ? \"settled\" : outcome,\n ...(settled === null ? {} : { \"screen.load.settled_ms\": settled }),\n });\n }\n\n /**\n * Mint the successor. Called directly by session rotation, which has to mint *after*\n * the new `session.id` is in place — `view.id` never spans a `session.id` (§4.5).\n * An unnamed successor carries the departing view's name: backgrounding and a session\n * rotation do not move the user off the screen they were on.\n */\n async beginView(successorLoadType: ViewLoadType, name?: string, source?: ViewNameSource): Promise<void> {\n this.notifyActivity();\n // Awaited while `this.view` is still the departing one — see `onBoundary` for why\n // the session-rotation boundary is the one that does not fire. A subscriber that\n // throws is swallowed: a broken frame window must not be able to abort view minting.\n if (successorLoadType !== \"session_rotation\") {\n for (const fn of this.boundaryListeners) {\n try { await fn(successorLoadType); } catch { /* a subscriber's failure is not this view's */ }\n }\n }\n const prev = this.view;\n const now = Date.now();\n this.retiredNames.set(prev.id, prev.name);\n if (this.retiredNames.size > MAX_RETIRED_VIEW_NAMES) {\n // Map iteration is insertion-ordered, so the first key is the oldest retired view.\n const oldest = this.retiredNames.keys().next();\n if (!oldest.done) this.retiredNames.delete(oldest.value);\n }\n this.view = {\n id: mintViewId(),\n name: name ?? prev.name,\n source: source ?? prev.source,\n referrer: prev.name,\n loadType: successorLoadType,\n elapsed: 0, resumedAt: now, errors: 0, actions: 0,\n // No runtime-ready seed: only `initial_load` has a platform marker to wait on.\n settle: new NetworkSettle(now),\n // A view start *extends* the live root; with none live it mints a `navigation`\n // one (§6.2). Its exit does not extend anything (§6.7).\n span: this.telemetry.trace?.viewSpan(now) ?? {},\n // A route change binds the successor to the route that minted it; a resume or a\n // rotation keeps the user on the same screen, so it keeps the same routes too.\n routes: successorLoadType === \"route_change\"\n ? (source === \"route\" || source === \"url\" ? { [source]: name } : {})\n : { ...prev.routes },\n // Route views anchor at entry (`span.start_time`). A resume or rotation successor\n // is the same screen continued, so it never gets a pending token.\n token: successorLoadType === \"route_change\",\n anchor: now,\n };\n }\n\n /** A boundary that stays inside one session: emit, then mint the successor. */\n async exit(successorLoadType: ViewLoadType, name?: string, source?: ViewNameSource): Promise<void> {\n await this.endView(successorLoadType);\n await this.beginView(successorLoadType, name, source);\n }\n\n /**\n * The background boundary. The successor is minted immediately — `view.id` must never\n * be absent — but its clock starts paused, so a night spent backgrounded does not land\n * as dwell on whatever screen the user left open.\n */\n async background(): Promise<void> {\n await this.exit(\"resume\");\n const v = this.view;\n v.elapsed += this.sinceResume();\n v.resumedAt = undefined;\n }\n\n /** The matching foreground edge: re-arm the paused clock. */\n foreground(): void {\n this.view.resumedAt ??= Date.now();\n }\n\n private sinceResume(): number {\n return this.view.resumedAt === undefined ? 0 : Date.now() - this.view.resumedAt;\n }\n\n private timeSpent(): number {\n return Math.max(0, this.view.elapsed + this.sinceResume());\n }\n}\n","// Trace and span core (§6, #98) — shared by both builds, because none of it is\n// platform-specific. It owns three things:\n//\n// 1. the carrier: the one root that is currently live, plus its 2 s idle / 10 s cap expiry;\n// 2. root minting — `launch` at construction, `navigation` at a view entry with no live\n// root, `request` at a send with no live root, and `interaction` at every click/tap.\n// 3. the key builders for the three tiers (§6.3), so no call site hand-assembles them.\n//\n// ⚠ **No request tag and no thread-local.** Android needs both because OkHttp runs its\n// interceptors on a dispatcher pool thread; both RN builds patch a single-threaded JS\n// transport, so a plain field read synchronously inside the patch is correct *by\n// construction* (§6.7). Android's process-global `lastRoot` is unnecessary for the same\n// reason: the crash and unhandled-rejection handlers read this carrier directly.\n//\n// The carrier is a field on a `Telemetry`-owned instance rather than a module-level `let`,\n// which is the one deliberate departure from §6.7's wording. The substance it asks for —\n// synchronous plain read, no tag, no thread-local — is unchanged; a module singleton would\n// instead let one `Telemetry` inherit another's live root inside a single process, which is\n// the hazard that actually exists here. `ViewManager` is owned the same way, for the same\n// reason.\n\nimport { randomHex } from \"../core/utils/uuid\";\nimport {\n allowsHost,\n formatTraceparent,\n normalizeAllowlist,\n parseTraceparent,\n type TraceOutcome,\n} from \"./traceHeader\";\n\n/** §6.1's four root types, plus `custom` — a manual span with no live root to join (#164). */\nexport type TraceRootType = \"launch\" | \"interaction\" | \"navigation\" | \"request\" | \"custom\";\n\n/**\n * Android's numbers unchanged (§6.7), and **internal constants, never `TelemetryOpts`\n * surface**. The case for raising the cap is chained requests on poor networks; it was\n * rejected on Android's own logic — `injected_expired` exists so the numbers are\n * falsifiable. Ship these, watch the expired ratio, tune on evidence.\n */\nconst ROOT_IDLE_MS = 2000;\nconst ROOT_CAP_MS = 10000;\n\ntype Root = {\n traceId: string;\n spanId: string;\n rootType: TraceRootType;\n /** The liveness clock's origin — always `Date.now()` at mint, never a reported value. */\n startedAt: number;\n /** The reported `span.start_time`. Differs from `startedAt` only for `launch` on web. */\n spanStartMs: number;\n lastTouch: number;\n};\n\n/** A flat bag of wire keys. An absent key means the SDK had nothing (§6.1). */\nexport type TraceAttributes = Record<string, string | number>;\n\n/** What the interceptor observed at `send()`, and nothing it had to interpret. */\nexport type RequestTraceCtx = {\n url: string;\n /** An unsampled session injects no header at all (§6.5). Sampling stays session-level. */\n sampled: boolean;\n /**\n * The consumer's own `traceparent`, captured by the interceptor **at their write time**.\n * Absent (not empty-string) means they set none — never sniffed back off the request.\n */\n consumerTraceparent?: string | null;\n /** fetch-only. `mode` is a fetch concept XHR cannot express, so native never sets it. */\n noCors?: boolean;\n};\n\nexport type RequestTrace = {\n /** The one header value to write, or nothing at all. Never a `flags=00` placeholder. */\n header?: string;\n finish: (endedAt: number) => TraceAttributes;\n /**\n * For a `send()` that throws synchronously and so never reaches its finisher (#160):\n * drops the root this request minted, if it is still the carrier. A joined root is left\n * alone — the action it belongs to outlives one failed send.\n */\n discard: () => void;\n};\n\n/** 32 lowercase hex, W3C (§6.1). */\nconst mintTraceId = () => randomHex(32);\n/** 16 lowercase hex, W3C (§6.1). */\nconst mintSpanId = () => randomHex(16);\n\nexport class TraceManager {\n private root?: Root;\n /** Bare hosts, punycode-normalized, ports ignored. Empty by default: v4 is dark on upgrade. */\n private readonly allowlist: ReadonlySet<string>;\n /** Kept whether or not it is still the carrier: `app.start` reports it at any age. */\n private launch: Root;\n\n /**\n * @param launchStartMs what `app.start` reports as `span.start_time` — and **neither\n * value is a fork time** (§6.2). Web passes `performance.timeOrigin` (true navigation\n * start); native leaves it defaulted to `initialize()`, because everything before the\n * JS bundle loads is invisible and JS cannot see process fork. Do not compare the two\n * platforms' launch envelopes as if they measured the same interval.\n */\n constructor(launchStartMs?: number, traceHostAllowlist?: string[]) {\n // Constructor-only (§6.4). Normalized once, here, so a malformed entry throws at the\n // one moment a developer is looking — not on the first request to a typo'd host.\n this.allowlist = normalizeAllowlist(traceHostAllowlist);\n const now = Date.now();\n // Minted here and not at `app.start`'s emit, because the initial view opens in the\n // same `Telemetry` constructor and has to parent to it: a view minting its own root\n // there would make a web hard load report `navigation` (§6.2).\n this.launch = this.mint(\"launch\", now, launchStartMs ?? now);\n }\n\n /**\n * §4.1's `sdk.trace_allowlist_size` — **count only, never the hosts**, so an operator can\n * tell \"nobody opted in\" apart from \"the header is being stripped\" without the SDK\n * shipping a customer's internal hostnames to the collector.\n */\n allowlistSize(): number {\n return this.allowlist.size;\n }\n\n /**\n * `app.start`'s own row — a root, so `span.id === rum.action.id` and there is no\n * `parent.span.id`. No `span.duration_ms` either: roots derive theirs server-side.\n */\n launchRootAttributes(): TraceAttributes {\n return spanKeys(this.launch, true, this.launch.spanStartMs).keys;\n }\n\n /**\n * Tier 1 for a `view`, captured at view **entry** — the action that opened the screen,\n * not the one that closed it (§6.3). A **point span**: `span.start_time` and never\n * `span.duration_ms`, because view dwell is not span duration and a width here would\n * stretch every tap-that-navigates envelope across the whole time the user sat there.\n */\n viewSpan(entryAt: number): TraceAttributes {\n const { root, isRoot } = this.attach(\"navigation\", entryAt);\n return spanKeys(root, isRoot, entryAt).keys;\n }\n\n /**\n * Tier 1 for a `ui.interaction`, captured at the click's **mint** (§4.6/§6.2). The one\n * unconditional mint in the table: a tap is a new user action by definition, so it\n * *replaces* whatever root was live rather than joining it — which is what makes the\n * request a tap fires a child of the tap and not of the route change before it.\n *\n * A root, so `span.id === rum.action.id`, no `parent.span.id`, and no `span.duration_ms`\n * (§6.1 — a root's width is derived server-side).\n */\n interactionSpan(mintedAt: number): TraceAttributes {\n const root = this.mint(\"interaction\", mintedAt, mintedAt);\n return spanKeys(root, true, mintedAt).keys;\n }\n\n /**\n * Tier 1 for a manual span (`task.complete`, #164), captured at **start**: a child of the\n * live root — whose idle clock the start extends, like any span start — or else a fresh\n * `custom` root. A leaf, never a parent: no context stack, so a request inside the span\n * parents to the root. `span.duration_ms` is added at the end, on root *and* child — the\n * flagged §6.3 exception, since a declared end is not derivable from children.\n */\n manualSpan(startedAt: number): TraceAttributes {\n const { root, isRoot } = this.attach(\"custom\", startedAt);\n return spanKeys(root, isRoot, startedAt).keys;\n }\n\n /**\n * Tier 1 for an `http.request`, captured at **send** — the root live then is the parent,\n * and `span.start_time` is the send — plus §6.5's outcome ladder and the one header the\n * SDK ever writes. Returns the finisher, so duration is stamped from the same pair of\n * timestamps the row's `http.duration_ms` uses.\n *\n * A `send()` that throws synchronously never calls the finisher; it calls `discard()`, so\n * a root it minted does not live on for 2 s with no row describing it (#160).\n */\n requestTrace(startedAt: number, ctx: RequestTraceCtx): RequestTrace {\n const decision = this.decide(ctx);\n\n // `adopted` is the consumer's trace, not ours: §6.1 says `span.id` mirrors the\n // foreign parent-id and `parent.span.id` is omitted, so the row is root-shaped inside\n // *their* trace. The carrier is deliberately left untouched — extending a local root\n // from a request that reports foreign ids would attribute their action to ours.\n if (decision === \"adopted\") {\n const foreign = parseTraceparent(ctx.consumerTraceparent)!;\n const keys: TraceAttributes = {\n \"trace.id\": foreign.traceId,\n \"span.id\": foreign.spanId,\n \"rum.action.id\": foreign.spanId,\n \"span.start_time\": new Date(startedAt).toISOString(),\n \"traceparent.outcome\": \"adopted\",\n };\n return { finish: () => keys, discard: () => { } };\n }\n\n // **Every skip still stamps local ids with no wire header** (§6.5) — that is what\n // makes \"missing DB join ⇒ header stripped in transit\" computable, so attribution\n // runs before the ladder is resolved and regardless of what it says.\n const { root, isRoot, attribution } = this.attach(\"request\", startedAt);\n const outcome: TraceOutcome | undefined =\n decision === \"inject\" ? attribution : decision;\n const span = spanKeys(root, isRoot, startedAt);\n const keys: TraceAttributes = {\n ...span.keys,\n ...(outcome ? { \"traceparent.outcome\": outcome } : {}),\n };\n // `span.duration_ms` is Tier 1 **children only** (§6.1) — a root's is derived.\n const finish = isRoot\n ? () => keys\n : (endedAt: number) => ({ ...keys, \"span.duration_ms\": Math.max(0, endedAt - startedAt) });\n\n const discard = () => { if (isRoot && this.root === root) this.root = undefined; };\n return decision === \"inject\"\n ? { finish, discard, header: formatTraceparent(root.traceId, span.spanId) }\n : { finish, discard };\n }\n\n /**\n * §6.5's ladder above the `injected_*` split, in table order — the precedence *is* the\n * order of these returns. `undefined` means the attribute is omitted entirely: absent\n * means not traced, which is the honest report for a consumer who never opted in and for\n * a sampled-out session (which injects no header at all, not a `flags=00` id).\n */\n private decide(ctx: RequestTraceCtx): TraceOutcome | \"inject\" | undefined {\n if (this.allowlist.size === 0 || !ctx.sampled) return undefined;\n if (!allowsHost(this.allowlist, ctx.url)) return \"skipped_off_allowlist\";\n // Outranks `skipped_consumer_set` because a `no-cors` request's headers guard drops\n // the *consumer's* traceparent too — mirroring its ids would manufacture a false\n // correlation against a header no server ever saw.\n if (ctx.noCors) return \"skipped_no_cors\";\n // Never-strip: ownership is the consumer's **write-time presence flag**, recorded by\n // the interceptor when they set it — never inferred from the value's shape, because\n // an SDK-minted and a consumer-minted traceparent are byte-identical by construction.\n if (ctx.consumerTraceparent != null) {\n return parseTraceparent(ctx.consumerTraceparent) ? \"adopted\" : \"skipped_consumer_set\";\n }\n return \"inject\";\n }\n\n /**\n * Tier 2 — annotation-only (§6.3): join the trace without occupying a span. No\n * `span.id`, no parent, no duration, and **no minting** — §6.2 lists the four events\n * that mint and these are not among them, so an untraced crash carries no trace keys\n * rather than inventing a root nothing else will ever join.\n */\n annotate(now: number = Date.now()): TraceAttributes {\n const live = this.liveRoot(now);\n if (!live) return {};\n return {\n \"trace.id\": live.traceId,\n \"rum.action.id\": live.spanId,\n \"trace.root_type\": live.rootType,\n };\n }\n\n /**\n * Drop the carrier. Background clears it on both builds, so a resumed app's first fetch\n * mints its own root rather than joining an action from before the user left (§6.2);\n * session rotation clears it because `trace.id` never spans a `session.id` (§6.6).\n */\n clear(): void {\n this.root = undefined;\n }\n\n /**\n * Retire the launch root and mint a replacement, keeping the *reported* launch time —\n * the process really did start then. For a session rotation that lands **before**\n * `app.start`, which is the expired-record cold launch and therefore §4.3's most common\n * path of all.\n *\n * Clearing alone would not do: `app.start` reports the launch root at any age, so its\n * root row would ship under the **new** session while the initial `view` it fathered\n * shipped under the **old** one. `trace.id` would span a `session.id` (§6.6, invariant 2)\n * and `GROUP BY rum.action.id` would never reassemble the launch envelope. Re-minting\n * keeps the retired trace wholly inside the retired session.\n *\n * ⚠ The retired trace then has children and no root row — the initial `view` row is a\n * rootless child. That is the same condition process death already produces by design\n * (a killed view emits nothing), and it is the cheaper of the two wrongs.\n */\n restartLaunchRoot(): void {\n this.launch = this.mint(\"launch\", Date.now(), this.launch.spanStartMs);\n }\n\n /**\n * Join the live root, or mint one of `mintAs`. A span's *start* extends the root.\n *\n * `attribution` is read **before** `liveRoot()` drops an expired carrier, which is the\n * only place the two unattributed causes are still distinguishable: a carrier that just\n * aged out is `injected_expired` (context lost), no carrier at all is\n * `injected_unattributed` (no action) — the split §6.5 asks the backend to keep.\n */\n private attach(mintAs: TraceRootType, now: number): {\n root: Root;\n isRoot: boolean;\n attribution: \"injected_attributed\" | \"injected_expired\" | \"injected_unattributed\";\n } {\n const hadCarrier = this.root !== undefined;\n const live = this.liveRoot(now);\n if (live) {\n live.lastTouch = now;\n return { root: live, isRoot: false, attribution: \"injected_attributed\" };\n }\n return {\n root: this.mint(mintAs, now, now),\n isRoot: true,\n attribution: hadCarrier ? \"injected_expired\" : \"injected_unattributed\",\n };\n }\n\n private mint(rootType: TraceRootType, now: number, spanStartMs: number): Root {\n const root: Root = {\n traceId: mintTraceId(),\n spanId: mintSpanId(),\n rootType,\n startedAt: now,\n spanStartMs,\n lastTouch: now,\n };\n this.root = root;\n return root;\n }\n\n /**\n * The carrier if it is still live, dropping it otherwise. Both boundaries are strict —\n * a root sitting exactly on one has not crossed it — matching the session boundaries.\n *\n * A **negative** delta is clamped to expired (§6.7): `Date.now()` can move backwards on\n * an NTP correction, and reading that as \"fresh\" would hold one root open indefinitely.\n */\n private liveRoot(now: number): Root | undefined {\n const root = this.root;\n if (!root) return undefined;\n const idle = now - root.lastTouch;\n const age = now - root.startedAt;\n if (idle < 0 || age < 0 || idle > ROOT_IDLE_MS || age > ROOT_CAP_MS) {\n this.root = undefined;\n return undefined;\n }\n return root;\n }\n}\n\n/**\n * §6.1's identity, in one place so no call site can get it wrong: `rum.action.id` is the\n * root's `span.id` — **equal to `span.id` on a root and to `parent.span.id` on a child**.\n * That is the single thing that makes an action's envelope one `GROUP BY` and not a\n * self-join. `trace.root_type` is denormalized onto every child so launch traffic separates\n * from tap traffic without joining back to the root.\n */\nfunction spanKeys(root: Root, isRoot: boolean, spanStartMs: number): { keys: TraceAttributes; spanId: string } {\n const spanId = isRoot ? root.spanId : mintSpanId();\n return {\n spanId,\n keys: {\n \"trace.id\": root.traceId,\n \"span.id\": spanId,\n ...(isRoot ? {} : { \"parent.span.id\": root.spanId }),\n \"rum.action.id\": root.spanId,\n \"trace.root_type\": root.rootType,\n \"span.start_time\": new Date(spanStartMs).toISOString(),\n },\n };\n}\n","// `app.hang` (#165, decision #143) — one JS-thread stall detector, shared by both builds:\n// a self-rescheduling timer that measures how late it fired. Nothing here is platform\n// specific — `setTimeout` and `performance.now()` are globals both runtimes provide.\n\nimport { debug } from \"../core/debug\";\nimport type { LogSnapshot } from \"../core/telemetry\";\nimport type { TraceAttributes } from \"./traceManager\";\n\n/** Internal constants, never `TelemetryOpts` surface. */\nexport const HANG_TICK_MS = 1000;\nexport const HANG_THRESHOLD_MS = 2000;\n/** Longer than this is a suspension (device sleep, a frozen tab), not a hang the user sat through. */\nexport const HANG_SUSPENSION_MS = 60000;\n\n/**\n * The stall between two ticks, or `undefined` when there is none to report: how late the\n * timer fired past its schedule, so the tick interval itself is never booked as stall.\n * ⚠ At 1 s resolution this under-reports by up to one tick — a stall that began mid-interval\n * is partly absorbed by the wait the timer would have done anyway. Never over-reports.\n */\nexport function stallMs(prevTick: number, now: number): number | undefined {\n const late = now - prevTick - HANG_TICK_MS;\n return late >= HANG_THRESHOLD_MS && late <= HANG_SUSPENSION_MS ? Math.round(late) : undefined;\n}\n\ntype Core = {\n snapshot(at?: number): LogSnapshot;\n trace: { annotate(now?: number): TraceAttributes };\n log(name: string, data?: Record<string, any>, snapshot?: LogSnapshot): Promise<void>;\n};\n\nexport class HangDetector {\n private timer?: ReturnType<typeof setTimeout>;\n /** The last good tick — what a stall is attributed to: where the user was when it froze. */\n private last?: { mono: number; snap: LogSnapshot; trace: TraceAttributes };\n\n constructor(private core: Core, private now: () => number = () => performance.now()) {}\n\n private active = false;\n private suspended = false;\n\n /** Driven by the lifecycle emitter: foreground only, so background suspension never reads as a hang. */\n setActive(active: boolean) {\n this.active = active;\n this.sync();\n }\n\n /** `disable()` / `enable()` (#172): off while collection is off, whatever the lifecycle says. */\n suspend(suspended: boolean) {\n this.suspended = suspended;\n this.sync();\n }\n\n private sync() {\n if (this.active && !this.suspended) this.start();\n else this.stop();\n }\n\n start() {\n if (this.timer === undefined) this.tick();\n }\n\n /** Idempotent. `shutdown()` and backgrounding call it; the next start begins a fresh baseline. */\n stop() {\n if (this.timer !== undefined) clearTimeout(this.timer);\n this.timer = undefined;\n this.last = undefined;\n }\n\n private tick = () => {\n const mono = this.now();\n const prev = this.last;\n const stall = prev && stallMs(prev.mono, mono);\n if (prev && stall !== undefined) {\n // Tier 2 from the last good tick's live root — read then, never minted (§6.3).\n // No stack: the frozen code has already returned by the time anything can look.\n this.core.log(\"app.hang\", { ...prev.trace, \"hang.duration_ms\": stall }, prev.snap)\n .catch((err) => debug.warn(\"app.hang failed:\", err));\n }\n const at = Date.now();\n this.last = { mono, snap: this.core.snapshot(at), trace: this.core.trace.annotate(at) };\n this.timer = setTimeout(this.tick, HANG_TICK_MS);\n };\n}\n","import type { StoreRead } from \"../core/store\";\nimport { evictIndex, type TelemetryEvent } from \"../core/telemetry\";\n\n// The offline queue's shared, platform-agnostic half (#89). Both senders keep failed\n// batches under one key; only the Store underneath them differs, so the decoding rules\n// live here once and stay in lockstep.\n\nexport const FAILED_EVENTS_KEY = \"telemetry_failed_events\";\n\n/**\n * Decode a stored batch.\n *\n * The Store port never throws, and neither does this. An unavailable store, a key that\n * was never written, a half-written payload and a non-array JSON value all mean the\n * same thing to a caller — nothing replayable — so they all return `[]`. Before the\n * port, this was a bare `JSON.parse(... || \"[]\")` that threw straight through\n * `replayFailed()` on any corrupt payload and took startup with it.\n */\nexport function decodeFailed(read: StoreRead): TelemetryEvent[] {\n if (read.status !== \"hit\") return [];\n try {\n const parsed = JSON.parse(read.value);\n return Array.isArray(parsed) ? parsed : [];\n } catch {\n return [];\n }\n}\n\n/**\n * The offline store's cap (§9.4). Real numbers, not chosen ones: Android caps AsyncStorage\n * at 6 MB for the whole app and web `localStorage` is the *host app's* ~5 MB — an\n * append-only telemetry queue inside either is a slow eviction of the consumer's own data.\n */\nexport const STORE_MAX_EVENTS = 500;\nexport const STORE_MAX_BYTES = 1_000_000;\n\n/** UTF-8 length where the runtime offers it. RN (Hermes) and every browser do; be safe anyway. */\nconst byteLength = (s: string): number =>\n typeof TextEncoder !== \"undefined\" ? new TextEncoder().encode(s).length : s.length;\n\n/**\n * Encode the queue after appending `incoming`, oldest first, capped per §9.4 and\n * reporting how many rows the cap cost.\n *\n * The caller books the count as `sdk.drop_reason = \"store_full\"`; returning it rather\n * than counting in here keeps this module free of the Telemetry instance it would\n * otherwise need a handle on.\n */\nexport function encodeFailed(\n existing: TelemetryEvent[],\n incoming: TelemetryEvent[],\n): { json: string; dropped: number } {\n const kept = [...existing, ...incoming];\n let dropped = 0;\n\n while (kept.length > STORE_MAX_EVENTS) { kept.splice(evictIndex(kept), 1); dropped++; }\n\n // Sized once per event, not once per eviction: a 500-event backlog of 100 KiB events\n // (the collector's per-event ceiling) would otherwise re-stringify ~50 MB per drop.\n // 2 for the brackets, 1 per separating comma.\n const sizes = kept.map(e => byteLength(JSON.stringify(e)));\n let total = sizes.reduce((a, b) => a + b, 0) + Math.max(kept.length - 1, 0) + 2;\n while (total > STORE_MAX_BYTES && kept.length > 0) {\n const i = evictIndex(kept);\n total -= sizes[i] + (kept.length > 1 ? 1 : 0); // no separating comma to reclaim on the last row\n sizes.splice(i, 1);\n kept.splice(i, 1);\n dropped++;\n }\n\n return { json: JSON.stringify(kept), dropped };\n}\n\n/**\n * One drain per sender, however many callers there are (#113).\n *\n * `takeFailed()` clears the key before the send is attempted, so a *single* drain can\n * never double-send. Two concurrent drains can: both read the payload before either\n * removes it, and the recovered batch goes out twice — worst exactly when the network\n * was bad, which is when the data mattered. Returning the in-flight promise makes the\n * second caller a no-op that still awaits the first, and the guard is per-sender rather\n * than per-module so two `Telemetry` instances in one process keep their own.\n */\nexport function guardedDrain(drain: () => Promise<void>): () => Promise<void> {\n let inFlight: Promise<void> | undefined;\n return () => (inFlight ??= drain().finally(() => { inFlight = undefined; }));\n}\n","/**\n * `JSON.stringify` that returns `undefined` instead of throwing — a cycle, a `toJSON` that\n * threw, a `BigInt`. Shared by `user.custom.*`'s bag rule (§4.10) and `flattenWithPrefix`'s\n * depth cap: both exist so a bad consumer payload is a dropped key rather than an exception\n * raised inside the SDK, in the host app's own call stack.\n */\nexport function stringifyOrDrop(value: unknown): string | undefined {\n try {\n return JSON.stringify(value) ?? undefined;\n } catch {\n return undefined;\n }\n}\n","// Manual spans (#164) — the bookkeeping half, shared by both builds: which spans are open,\n// the bounds, supersede-by-name, and the persisted shape. Core owns the trace keys, the\n// identity freeze and the `task.complete` emit; nothing here touches either.\n\nimport { stringifyOrDrop } from \"../core/utils/json\";\nimport type { TraceAttributes } from \"./traceManager\";\n\n/** A leak in host code must not grow without bound. Internal, never `TelemetryOpts`. */\nexport const MAX_OPEN_SPANS = 32;\nconst TASK_NAME_MAX = 255;\n\nexport type TaskOutcome = \"completed\" | \"failed\" | \"abandoned\";\n\nexport type OpenSpan = {\n name: string;\n start: number;\n attrs?: Record<string, unknown>;\n /** Frozen at start (§3.1). Unset only while a start waits on an expired session's rotation. */\n keys?: TraceAttributes;\n viewId?: string;\n sessionId?: string;\n sessionStart?: number;\n /** That rotation — an end arriving before it settles waits on it. */\n ready?: Promise<void>;\n};\n\n/** The persisted form: identity frozen, attributes as a JSON string so a cycle cannot break the record. */\nexport type PersistedSpan = Omit<OpenSpan, \"attrs\" | \"ready\"> & { attrs?: string };\n\n/**\n * Attributes a span carries can annotate but never forge the join keys: anything in the\n * `task`, `span`, `trace`, `parent` or `rum` namespaces is dropped, flattened or not.\n * Identity keys need no filter — core assembles them after caller data.\n */\nconst RESERVED = /^(task|span|trace|parent|rum)(\\.|$)/;\nexport function spanAttributes(attrs: unknown): Record<string, unknown> | undefined {\n if (!attrs || typeof attrs !== \"object\") return undefined;\n const out: Record<string, unknown> = {};\n for (const [k, v] of Object.entries(attrs)) if (!RESERVED.test(k)) out[k] = v;\n return out;\n}\n\n/** Unnormalized and capped at 255; blank or non-string is inert (`undefined`). */\nexport function taskName(name: unknown): string | undefined {\n return typeof name === \"string\" && name.trim() !== \"\" ? name.slice(0, TASK_NAME_MAX) : undefined;\n}\n\nexport class SpanRegistry {\n private open = new Map<string, OpenSpan>();\n\n /**\n * Opens `name`, superseding an open span of the same name — dropped without a row, since\n * `abandoned` means \"the session ended first\" and nothing else. `undefined` past the cap.\n */\n start(name: string, start: number, attrs?: Record<string, unknown>): OpenSpan | undefined {\n if (!this.open.has(name) && this.open.size >= MAX_OPEN_SPANS) return undefined;\n const span: OpenSpan = { name, start, attrs };\n this.open.delete(name);\n this.open.set(name, span);\n return span;\n }\n\n /** Close by name. With `only`, a superseded handle cannot close its successor. */\n take(name: string, only?: OpenSpan): OpenSpan | undefined {\n const span = this.open.get(name);\n if (!span || (only && span !== only)) return undefined;\n this.open.delete(name);\n return span;\n }\n\n /** `disable()` (#172): an opt-out keeps nothing, open journeys included. */\n clear(): void {\n this.open.clear();\n }\n\n has(span: OpenSpan): boolean {\n return this.open.get(span.name) === span;\n }\n\n /** Every span frozen to `sessionId`, removed — the ones a finalize owes `abandoned`. */\n takeSession(sessionId: string): OpenSpan[] {\n const out = [...this.open.values()].filter((s) => s.sessionId === sessionId);\n for (const s of out) this.open.delete(s.name);\n return out;\n }\n\n toJSON(): PersistedSpan[] {\n return [...this.open.values()]\n .filter((s) => s.sessionId !== undefined)\n .map(({ ready: _r, attrs, ...s }) => ({ ...s, attrs: attrs && stringifyOrDrop(attrs) }));\n }\n\n /** Adopt a persisted record's spans. Anything malformed is skipped, never thrown. */\n restore(saved: unknown): void {\n this.open.clear();\n if (!Array.isArray(saved)) return;\n for (const s of saved.slice(0, MAX_OPEN_SPANS)) {\n if (typeof s?.name !== \"string\" || typeof s.start !== \"number\" || typeof s.sessionId !== \"string\") continue;\n let attrs: Record<string, unknown> | undefined;\n try { attrs = s.attrs ? JSON.parse(s.attrs) : undefined; } catch { attrs = undefined; }\n this.open.set(s.name, { ...s, attrs });\n }\n }\n}\n","// §4.10, #107 — the profile attributes for `user.profile.update`, and nothing else.\n//\n// PII used to ride the Context block of every event: a 10,000-event session put 10,000\n// copies of an email address on the wire and at rest. It now appears on the one event\n// that needs it, keyed by `user.id` (which `identify({ userId })` sets).\n//\n// The bag rule here retires three v3 defects at once — `flattenWithPrefix` had no depth\n// guard, so a cyclic `customAttributes` value recursed to a `RangeError` *inside the SDK*\n// and crashed the host app on a bad `identify()`; arrays passed through raw against the\n// primitive-values rule; and nested objects recursed into the bag. A bad payload is a\n// dropped key, never a throw.\n\nimport { isDev } from \"./debug\";\nimport { stringifyOrDrop } from \"./utils/json\";\nimport type { UserProfile } from \"./telemetry\";\n\n// Backend column widths (§4.10, work-list item 14). `rum_users.phone` is VARCHAR(50).\nexport const NAME_CAP = 255;\nexport const EMAIL_CAP = 255;\nexport const PHONE_CAP = 50;\nexport const CUSTOM_MAX_KEYS = 64;\nexport const CUSTOM_KEY_CAP = 64;\nexport const CUSTOM_VALUE_CAP = 255;\n\nlet warnedOnce = false;\n\nfunction capString(value: unknown, max: number): string | undefined {\n if (typeof value !== \"string\") return undefined;\n const trimmed = value.slice(0, max);\n return trimmed.length ? trimmed : undefined;\n}\n\n/**\n * A primitive rides as itself; anything else is stringified and truncated. A value that\n * cannot be stringified — a cycle, a throwing `toJSON` — drops the key rather than the\n * process. Consumer keys pass through **verbatim, casing included** (§4.10): the SDK\n * imposes no normalization here, so an over-long key is dropped, never truncated.\n */\nexport function customValue(value: unknown): string | number | boolean | undefined {\n if (value === null || value === undefined) return undefined;\n if (typeof value === \"number\" || typeof value === \"boolean\") return value;\n if (typeof value === \"string\") return value.slice(0, CUSTOM_VALUE_CAP) || undefined;\n const flat = stringifyOrDrop(value);\n return flat === undefined ? undefined : flat.slice(0, CUSTOM_VALUE_CAP) || undefined;\n}\n\n/**\n * The wire keys for `user.profile.update`. `user.id` is not here — it rides the Context\n * block, where it is present on this event by construction.\n */\nexport function buildProfileAttributes(profile: UserProfile | undefined): Record<string, any> {\n const attrs: Record<string, any> = {};\n if (!profile) return attrs;\n\n const name = capString(profile.fullName, NAME_CAP);\n const email = capString(profile.email, EMAIL_CAP);\n const phone = capString(profile.phone, PHONE_CAP);\n if (name !== undefined) attrs[\"user.name\"] = name;\n if (email !== undefined) attrs[\"user.email\"] = email;\n if (phone !== undefined) attrs[\"user.phone\"] = phone;\n\n let dropped = 0;\n let kept = 0;\n for (const key of Object.keys(profile.customAttributes || {})) {\n if (key.length > CUSTOM_KEY_CAP || kept >= CUSTOM_MAX_KEYS) { dropped++; continue; }\n const value = customValue((profile.customAttributes as any)[key]);\n if (value === undefined) { dropped++; continue; }\n attrs[`user.custom.${key}`] = value;\n kept++;\n }\n\n if (dropped > 0) {\n attrs[\"user.custom_dropped\"] = dropped;\n if (isDev() && !warnedOnce) {\n warnedOnce = true;\n console.warn(\n `[edge-telemetry] identify(): ${dropped} custom attribute(s) dropped. ` +\n `user.custom.* is bounded at ${CUSTOM_MAX_KEYS} keys, ${CUSTOM_KEY_CAP}-char keys ` +\n `and ${CUSTOM_VALUE_CAP}-char values; unserializable values are dropped.`\n );\n }\n }\n\n return attrs;\n}\n","import { customValue } from \"./userProfile\";\n\n/** #167's bounds on one crumb, so 20 of them cannot blow `app.crash`'s budget. */\nexport const CRUMB_NAME_MAX = 64;\nexport const CRUMB_DATA_KEYS = 8;\n\n/**\n * A crumb, bounded: `name` capped at 64, the first 8 `data` keys kept, each value by the\n * `user.custom.*` bag rule (primitive as itself, else stringified; capped at 255; dropped if it\n * cannot be stringified). `name` and `timestamp` are set last, so `data` cannot rename the crumb.\n * No `category`, no `level` — a crumb is a name and a little context.\n */\nexport function boundCrumb(name: unknown, data?: Record<string, unknown>, at: Date = new Date()): Record<string, unknown> {\n const out: Record<string, unknown> = {};\n if (data && typeof data === \"object\") {\n for (const [k, v] of Object.entries(data).slice(0, CRUMB_DATA_KEYS)) {\n const value = customValue(v);\n if (value !== undefined) out[k] = value;\n }\n }\n out.name = String(name).slice(0, CRUMB_NAME_MAX);\n out.timestamp = at.toISOString();\n return out;\n}\n\n/**\n * Fixed-size ring buffer of recent actions, attached to `app.crash` as the\n * JSON-stringified `crash.breadcrumbs` (last N, oldest evicted first). See #28.\n */\nexport class BreadcrumbBuffer {\n private items: any[] = [];\n\n constructor(private max = 20) {}\n\n add(item: any): void {\n this.items.push(item);\n if (this.items.length > this.max) this.items.shift();\n }\n\n list(): any[] {\n return [...this.items];\n }\n\n toJSON(): string {\n return JSON.stringify(this.items);\n }\n}\n","import { debug } from \"./debug\";\nimport type { TelemetryEvent } from \"./telemetry\";\n\n/**\n * The consumer's scrubbing hook (§3.6). One event, **synchronous**, run at **enqueue**.\n *\n * Enqueue and not flush: a failed send persists the batch through the `Store`, so a\n * flush-time hook would let unscrubbed PII hit disk — and on native that disk outlives\n * the process. Synchronous because `app.crash` flushes during teardown and a\n * Promise-returning hook would put a host `await` in a dying app's path.\n */\nexport type BeforeSend = (event: TelemetryEvent) => TelemetryEvent | null;\n\nexport type HookOutcome =\n | { kind: \"kept\"; event: TelemetryEvent }\n | { kind: \"dropped\" } // returned null — the hook working as intended (sdk.hook_dropped)\n | { kind: \"failed\" }; // threw — fail closed (sdk.hook_failed)\n\n/**\n * Tier A — immutable. Re-stamped from the original after the hook returns, never\n * defended by throwing: the realistic hook is `delete attrs[k]` in a loop and the\n * realistic failure is over-deletion, so an over-broad hook must not be able to get a\n * consumer's whole feed silently discarded behind a 2xx.\n *\n * A writable `eventName` would also restore the public path to `app.crash` that the\n * allowlist removes on purpose.\n */\nconst TIER_A_KEYS = new Set([\n // `session.sequence` is not in the contract's §3.6 list, which names only `event.sequence`.\n // Both are transmission ordinals with no scrubbing use case: (session.id, session.sequence)\n // orders a session's batches (#92) and (session.id, event.sequence) is the backend's dedup\n // key (#94, §2.4) — a hook that could delete either would break the thing it keys.\n //\n // `event.sequence` is stamped in `enqueue()` *after* this hook runs, so on the way in it is\n // absent and the re-stamp is a no-op; it is listed because the hook must not be able to\n // forge one, and because a re-run over an already-stamped event must leave it alone.\n \"session.id\", \"session.start_time\", \"session.sequence\", \"event.sequence\",\n \"device.platform\", \"trace.id\", \"span.id\", \"parent.span.id\",\n \"rum.action.id\", \"view.id\",\n]);\nconst isTierA = (key: string) =>\n TIER_A_KEYS.has(key) || key.startsWith(\"sdk.\") || key.startsWith(\"app.\");\n\n/**\n * Tier B — rewritable, not deletable. Hashing `device.id` to a tenant-local id is a\n * legitimate ask; deleting it 400s the entire batch at the collector (§2.3).\n * Everything else is Tier C and untouched — that is where the PII actually lives.\n */\nconst TIER_B_KEY = \"device.id\";\n\n/** Run the hook and enforce the tiers on what comes back. */\nexport function applyBeforeSend(original: TelemetryEvent, hook: BeforeSend): HookOutcome {\n let returned: TelemetryEvent | null;\n try {\n // The hook gets a copy, never `original`. The realistic hook is `delete\n // attrs[k]` in a loop, and re-stamping from an object the hook already mutated\n // would restore nothing — the tier table would be decorative.\n returned = hook({ ...original, attributes: { ...original.attributes } });\n } catch (err) {\n // Fail closed. Sending the original would ship the exact field the hook existed\n // to remove, which is the one outcome a broken scrubber must never produce.\n debug.warn(\"Telemetry: beforeSend threw — event dropped\", err);\n return { kind: \"failed\" };\n }\n // Only an explicit `null` is the documented \"drop this row\". Anything else the hook\n // hands back that isn't an event — `undefined` from a forgotten `return`, a string,\n // a number — is a *bug*, and counting it as dropped would inflate the \"my rule is\n // working\" counter with the exact case §3.6 says the two counters exist to separate.\n if (returned === null) return { kind: \"dropped\" };\n if (typeof returned !== \"object\") {\n debug.warn(\"Telemetry: beforeSend returned a non-event — event dropped\", returned);\n return { kind: \"failed\" };\n }\n return { kind: \"kept\", event: restamp(original, returned) };\n}\n\n/** Replace the Tier A slice wholesale — that covers deletion and forgery in one pass. */\nfunction restamp(original: TelemetryEvent, returned: TelemetryEvent): TelemetryEvent {\n const attributes: Record<string, any> = {};\n for (const [k, v] of Object.entries(returned.attributes ?? {})) {\n if (!isTierA(k)) attributes[k] = v;\n }\n for (const [k, v] of Object.entries(original.attributes ?? {})) {\n if (isTierA(k)) attributes[k] = v;\n }\n // Not just `undefined`: a hook writing `null` or `\"\"` here 400s the batch exactly the\n // same way `delete` does, so anything that isn't a usable id is treated as a deletion.\n const rewritten = attributes[TIER_B_KEY];\n if (typeof rewritten !== \"string\" || rewritten === \"\") {\n const originalId = original.attributes?.[TIER_B_KEY];\n if (originalId === undefined) delete attributes[TIER_B_KEY];\n else attributes[TIER_B_KEY] = originalId;\n }\n\n // Built key by key rather than spread: a hook that bolts `metricName` onto an event\n // must not be able to move a row onto the metric path.\n const kept: TelemetryEvent = {\n type: original.type,\n timestamp: original.timestamp,\n attributes,\n };\n if (original.eventName !== undefined) kept.eventName = original.eventName;\n if (original.metricName !== undefined) kept.metricName = original.metricName;\n // `value` is Tier C — rewritable — but a metric without one is not a metric.\n if (original.type === \"metric\") kept.value = returned.value ?? original.value;\n return kept;\n}\n","import { debug, isDev } from \"./debug\";\nimport { isRejected, statusOf } from \"../adapters/batch\";\nimport { ViewManager, type ViewNameSource } from \"../adapters/viewManager\";\nimport { TraceManager } from \"../adapters/traceManager\";\nimport { HangDetector } from \"../adapters/hangDetector\";\nimport { FAILED_EVENTS_KEY } from \"../adapters/failedEvents\";\nimport { SpanRegistry, spanAttributes, taskName, type OpenSpan, type PersistedSpan, type TaskOutcome } from \"../adapters/manualSpans\";\nimport { BreadcrumbBuffer, boundCrumb } from \"./breadcrumbs\";\nimport { buildErrorAttributes, type ErrorSource } from \"../adapters/crashCapture\";\nimport { randomHex } from \"./utils/uuid\";\nimport type { Store } from \"./store\";\nimport { memoryStore } from \"./memoryStore\";\nimport { applyBeforeSend, type BeforeSend } from \"./beforeSend\";\nimport { buildProfileAttributes } from \"./userProfile\";\nimport { stringifyOrDrop } from \"./utils/json\";\nimport { version as PKG_VERSION } from \"../../package.json\";\n\nexport type { BeforeSend } from \"./beforeSend\";\nimport type { Orientation } from \"../adapters/viewport\";\nexport type { Orientation };\n\n// v3 wire contract constants\n// §3.3 / §12's item 10 — `react-native-{Platform.OS}`, joining Flutter's `flutter-{os}` shape.\n// ⚠ NOT a closed three-value enum: RN-Windows emits `react-native-windows`. The bare\n// framework name survives only for a core `new Telemetry()` with no entry-declared\n// platform — tests only: neither core nor the entry classes are constructible publicly (#159).\nconst sdkPlatform = (platform?: string) => platform ? `react-native-${platform}` : \"react-native\";\nconst SDK_VERSION = PKG_VERSION; // sdk.version follows the published package version\nconst SESSION_IDLE_MS = 30 * 60 * 1000; // rotate the session after 30 min of inactivity (iOS ADR-004)\n// New in v4 (§4.2). Removing the process-death boundary lets a backgrounded app's\n// http.request traffic hold one session open forever; this bounds length, not count.\nconst SESSION_MAX_MS = 4 * 60 * 60 * 1000;\n\n// A cycle needs *a* bound, not a visited-set. Nothing on this wire nests past deviceInfo's\n// two levels, so 8 is unreachable for a real payload and a cycle stops here (§4.10).\nconst FLATTEN_MAX_DEPTH = 8;\n\n/**\n * The in-memory queue's cap (§9.4). Drop-oldest, `app.crash` evicted last: a long\n * offline period on an unbounded queue grows inside the host app's heap, and evicting\n * crashes first would make the crash-free rate read *better* the worse the network is.\n */\nconst QUEUE_MAX_EVENTS = 500;\n\n/**\n * §2.4's draining `flush()`: at most this many batches per call, sequential, paced to the\n * collector's 10 req/s burst — it 429s at batch 11 otherwise (§2.3). Internal constants.\n */\nconst DRAIN_MAX_BATCHES = 50;\nconst DRAIN_PACE_MS = 100;\n/** A 429 with no usable `X-RateLimit-Reset` still holds off for one burst window. */\nconst RATE_LIMIT_DEFAULT_HOLD_MS = 1000;\n\n/** §2.5's one `__DEV__` warning for a rejected batch — once per process. */\nlet warnedRejected = false;\n\n/** `sdk.drop_reason` (§11). `rejected` is a 4xx-dropped batch (§2.5, #162). */\nexport type DropReason = \"queue_full\" | \"store_full\" | \"rejected\";\n\n/**\n * Which row to evict to get back under a cap: the oldest non-crash, or — when every\n * row is a crash — the oldest, because growing past the cap is not an option either.\n *\n * Shared with the offline store (`adapters/failedEvents.ts`) so the in-memory queue and\n * the disk queue can never disagree about what survives.\n *\n * ponytail: O(n) scan per eviction, n <= 500. Track the first non-crash index if a\n * profile ever shows this on a hot path.\n */\n/** An event's `event.sequence`, or -1 before `enqueue()` has stamped one. */\nconst seqOf = (e: TelemetryEvent): number => e.attributes?.['event.sequence'] ?? -1;\n\n/**\n * §4.7's two error names. Both book `sdk.error_count` and `view.error_count` — a closed\n * enumeration, not resource failures and not `console.warn`. Only `app.crash` gets the\n * dedicated crash path and the eviction reprieve, which is the whole point of the split:\n * `COUNT(event_name='app.crash')` must stay a crash count nobody can forget to filter.\n */\nexport const isErrorName = (name?: string): boolean =>\n name === \"app.crash\" || name === \"app.error\";\n\nexport function evictIndex(events: TelemetryEvent[]): number {\n const i = events.findIndex(e => e.eventName !== \"app.crash\");\n return i === -1 ? 0 : i;\n}\n\n/** Store key for the self-minted, persisted `device.id` (#91). */\nexport const DEVICE_ID_KEY = \"telemetry_device_id\";\n/** Store key for the resumable session record (#92). */\nexport const SESSION_KEY = \"telemetry_session\";\n\n/** Why a session started/ended. `launch` is internal only — it ships as no `session.reason` (catalogue #179). */\nexport type SessionReason = \"launch\" | \"timeout\" | \"max_duration\" | \"manual\";\nexport type SessionEndReason = Exclude<SessionReason, \"launch\">;\n\n/**\n * What survives process death, tab close, hard reload and bfcache restore (§4.2).\n * On web the Store is `localStorage`, so this record is browser-wide and shared\n * across tabs — intended, not a leak.\n */\ntype PersistedSession = {\n id: string;\n start: number;\n lastActivity: number;\n sequence: number;\n // Per-session, per-event ordinal (§2.4). Persisted for the same reason `sequence` is:\n // a resumed session restarting at 0 emits duplicate (session.id, event.sequence) pairs,\n // which is exactly the key the backend's dedup index is built on.\n eventSequence: number;\n eventCount: number;\n errorCount: number;\n // The sticky sample decision and the rate it was rolled at (§3.6). Both travel with\n // the session, because a resume is not a rotation — re-rolling on relaunch produces\n // a half-sampled session, and shipping the *current* config rate on a session rolled\n // at the old one makes every extrapolation off it wrong.\n sampled: boolean;\n sampleRate: number;\n // Open manual spans (#164): a journey crossing process death is closable by name after\n // the resume, and one the session outlives is `abandoned` at its finalize.\n spans?: PersistedSpan[];\n};\n\n/** What hydration decided, so the emitting half stays free of storage concerns. */\ntype SessionHydration =\n | { kind: \"resumed\" } // inside the idle window: no session.started (§4.1)\n | { kind: \"nothing\" } // miss or unavailable — storage told us nothing\n | { kind: \"expired\"; reason: SessionEndReason }; // adopted, now owed a finalize + a fresh session\n/** The collector caps `user.id` at 255; truncate at source rather than be rejected (§3.2). */\nconst USER_ID_MAX = 255;\n\n// Names the backend routes — the processor's event catalogue (`catalogue.version`, #179). Anything\n// else is remapped to `custom.event` with the original name carried as `event.name`, and that\n// includes `custom.event` itself, so the row always carries its `event.name`. Includes metric\n// names so the metric path isn't remapped.\nconst ALLOWED_NAMES = new Set<string>([\n // `navigation` and `screen.duration` are **removed in v5** (#163, §4.0): the `view` entity\n // is the only screen feed; the processor derives both from it (catalogue `derives:`).\n \"session.started\", \"session.finalized\", \"app.lifecycle\",\n \"http.request\", \"network.change\",\n \"user.profile.update\", \"app.crash\", \"view\", \"screen.load\",\n \"app.error\", \"ui.interaction\", \"app.start\", \"task.complete\", \"app.hang\",\n \"frame.summary\", \"memory.usage\", \"custom.metric\",\n \"perf.lcp\", \"perf.fcp\", \"perf.cls\", \"perf.inp\", \"perf.ttfb\",\n // ⚠ `page_load`, `resource_timing` and `long_task` are **retired, not deferred**\n // (§10.2, #109) — as `user.interaction` was in #102. Do not add them back: `page_load`'s\n // job is done three ways over (`view` + `view.loading_time` + the vitals), `resource_timing`\n // would blow the 500-event queue on one asset-heavy view, and `long_task`'s only APIs are\n // Chromium-only while `frame.summary` detects jank on every runtime.\n]);\n\n/**\n * §5.1's `metric.unit` on the SDK's own metrics — the five vitals. A CLS of `0.08` is a\n * `score`, not `ms`. These names are also **reserved** against `recordMetric()`.\n */\nconst METRIC_UNIT: Record<string, string> = {\n \"perf.lcp\": \"ms\", \"perf.fcp\": \"ms\", \"perf.inp\": \"ms\", \"perf.ttfb\": \"ms\",\n \"perf.cls\": \"score\",\n};\n\n/**\n * Catalogue *events* that keep metric semantics (#179): periodic samples, so they are not\n * session activity, extend no breadcrumb trail and carry no trace keys (Tier 3).\n */\nconst SAMPLE_NAMES = new Set<string>([\"frame.summary\", \"memory.usage\"]);\n\n/**\n * §6.3's Tier 2 — annotation-only: `trace.id`, `rum.action.id` and `trace.root_type`, no\n * span. Stamped here because these rows have no earlier capture point; Tier 1 rows\n * (`app.start`, `view`, `http.request`) carry keys captured at launch / view entry / send\n * and hand them in as `data`, and everything else is Tier 3 — **trace-free, all metrics\n * included**. A windowed aggregate belongs to no single action, and a `rum.action.id` on\n * one would invite a `GROUP BY` over a number that was never attributable.\n *\n * ⚠ \"% of errors attributed to an action\" is bounded well below 100% by design: a consumer\n * calling `captureError()` from a background retry has no live root and gets no trace keys at\n * all. `ui.interaction` is Tier 1: its keys are captured at the click's\n * mint and handed in as `data`, like the other three.\n */\nconst TIER_2_NAMES = new Set<string>([\"app.crash\", \"app.error\", \"custom.event\"]);\n\n/**\n * §4.6's mint/emit split, for the one event that has one. A `ui.interaction` is emitted\n * after its dead-click window, so its wire `timestamp` and its `view.id` / `view.name` /\n * `session.id` are snapshotted at the click and replayed here — otherwise a tap that\n * navigates is booked against the view it opened.\n */\nexport type LogSnapshot = {\n /**\n * Epoch ms of the click. Becomes the row's `timestamp`. **Omitted by a span-carrying row\n * that is not deferred** — an `http.request` freezes its *attribution* at send but still\n * reports the completion time §4.4 gives it.\n */\n at?: number;\n viewId: string;\n sessionId: string;\n /** Epoch ms — `session.start_time` freezes with the id it belongs to (§3.1). */\n sessionStart: number;\n};\n\n// Events carry `eventName`; metrics carry `metricName` + numeric `value` (v3 §\"Event vs Metric\").\n// Kept as one loose shape (not a strict union) so callers can read `.eventName` without narrowing;\n// the emit helpers (log / logMetric) set the right fields, and JSON.stringify drops the undefined ones.\nexport type TelemetryEvent = {\n type: 'event' | 'metric';\n eventName?: string;\n metricName?: string;\n value?: number;\n timestamp: string; // ISO 8601 (v3 wire contract) — never ms epoch\n attributes?: Record<string, any>;\n};\n\nexport interface Sender {\n send(events: TelemetryEvent[]): Promise<void>;\n /**\n * Persist a batch that could not be sent. Returns how many rows the offline store's\n * cap cost, so core can book them as `sdk.drop_reason = \"store_full\"` (§9.4) — the\n * counter lives on the Context block, which only core assembles. `void` is still a\n * valid return: a consumer's own sender is not obliged to have a cap.\n */\n onFailure?(events: TelemetryEvent[]): Promise<number | void>;\n replayFailed?(): Promise<void>;\n}\n\n\n\nexport interface CrashHandlerOptions {\n // console.error -> app.error, console.warn -> a breadcrumb. Default OFF (§4.7, #100):\n // React's own dev-mode warnings dominated v3's crash count.\n captureConsole?: boolean;\n}\n\nexport interface CrashHandler {\n attach(options?: CrashHandlerOptions): Promise<void>;\n}\nexport interface NetworkInfo {\n type?: string; // \"wifi\", \"cellular\", \"ethernet\", \"unknown\", etc.\n is_connected?: boolean;\n}\n\nexport interface NetworkInfoHandler {\n start(telemetry: Telemetry): Promise<NetworkInfo>;\n collect(): Promise<NetworkInfo>;\n}\n\nexport interface DeviceInfoHandler {\n start(telemetry: Telemetry): Promise<void>;\n collect(): Promise<DeviceInfo>;\n}\nexport interface FrameDropsHandler {\n start(): Promise<void>;\n}\n\nexport interface NetworkHandler {\n start(): Promise<void>;\n}\n\nexport interface MemoryHandler {\n start(): Promise<void>;\n /** Torn down by `shutdown()`: unlike the rAF-driven trackers this one owns a timer. */\n stop?(): void;\n}\n\n/**\n * #173's device state. `battery()` is synchronous on purpose — a cached last read — so no\n * failure row ever awaits a native call. Native implements all of it; web only `accessibility`.\n */\nexport interface DeviceStateHandler {\n battery?(): Record<string, number | boolean>;\n refresh?(): Promise<void>;\n start?(): void;\n stop?(): void;\n /** Read once per session, onto `session.started`. A failed read omits only its own key. */\n accessibility(): Promise<Record<string, number | boolean>>;\n}\n\nexport interface NavigationHandler {\n start(): Promise<void>;\n}\n\n\nexport interface DeviceInfo {\n app: {\n name: string;\n version: string;\n build_number?: string;\n package_name?: string;\n };\n device: {\n // No `id` here (#91): core self-mints and persists device.id, and stamps it onto the\n // Context block *after* this block is flattened — an adapter-set id would be dead.\n platform: string;\n platform_version?: string;\n model?: string;\n manufacturer?: string;\n brand?: string;\n android_sdk?: number; // catalogue: int (#179)\n android_release?: string;\n hardware?: string;\n product?: string;\n system_name?: string; // iOS only; catalogue device.system_name (#179)\n // §3.3 ✱ — native only. \"Does this crash only on cheap devices?\"\n cpu_abi?: string;\n low_ram?: boolean;\n // §3.3 ✱ — both builds, never null: CLS and LCP scale with the viewport, and\n // `orientation` splits CLS, dwell and interactions. Read at log time, like\n // `network.*`, because a device rotates mid-session (§3.1).\n screen_density?: number;\n screen_width_px?: number;\n screen_height_px?: number;\n orientation?: Orientation;\n };\n}\n\nexport interface UserProfile {\n userId?: string;\n /** @deprecated Removed in v6 — use `identify({ name })`. Still the source of `user.name`. */\n fullName?: string;\n /** @deprecated Removed in v6 — never reached the wire; `identify()` could not set it. */\n firstName?: string;\n /** @deprecated Removed in v6 — never reached the wire; `identify()` could not set it. */\n lastName?: string;\n email?: string;\n phone?: string;\n /** @deprecated Removed in v6 — no column and no reader; `user.avatar` is off the wire (§3.4). */\n avatar?: string;\n customAttributes?: Record<string, any>;\n /** @deprecated Removed in v6 — in-memory only, so it meant \"first identify() this process\" (§3.4). */\n createdAt?: number;\n /** @deprecated Removed in v6 — byte-identical to `createdAt` for any one-identify() app (§3.4). */\n updatedAt?: number;\n}\n\n\ntype Opts = {\n sender?: Sender;\n batchSize?: number;\n flushIntervalMs?: number;\n endpoint?: string;\n sessionId?: string;\n userId?: string;\n sdkVersion?: string;\n platform?: string; // device OS (ios|android|web); forms the device/session id suffix\n // What `app.start` reports as `span.start_time` (§6.2). Web passes\n // `performance.timeOrigin`; native leaves it defaulted to `initialize()`. Neither is a\n // fork time, and the two are not comparable — see TraceManager.\n traceLaunchStart?: number;\n deviceInfoHandler?: DeviceInfoHandler;\n deviceStateHandler?: DeviceStateHandler; // #173 — battery on failure rows, accessibility on session.started\n networkInfoHandler?: NetworkInfoHandler;\n store?: Store; // persisted state port (#89); defaulted per build by the entry\n // Constructor-only (§3.6). A runtime setter leaves a window between init and\n // registration where session.started, the launch root and the early http.requests\n // all land — that window is the reason, and it is not negotiable.\n beforeSend?: BeforeSend;\n sessionSampleRate?: number; // 0.0-1.0, sticky per session; default 1 (send everything)\n // §6.4, #99. Bare hosts, exact match, ports ignored, **empty by default** — v4 is dark\n // on upgrade, so nobody's CORS breaks until they opt in. Listing a host is the\n // consumer's assertion that that host's CORS config allows the `traceparent` header.\n traceHostAllowlist?: string[];\n // §4.8's symbolication resolve key, third part of `(app_id, device.platform, app.build_id)`.\n // Consumer-supplied — the SDK has zero OTA awareness and cannot derive one — omitted when\n // unset, and **never** falls back to version + build_number: under Expo Updates or\n // CodePush the binary is unchanged, so that fallback resolves against the wrong map and\n // produces frames that are plausible and wrong, with nothing on the row marking them.\n buildId?: string;\n // #172 — `false` constructs dark until `enable()`. Default true.\n enabled?: boolean;\n};\n\nconst validRate = (r: unknown): r is number =>\n typeof r === \"number\" && Number.isFinite(r) && r >= 0 && r <= 1;\n\n/** The durable session record, or nothing when it is absent, corrupt or untrustworthy. */\nfunction parseSessionRecord(raw: string | null | undefined): Partial<PersistedSession> & Pick<PersistedSession, \"id\" | \"start\" | \"lastActivity\"> | undefined {\n if (typeof raw !== \"string\") return undefined;\n let saved: Partial<PersistedSession>;\n try { saved = JSON.parse(raw); } catch { return undefined; }\n if (typeof saved?.id !== \"string\"\n || typeof saved.start !== \"number\"\n || typeof saved.lastActivity !== \"number\") return undefined;\n return saved as any;\n}\n\n/**\n * A bad rate must not silently mute a deployment: `Math.random() < NaN` is always false,\n * so an unvalidated `undefined`-shaped value would sample every session out and look\n * exactly like a dead collector. Out of range means \"the consumer meant something\", and\n * the only safe reading of that is 1.\n */\nfunction normalizeSampleRate(rate: number | undefined): number {\n if (rate === undefined) return 1;\n // Number.isFinite is false for a non-number too, so this covers a JS caller's \"0.5\".\n if (!Number.isFinite(rate) || rate < 0 || rate > 1) {\n debug.warn(`Telemetry: sessionSampleRate must be a number in [0,1] — got ${rate}; using 1`);\n return 1;\n }\n return rate;\n}\n\n/**\n * Telemetry core: queueing, batching, retries, auto-replay and session/user management.\n * Keeps the external API you already use: log(name, data?), flush(), shutdown().\n */\nexport class Telemetry {\n private queue: TelemetryEvent[] = [];\n private sender?: Sender;\n private batchSize: number;\n private flushIntervalMs: number;\n private intervalId: any = null;\n private endpoint?: string;\n private crashHandler?: CrashHandler;\n // The View entity (§4.5, #96): view.id/view.name on every row, the `view` event at each\n // of the four exit boundaries, and the name ladder. Public because the route, lifecycle\n // and interaction adapters all feed it.\n public readonly views: ViewManager;\n // Trace and span core (§6, #98): the live-root carrier, the three roots this ticket\n // mints and the tier key builders. Public for the same reason `views` is — the\n // interceptors, the lifecycle adapter and ViewManager all read it, synchronously.\n public readonly trace: TraceManager;\n // The web click tracker, parked here so `trackInteractions()` is idempotent: a second\n // call must reuse this tracker rather than add a second capture-phase listener (#102).\n // Untyped and unset on native, whose producer is the public `trackTap(name)` (#103) and\n // needs no tracker here — its only state is a rage window, held by TelemetryNative.\n public webInteractions?: { start(): void };\n // The web vitals tracker, parked here for the same reason (§5.3, #106): `trackWebVitals()`\n // must reuse it, or a second call double-subscribes and doubles every vital row. Unset on\n // native, which emits no vitals ever.\n public webVitals?: { start(): Promise<void>; stop(): void };\n // #165's stall detector. Off under `__DEV__` — a debugger pause is not a hang — and\n // otherwise driven by the lifecycle emitter, so it only ticks in the foreground.\n public readonly hangs?: HangDetector;\n // #173. Public so the lifecycle emitter can refresh the battery cache on foreground.\n public readonly deviceState?: DeviceStateHandler;\n\n private networkInfoHandler: NetworkInfoHandler;\n private networkStarted = false;\n private deviceInfoHandler: DeviceInfoHandler;\n\n // Persisted state (#89). The entry injects webStore()/nativeStore(); shared core\n // never imports either. Both entries always inject, so the fallback below only\n // covers a direct `new Telemetry()` — it reports `unavailable`, putting such a\n // caller on the same branch as incognito rather than crashing.\n // Public because it is this seam's only observation point until v4's device.id,\n // session resume, sticky sample rate and capped offline store read it.\n public readonly store: Store;\n\n private frameDropsHandler?: FrameDropsHandler;\n private networkHandler?: NetworkHandler;\n private memoryHandler?: MemoryHandler;\n private navigationHandler?: NavigationHandler;\n\n\n // session / user state\n // Consumer-owned (#91). No anonymous mint: absent until the host app supplies one,\n // so COUNT(DISTINCT user.id) is known-user reach and not a visitor count.\n private userId?: string = undefined;\n // SDK-owned, persisted, uninstall-scoped, never rotates — not on login, not on logout.\n private deviceIdEphemeral = false;\n private deviceIdPromise?: Promise<string>;\n private userProfile?: UserProfile = undefined;\n private sessionId: string;\n private sessionStart: number;\n private sdkVersion: string;\n private platform?: string;\n private eventCount = 0;\n // last-20 action trail, attached to app.crash as error.breadcrumbs (#28, §4.7)\n private breadcrumbs = new BreadcrumbBuffer(20);\n // session lifecycle (#29)\n private lastActivity?: number; // last non-session event time; drives 30-min idle rotation\n private sessionSequence = 0; // increments per acknowledged (2xx) batch\n private eventSequence = 0; // event.sequence — per-session ordinal, stamped at enqueue\n private sessionEventCount = 0; // events this session (journey summary)\n private errorCount = 0; // app.crash + app.error this session (sdk.error_count)\n\n // Sampling and scrubbing (#93, §3.6). `configuredSampleRate` is what the constructor\n // was given and what every rotation re-rolls at; `sampleRate` is what *this* session\n // was rolled at and what ships as session.sample_rate, so a consumer retuning\n // mid-quarter can't retroactively mis-scale a session already in flight.\n private readonly configuredSampleRate: number;\n private sampleRate: number;\n private sampled: boolean;\n private readonly beforeSend?: BeforeSend;\n /** `app.build_id` (§4.8). Empty string is *not* a build id — it is an unset one. */\n private readonly buildId?: string;\n private hookDropped = 0; // sdk.hook_dropped — the hook working\n private hookFailed = 0; // sdk.hook_failed — the hook broken\n\n // Drop accounting (§3.7). Process-lifetime and monotonic — deliberately not reset by a\n // rotation, so \"how much did this install lose\" is one subtraction and not a sum.\n // These are lossy about their own loss by construction: they only arrive if a *later*\n // event gets through, so the tab that closes and never returns reports nothing.\n // `event.sequence`'s gaps are what actually covers that.\n private eventsDropped = 0;\n private dropReason?: DropReason;\n // Highest `event.sequence` the crash path has already written to the offline store, so a\n // second crash persists only the rows the first one did not. -1 means \"nothing yet\".\n private crashPersistedThrough = -1;\n // `app.start` is once per *process* (§6.2), and web re-enters resumeOrStartSession() on a\n // bfcache restore — which resumes a process rather than starting one.\n private appStartEmitted = false;\n /** `app.start.js_ready_ms` (§4.3, #171) — native only; the entry's reader, run at emit. */\n public jsReadyMs?: () => number | undefined;\n /** `app.start.duration_ms` (#179) — the entry's reader; resolves `undefined` when unknown. */\n public appStartMs?: () => Promise<number | undefined>;\n // Open manual spans (#164). Persisted with the session record.\n private readonly spans = new SpanRegistry();\n // Set while finalizeSession() emits its `abandoned` rows: they are bookkeeping, and\n // letting them through log()'s expiry check would rotate an expired session again.\n private finalizing = false;\n // #172's kill-switch. Off: nothing is emitted, sent or written, and the timers are stopped.\n private enabled: boolean;\n // A dark start owes the session it skipped — announced at the first `enable()`.\n private pendingStart = false;\n\n constructor(opts?: Opts) {\n this.sender = opts?.sender;\n // Android's numbers, deliberately (§9.4). These SDKs feed shared tables, so a\n // per-SDK cadence makes cross-platform arrival comparisons quietly wrong. POSTs get\n // ~25x larger and 3x rarer; the collector clears a 50-event batch ~20x over (§2.3).\n this.batchSize = opts?.batchSize ?? 50;\n this.flushIntervalMs = opts?.flushIntervalMs ?? 30000;\n this.endpoint = opts?.endpoint;\n this.platform = opts?.platform; // set before id generation (suffix source)\n this.store = opts?.store ?? memoryStore({ unavailable: true });\n this.beforeSend = opts?.beforeSend;\n // \"Omitted when unset, never `\\\"\\\"`\" (§4.8): an empty-string build id would reproduce\n // §9.3's `rum_apps` collapse inside symbolication, where absence is itself the signal.\n this.buildId = typeof opts?.buildId === \"string\" && opts.buildId !== \"\" ? opts.buildId : undefined;\n this.enabled = opts?.enabled !== false;\n // A dark-started process skips `app.start` for good: it documents a launch, and a\n // launch the user had not consented to be measured is not one to fabricate later.\n if (!this.enabled) this.appStartEmitted = true;\n this.configuredSampleRate = normalizeSampleRate(opts?.sessionSampleRate);\n this.sampleRate = this.configuredSampleRate;\n // Rolled here so a bare `new Telemetry()` — no resumeOrStartSession() — is decided\n // too. hydrateSession() overwrites it when a durable record says otherwise.\n this.sampled = this.rollSample();\n\n // start a session\n this.sessionId = opts?.sessionId ?? this.generateSessionId();\n if (opts?.userId) this.setUserId(opts.userId);\n this.sessionStart = Date.now();\n this.sdkVersion = opts?.sdkVersion ?? SDK_VERSION;\n\n if (this.enabled) this.startDelivery();\n\n // Before the ViewManager, not after: the launch root is minted in this constructor so\n // the initial view can parent to it. A view that minted its own root instead would\n // make a web hard load report `trace.root_type = navigation` (§6.2).\n this.trace = new TraceManager(opts?.traceLaunchStart, opts?.traceHostAllowlist);\n this.deviceState = opts?.deviceStateHandler;\n if (this.enabled) this.deviceState?.start?.();\n if (!isDev()) {\n this.hangs = new HangDetector(this);\n this.hangs.suspend(!this.enabled);\n }\n // The initial view opens here, at SDK init — so no row can ever precede a view (§4.5).\n this.views = new ViewManager(this);\n\n this.deviceInfoHandler = opts?.deviceInfoHandler ?? {\n start: async () => Promise.resolve(),\n collect: async () => Promise.resolve({\n app: { name: '', version: '' },\n device: { platform: '' }\n })\n };\n this.networkInfoHandler = opts?.networkInfoHandler ?? {\n start: async () => Promise.resolve({}),\n collect: async () => Promise.resolve({})\n };\n // #179: the tracker is what emits `network.change`; it ran only if the host called\n // getNetworkInfo(), so a normal app never sent one.\n if (opts?.networkInfoHandler) this.getNetworkInfo(opts.networkInfoHandler);\n\n }\n\n // ---------- Session & User APIs ----------\n\n /**\n * §4.7 — report a handled error. Accepts `unknown` on purpose: half of real `catch`\n * blocks receive a string or an axios rejection object, and a consumer should not have\n * to prove to TypeScript that it is an `Error` before reporting it.\n *\n * Emits `app.error`, **never** `app.crash`. There is deliberately no public path to\n * `app.crash` — a consumer's own code must not be able to manufacture rows in the one\n * table an unfiltered crash-free rate is read from.\n *\n * `source` is SDK-internal (`captureConsole` passes `\"console\"`); the public wrappers\n * forward two arguments, so a consumer can only ever produce `\"reported\"`. Routing the\n * console path through here rather than through `log()` directly is what keeps the\n * `error.fatal` rule in one place.\n */\n public captureError(error: unknown, context?: Record<string, any>, source: ErrorSource = \"reported\") {\n // `error.fatal` is native-only (§4.7): on web nothing is fatal, so the key is omitted\n // rather than shipped as a permanent `false` that scores web at a perfect crash-free\n // rate forever. Nothing *reported* is fatal, so on native it is always `false`. The\n // platform opt is the same one that suffixes the ids — the entry's declaration, not a\n // branch on a runtime global.\n const fatal = this.isNativePlatform() ? { fatal: false } : {};\n // Context first: the SDK's own `error.*` keys win a collision.\n return this.log(\"app.error\", { ...context, ...buildErrorAttributes(source, error, fatal) });\n }\n\n /**\n * Extend the breadcrumb trail without emitting anything. §4.7 demotes `console.warn` to\n * exactly this — React's dev-mode warnings were the bulk of v3's `app.crash` volume.\n *\n * Also the public `addBreadcrumb()` (#167) — one path, so the SDK's own crumbs and the\n * host's obey the same bounds (`boundCrumb`). Shows on `app.crash` and `app.hang`.\n */\n public addBreadcrumb(name: string, data?: Record<string, any>) {\n this.breadcrumbs.add(boundCrumb(name, data));\n }\n\n /**\n * `startNewSession()` (#167) — logout/login. The same finalize + started pair as an idle\n * or max-duration rotation, with `session.reason: manual` on both.\n */\n public async startNewSession() {\n await this.rotateSession(\"manual\");\n }\n\n public trackErrors(crashHandler: CrashHandler, options?: CrashHandlerOptions) {\n this.crashHandler = crashHandler;\n void crashHandler.attach(options).catch((err) => {\n debug.warn(\"Telemetry crashHandler attach failed:\", err);\n });\n }\n\n getDeviceInfo(deviceInfoHandler: DeviceInfoHandler) {\n this.deviceInfoHandler = deviceInfoHandler;\n void deviceInfoHandler.start(this).catch((err) => {\n debug.warn(\"Telemetry deviceInfo tracking start failed:\", err);\n });\n }\n\n /** Starts the network tracker once; later calls are no-ops, so listeners never stack. */\n getNetworkInfo(networkInfoHandler: NetworkInfoHandler) {\n if (this.networkStarted) return;\n this.networkStarted = true;\n this.networkInfoHandler = networkInfoHandler;\n void networkInfoHandler.start(this).catch((err) => {\n debug.warn(\"Telemetry networkInfoHandler start failed:\", err);\n });\n }\n\n public trackFrameDrops(frameDropsHandler: FrameDropsHandler) {\n this.frameDropsHandler = frameDropsHandler;\n void frameDropsHandler.start().catch((err) => {\n debug.warn(\"Telemetry frameDropsHandler start failed:\", err);\n });\n }\n\n public trackNetworkRequests(networkHandler: NetworkHandler) {\n this.networkHandler = networkHandler;\n void networkHandler.start().catch((err) => {\n debug.warn(\"Telemetry networkHandler start failed:\", err);\n });\n }\n\n /** The offline replay and the flush timer — at construction, and again at each `enable()`. */\n private startDelivery() {\n // auto replay if supported — best-effort, never blocks\n if (this.sender?.replayFailed) {\n this.sender.replayFailed().catch((err: any) => {\n debug.warn(\"Telemetry replay failed Telemetry class:\", err);\n });\n }\n if (this.flushIntervalMs > 0 && !this.intervalId) {\n this.intervalId = setInterval(() => this.flush().catch(() => { }), this.flushIntervalMs);\n }\n }\n\n isEnabled(): boolean {\n return this.enabled;\n }\n\n /**\n * The consent kill-switch (#172). Synchronous: the flag is off before this returns. The\n * in-memory queue, the offline store and the session record are dropped — an opt-out\n * means nothing is sent **and nothing is kept**, open spans included — and every timer\n * stops; the rAF loop keeps running but `logMetric` discards its samples. While off the\n * network patches pass through untouched. `device.id` is kept: it is not telemetry, and\n * minting a new one at re-consent would read as a new install.\n */\n disable(): void {\n if (!this.enabled) return;\n this.enabled = false;\n this.queue = [];\n if (this.intervalId) { clearInterval(this.intervalId); this.intervalId = null; }\n this.memoryHandler?.stop?.();\n this.deviceState?.stop?.();\n this.hangs?.suspend(true);\n this.spans.clear();\n for (const key of [FAILED_EVENTS_KEY, SESSION_KEY]) {\n Promise.resolve(this.store.remove(key)).catch((err) => debug.warn(\"disable: store remove failed:\", err));\n }\n }\n\n /**\n * Resume collection (#172) and run the lazy session-expiry check — a session can expire\n * while disabled. A dark-started process announces its session here (`session.started`,\n * unless a live record resumes) and never emits `app.start`.\n */\n async enable(): Promise<void> {\n if (this.enabled) return;\n this.enabled = true;\n this.startDelivery();\n if (this.memoryHandler) void this.memoryHandler.start().catch((err) => debug.warn(\"Telemetry memoryHandler start failed:\", err));\n this.hangs?.suspend(false);\n this.deviceState?.start?.();\n if (this.pendingStart) {\n this.pendingStart = false;\n await this.hydrateAndAnnounce();\n return;\n }\n const reason = this.expiryReason(Date.now());\n if (reason) await this.rotateSession(reason);\n }\n\n public trackMemoryUsage(memoryHandler: MemoryHandler) {\n // Re-registration retires the incumbent's timer. `trackMemoryUsage()` is auto-started\n // in the native constructor *and* public, so a consumer calling it hands core a second\n // tracker — without this, two 30-second loops and double the sample volume.\n this.memoryHandler?.stop?.();\n this.memoryHandler = memoryHandler;\n if (this.enabled) void memoryHandler.start().catch((err) => {\n debug.warn(\"Telemetry memoryHandler start failed:\", err);\n });\n }\n\n public autoTrackNavigation(navigationHandler?: NavigationHandler) {\n this.navigationHandler = navigationHandler;\n void navigationHandler?.start().catch((err) => {\n debug.warn(\"Telemetry navigationHandler start failed:\", err);\n });\n }\n\n\n /**\n * The per-session sample roll (§3.6). Never per-event: per-event sampling punches\n * holes that desynchronise the per-view counters by a random factor per view.\n *\n * `Math.random()` is deliberate here where `randomHex` refuses it — this decides one\n * boolean that dies with the session, not an id that persists forever, and a biased\n * PRNG costs a fraction of a percent of sample accuracy rather than a permanent\n * identity collision.\n */\n private rollSample(): boolean {\n return Math.random() < this.sampleRate;\n }\n\n /** §3.3 / §4.7's platform split, from the entry's declared `platform` opt — never a global. */\n private isNativePlatform(): boolean {\n return this.platform === \"ios\" || this.platform === \"android\";\n }\n\n private generateSessionId(): string {\n const base = `session_${Date.now()}_${randomHex(16)}`;\n // §3.3 / §12's item 13 — suffixed on all three platforms in v4; the web build gained\n // `_web` here, so this is now the same rule `device.id` follows. Nothing parses it.\n return this.platform ? `${base}_${this.platform}` : base;\n }\n\n public setSessionId(id: string) {\n this.sessionId = id;\n this.sessionStart = Date.now();\n }\n\n public getSessionId(): string {\n return this.sessionId;\n }\n\n /**\n * Freeze the identity a deferred row must report (§4.6). Read **synchronously at the\n * moment the thing happened**, so a `log()` that lands after a route change or a session\n * rotation still books the click where it occurred.\n */\n public snapshot(at?: number): LogSnapshot {\n return {\n at,\n viewId: this.views.id,\n sessionId: this.sessionId,\n sessionStart: this.sessionStart,\n };\n }\n\n /** Collector endpoint, so fetch/XHR adapters can skip self-capturing the SDK's own POST. */\n public getEndpoint(): string | undefined {\n return this.endpoint;\n }\n\n /**\n * Sampling stays **session-level** (§6.5): an unsampled session injects no header at\n * all — not a `flags=00` id. Read by the interceptors, which sit outside `log()`'s own\n * sampled-out early return and so need the decision directly.\n */\n isSampled(): boolean {\n return this.sampled;\n }\n\n // ---------- Session lifecycle (#29) ----------\n\n /**\n * The entry's one call at init (§4.2): resume the durable session when the gap is\n * inside the idle window, otherwise close the stale one out and start fresh.\n *\n * Process death, tab close, hard reload and bfcache restore all land here, and all\n * four **resume** — which is why a resumed session must not re-emit `session.started`\n * (§4.1), or `COUNT(session.started)` stops equalling session count.\n */\n public async resumeOrStartSession() {\n // Dark (#172): no record read, no session announced, nothing written until `enable()`.\n if (!this.enabled) { this.pendingStart = true; return; }\n await this.hydrateAndAnnounce();\n // Once per process and on every path — a resume emits no `session.started` at all\n // (§4.1), so `session.reason: \"launch\"` undercounts launches and `app.start` is the\n // compensator (§4.3). It is also the launch root's own row (§6.2).\n await this.emitAppStart();\n }\n\n private async hydrateAndAnnounce() {\n const decision = await this.hydrateSession();\n if (decision.kind === \"resumed\") return;\n // Expired: hydration adopted the old id/start so the finalize ships under them.\n if (decision.kind === \"expired\") { await this.rotateSession(decision.reason); return; }\n\n // Storage told us nothing. At init that means launch. On a bfcache restore this method\n // runs a second time with a session already going — storage having nothing to say is no\n // reason to discard it and re-announce a session that never ended. Just re-check the\n // boundaries, which is the whole point of re-running after a long freeze.\n if (this.lastActivity === undefined) { await this.startSession(\"launch\"); return; }\n const reason = this.expiryReason(Date.now());\n if (reason) await this.rotateSession(reason);\n }\n\n /**\n * `app.start` (§4.3/§6.2): once per process, a **root** of `trace.root_type = launch`,\n * carrying the launch root minted in the constructor. Idempotent because the web build\n * re-runs `resumeOrStartSession()` on a bfcache restore, which is a resumed process and\n * not a new one.\n */\n private async emitAppStart() {\n if (this.appStartEmitted) return;\n this.appStartEmitted = true;\n const emit = (ms?: number) => {\n const jsReady = this.jsReadyMs?.();\n return this.log(\"app.start\", {\n ...this.trace.launchRootAttributes(),\n // Cold only by construction: RN's JS context survives backgrounding (§4.3).\n \"app.start.type\": \"cold\",\n ...(ms === undefined ? {} : { \"app.start.duration_ms\": Math.round(ms) }),\n ...(jsReady === undefined ? {} : { \"app.start.js_ready_ms\": jsReady }),\n });\n };\n // The end marker (first display) can land after init, and init must never wait for it.\n const end = this.appStartMs?.();\n if (!end) return emit();\n end.then(emit, () => emit()).catch((err) => debug.warn(\"app.start failed:\", err));\n }\n\n /**\n * Read the durable record and adopt it. Adoption happens even when the session has\n * expired: `session.finalized` has to ship under the *old* `session.id` and\n * `session.start_time` before the fresh one takes over.\n */\n private async hydrateSession(): Promise<SessionHydration> {\n const read = await this.store.get(SESSION_KEY);\n // `unavailable` is not `miss` — incognito, a partitioned iframe, ITP eviction or a full\n // disk means this process can never resume and can never be resumed FROM, so every\n // launch mints a session and COUNT(session.started) over-counts. There is no\n // `session.id_ephemeral` on the contract to say so, and inventing one needs backend\n // sign-off — but the same store failed the device.id round-trip, so every event from\n // this population already carries `device.id_ephemeral: true`. Filter on that.\n if (read.status === \"unavailable\") {\n debug.warn(\"Telemetry: session storage unavailable — this session cannot be resumed\");\n return { kind: \"nothing\" };\n }\n if (read.status === \"miss\") return { kind: \"nothing\" };\n\n // A record we can't trust is not a session to resume; mint rather than guess.\n const saved = parseSessionRecord(read.value);\n if (!saved) return { kind: \"nothing\" };\n\n this.sessionId = saved.id;\n this.sessionStart = saved.start;\n this.lastActivity = saved.lastActivity;\n this.sessionSequence = saved.sequence ?? 0;\n this.eventSequence = saved.eventSequence ?? 0;\n this.sessionEventCount = saved.eventCount ?? 0;\n this.errorCount = saved.errorCount ?? 0;\n this.spans.restore(saved.spans);\n // A resume is not a rotation: the decision and the rate it was rolled at are\n // adopted as-is, so a relaunch can't half-sample a session. A record written\n // before this field existed reads as `undefined` and keeps the fresh roll.\n // The rate is stamped on every row of the resumed session, and on web the record is\n // browser-wide localStorage — so an out-of-range value would ship as a divisor and\n // silently mis-scale every count taken off it. A record we can't trust here loses\n // its decision too, and the fresh constructor roll stands.\n if (typeof saved.sampled === \"boolean\" && validRate(saved.sampleRate)) {\n this.sampled = saved.sampled;\n this.sampleRate = saved.sampleRate!;\n }\n\n const reason = this.expiryReason(Date.now());\n return reason ? { kind: \"expired\", reason } : { kind: \"resumed\" };\n }\n\n /**\n * Another tab wrote the shared session record (#161, web's `storage` event). Two tabs keep\n * their own in-memory `lastActivity`, so without this one can idle-expire a session the\n * other is still using, or both can finalize the same `session.id`.\n *\n * Same id: fold in the other tab's progress — activity and the ordinals only ever move\n * forward, so `max` is the merge. A different id is the other tab's rotation: this tab's\n * live view is emitted under the session it belongs to, then the successor session is\n * adopted **silently** — its `session.started` already shipped from the tab that rotated,\n * and the retired one's `session.finalized` too, which is the whole point.\n *\n * Shared core, no platform branch: the entry decides what feeds it.\n */\n public async adoptSessionRecord(raw: string | null | undefined) {\n const rec = parseSessionRecord(raw);\n if (!rec) return;\n if (rec.id === this.sessionId) {\n this.lastActivity = Math.max(this.lastActivity ?? rec.lastActivity, rec.lastActivity);\n this.sessionSequence = Math.max(this.sessionSequence, rec.sequence ?? 0);\n this.eventSequence = Math.max(this.eventSequence, rec.eventSequence ?? 0);\n this.sessionEventCount = Math.max(this.sessionEventCount, rec.eventCount ?? 0);\n this.errorCount = Math.max(this.errorCount, rec.errorCount ?? 0);\n return;\n }\n // An older record landing late (a slow tab persisting its pre-rotation state) must not\n // drag this tab back into a session it has already left.\n if (rec.start < this.sessionStart) return;\n\n await this.views.endView();\n await this.abandonSpans(); // the sibling finalized it; our open journeys end with it\n this.sessionId = rec.id;\n this.sessionStart = rec.start;\n this.lastActivity = rec.lastActivity;\n this.sessionSequence = rec.sequence ?? 0;\n this.eventSequence = rec.eventSequence ?? 0;\n this.sessionEventCount = rec.eventCount ?? 0;\n this.errorCount = rec.errorCount ?? 0;\n this.crashPersistedThrough = -1;\n if (typeof rec.sampled === \"boolean\" && validRate(rec.sampleRate)) {\n this.sampled = rec.sampled;\n this.sampleRate = rec.sampleRate!;\n }\n this.trace.clear(); // `trace.id` never spans a `session.id` (§6.6)\n await this.views.beginView(\"session_rotation\");\n }\n\n /**\n * Which boundary, if any, the current session has crossed. Idle is checked first:\n * when a long session has also gone quiet, the reason it ended is that the user left.\n *\n * Inert until `lastActivity` is set, so a bare `new Telemetry()` that never started a\n * session never rotates one.\n */\n private expiryReason(now: number): SessionEndReason | undefined {\n if (this.lastActivity === undefined) return undefined;\n // Both boundaries are strict: a session sitting exactly on one has not crossed it.\n if (now - this.lastActivity > SESSION_IDLE_MS) return \"timeout\";\n if (now - this.sessionStart > SESSION_MAX_MS) return \"max_duration\";\n return undefined;\n }\n\n /**\n * Write the session through the `Store` so the next process can resume it.\n *\n * ponytail: one write per event. Web's is a synchronous `localStorage` write; native's\n * is an AsyncStorage round-trip — debounce here if it ever shows up in a trace.\n */\n private async persistSession() {\n if (!this.enabled) return; // #172: nothing is written while disabled\n const record: PersistedSession = {\n id: this.sessionId,\n start: this.sessionStart,\n lastActivity: this.lastActivity ?? this.sessionStart,\n sequence: this.sessionSequence,\n eventSequence: this.eventSequence,\n eventCount: this.sessionEventCount,\n errorCount: this.errorCount,\n sampled: this.sampled,\n sampleRate: this.sampleRate,\n spans: this.spans.toJSON(),\n };\n const write = await this.store.set(SESSION_KEY, JSON.stringify(record));\n // Same first-class `unavailable` path as the read: nothing to retry and nothing to\n // throw, but it must not read as a successful write. See hydrateSession().\n if (write.status === \"unavailable\") debug.log(\"Telemetry: session not persisted (store unavailable)\");\n }\n\n /** Emit session.started for the current session. */\n public async startSession(reason: SessionReason) {\n this.lastActivity = Date.now();\n await this.persistSession(); // durable before it is announced\n // #173: accessibility, once per session. Its own reads' settle is the only wait, and a\n // failed read omits only that key — never the event.\n const a11y = await this.deviceState?.accessibility().catch(() => ({})) ?? {};\n await this.log(\"session.started\", {\n ...a11y,\n // Catalogue session.yaml (#179): no `launch` in the enum — a launch start carries no reason.\n ...(reason === \"launch\" ? {} : { \"session.reason\": reason }),\n // §4.1, count only — never the hosts (#99). Ships on every session so a zero is\n // legible as \"nobody opted in\" rather than as a stripped header.\n \"sdk.trace_allowlist_size\": this.trace.allowlistSize(),\n });\n }\n\n /**\n * Finalize the current session: journey summary + sdk.error_count, then an immediate flush.\n *\n * The backend discards `duration_ms` and `event_count` and derives both (§4.2) — they\n * stay on the wire because the event survives as the carrier for `session.reason` and\n * `sdk.error_count`, neither of which is derivable. Duration is stamped from\n * `lastActivity`, never `now`: a lazily-detected rotation must report 2 minutes of use,\n * not the 6 idle hours that followed it.\n */\n public async finalizeSession(reason: SessionEndReason) {\n // #164: a span still open when its session ends is `abandoned` — here and only here,\n // under the session it was frozen to. Ended at the last activity, like the session's\n // own duration, so an idle rotation does not book 30 idle minutes as span width.\n await this.abandonSpans();\n await this.log(\"session.finalized\", {\n \"session.duration_ms\": Math.max(0, (this.lastActivity ?? this.sessionStart) - this.sessionStart),\n \"session.event_count\": this.sessionEventCount,\n \"sdk.error_count\": this.errorCount,\n \"session.reason\": reason,\n });\n await this.flush();\n }\n\n /** Every span frozen to the session being left ships `abandoned` under it — before the switch. */\n private async abandonSpans() {\n this.finalizing = true;\n try {\n for (const span of this.spans.takeSession(this.sessionId)) {\n await this.emitTask(span, \"abandoned\", undefined, Math.max(span.start, this.lastActivity ?? span.start));\n }\n } finally {\n this.finalizing = false;\n }\n }\n\n /** Begin a fresh session: new id/start, reset per-session counters, emit session.started. */\n public async newSession(reason: SessionReason) {\n this.sessionId = this.generateSessionId();\n this.sessionStart = Date.now();\n this.sessionSequence = 0;\n this.eventSequence = 0; // the ordinal is per session, and this is a new one\n this.crashPersistedThrough = -1; // the watermark is an event.sequence, so it resets with it\n this.sessionEventCount = 0;\n this.errorCount = 0;\n // Re-rolled at the *configured* rate, not the retired session's — the previous\n // session may have been resumed from a record written under an older config.\n this.sampleRate = this.configuredSampleRate;\n this.sampled = this.rollSample();\n // `trace.id` never spans a `session.id` (§6.6, invariant 2) — dropped before the\n // successor view mints, so that view starts a fresh `navigation` root rather than\n // extending an action from the retired session.\n //\n // Before `app.start` has shipped, dropping is not enough: it reports the launch root\n // at any age, so its root row would land in the new session while the initial `view`\n // it fathered landed in the old one. That is the expired-record cold launch — §4.3's\n // most common path — so the launch root is re-minted instead of merely cleared.\n if (this.appStartEmitted) this.trace.clear();\n else this.trace.restartLaunchRoot();\n // After the new session.id is in place and before the first row of it is emitted:\n // `view.id` never spans a `session.id` (§4.5). rotateSession() has already emitted\n // the departing view's `view` event under the *old* id.\n await this.views.beginView(\"session_rotation\");\n await this.startSession(reason);\n }\n\n // ---------- Manual spans (#164) ----------\n\n /**\n * Open a manual span — **synchronously**, so the trace keys, `view.id` and `session.id`\n * freeze at the call (§3.1). Inert (`undefined`, reported through `debug()`) for a blank\n * name or past 32 open spans; never throws. Refreshes `lastActivity` but is not an\n * action: `view.action_count` counts `ui.interaction` only.\n *\n * On a session that has already expired the freeze waits for the rotation the start\n * itself triggers, so a journey begun after a long idle belongs to the new session\n * rather than being `abandoned` by the very next row.\n */\n public startSpan(name: unknown, attrs?: Record<string, unknown>, at: number = Date.now()): OpenSpan | undefined {\n if (!this.enabled) return undefined; // #172: inert while disabled\n const n = taskName(name);\n if (!n) { debug.warn(\"startSpan: blank name — span is inert\"); return undefined; }\n const span = this.spans.start(n, at, spanAttributes(attrs));\n if (!span) { debug.warn(`startSpan: ${n} — more than 32 open spans, span is inert`); return undefined; }\n const freeze = () => {\n span.keys = this.trace.manualSpan(at);\n span.viewId = this.views.id;\n span.sessionId = this.sessionId;\n span.sessionStart = this.sessionStart;\n this.lastActivity = Math.max(this.lastActivity ?? at, at);\n this.persistSession().catch((err) => debug.warn(\"startSpan: persist failed:\", err));\n };\n const reason = this.expiryReason(at);\n if (reason) {\n span.ready = this.rotateSession(reason)\n .catch((err) => debug.warn(\"startSpan: rotation failed:\", err))\n .then(() => { if (this.spans.has(span)) freeze(); });\n } else {\n freeze();\n }\n return span;\n }\n\n /**\n * Close a span by name and emit its one `task.complete`. An unknown or already-closed\n * name is a no-op. With `only`, the close is a handle's, and a superseded handle cannot\n * close the span that replaced it.\n */\n public async endSpan(name: unknown, outcome: TaskOutcome = \"completed\", attrs?: Record<string, unknown>, at: number = Date.now(), only?: OpenSpan, reason?: unknown) {\n const n = taskName(name);\n const span = n === undefined ? undefined : this.spans.take(n, only);\n if (!span) { debug.log(`endSpan: no open span named ${String(name)}`); return; }\n await span.ready;\n await this.emitTask(span, outcome, spanAttributes(attrs), at, outcome === \"failed\" ? taskName(reason) : undefined);\n }\n\n private async emitTask(span: OpenSpan, outcome: TaskOutcome, attrs: Record<string, unknown> | undefined, end: number, failureReason?: string) {\n if (!span.keys || !span.viewId || !span.sessionId || span.sessionStart === undefined) return;\n await this.log(\"task.complete\", {\n ...span.attrs,\n ...attrs,\n ...span.keys,\n \"task.name\": span.name,\n \"task.outcome\": outcome,\n ...(failureReason === undefined ? {} : { \"task.failure_reason\": failureReason }),\n // On root *and* child — the flagged §6.3 exception: a declared end is not\n // derivable from children, so a root's width cannot be left to the server.\n \"span.duration_ms\": Math.max(0, end - span.start),\n }, { at: end, viewId: span.viewId, sessionId: span.sessionId, sessionStart: span.sessionStart });\n }\n\n /** Boundary rotation: finalize the old session then start a fresh one (the pair). */\n public async rotateSession(reason: SessionEndReason) {\n // The session-rotation view boundary (§4.5), emitted first so the `view` row lands\n // under the session it belongs to. newSession() mints the successor.\n await this.views.endView();\n await this.finalizeSession(reason);\n await this.newSession(reason);\n }\n\n /** Truncated at source (§3.2): the collector caps at 255 and we must not be the one over. */\n public setUserId(id: string) {\n this.userId = id ? id.slice(0, USER_ID_MAX) : undefined;\n }\n\n public getUserId(): string | undefined {\n return this.userId;\n }\n\n /**\n * The SDK-owned `device.id` (§3.2/§3.3): self-minted, written through the `Store`,\n * uninstall-scoped, stable across process restarts, and never rotated by login,\n * logout or a profile clear.\n *\n * The platform suffix is the entry's (ios|android|web), not the device-info adapter's:\n * this id is persisted forever, so it must not depend on a call that can throw on first run.\n *\n * `getUniqueId()` is deliberately not used — it already carries two lifetimes on RN\n * alone (ANDROID_ID survives reinstall, identifierForVendor does not), so one identity\n * column would mean two things.\n *\n * When the Store reports `unavailable` — incognito, a partitioned iframe, ITP\n * eviction, a full disk — the id lives for one process only and `device.id_ephemeral`\n * rides the Context block to say so, because that population is otherwise\n * indistinguishable from real installs and reads as traffic growth.\n */\n private async getDeviceId(): Promise<string> {\n this.deviceIdPromise ??= (async () => {\n const read = await this.store.get(DEVICE_ID_KEY);\n if (read.status === \"hit\") return read.value;\n const suffix = this.platform ? `_${this.platform}` : \"\";\n const id = `device_${Date.now()}_${randomHex(16)}${suffix}`;\n const write = await this.store.set(DEVICE_ID_KEY, id);\n // Either end of the round-trip failing means this id never comes back.\n this.deviceIdEphemeral = read.status === \"unavailable\" || write.status === \"unavailable\";\n return id;\n })();\n return this.deviceIdPromise;\n }\n\n // ---------- User Profile Management ----------\n\n /**\n * Set complete user profile information\n */\n public setUserProfile(profile: Partial<UserProfile>): void {\n const now = Date.now();\n \n // If this is a new profile or userId changed, set createdAt\n const isNewProfile = !this.userProfile || (profile.userId && profile.userId !== this.userProfile.userId);\n \n this.userProfile = {\n ...this.userProfile,\n ...profile,\n updatedAt: now,\n ...(isNewProfile && { createdAt: now })\n };\n\n // Update userId if provided in profile (truncated at source, §3.2)\n if (profile.userId) {\n this.setUserId(profile.userId);\n this.userProfile.userId = this.userId;\n } else if (this.userProfile && !this.userProfile.userId) {\n // Mirror the current id into the profile — undefined while still anonymous\n this.userProfile.userId = this.userId;\n }\n\n debug.log(\"Telemetry: User profile updated\", this.userProfile);\n }\n\n /**\n * EdgeRum-style identify(): record the host-app profile and emit the one event that\n * carries it — `user.profile.update` (§4.10, #107). The PII is no longer on the\n * Context block of every event.\n *\n * `userId` is optional and new in v4: the one call that sends a profile should also\n * set the key that profile attaches to, since `user.id` is consumer-supplied (§3.2)\n * and an unkeyed profile has nothing to upsert on. Omitting it leaves `user.id`\n * exactly as it was — identify never mints one.\n */\n public async identify(profile: {\n userId?: string;\n name?: string;\n email?: string;\n phone?: string;\n avatar?: string;\n customAttributes?: Record<string, any>;\n }) {\n if (profile.userId !== undefined) this.setUserId(profile.userId);\n // Only what this call actually supplied — `setUserProfile` merges by spread, so\n // passing `email: undefined` would wipe an email a prior setUserContact() set.\n this.setUserProfile({\n ...(profile.name !== undefined ? { fullName: profile.name } : {}),\n ...(profile.email !== undefined ? { email: profile.email } : {}),\n ...(profile.phone !== undefined ? { phone: profile.phone } : {}),\n ...(profile.avatar !== undefined ? { avatar: profile.avatar } : {}),\n ...(profile.customAttributes !== undefined ? { customAttributes: profile.customAttributes } : {}),\n });\n // Built from the live profile, not from this call's arguments, so a preceding\n // setUserContact()/setUserName() ships too.\n await this.log(\"user.profile.update\", buildProfileAttributes(this.userProfile));\n }\n\n /**\n * Set user details with individual parameters\n */\n public setUserDetails(details: {\n fullName?: string;\n firstName?: string;\n lastName?: string;\n email?: string;\n phone?: string;\n avatar?: string;\n customAttributes?: Record<string, any>;\n }): void {\n this.setUserProfile(details);\n }\n\n /**\n * Update specific user profile fields\n */\n public updateUserProfile(updates: Partial<UserProfile>): void {\n if (!this.userProfile) {\n // If no profile exists, create one\n this.setUserProfile(updates);\n return;\n }\n\n this.userProfile = {\n ...this.userProfile,\n ...updates,\n updatedAt: Date.now()\n };\n\n debug.log(\"Telemetry: User profile updated\", this.userProfile);\n }\n\n /**\n * Get current user profile\n */\n public getUserProfile(): UserProfile | undefined {\n return this.userProfile;\n }\n\n /**\n * Clear user profile data\n */\n public clearUserProfile(): void {\n this.userProfile = undefined;\n this.userId = undefined; // consumer-owned (§3.2): cleared here, unlike device.id\n debug.log(\"Telemetry: User profile cleared\");\n }\n\n /**\n * Set user name (convenience method)\n */\n public setUserName(fullName: string, firstName?: string, lastName?: string): void {\n this.setUserProfile({\n fullName,\n firstName,\n lastName\n });\n }\n\n /**\n * Set user contact info (convenience method)\n */\n public setUserContact(email?: string, phone?: string): void {\n this.setUserProfile({\n email,\n phone\n });\n }\n\n // ---------- Logging APIs ----------\n\n /**\n * Log a named event. Keeps existing signature compatibility.\n * Automatically attaches userId and sessionId to every queued event.\n */\n async log(name: string, data?: Record<string, any>, snapshot?: LogSnapshot) {\n if (!this.enabled) return; // #172: nothing is emitted while disabled\n this.eventCount++;\n let activity = false;\n let crashed = false;\n\n // Session activity and the two boundaries — 30-min idle and the 4-hour cap (§4.2).\n // Session events don't count as activity (they're emitted *by* the lifecycle), so\n // they never re-trigger a rotation.\n // `view` joins the session events here: it is emitted *by* a boundary, from inside\n // rotateSession() among others, so letting it re-enter the expiry check would recurse\n // forever on an already-expired session. It is bookkeeping, not user activity.\n // `screen.load` (#179) is emitted from the same endView() call, so it is exempt too —\n // without it an expired session rotated, ended its view, re-entered, and looped to OOM.\n // Samples (`frame.summary`, `memory.usage`) are checked against the boundaries like a\n // metric but never refresh activity: a periodic sampler must not keep a session alive.\n const sample = SAMPLE_NAMES.has(name);\n if (sample) {\n const reason = this.expiryReason(Date.now());\n if (reason) await this.rotateSession(reason);\n } else if (!name.startsWith('session.') && name !== 'view' && name !== 'screen.load' && !this.finalizing) {\n const now = Date.now();\n const reason = this.expiryReason(now);\n if (reason) await this.rotateSession(reason);\n this.lastActivity = now;\n this.sessionEventCount++;\n if (isErrorName(name)) this.errorCount++;\n activity = true;\n }\n\n // A sampled-out session sends nothing at all — not a skeleton record, and\n // crashes are no exception (§3.6): 100% of crashes over 10% of sessions makes\n // the unfiltered crash-free query read 10x too high with no WHERE to repair it.\n // The boundary bookkeeping above still runs, so the rotation that re-rolls the\n // decision still happens on schedule.\n if (this.sampled) {\n // The allowlist: unknown names ship as custom.event, original kept as event.name\n const isAllowed = ALLOWED_NAMES.has(name);\n const eventName = isAllowed ? name : 'custom.event';\n\n const attributes = await this.collectContext(data);\n if (!isAllowed) attributes['event.name'] = name;\n\n // §6.3's Tier 2. Tier 1's keys were captured earlier — at launch, at view entry,\n // at request send — and arrived through `data`; Tier 3 gets nothing at all.\n // Assigned after `collectContext`, so a caller's `data` cannot forge them.\n if (TIER_2_NAMES.has(eventName)) Object.assign(attributes, this.trace.annotate());\n\n // `app.crash` carries the trail of prior actions; other events extend the trail.\n // ⚠ Breadcrumbs ride `app.crash` **only** (§4.7): `app.error` volume is\n // consumer-controlled, and a 1-2 KB blob on a high-volume event is how the\n // transport budget gets spent by the SDK's own doing. Stringified, because\n // `stringAttr` renders a real array through `fmt.Sprint` as Go map syntax.\n // `app.hang` carries the trail too (#165) — what led to the freeze — but it is not\n // an error: no counter, no forced flush, no eviction reprieve.\n if (eventName === 'app.crash' || eventName === 'app.hang') {\n attributes['error.breadcrumbs'] = this.breadcrumbs.toJSON();\n }\n // #173: the cached battery read on failure rows only — the 39-key Context block is\n // untouched. Synchronous: a crash never waits on a native call. Native only.\n if (eventName === 'app.crash' || eventName === 'app.error' || eventName === 'app.hang') {\n Object.assign(attributes, this.deviceState?.battery?.());\n }\n if (eventName === 'app.crash') {\n crashed = true;\n } else if (!sample) {\n this.breadcrumbs.add({ name: eventName, timestamp: new Date().toISOString() });\n }\n\n // Two of §4.5's three counters, booked against the view this row is pinned to.\n // `view.error_count` is a closed enumeration — crashes only, not failed requests\n // and not console.warn — but `app.error` counts too (§4.5). `view.request_count`\n // is NOT booked here: §4.5.2 counts\n // requests *started* in the view, and this row is emitted at completion, which\n // can be a route change later. The interceptors book it at send time instead.\n if (isErrorName(eventName)) this.views.countError();\n else if (eventName === 'ui.interaction') this.views.countAction();\n\n // §3.1's attribution freeze, and §4.6's mint/emit split — one mechanism. A\n // span-carrying row reports the identity live at **span start**, not at emit:\n // §4.2's 4-hour cap can rotate a session while a request is in flight, and a tap\n // that navigates would otherwise be booked against the view it opened, silently\n // inverting every \"which screen frustrates users\" query. Applied after\n // `collectContext`, with the identity keys, so it is the SDK's snapshot and never\n // a caller's `data`. Point events pass none and are unaffected.\n if (snapshot) {\n attributes['view.id'] = snapshot.viewId;\n // Resolved at log time by lookup on the *frozen* id (§3.1), never replayed\n // from the snapshot: a rung upgrade between mint and emit renames the view\n // in place, and a row must never carry a name that disagrees with its own id.\n attributes['view.name'] = this.views.nameOf(snapshot.viewId);\n attributes['session.id'] = snapshot.sessionId;\n attributes['session.start_time'] = new Date(snapshot.sessionStart).toISOString();\n }\n\n this.enqueue({\n type: 'event',\n eventName,\n timestamp: new Date(snapshot?.at ?? Date.now()).toISOString(),\n attributes,\n });\n\n debug.log(\"Telemetry queued event:\", name, \"Queue size:\", this.queue.length);\n debug.log(\"Event attributes:\", attributes);\n }\n\n // After the enqueue, never before it: the durable record is for the *next* process,\n // and on native this is an AsyncStorage round-trip that must not sit in front of the\n // event it describes.\n if (activity) await this.persistSession();\n\n // A crash is the row the process may not survive to send twice, so it does not wait\n // for the batch to fill. Awaited, unlike the batch-full flush: `app.crash` is emitted\n // from a dying process's teardown, and a fire-and-forget send there is a send that\n // never happens.\n if (crashed) {\n await this.flushCrash();\n } else if (this.queue.length >= this.batchSize) {\n void this.flush();\n }\n }\n\n /** §2.5 4xx: drop the batch, book it, and tell a dev once — it is usually a wrong apiKey. */\n private reject(err: unknown, count: number) {\n this.recordDrop(\"rejected\", count);\n if (isDev() && !warnedRejected) {\n warnedRejected = true;\n console.warn(`edge-telemetry: the collector rejected a batch with HTTP ${statusOf(err)} — `\n + \"dropped, not retried. Check the apiKey and endpoint. (Shown once, in dev only.)\");\n }\n }\n\n /** §2.5 429: halt the drain until `X-RateLimit-Reset`, 1 s when the header is absent. */\n private holdFor(err: unknown) {\n const resetAt = (err as { resetAt?: unknown } | undefined)?.resetAt;\n this.holdUntil = typeof resetAt === \"number\" ? resetAt : Date.now() + RATE_LIMIT_DEFAULT_HOLD_MS;\n }\n\n /**\n * The crash path (§2 / §9.4): persist the whole queue, then send **one** batch reordered\n * so the crash rides in it. Not a drain — a dying process gets one round trip.\n *\n * ⚠ The web/native asymmetry is real and is not fixed here. On web the `Store` is\n * synchronous `localStorage`, so the persist has *landed* by the time the next line runs\n * and the loss window closes. On native it is an AsyncStorage round-trip that a SIGKILL\n * can outrun, so the window only narrows. Awaiting harder does not change that; the\n * asymmetry is the `Store` port's whole point (`core/store.ts`).\n *\n * The persisted copy is a safety copy, not a handoff: the queue is left intact, because\n * an `app.crash` is not always fatal — `window.onerror` fires and the page keeps running\n * — and the process usually lives on. A successful send therefore\n * leaves a duplicate on disk to replay next launch — which is what `event.sequence` and\n * the backend's `(session_id, event_sequence)` dedup exist for (§2.4).\n *\n * *One* duplicate. Each row is written at most once by this path, watermarked on\n * `event.sequence`: a chatty app crash-flushes often, and re-persisting the whole queue\n * each time would fill the store with copies of\n * its own backlog and book `store_full` drops that are not loss — corrupting the very\n * counter this change adds.\n */\n private async flushCrash() {\n if (!this.enabled) return;\n if (!this.sender || this.queue.length === 0) return;\n\n // Move crashes to the front, relative order intact: at batchSize 50 a crash enqueued\n // behind 49 older events would otherwise miss the only batch this process gets.\n const isCrash = (e: TelemetryEvent) => e.eventName === 'app.crash';\n this.queue = [...this.queue.filter(isCrash), ...this.queue.filter(e => !isCrash(e))];\n\n const pending = this.queue.filter(e => seqOf(e) > this.crashPersistedThrough);\n if (pending.length > 0 && this.sender.onFailure) {\n try {\n this.recordDrop(\"store_full\", await this.sender.onFailure(pending));\n // Advanced only on a write that returned: a throw leaves the watermark where\n // it was, so the next crash retries these rows rather than abandoning them.\n this.crashPersistedThrough = Math.max(this.crashPersistedThrough, ...pending.map(seqOf));\n } catch (err) {\n debug.warn(\"Telemetry: crash-path persist failed:\", err);\n }\n }\n\n // Spliced *before* the send, not after: both the interval and the batch-full trigger\n // fire flush() unawaited, so a concurrent flush() splices this same front — and a\n // post-send splice would then delete rows this batch never carried, silently and\n // without booking them. Sent directly rather than through flush() because the rows\n // are already on disk and flush()'s failure path would persist them a second time.\n const batch = this.queue.splice(0, this.batchSize);\n try {\n await this.sender.send(batch);\n await this.ackBatch();\n } catch (err) {\n debug.warn(\"Telemetry: crash-path send failed:\", err);\n // §2.5 holds here too: a 4xx batch is dropped, never requeued.\n if (isRejected(err)) { this.reject(err, batch.length); return; }\n if (statusOf(err) === 429) this.holdFor(err);\n // Requeue only what the store does not already hold — the rest is safe on disk\n // and requeueing it would send it twice for no gain.\n const unsaved = batch.filter(e => seqOf(e) > this.crashPersistedThrough);\n if (unsaved.length > 0) this.queue.unshift(...unsaved);\n }\n }\n\n /**\n * Build the v3 Context block that rides on every event AND metric: the flattened\n * device/network snapshot, the caller's data, identity + session + sdk fields, and the\n * user profile. Shared by log() and logMetric() so both carry the identical iOS-clean set.\n */\n private async collectContext(data?: Record<string, any>): Promise<Record<string, any>> {\n let deviceInfo: Record<string, any> = {};\n let networkInfo: Record<string, any> = {};\n\n try {\n deviceInfo = (await this.deviceInfoHandler?.collect()) || {};\n } catch (err) {\n debug.warn(\"Telemetry: failed to fetch device info\", err);\n }\n\n try {\n networkInfo = (await this.networkInfoHandler?.collect()) || {};\n } catch (err) {\n debug.warn(\"Telemetry: failed to fetch network info\", err);\n }\n\n // Mint/read before assembling. device.id is persisted forever, so its suffix comes\n // from the entry-supplied platform and never from collect(), which can throw.\n const deviceId = await this.getDeviceId();\n\n const attributes: Record<string, any> = {\n // deviceInfo already namespaces its own keys (app.*, device.*) — flatten flat\n ...this.flattenWithPrefix('', deviceInfo),\n ...this.flattenWithPrefix('network', networkInfo),\n ...this.flattenWithPrefix('', data || {}),\n // Identity keys land after caller data: `data` may override app./device./network.*\n // but must never override these (§3.3).\n // With the identity keys, not with deviceInfo's `app.*`: it is the symbolication\n // join key, so a stray `log()` payload must not be able to shift which map a\n // crash resolves against.\n ...(this.buildId ? { 'app.build_id': this.buildId } : {}),\n 'device.id': deviceId,\n ...(this.deviceIdEphemeral ? { 'device.id_ephemeral': true } : {}),\n // Omitted entirely on anonymous traffic (§3.2) — no \"\", no placeholder.\n ...(this.userId ? { 'user.id': this.userId } : {}),\n // Denormalized onto every row (§4.5) so \"errors by screen\" needs no join. The id\n // is the join key; the name is the view's current best, resolved here at log time\n // by lookup on that id, so a row can never carry a name that disagrees with it.\n 'view.id': this.views.id,\n 'view.name': this.views.name,\n 'session.id': this.sessionId,\n 'session.start_time': new Date(this.sessionStart).toISOString(),\n 'session.sequence': this.sessionSequence,\n // Extrapolation is arithmetic when the rate is on the row: it survives a\n // consumer retuning mid-quarter, which config-in-a-spreadsheet does not.\n 'session.sample_rate': this.sampleRate,\n // Monotonic and always present; the reason stays omitted until there is one,\n // so `sdk.drop_reason IS NOT NULL` is a usable filter for \"this install lost data\".\n 'sdk.events_dropped': this.eventsDropped,\n ...(this.dropReason ? { 'sdk.drop_reason': this.dropReason } : {}),\n 'sdk.hook_dropped': this.hookDropped,\n 'sdk.hook_failed': this.hookFailed,\n 'sdk.platform': sdkPlatform(this.platform),\n 'sdk.version': this.sdkVersion,\n };\n\n // §4.10, #107 — the profile keys are deliberately NOT here; they ride\n // `user.profile.update` alone. `user.id` above is the join key and stays.\n\n return attributes;\n }\n\n /**\n * Emit a metric on the v3 `type:\"metric\"` path: { type, metricName, value, timestamp, attributes }.\n * Carries the same Context block as events. Metrics are samples, not user actions, so they\n * don't extend the breadcrumb trail and don't count as session activity — a periodic sampler\n * (memory/frames) must not keep a session alive and defeat the 30-min idle rotation.\n */\n async logMetric(metricName: string, value: number, data?: Record<string, any>, unitOverride?: string, hostName?: string) {\n if (!this.enabled) return; // #172 — this is where the rAF loop's samples are discarded\n this.eventCount++;\n // A metric is a sample, not a user action: it must not refresh `lastActivity` and\n // keep a dead session alive. It is still *checked* against the boundaries, or a\n // metric-only stream (a backgrounded app sampling memory) would ship forever under\n // a session that expired hours ago and never hit the 4-hour cap (§4.2).\n const reason = this.expiryReason(Date.now());\n if (reason) await this.rotateSession(reason);\n\n if (!this.sampled) return;\n\n const attributes = await this.collectContext(data);\n // §5.1 — assembled after caller `data`, so a stray attribute cannot mislabel the\n // unit of the column it lands in. Omitted for a name we have no unit for.\n const unit = METRIC_UNIT[metricName] ?? unitOverride;\n if (unit) attributes['metric.unit'] = unit;\n if (hostName !== undefined) attributes['metric.name'] = hostName;\n\n this.enqueue({\n type: 'metric',\n metricName,\n value,\n timestamp: new Date().toISOString(),\n attributes,\n });\n if (this.queue.length >= this.batchSize) {\n void this.flush();\n }\n }\n\n /**\n * The single enqueue point: neither the sample decision nor `beforeSend` can be\n * bypassed by a future emit path, and the hook runs *before* the queue — which is\n * what keeps scrubbed fields off disk when a send fails and the batch is persisted.\n *\n * The sample check is repeated by log()/logMetric() ahead of `collectContext()`, so\n * a sampled-out session does no work per event; this one is the backstop that makes\n * the guarantee structural rather than a convention two call sites happen to follow.\n *\n * The two counters are separate on purpose: \"my volume is down 40%\" has to\n * distinguish *my rule is too broad* from *my rule is crashing*, and one merged\n * counter answers neither.\n */\n private enqueue(e: TelemetryEvent) {\n // `enabled` re-checked here: `log()` awaits the Context block, and a `disable()` can land in between.\n if (!this.sampled || !this.enabled) return;\n\n let kept = e;\n if (this.beforeSend) {\n const outcome = applyBeforeSend(e, this.beforeSend);\n if (outcome.kind === \"failed\") { this.hookFailed++; return; }\n if (outcome.kind === \"dropped\") { this.hookDropped++; return; }\n kept = outcome.event;\n }\n\n // After the hook, never before (§2.4): an event the hook drops must not consume an\n // ordinal, or every scrubbed row would read as a gap — and gaps are precisely how\n // the backend tells real loss from a replay. Tier A already protects the key, so a\n // hook cannot forge or delete one once stamped.\n (kept.attributes ??= {})['event.sequence'] = this.eventSequence++;\n\n this.queue.push(kept);\n this.capQueue();\n }\n\n /**\n * Hold the in-memory queue at its cap (§9.4), booking what it costs.\n *\n * The count lands on the *next* event's Context block, not this one's — `collectContext()`\n * has already run by the time we get here. That is §3.7's stated behaviour, not a bug.\n */\n private capQueue() {\n while (this.queue.length > QUEUE_MAX_EVENTS) {\n this.queue.splice(evictIndex(this.queue), 1);\n this.recordDrop(\"queue_full\");\n }\n }\n\n /**\n * Book dropped rows against the monotonic counter and the reason that shipped last.\n * Takes `Sender.onFailure`'s return shape as-is — a sender with no cap returns nothing.\n */\n private recordDrop(reason: DropReason, count: number | void = 1) {\n if (!count || count <= 0) return;\n this.eventsDropped += count;\n this.dropReason = reason;\n }\n\n private flattenWithPrefix(prefix: string, obj: Record<string, any>, depth = 0): Record<string, any> {\n const result: Record<string, any> = {};\n\n for (const key in obj) {\n if (!Object.prototype.hasOwnProperty.call(obj, key)) continue;\n\n const value = obj[key];\n const prefixedKey = prefix ? `${prefix}.${key}` : key;\n\n // §3.3's null discipline — \"absent means the SDK had nothing\" (#108). An\n // `undefined` value was already dropped by the sender's `JSON.stringify`, so\n // this is wire-neutral; what it fixes is the in-memory bag, where\n // `device.android_sdk: undefined` on a web row made the 39-key shape\n // unassertable and handed `beforeSend` keys that never ship.\n if (value === undefined) continue;\n\n // §4.10, #107 — the depth guard. Without it a cyclic value recursed until the\n // stack blew, *inside* the SDK, taking the host app's render tree with it. A\n // bad payload is a dropped key, never a RangeError.\n if (typeof value === 'object' && value !== null && !Array.isArray(value) && depth < FLATTEN_MAX_DEPTH) {\n Object.assign(result, this.flattenWithPrefix(prefixedKey, value, depth + 1));\n } else if (typeof value === 'object' && value !== null) {\n // An array, or an object at the depth cap. Both ride as a JSON string rather\n // than as themselves — the primitive-values rule, and the only way to close\n // the hole a cycle *inside an array* leaves: the array branch never recurses,\n // so the depth guard cannot see it and the throw would land in the sender's\n // `JSON.stringify`, where `flush()` swallows it and the whole batch is lost\n // silently. Stringifying is also what the collector's `fmt.Sprint` would do\n // to a raw array, only in Go map syntax rather than JSON.\n const flat = stringifyOrDrop(value);\n if (flat !== undefined) result[prefixedKey] = flat;\n } else {\n result[prefixedKey] = value;\n }\n }\n\n return result;\n }\n\n\n\n /**\n * The public metric path (#167), sent as `custom.metric` with the host's name in\n * `metric.name` (processor #41). The SDK's own names stay **reserved**, and no cap on distinct\n * names. A non-finite value is dropped, never shipped as a fabricated number. `unit`\n * becomes `metric.unit`, stamped after `data` so an attribute cannot mislabel it.\n */\n recordMetric(name: string, value: number, data?: Record<string, any>, opts?: { unit?: string }) {\n if (typeof name !== \"string\" || name.trim() === \"\") { debug.warn(\"recordMetric: blank name — dropped\"); return; }\n if (Object.prototype.hasOwnProperty.call(METRIC_UNIT, name)) { debug.warn(`recordMetric: ${name} is reserved by the SDK — dropped`); return; }\n if (typeof value !== \"number\" || !Number.isFinite(value)) { debug.warn(`recordMetric: ${name} value is not finite — dropped`); return; }\n const unit = typeof opts?.unit === \"string\" && opts.unit !== \"\" ? opts.unit : undefined;\n // `custom.metric` (processor #41): the host's name rides `metric.name`, after `data`.\n return this.logMetric(\"custom.metric\", value, data, unit, name);\n }\n\n // ---------- Flush / Persistence ----------\n\n /**\n * §2.4's draining flush (#162): batches go **sequentially** until the queue is empty,\n * stopping at the first failure, at most `DRAIN_MAX_BATCHES` per call and paced to the\n * collector's 10 req/s burst. Sequential because parallel batches are how a cold backend\n * gets stampeded by a replay. Retry + backoff live in the Sender (`sendWithRetry`).\n *\n * A call landing while a drain is in flight joins it rather than starting a second loop:\n * the interval and the batch-full trigger both fire `flush()` unawaited, and two loops\n * would interleave their sends and break the pacing.\n */\n flush(): Promise<void> {\n return this.draining ??= this.drain().finally(() => { this.draining = undefined; });\n }\n\n private draining?: Promise<void>;\n /** Epoch ms before which no batch may be sent — a 429's `X-RateLimit-Reset` (§2.5). */\n private holdUntil = 0;\n\n private async drain() {\n for (let i = 0; i < DRAIN_MAX_BATCHES; i++) {\n if (i > 0 && this.queue.length > 0) await new Promise(r => setTimeout(r, DRAIN_PACE_MS));\n if (!this.sender || this.queue.length === 0 || Date.now() < this.holdUntil) return;\n\n const toSend = this.queue.splice(0, this.batchSize);\n try {\n await this.sender.send(toSend);\n await this.ackBatch();\n } catch (err) {\n await this.onSendFailure(toSend, err);\n debug.error(\"Telemetry flush failed:\", err);\n throw err;\n }\n }\n }\n\n /**\n * §2.5's status table, for a batch the sender gave up on.\n *\n * | 4xx | dropped — no persist — booked `rejected`, one `__DEV__` warning per process |\n * | 429 | requeued at the front; the drain halts until `X-RateLimit-Reset` |\n * | 5xx / network | persisted through the sender, or requeued when it cannot persist |\n *\n * A wrong credential is the realistic 4xx, and persisting it would make it terminal: the\n * drain halts at batch 1 on every launch forever while the store fills and evicts.\n */\n private async onSendFailure(batch: TelemetryEvent[], err: unknown) {\n if (!this.enabled) return; // #172: a batch in flight at disable() is not kept\n if (isRejected(err)) { this.reject(err, batch.length); return; }\n if (statusOf(err) === 429) {\n this.queue.unshift(...batch);\n this.holdFor(err);\n return;\n }\n if (this.sender?.onFailure) {\n try {\n this.recordDrop(\"store_full\", await this.sender.onFailure(batch));\n } catch (persistErr) {\n // If persistence fails, requeue to avoid data loss\n this.queue.unshift(...batch);\n debug.warn(\"Sender.onFailure failed, requeued events:\", persistErr);\n }\n } else {\n this.queue.unshift(...batch);\n }\n }\n\n /**\n * Book an acknowledged (2xx) batch. `session.sequence` orders a session's batches (#29),\n * and it is persisted because a resumed session restarting at 0 would emit duplicate\n * (session.id, session.sequence) pairs and stop ordering anything (#92).\n */\n private async ackBatch() {\n this.sessionSequence++;\n await this.persistSession();\n }\n\n getQueue() {\n return [...this.queue];\n }\n\n async shutdown() {\n if (this.intervalId) clearInterval(this.intervalId);\n this.memoryHandler?.stop?.();\n this.webVitals?.stop(); // #160 — no vital may logMetric after shutdown\n this.hangs?.stop();\n this.deviceState?.stop?.();\n await this.flush();\n }\n\n // Expose some internal counters (optional)\n getEventCount() {\n return this.eventCount;\n }\n\n /**\n * A route change (§4.5): rung 2 of the name ladder. The two deprecated feeds it used to\n * emit alongside — `navigation` and `screen.duration` — are gone in v5 (#163).\n */\n async recordRouteChange(to: string) {\n await this.enterView(to, \"route\");\n }\n\n /**\n * Feed the name ladder (§4.5.1). Rungs 1 and 2 arrive unnormalized; rung 3's caller\n * normalizes before calling. Whether this re-stamps the current view or mints a\n * successor is the ladder's decision, not the caller's.\n */\n async enterView(name: string, source: ViewNameSource) {\n await this.views.navigate(name, source);\n }\n\n\n}\n\n"],"names":["CONTRACT_VERSION","IDENTITY","identityOf","e","k","buildBatch","events","a","attributes","byIdentity","groups","replayGroups","stored","post","persist","i","err","rest","isRejected","buildHeaders","credential","HttpStatusError","status","resetAt","statusOf","s","resetAtOf","headers","now","raw","sendWithRetry","retryCount","backoffMs","lastError","attempt","res","r","DEFAULT_ENDPOINT","randomHex","length","bytes","out","b","RANK","UNKNOWN_VIEW_NAME","MAX_RETIRED_VIEW_NAMES","mintViewId","ViewManager","telemetry","NetworkSettle","processStart","at","v","id","name","source","bound","rank","current","fn","cause","loadingTime","outcome","ready","reported","settled","successorLoadType","prev","oldest","ROOT_IDLE_MS","ROOT_CAP_MS","mintTraceId","mintSpanId","TraceManager","launchStartMs","traceHostAllowlist","normalizeAllowlist","spanKeys","entryAt","root","isRoot","mintedAt","startedAt","ctx","decision","foreign","parseTraceparent","keys","attribution","span","finish","endedAt","discard","formatTraceparent","allowsHost","live","mintAs","hadCarrier","rootType","spanStartMs","idle","age","spanId","HANG_TICK_MS","HANG_THRESHOLD_MS","HANG_SUSPENSION_MS","stallMs","prevTick","late","HangDetector","core","mono","stall","debug","active","suspended","FAILED_EVENTS_KEY","decodeFailed","read","parsed","STORE_MAX_EVENTS","STORE_MAX_BYTES","byteLength","encodeFailed","existing","incoming","kept","dropped","evictIndex","sizes","total","guardedDrain","drain","inFlight","stringifyOrDrop","value","MAX_OPEN_SPANS","TASK_NAME_MAX","RESERVED","spanAttributes","attrs","taskName","SpanRegistry","start","only","sessionId","_r","saved","NAME_CAP","EMAIL_CAP","PHONE_CAP","CUSTOM_MAX_KEYS","CUSTOM_KEY_CAP","CUSTOM_VALUE_CAP","warnedOnce","capString","max","trimmed","customValue","flat","buildProfileAttributes","profile","email","phone","key","isDev","CRUMB_NAME_MAX","CRUMB_DATA_KEYS","boundCrumb","data","BreadcrumbBuffer","item","TIER_A_KEYS","isTierA","TIER_B_KEY","applyBeforeSend","original","hook","returned","restamp","rewritten","originalId","sdkPlatform","platform","SDK_VERSION","PKG_VERSION","SESSION_IDLE_MS","SESSION_MAX_MS","FLATTEN_MAX_DEPTH","QUEUE_MAX_EVENTS","DRAIN_MAX_BATCHES","DRAIN_PACE_MS","RATE_LIMIT_DEFAULT_HOLD_MS","warnedRejected","seqOf","isErrorName","DEVICE_ID_KEY","SESSION_KEY","USER_ID_MAX","ALLOWED_NAMES","METRIC_UNIT","SAMPLE_NAMES","TIER_2_NAMES","validRate","parseSessionRecord","normalizeSampleRate","rate","Telemetry","opts","memoryStore","error","context","fatal","buildErrorAttributes","crashHandler","options","deviceInfoHandler","networkInfoHandler","frameDropsHandler","networkHandler","reason","memoryHandler","navigationHandler","base","emit","ms","jsReady","end","rec","record","a11y","n","freeze","failureReason","suffix","write","isNewProfile","details","updates","fullName","firstName","lastName","snapshot","activity","crashed","sample","isAllowed","eventName","count","isCrash","pending","batch","unsaved","deviceInfo","networkInfo","deviceId","metricName","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