@nathanclaire/edge-telemetry-sdk 4.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 (272) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +185 -30
  3. package/dist/appLifecycle-DS_fEclk.cjs +2 -0
  4. package/dist/appLifecycle-DS_fEclk.cjs.map +1 -0
  5. package/dist/{appLifecycle-DQErzJIR.js → appLifecycle-PffQ4vC1.js} +5 -3
  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-FupMnr1U.js → crashHandlerNative.native-DsCRd-oN.js} +13 -13
  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-BoeTZcD6.cjs.map → deviceInfo.native-D5gNBG7m.cjs.map} +1 -1
  21. package/dist/deviceInfo.native-DiiHrnI3.js +53 -0
  22. package/dist/{deviceInfo.native-BJ-3Jj1T.js.map → deviceInfo.native-DiiHrnI3.js.map} +1 -1
  23. package/dist/{deviceInfo.web-BFB1-pcA.js → deviceInfo.web-BHsjVveq.js} +3 -3
  24. package/dist/{deviceInfo.web-BFB1-pcA.js.map → deviceInfo.web-BHsjVveq.js.map} +1 -1
  25. package/dist/{deviceInfo.web-3L3IDQQA.cjs → deviceInfo.web-DGCUHAnv.cjs} +2 -2
  26. package/dist/{deviceInfo.web-3L3IDQQA.cjs.map → deviceInfo.web-DGCUHAnv.cjs.map} +1 -1
  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-DdB8W_kC.js → frameTracker-BzXnxSkb.js} +18 -19
  38. package/dist/frameTracker-BzXnxSkb.js.map +1 -0
  39. package/dist/{httpAttributes-BrrtM8zh.js → httpAttributes-BWXOr4eP.js} +1 -1
  40. package/dist/{httpAttributes-BrrtM8zh.js.map → httpAttributes-BWXOr4eP.js.map} +1 -1
  41. package/dist/{httpAttributes-D0m6UID7.cjs → httpAttributes-COY0_kiF.cjs} +1 -1
  42. package/dist/{httpAttributes-D0m6UID7.cjs.map → httpAttributes-COY0_kiF.cjs.map} +1 -1
  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 +128 -71
  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 +51 -38
  52. package/dist/index.web.js.map +1 -1
  53. package/dist/{interactionWeb.web-CJAviVQ7.js → interactionWeb.web-BWBjmovb.js} +8 -8
  54. package/dist/{interactionWeb.web-CJAviVQ7.js.map → interactionWeb.web-BWBjmovb.js.map} +1 -1
  55. package/dist/interactionWeb.web-CKDJLD9r.cjs +2 -0
  56. package/dist/{interactionWeb.web-Bl_cZlgh.cjs.map → interactionWeb.web-CKDJLD9r.cjs.map} +1 -1
  57. package/dist/{interceptFetchWeb.web-UXC2Lb6X.js → interceptFetchWeb.web-DjSR_Rft.js} +18 -17
  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-UXC2Lb6X.js.map → interceptFetchWeb.web-ZHw6IQkU.cjs.map} +1 -1
  61. package/dist/{interceptHttpNative.native-BVpFuoNB.cjs → interceptHttpNative.native-C5scIcgY.cjs} +2 -2
  62. package/dist/{interceptHttpNative.native-BVpFuoNB.cjs.map → interceptHttpNative.native-C5scIcgY.cjs.map} +1 -1
  63. package/dist/{interceptHttpNative.native-rX-lPNST.js → interceptHttpNative.native-vF_Fksjk.js} +2 -2
  64. package/dist/{interceptHttpNative.native-rX-lPNST.js.map → interceptHttpNative.native-vF_Fksjk.js.map} +1 -1
  65. package/dist/{loadingTime-Bhomd9qq.cjs → loadingTime-Cj5Oh8lT.cjs} +1 -1
  66. package/dist/{loadingTime-Bhomd9qq.cjs.map → loadingTime-Cj5Oh8lT.cjs.map} +1 -1
  67. package/dist/{loadingTime-ZkYvFijA.js → loadingTime-DMc0zTY8.js} +1 -1
  68. package/dist/{loadingTime-ZkYvFijA.js.map → loadingTime-DMc0zTY8.js.map} +1 -1
  69. package/dist/memoryNative.native-CK3QFVjY.cjs +2 -0
  70. package/dist/memoryNative.native-CK3QFVjY.cjs.map +1 -0
  71. package/dist/{memoryNative.native-C42h9SjK.js → memoryNative.native-DkA6f7id.js} +12 -12
  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-B2YlLNsI.js → networkInfo.web-CcUpXMUK.js} +2 -2
  94. package/dist/networkInfo.web-CcUpXMUK.js.map +1 -0
  95. package/dist/{networkInfo.web-PltJTHsy.cjs → networkInfo.web-DfO-BUFx.cjs} +2 -2
  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-C8fdIbVR.js → runtimeReady.web-JuE239Tg.js} +2 -2
  106. package/dist/{runtimeReady.web-C8fdIbVR.js.map → runtimeReady.web-JuE239Tg.js.map} +1 -1
  107. package/dist/{runtimeReady.web-DHW682RN.cjs → runtimeReady.web-vhAJFU61.cjs} +2 -2
  108. package/dist/{runtimeReady.web-DHW682RN.cjs.map → runtimeReady.web-vhAJFU61.cjs.map} +1 -1
  109. package/dist/{seedRuntimeReady-Cz8nOKoo.js → seedRuntimeReady-BlRdf3pR.js} +2 -2
  110. package/dist/{seedRuntimeReady-Cz8nOKoo.js.map → seedRuntimeReady-BlRdf3pR.js.map} +1 -1
  111. package/dist/seedRuntimeReady-CbjqbWCd.cjs +2 -0
  112. package/dist/{seedRuntimeReady-BKwkBEAF.cjs.map → seedRuntimeReady-CbjqbWCd.cjs.map} +1 -1
  113. package/dist/src/adapters/appLifecycle.d.ts +3 -3
  114. package/dist/src/adapters/batch.d.ts +44 -0
  115. package/dist/src/adapters/crashCapture.d.ts +5 -1
  116. package/dist/src/adapters/deviceState.d.ts +9 -0
  117. package/dist/src/adapters/frameAggregate.d.ts +15 -13
  118. package/dist/src/adapters/frameTracker.d.ts +1 -1
  119. package/dist/src/adapters/hangDetector.d.ts +41 -0
  120. package/dist/src/adapters/manualSpans.d.ts +41 -0
  121. package/dist/src/adapters/native/autoTaps.native.d.ts +15 -0
  122. package/dist/src/adapters/native/deviceState.native.d.ts +15 -0
  123. package/dist/src/adapters/native/memoryNative.native.d.ts +3 -3
  124. package/dist/src/adapters/native/networkInfo.native.d.ts +1 -1
  125. package/dist/src/adapters/native/runtimeReady.native.d.ts +16 -0
  126. package/dist/src/adapters/navigationRef.d.ts +17 -9
  127. package/dist/src/adapters/networkChange.d.ts +2 -2
  128. package/dist/src/adapters/traceManager.d.ts +18 -5
  129. package/dist/src/adapters/uiInteraction.d.ts +1 -1
  130. package/dist/src/adapters/viewManager.d.ts +24 -8
  131. package/dist/src/adapters/web/deviceState.web.d.ts +10 -0
  132. package/dist/src/adapters/web/navigationWeb.web.d.ts +6 -10
  133. package/dist/src/adapters/web/webVitals.web.d.ts +7 -0
  134. package/dist/src/adapters/xhrIntercept.d.ts +2 -0
  135. package/dist/src/core/breadcrumbs.d.ts +10 -0
  136. package/dist/src/core/telemetry.d.ts +139 -29
  137. package/dist/src/core/userProfile.d.ts +7 -0
  138. package/dist/src/createTelemetry.native.d.ts +3 -1
  139. package/dist/src/createTelemetry.web.d.ts +2 -1
  140. package/dist/src/golden.helper.d.ts +4 -0
  141. package/dist/src/index.base.d.ts +80 -6
  142. package/dist/src/index.native.d.ts +4 -61
  143. package/dist/src/index.web.d.ts +4 -51
  144. package/dist/src/react.d.ts +45 -0
  145. package/dist/src/telemetryNative.native.d.ts +79 -0
  146. package/dist/src/telemetryWeb.web.d.ts +59 -0
  147. package/dist/{store.native-TPqXngmF.cjs → store.native-BbS76uWV.cjs} +1 -1
  148. package/dist/{store.native-TPqXngmF.cjs.map → store.native-BbS76uWV.cjs.map} +1 -1
  149. package/dist/{store.native-BYBJcy6o.js → store.native-MlWyGgBp.js} +1 -1
  150. package/dist/{store.native-BYBJcy6o.js.map → store.native-MlWyGgBp.js.map} +1 -1
  151. package/dist/{store.web-CvqqN-_Z.cjs → store.web-BzKaP57Z.cjs} +1 -1
  152. package/dist/{store.web-CvqqN-_Z.cjs.map → store.web-BzKaP57Z.cjs.map} +1 -1
  153. package/dist/{store.web-DJAlN0nc.js → store.web-rhh0NOfs.js} +1 -1
  154. package/dist/{store.web-DJAlN0nc.js.map → store.web-rhh0NOfs.js.map} +1 -1
  155. package/dist/telemetry-60sfWkh0.js +1754 -0
  156. package/dist/telemetry-60sfWkh0.js.map +1 -0
  157. package/dist/telemetry-CW63glwb.cjs +2 -0
  158. package/dist/telemetry-CW63glwb.cjs.map +1 -0
  159. package/dist/{uiInteraction-DAqxxz0q.js → uiInteraction-BIDOMcrL.js} +39 -34
  160. package/dist/{uiInteraction-DAqxxz0q.js.map → uiInteraction-BIDOMcrL.js.map} +1 -1
  161. package/dist/uiInteraction-DxlwCVSn.cjs +2 -0
  162. package/dist/{uiInteraction-CdzvEI1p.cjs.map → uiInteraction-DxlwCVSn.cjs.map} +1 -1
  163. package/dist/{viewport-Dd85GUNO.cjs → viewport-9JcVIXYF.cjs} +1 -1
  164. package/dist/{viewport-Dd85GUNO.cjs.map → viewport-9JcVIXYF.cjs.map} +1 -1
  165. package/dist/{viewport-Dzmt5QwK.js → viewport-GWTEBt2K.js} +1 -1
  166. package/dist/{viewport-Dzmt5QwK.js.map → viewport-GWTEBt2K.js.map} +1 -1
  167. package/dist/{web-vitals.attribution-CVCPiX-h.cjs → web-vitals.attribution-DAvBvdng.cjs} +1 -1
  168. package/dist/{web-vitals.attribution-CVCPiX-h.cjs.map → web-vitals.attribution-DAvBvdng.cjs.map} +1 -1
  169. package/dist/{web-vitals.attribution-xw9N5MKQ.js → web-vitals.attribution-DcoMtvlY.js} +1 -1
  170. package/dist/{web-vitals.attribution-xw9N5MKQ.js.map → web-vitals.attribution-DcoMtvlY.js.map} +1 -1
  171. package/dist/webSender-DA087xb5.cjs +2 -0
  172. package/dist/webSender-DA087xb5.cjs.map +1 -0
  173. package/dist/webSender-g4rs5TIg.js +44 -0
  174. package/dist/webSender-g4rs5TIg.js.map +1 -0
  175. package/dist/{webVitals.web-CNIpsKlA.js → webVitals.web-DRTDK6s5.js} +39 -24
  176. package/dist/webVitals.web-DRTDK6s5.js.map +1 -0
  177. package/dist/webVitals.web-DvScDIjX.cjs +2 -0
  178. package/dist/webVitals.web-DvScDIjX.cjs.map +1 -0
  179. package/dist/{xhrIntercept-BNiA41Mj.js → xhrIntercept-9uAkQh3N.js} +16 -14
  180. package/dist/xhrIntercept-9uAkQh3N.js.map +1 -0
  181. package/dist/xhrIntercept-xG1Yl5RI.cjs +2 -0
  182. package/dist/xhrIntercept-xG1Yl5RI.cjs.map +1 -0
  183. package/docs/migration-v4.md +1 -1
  184. package/docs/migration-v5.md +178 -0
  185. package/package.json +12 -4
  186. package/dist/appLifecycle-CECgRVu_.cjs +0 -2
  187. package/dist/appLifecycle-CECgRVu_.cjs.map +0 -1
  188. package/dist/appLifecycle-DQErzJIR.js.map +0 -1
  189. package/dist/batch-CwoO7noL.js +0 -56
  190. package/dist/batch-CwoO7noL.js.map +0 -1
  191. package/dist/batch-DNu8Xr9T.cjs +0 -2
  192. package/dist/batch-DNu8Xr9T.cjs.map +0 -1
  193. package/dist/crashCapture-BOJ8nSAZ.cjs +0 -4
  194. package/dist/crashCapture-BOJ8nSAZ.cjs.map +0 -1
  195. package/dist/crashCapture-BW8WuyaU.js +0 -70
  196. package/dist/crashCapture-BW8WuyaU.js.map +0 -1
  197. package/dist/crashHandler.web-8F_k2veo.js +0 -29
  198. package/dist/crashHandler.web-8F_k2veo.js.map +0 -1
  199. package/dist/crashHandler.web-CWmF56mJ.cjs +0 -2
  200. package/dist/crashHandler.web-CWmF56mJ.cjs.map +0 -1
  201. package/dist/crashHandlerNative.native-C2kSikDt.cjs +0 -2
  202. package/dist/crashHandlerNative.native-C2kSikDt.cjs.map +0 -1
  203. package/dist/crashHandlerNative.native-FupMnr1U.js.map +0 -1
  204. package/dist/deviceInfo.native-BJ-3Jj1T.js +0 -53
  205. package/dist/deviceInfo.native-BoeTZcD6.cjs +0 -2
  206. package/dist/frameTracker-CHG6sIx9.cjs +0 -2
  207. package/dist/frameTracker-CHG6sIx9.cjs.map +0 -1
  208. package/dist/frameTracker-DdB8W_kC.js.map +0 -1
  209. package/dist/index-BtLlV1HA.js +0 -57
  210. package/dist/index-BtLlV1HA.js.map +0 -1
  211. package/dist/index-C2XQ-EYw.js +0 -1122
  212. package/dist/index-C2XQ-EYw.js.map +0 -1
  213. package/dist/index-CXsVZY35.cjs +0 -2
  214. package/dist/index-CXsVZY35.cjs.map +0 -1
  215. package/dist/index-DLquF88M.cjs +0 -2
  216. package/dist/index-DLquF88M.cjs.map +0 -1
  217. package/dist/interactionWeb.web-Bl_cZlgh.cjs +0 -2
  218. package/dist/interceptFetchWeb.web-T88kO-bE.cjs +0 -2
  219. package/dist/interceptFetchWeb.web-T88kO-bE.cjs.map +0 -1
  220. package/dist/memoryNative.native-C42h9SjK.js.map +0 -1
  221. package/dist/memoryNative.native-CA-7w9w1.cjs +0 -2
  222. package/dist/memoryNative.native-CA-7w9w1.cjs.map +0 -1
  223. package/dist/memoryStore-BIGZmmfD.cjs +0 -2
  224. package/dist/memoryStore-BIGZmmfD.cjs.map +0 -1
  225. package/dist/memoryStore-F5I-GQKM.js +0 -193
  226. package/dist/memoryStore-F5I-GQKM.js.map +0 -1
  227. package/dist/nativeSender-CfQaRuDK.cjs +0 -2
  228. package/dist/nativeSender-CfQaRuDK.cjs.map +0 -1
  229. package/dist/nativeSender-pgVSIv-X.js +0 -59
  230. package/dist/nativeSender-pgVSIv-X.js.map +0 -1
  231. package/dist/navigationRef-BzYbs8cm.js +0 -28
  232. package/dist/navigationRef-BzYbs8cm.js.map +0 -1
  233. package/dist/navigationRef-C-_qhb43.cjs +0 -2
  234. package/dist/navigationRef-C-_qhb43.cjs.map +0 -1
  235. package/dist/navigationTracker-BmywA_Bg.js +0 -19
  236. package/dist/navigationTracker-BmywA_Bg.js.map +0 -1
  237. package/dist/navigationTracker-HkwVyywz.cjs +0 -2
  238. package/dist/navigationTracker-HkwVyywz.cjs.map +0 -1
  239. package/dist/navigationWeb.web-CW_z7Ca4.cjs +0 -2
  240. package/dist/navigationWeb.web-CW_z7Ca4.cjs.map +0 -1
  241. package/dist/navigationWeb.web-CcwgKuIZ.js +0 -55
  242. package/dist/navigationWeb.web-CcwgKuIZ.js.map +0 -1
  243. package/dist/networkChange-CUO1hRLj.cjs.map +0 -1
  244. package/dist/networkChange-D39hdSb0.js.map +0 -1
  245. package/dist/networkInfo.native-CGrx9cnH.js +0 -343
  246. package/dist/networkInfo.native-CGrx9cnH.js.map +0 -1
  247. package/dist/networkInfo.native-YVySdv3S.cjs +0 -2
  248. package/dist/networkInfo.native-YVySdv3S.cjs.map +0 -1
  249. package/dist/networkInfo.web-B2YlLNsI.js.map +0 -1
  250. package/dist/networkInfo.web-PltJTHsy.cjs.map +0 -1
  251. package/dist/runtimeReady.native-Bh7EcYmK.js +0 -14
  252. package/dist/runtimeReady.native-Bh7EcYmK.js.map +0 -1
  253. package/dist/runtimeReady.native-jUmuE1lV.cjs +0 -2
  254. package/dist/runtimeReady.native-jUmuE1lV.cjs.map +0 -1
  255. package/dist/seedRuntimeReady-BKwkBEAF.cjs +0 -2
  256. package/dist/src/adapters/navigationTracker.d.ts +0 -6
  257. package/dist/src/adapters/screenTiming.d.ts +0 -15
  258. package/dist/telemetry-ByDJIz_9.js +0 -1280
  259. package/dist/telemetry-ByDJIz_9.js.map +0 -1
  260. package/dist/telemetry-CrU7i1Jc.cjs +0 -2
  261. package/dist/telemetry-CrU7i1Jc.cjs.map +0 -1
  262. package/dist/uiInteraction-CdzvEI1p.cjs +0 -2
  263. package/dist/webSender-BIwslfpT.js +0 -63
  264. package/dist/webSender-BIwslfpT.js.map +0 -1
  265. package/dist/webSender-CVtE4sOF.cjs +0 -2
  266. package/dist/webSender-CVtE4sOF.cjs.map +0 -1
  267. package/dist/webVitals.web-CNIpsKlA.js.map +0 -1
  268. package/dist/webVitals.web-DpWJ-iYp.cjs +0 -2
  269. package/dist/webVitals.web-DpWJ-iYp.cjs.map +0 -1
  270. package/dist/xhrIntercept-BADex6Cq.cjs +0 -2
  271. package/dist/xhrIntercept-BADex6Cq.cjs.map +0 -1
  272. package/dist/xhrIntercept-BNiA41Mj.js.map +0 -1
@@ -0,0 +1,1754 @@
1
+ import { n as X, p as R, f as Y, a as Q, d as h, e as g, m as G, b as Z } from "./react-urNtDGTL.js";
2
+ import { N as D } from "./loadingTime-DMc0zTY8.js";
3
+ const tt = "4.3.0", L = ["device.id", "app.name", "app.package_name", "app.version", "app.build_number", "sdk.version", "sdk.platform"], et = (i) => JSON.stringify(L.map((t) => i.attributes?.[t]));
4
+ function Qt(i) {
5
+ const t = i[0]?.attributes ?? {};
6
+ return JSON.stringify({
7
+ type: "telemetry_batch",
8
+ contract_version: tt,
9
+ timestamp: (/* @__PURE__ */ new Date()).toISOString(),
10
+ batch_size: i.length,
11
+ device_id: t["device.id"],
12
+ sdk: { name: "react_native", version: t["sdk.version"] },
13
+ app: {
14
+ name: t["app.name"],
15
+ package_name: t["app.package_name"],
16
+ platform: t["device.platform"],
17
+ version: t["app.version"],
18
+ build_number: t["app.build_number"]
19
+ },
20
+ events: i.map((e) => {
21
+ const s = { ...e.attributes };
22
+ for (const r of L) delete s[r];
23
+ return { ...e, attributes: s };
24
+ })
25
+ });
26
+ }
27
+ function st(i) {
28
+ const t = /* @__PURE__ */ new Map();
29
+ for (const e of i) {
30
+ const s = et(e);
31
+ t.set(s, [...t.get(s) ?? [], e]);
32
+ }
33
+ return [...t.values()];
34
+ }
35
+ async function Gt(i, t, e) {
36
+ const s = st(i);
37
+ for (let r = 0; r < s.length; r++)
38
+ try {
39
+ await t(s[r]);
40
+ } catch (n) {
41
+ const a = s.slice(_(n) ? r + 1 : r).flat();
42
+ throw a.length > 0 && await e(a), n;
43
+ }
44
+ }
45
+ function Zt(i) {
46
+ return {
47
+ "Content-Type": "application/json",
48
+ ...i ? { "X-API-Key": i } : {}
49
+ };
50
+ }
51
+ class it extends Error {
52
+ constructor(t, e) {
53
+ super(`Telemetry send failed: ${t}`), this.status = t, this.resetAt = e;
54
+ }
55
+ }
56
+ function u(i) {
57
+ const t = i?.status;
58
+ return typeof t == "number" ? t : void 0;
59
+ }
60
+ const _ = (i) => {
61
+ const t = u(i);
62
+ return t !== void 0 && t >= 400 && t < 500 && t !== 429;
63
+ };
64
+ function rt(i, t = Date.now()) {
65
+ const e = Number(i?.get?.("x-ratelimit-reset"));
66
+ if (!(!Number.isFinite(e) || e < 0))
67
+ return e > 1e9 ? e * 1e3 : t + e * 1e3;
68
+ }
69
+ async function te(i, t, e) {
70
+ let s;
71
+ for (let r = 1; r <= t; r++) {
72
+ try {
73
+ const n = await i();
74
+ if (n.ok) return;
75
+ const a = new it(n.status, n.status === 429 ? rt(n.headers) : void 0);
76
+ if (n.status >= 400 && n.status < 500) throw a;
77
+ s = a;
78
+ } catch (n) {
79
+ if (u(n) !== void 0 && u(n) < 500) throw n;
80
+ s = n;
81
+ }
82
+ r < t && await new Promise((n) => setTimeout(n, e(r)));
83
+ }
84
+ throw s;
85
+ }
86
+ const ee = "https://your.telemetry.endpoint/telemetry";
87
+ function p(i = 16) {
88
+ if (typeof globalThis.crypto?.getRandomValues != "function")
89
+ throw new Error(
90
+ "edge-telemetry: crypto.getRandomValues is unavailable, so no id can be minted. On React Native this means react-native-get-random-values failed to load — reinstall it and rebuild."
91
+ );
92
+ const t = new Uint8Array(Math.ceil(i / 2));
93
+ crypto.getRandomValues(t);
94
+ let e = "";
95
+ for (const s of t) e += s.toString(16).padStart(2, "0");
96
+ return e.slice(0, i);
97
+ }
98
+ const M = { none: 0, url: 1, route: 2, explicit: 3 }, P = "unknown", nt = 16;
99
+ function O() {
100
+ return `view_${Date.now()}_${p(16)}`;
101
+ }
102
+ class at {
103
+ constructor(t) {
104
+ this.telemetry = t, this.activityListeners = /* @__PURE__ */ new Set(), this.boundaryListeners = /* @__PURE__ */ new Set(), this.retiredNames = /* @__PURE__ */ new Map(), this.markedNames = /* @__PURE__ */ new Set(), this.host = typeof location < "u" && location?.origin ? location.origin : void 0;
105
+ const e = Date.now();
106
+ this.view = {
107
+ id: O(),
108
+ name: P,
109
+ source: "none",
110
+ referrer: "",
111
+ loadType: "initial_load",
112
+ elapsed: 0,
113
+ resumedAt: e,
114
+ errors: 0,
115
+ actions: 0,
116
+ // The launch view is the one `load_type` that seeds from the platform's
117
+ // runtime-ready marker: it is busy until the bundle has evaluated (§4.5.2).
118
+ settle: new D(e, { awaitRuntimeReady: !0 }),
119
+ // The launch root is live here — it is minted in the same `Telemetry` constructor,
120
+ // just above this one — so the initial view is its child and a web hard load
121
+ // reports `launch`, never `navigation` (§6.2).
122
+ span: t.trace?.viewSpan(e) ?? {},
123
+ routes: {},
124
+ // Anchored at process start by the entry (`anchorInitial`), never at SDK init:
125
+ // one column, one anchor. Until then, and on a runtime with no marker, not judged.
126
+ token: !0
127
+ };
128
+ }
129
+ /**
130
+ * The initial view's ready anchor — process start: web `performance.timeOrigin`, native
131
+ * `rnStartupTiming.startTime` (#171). So its `view.ready_time` *is* cold-start-to-ready.
132
+ * `undefined` (native Old Architecture) leaves the initial view unjudged.
133
+ */
134
+ anchorInitial(t) {
135
+ this.view.loadType === "initial_load" && (this.view.anchor = t);
136
+ }
137
+ /**
138
+ * `markScreenReady()`'s bind (#171) — the caller stamped `at` synchronously and arrives here
139
+ * a macrotask later, so a mount-effect mark lands on the view that mount belongs to. First
140
+ * mark per view wins; a view with no token (a resume or rotation successor) ignores it.
141
+ */
142
+ markReady(t) {
143
+ const e = this.view;
144
+ e.token && e.readyAt === void 0 && (e.readyAt = t);
145
+ }
146
+ /** The two keys the Context block carries on every row. Name resolves at log time. */
147
+ get id() {
148
+ return this.view.id;
149
+ }
150
+ get name() {
151
+ return this.view.name;
152
+ }
153
+ /**
154
+ * §3.1 — `view.name` for a **frozen** `view.id`. A span-carrying row pins itself to the
155
+ * view live at span start, and its name is still resolved at log time, so an
156
+ * `http.request` that outlives a route change reports the departing view's *current*
157
+ * best name rather than a stale copy taken at send.
158
+ *
159
+ * ponytail: a bounded ring of retired names, not a full history. A span outliving
160
+ * `MAX_RETIRED_VIEW_NAMES` boundaries is a request the settle cap (30 s) already gave up
161
+ * on; it degrades to `"unknown"`, which is what a never-named view reports anyway.
162
+ */
163
+ nameOf(t) {
164
+ return t === this.view.id ? this.view.name : this.retiredNames.get(t) ?? P;
165
+ }
166
+ /**
167
+ * The name ladder (§4.5.1), and the only path that mints a view from a *name*.
168
+ *
169
+ * - a **higher** rung re-stamps the name and never changes `view.id` — that is what
170
+ * "rank beats order" means, and it is why a route name arriving after a URL-derived
171
+ * one upgrades the view in place instead of splitting it in two;
172
+ * - a **lower** rung does not overwrite the name — **but a route change is always a
173
+ * boundary** (#169, the v5 ladder ruling). Rank-beats-order applies only *within one
174
+ * route*, the upgrade window where two rungs describe one navigation: a route or URL
175
+ * event naming a different route than the one this view was bound to emits `view` and
176
+ * mints a successor, so `screenStart()` can no longer pin a view across route changes;
177
+ * - the **same** rung naming a different screen is a genuine navigation, so it ends the
178
+ * view and mints a successor.
179
+ *
180
+ * Rungs 1 and 2 are handed through unnormalized: a host naming a screen "Step 2 of 3"
181
+ * must not receive "Step {id} of {id}". The caller normalizes rung 3, not this method.
182
+ */
183
+ async navigate(t, e) {
184
+ if (e === "route" || e === "url") {
185
+ const n = this.view.routes[e];
186
+ if (n !== void 0 && n !== t) {
187
+ await this.exit("route_change", t, e);
188
+ return;
189
+ }
190
+ this.view.routes[e] = t;
191
+ }
192
+ const s = M[e], r = M[this.view.source];
193
+ if (!(s < r)) {
194
+ if (s > r) {
195
+ this.view.name = t, this.view.source = e;
196
+ return;
197
+ }
198
+ t !== this.view.name && await this.exit("route_change", t, e);
199
+ }
200
+ }
201
+ /** `view.error_count` — `app.crash` rows sharing this `view.id`. A closed enumeration. */
202
+ countError() {
203
+ this.view.errors++;
204
+ }
205
+ /** `view.action_count` — interaction rows sharing this `view.id`. */
206
+ countAction() {
207
+ this.view.actions++;
208
+ }
209
+ /**
210
+ * An HTTP request started (§4.5.2). Returns its completion callback, **bound to the view
211
+ * that was live at start** — a request that finishes after a route change belongs to the
212
+ * view it started in and does not hold the arriving one open. The collector's own POST
213
+ * never reaches here; the interceptors filter it before calling.
214
+ */
215
+ requestStarted(t) {
216
+ return this.notifyActivity(), this.view.settle.requestStarted(t);
217
+ }
218
+ /**
219
+ * §4.6's dead-click gate, in the two places this manager already sees: a request started
220
+ * and a view minted (a route change, a resume, a session rotation). The web tracker adds
221
+ * DOM mutation on top, which it can observe on its own; these two it cannot.
222
+ *
223
+ * Deliberately fires for the background and rotation boundaries too. Those are not
224
+ * navigations the click caused, so counting them as aliveness **under-reports** dead
225
+ * clicks — which is the direction §4.6 requires: `ui.dead` must never falsely accuse.
226
+ *
227
+ * @returns an unsubscribe, so a tracker that is torn down does not keep the manager alive.
228
+ */
229
+ onActivity(t) {
230
+ return this.activityListeners.add(t), () => {
231
+ this.activityListeners.delete(t);
232
+ };
233
+ }
234
+ notifyActivity() {
235
+ for (const t of this.activityListeners) t();
236
+ }
237
+ /**
238
+ * §5.1's view-boundary reset. A subscriber is **awaited inside `beginView`, before the
239
+ * successor replaces the current view**, so anything it emits is stamped with the
240
+ * departing `view.id`. That ordering is the whole feature: a fixed 10 s frame window
241
+ * straddling a route change otherwise charges the departing screen's dropped frames to
242
+ * the arriving one — backwards for the one query the metric exists to serve.
243
+ *
244
+ * ⚠ **It does not fire on the `session_rotation` boundary**, and that is deliberate.
245
+ * `newSession()` installs the new `session.id` *before* minting the successor view, so a
246
+ * row emitted there would carry the new `session.id` with the departing `view.id` — the
247
+ * one thing §4.5's "`view.id` never spans a `session.id`" forbids. Emitting *before* the
248
+ * rotation instead is worse: `logMetric` re-checks session expiry, `lastActivity` is
249
+ * still stale at that point, and the emit would rotate the session a second time. The
250
+ * accepted residue is a frame window that carries across a rotation — at most one
251
+ * unflushed window, of a session that ended by idleness.
252
+ *
253
+ * The successor's load type is handed to the subscriber so it can tell the two firing
254
+ * boundaries apart: `frame_render_time` wants both, while §5.3's running CLS/INP values
255
+ * want **`"resume"` — the background boundary — only**. Emitting a page-load-scoped vital
256
+ * at a soft navigation would ship a second row for the same page load and stamp it with
257
+ * a `view.id` that is not the initial view's.
258
+ *
259
+ * @returns an unsubscribe, so a torn-down subscriber does not keep the manager alive.
260
+ */
261
+ onBoundary(t) {
262
+ return this.boundaryListeners.add(t), () => {
263
+ this.boundaryListeners.delete(t);
264
+ };
265
+ }
266
+ /**
267
+ * The platform's runtime-ready marker — `loadEventEnd` on web,
268
+ * `performance.rnStartupTiming` on native — or `undefined` where the platform has none.
269
+ *
270
+ * Forwarded to whatever view is current, which is safe because a view that was never gated
271
+ * *ignores* the seed — enforced in `NetworkSettle`, not assumed here. On web the `load`
272
+ * event routinely arrives after the first route change, and flooring that view's settle at
273
+ * the page's load time would charge the launch's cost to a route change.
274
+ */
275
+ seedRuntimeReady(t) {
276
+ this.view.settle.seedRuntimeReady(t);
277
+ }
278
+ /**
279
+ * Emit the `view` event for the current view. Its `view.name` is authoritative and its
280
+ * `view.name_source` reports the *final* rung; the Context-block copy on rows emitted
281
+ * early in the view may still carry a lower rung's name (§4.5.1).
282
+ *
283
+ * `view.loading_time` is **omitted when null**, following this contract's general
284
+ * absent-means-the-SDK-had-nothing discipline (§4.11 names `navigation.from_screen` as the
285
+ * only explicit wire null). `view.loading_time_outcome` always ships: it is what tells the
286
+ * three null causes apart, and reading p75-of-settled beside %-capped is the whole point.
287
+ */
288
+ async endView(t = "session_rotation") {
289
+ const e = this.view, { loadingTime: s, outcome: r } = e.settle.resolve();
290
+ let n = {};
291
+ if (e.token && e.anchor !== void 0 && (e.readyAt !== void 0 ? (this.markedNames.add(e.name), n = { "view.ready_time": Math.max(0, e.readyAt - e.anchor), "view.ready_outcome": "ready" }) : t !== "resume" && this.markedNames.has(e.name) && (n = { "view.ready_outcome": "abandoned" })), await this.telemetry.log("view", {
292
+ // A **point span** (§6.3): `span.start_time` from view entry and never
293
+ // `span.duration_ms`. View dwell is `view.time_spent`, not span width — a width
294
+ // here would stretch every tap-that-navigates envelope across the whole visit.
295
+ ...e.span,
296
+ ...this.host ? { "view.host": this.host } : {},
297
+ "view.referrer": e.referrer,
298
+ "view.load_type": e.loadType,
299
+ "view.name_source": e.source,
300
+ "view.time_spent": this.timeSpent(),
301
+ ...s === null ? {} : { "view.loading_time": s },
302
+ "view.loading_time_outcome": r,
303
+ "view.error_count": e.errors,
304
+ "view.action_count": e.actions,
305
+ "view.request_count": e.settle.requestCount,
306
+ ...n
307
+ }), e.loadType !== "initial_load" && e.loadType !== "route_change") return;
308
+ const a = typeof n["view.ready_time"] == "number", o = a ? n["view.ready_time"] : s;
309
+ await this.telemetry.log("screen.load", {
310
+ "screen.name": e.name,
311
+ "screen.load.source": a ? "reported" : "inferred",
312
+ "screen.load.outcome": a ? "settled" : r,
313
+ ...o === null ? {} : { "screen.load.settled_ms": o }
314
+ });
315
+ }
316
+ /**
317
+ * Mint the successor. Called directly by session rotation, which has to mint *after*
318
+ * the new `session.id` is in place — `view.id` never spans a `session.id` (§4.5).
319
+ * An unnamed successor carries the departing view's name: backgrounding and a session
320
+ * rotation do not move the user off the screen they were on.
321
+ */
322
+ async beginView(t, e, s) {
323
+ if (this.notifyActivity(), t !== "session_rotation")
324
+ for (const a of this.boundaryListeners)
325
+ try {
326
+ await a(t);
327
+ } catch {
328
+ }
329
+ const r = this.view, n = Date.now();
330
+ if (this.retiredNames.set(r.id, r.name), this.retiredNames.size > nt) {
331
+ const a = this.retiredNames.keys().next();
332
+ a.done || this.retiredNames.delete(a.value);
333
+ }
334
+ this.view = {
335
+ id: O(),
336
+ name: e ?? r.name,
337
+ source: s ?? r.source,
338
+ referrer: r.name,
339
+ loadType: t,
340
+ elapsed: 0,
341
+ resumedAt: n,
342
+ errors: 0,
343
+ actions: 0,
344
+ // No runtime-ready seed: only `initial_load` has a platform marker to wait on.
345
+ settle: new D(n),
346
+ // A view start *extends* the live root; with none live it mints a `navigation`
347
+ // one (§6.2). Its exit does not extend anything (§6.7).
348
+ span: this.telemetry.trace?.viewSpan(n) ?? {},
349
+ // A route change binds the successor to the route that minted it; a resume or a
350
+ // rotation keeps the user on the same screen, so it keeps the same routes too.
351
+ routes: t === "route_change" ? s === "route" || s === "url" ? { [s]: e } : {} : { ...r.routes },
352
+ // Route views anchor at entry (`span.start_time`). A resume or rotation successor
353
+ // is the same screen continued, so it never gets a pending token.
354
+ token: t === "route_change",
355
+ anchor: n
356
+ };
357
+ }
358
+ /** A boundary that stays inside one session: emit, then mint the successor. */
359
+ async exit(t, e, s) {
360
+ await this.endView(t), await this.beginView(t, e, s);
361
+ }
362
+ /**
363
+ * The background boundary. The successor is minted immediately — `view.id` must never
364
+ * be absent — but its clock starts paused, so a night spent backgrounded does not land
365
+ * as dwell on whatever screen the user left open.
366
+ */
367
+ async background() {
368
+ await this.exit("resume");
369
+ const t = this.view;
370
+ t.elapsed += this.sinceResume(), t.resumedAt = void 0;
371
+ }
372
+ /** The matching foreground edge: re-arm the paused clock. */
373
+ foreground() {
374
+ this.view.resumedAt ??= Date.now();
375
+ }
376
+ sinceResume() {
377
+ return this.view.resumedAt === void 0 ? 0 : Date.now() - this.view.resumedAt;
378
+ }
379
+ timeSpent() {
380
+ return Math.max(0, this.view.elapsed + this.sinceResume());
381
+ }
382
+ }
383
+ const ot = 2e3, ht = 1e4, ct = () => p(32), K = () => p(16);
384
+ class dt {
385
+ /**
386
+ * @param launchStartMs what `app.start` reports as `span.start_time` — and **neither
387
+ * value is a fork time** (§6.2). Web passes `performance.timeOrigin` (true navigation
388
+ * start); native leaves it defaulted to `initialize()`, because everything before the
389
+ * JS bundle loads is invisible and JS cannot see process fork. Do not compare the two
390
+ * platforms' launch envelopes as if they measured the same interval.
391
+ */
392
+ constructor(t, e) {
393
+ this.allowlist = X(e);
394
+ const s = Date.now();
395
+ this.launch = this.mint("launch", s, t ?? s);
396
+ }
397
+ /**
398
+ * §4.1's `sdk.trace_allowlist_size` — **count only, never the hosts**, so an operator can
399
+ * tell "nobody opted in" apart from "the header is being stripped" without the SDK
400
+ * shipping a customer's internal hostnames to the collector.
401
+ */
402
+ allowlistSize() {
403
+ return this.allowlist.size;
404
+ }
405
+ /**
406
+ * `app.start`'s own row — a root, so `span.id === rum.action.id` and there is no
407
+ * `parent.span.id`. No `span.duration_ms` either: roots derive theirs server-side.
408
+ */
409
+ launchRootAttributes() {
410
+ return f(this.launch, !0, this.launch.spanStartMs).keys;
411
+ }
412
+ /**
413
+ * Tier 1 for a `view`, captured at view **entry** — the action that opened the screen,
414
+ * not the one that closed it (§6.3). A **point span**: `span.start_time` and never
415
+ * `span.duration_ms`, because view dwell is not span duration and a width here would
416
+ * stretch every tap-that-navigates envelope across the whole time the user sat there.
417
+ */
418
+ viewSpan(t) {
419
+ const { root: e, isRoot: s } = this.attach("navigation", t);
420
+ return f(e, s, t).keys;
421
+ }
422
+ /**
423
+ * Tier 1 for a `ui.interaction`, captured at the click's **mint** (§4.6/§6.2). The one
424
+ * unconditional mint in the table: a tap is a new user action by definition, so it
425
+ * *replaces* whatever root was live rather than joining it — which is what makes the
426
+ * request a tap fires a child of the tap and not of the route change before it.
427
+ *
428
+ * A root, so `span.id === rum.action.id`, no `parent.span.id`, and no `span.duration_ms`
429
+ * (§6.1 — a root's width is derived server-side).
430
+ */
431
+ interactionSpan(t) {
432
+ const e = this.mint("interaction", t, t);
433
+ return f(e, !0, t).keys;
434
+ }
435
+ /**
436
+ * Tier 1 for a manual span (`task.complete`, #164), captured at **start**: a child of the
437
+ * live root — whose idle clock the start extends, like any span start — or else a fresh
438
+ * `custom` root. A leaf, never a parent: no context stack, so a request inside the span
439
+ * parents to the root. `span.duration_ms` is added at the end, on root *and* child — the
440
+ * flagged §6.3 exception, since a declared end is not derivable from children.
441
+ */
442
+ manualSpan(t) {
443
+ const { root: e, isRoot: s } = this.attach("custom", t);
444
+ return f(e, s, t).keys;
445
+ }
446
+ /**
447
+ * Tier 1 for an `http.request`, captured at **send** — the root live then is the parent,
448
+ * and `span.start_time` is the send — plus §6.5's outcome ladder and the one header the
449
+ * SDK ever writes. Returns the finisher, so duration is stamped from the same pair of
450
+ * timestamps the row's `http.duration_ms` uses.
451
+ *
452
+ * A `send()` that throws synchronously never calls the finisher; it calls `discard()`, so
453
+ * a root it minted does not live on for 2 s with no row describing it (#160).
454
+ */
455
+ requestTrace(t, e) {
456
+ const s = this.decide(e);
457
+ if (s === "adopted") {
458
+ const l = R(e.consumerTraceparent), W = {
459
+ "trace.id": l.traceId,
460
+ "span.id": l.spanId,
461
+ "rum.action.id": l.spanId,
462
+ "span.start_time": new Date(t).toISOString(),
463
+ "traceparent.outcome": "adopted"
464
+ };
465
+ return { finish: () => W, discard: () => {
466
+ } };
467
+ }
468
+ const { root: r, isRoot: n, attribution: a } = this.attach("request", t), o = s === "inject" ? a : s, c = f(r, n, t), d = {
469
+ ...c.keys,
470
+ ...o ? { "traceparent.outcome": o } : {}
471
+ }, T = n ? () => d : (l) => ({ ...d, "span.duration_ms": Math.max(0, l - t) }), N = () => {
472
+ n && this.root === r && (this.root = void 0);
473
+ };
474
+ return s === "inject" ? { finish: T, discard: N, header: Y(r.traceId, c.spanId) } : { finish: T, discard: N };
475
+ }
476
+ /**
477
+ * §6.5's ladder above the `injected_*` split, in table order — the precedence *is* the
478
+ * order of these returns. `undefined` means the attribute is omitted entirely: absent
479
+ * means not traced, which is the honest report for a consumer who never opted in and for
480
+ * a sampled-out session (which injects no header at all, not a `flags=00` id).
481
+ */
482
+ decide(t) {
483
+ if (!(this.allowlist.size === 0 || !t.sampled))
484
+ return Q(this.allowlist, t.url) ? t.noCors ? "skipped_no_cors" : t.consumerTraceparent != null ? R(t.consumerTraceparent) ? "adopted" : "skipped_consumer_set" : "inject" : "skipped_off_allowlist";
485
+ }
486
+ /**
487
+ * Tier 2 — annotation-only (§6.3): join the trace without occupying a span. No
488
+ * `span.id`, no parent, no duration, and **no minting** — §6.2 lists the four events
489
+ * that mint and these are not among them, so an untraced crash carries no trace keys
490
+ * rather than inventing a root nothing else will ever join.
491
+ */
492
+ annotate(t = Date.now()) {
493
+ const e = this.liveRoot(t);
494
+ return e ? {
495
+ "trace.id": e.traceId,
496
+ "rum.action.id": e.spanId,
497
+ "trace.root_type": e.rootType
498
+ } : {};
499
+ }
500
+ /**
501
+ * Drop the carrier. Background clears it on both builds, so a resumed app's first fetch
502
+ * mints its own root rather than joining an action from before the user left (§6.2);
503
+ * session rotation clears it because `trace.id` never spans a `session.id` (§6.6).
504
+ */
505
+ clear() {
506
+ this.root = void 0;
507
+ }
508
+ /**
509
+ * Retire the launch root and mint a replacement, keeping the *reported* launch time —
510
+ * the process really did start then. For a session rotation that lands **before**
511
+ * `app.start`, which is the expired-record cold launch and therefore §4.3's most common
512
+ * path of all.
513
+ *
514
+ * Clearing alone would not do: `app.start` reports the launch root at any age, so its
515
+ * root row would ship under the **new** session while the initial `view` it fathered
516
+ * shipped under the **old** one. `trace.id` would span a `session.id` (§6.6, invariant 2)
517
+ * and `GROUP BY rum.action.id` would never reassemble the launch envelope. Re-minting
518
+ * keeps the retired trace wholly inside the retired session.
519
+ *
520
+ * ⚠ The retired trace then has children and no root row — the initial `view` row is a
521
+ * rootless child. That is the same condition process death already produces by design
522
+ * (a killed view emits nothing), and it is the cheaper of the two wrongs.
523
+ */
524
+ restartLaunchRoot() {
525
+ this.launch = this.mint("launch", Date.now(), this.launch.spanStartMs);
526
+ }
527
+ /**
528
+ * Join the live root, or mint one of `mintAs`. A span's *start* extends the root.
529
+ *
530
+ * `attribution` is read **before** `liveRoot()` drops an expired carrier, which is the
531
+ * only place the two unattributed causes are still distinguishable: a carrier that just
532
+ * aged out is `injected_expired` (context lost), no carrier at all is
533
+ * `injected_unattributed` (no action) — the split §6.5 asks the backend to keep.
534
+ */
535
+ attach(t, e) {
536
+ const s = this.root !== void 0, r = this.liveRoot(e);
537
+ return r ? (r.lastTouch = e, { root: r, isRoot: !1, attribution: "injected_attributed" }) : {
538
+ root: this.mint(t, e, e),
539
+ isRoot: !0,
540
+ attribution: s ? "injected_expired" : "injected_unattributed"
541
+ };
542
+ }
543
+ mint(t, e, s) {
544
+ const r = {
545
+ traceId: ct(),
546
+ spanId: K(),
547
+ rootType: t,
548
+ startedAt: e,
549
+ spanStartMs: s,
550
+ lastTouch: e
551
+ };
552
+ return this.root = r, r;
553
+ }
554
+ /**
555
+ * The carrier if it is still live, dropping it otherwise. Both boundaries are strict —
556
+ * a root sitting exactly on one has not crossed it — matching the session boundaries.
557
+ *
558
+ * A **negative** delta is clamped to expired (§6.7): `Date.now()` can move backwards on
559
+ * an NTP correction, and reading that as "fresh" would hold one root open indefinitely.
560
+ */
561
+ liveRoot(t) {
562
+ const e = this.root;
563
+ if (!e) return;
564
+ const s = t - e.lastTouch, r = t - e.startedAt;
565
+ if (s < 0 || r < 0 || s > ot || r > ht) {
566
+ this.root = void 0;
567
+ return;
568
+ }
569
+ return e;
570
+ }
571
+ }
572
+ function f(i, t, e) {
573
+ const s = t ? i.spanId : K();
574
+ return {
575
+ spanId: s,
576
+ keys: {
577
+ "trace.id": i.traceId,
578
+ "span.id": s,
579
+ ...t ? {} : { "parent.span.id": i.spanId },
580
+ "rum.action.id": i.spanId,
581
+ "trace.root_type": i.rootType,
582
+ "span.start_time": new Date(e).toISOString()
583
+ }
584
+ };
585
+ }
586
+ const B = 1e3, ut = 2e3, lt = 6e4;
587
+ function ft(i, t) {
588
+ const e = t - i - B;
589
+ return e >= ut && e <= lt ? Math.round(e) : void 0;
590
+ }
591
+ class pt {
592
+ constructor(t, e = () => performance.now()) {
593
+ this.core = t, this.now = e, this.active = !1, this.suspended = !1, this.tick = () => {
594
+ const s = this.now(), r = this.last, n = r && ft(r.mono, s);
595
+ r && n !== void 0 && this.core.log("app.hang", { ...r.trace, "hang.duration_ms": n }, r.snap).catch((o) => h.warn("app.hang failed:", o));
596
+ const a = Date.now();
597
+ this.last = { mono: s, snap: this.core.snapshot(a), trace: this.core.trace.annotate(a) }, this.timer = setTimeout(this.tick, B);
598
+ };
599
+ }
600
+ /** Driven by the lifecycle emitter: foreground only, so background suspension never reads as a hang. */
601
+ setActive(t) {
602
+ this.active = t, this.sync();
603
+ }
604
+ /** `disable()` / `enable()` (#172): off while collection is off, whatever the lifecycle says. */
605
+ suspend(t) {
606
+ this.suspended = t, this.sync();
607
+ }
608
+ sync() {
609
+ this.active && !this.suspended ? this.start() : this.stop();
610
+ }
611
+ start() {
612
+ this.timer === void 0 && this.tick();
613
+ }
614
+ /** Idempotent. `shutdown()` and backgrounding call it; the next start begins a fresh baseline. */
615
+ stop() {
616
+ this.timer !== void 0 && clearTimeout(this.timer), this.timer = void 0, this.last = void 0;
617
+ }
618
+ }
619
+ const mt = "telemetry_failed_events";
620
+ function se(i) {
621
+ if (i.status !== "hit") return [];
622
+ try {
623
+ const t = JSON.parse(i.value);
624
+ return Array.isArray(t) ? t : [];
625
+ } catch {
626
+ return [];
627
+ }
628
+ }
629
+ const vt = 500, wt = 1e6, yt = (i) => typeof TextEncoder < "u" ? new TextEncoder().encode(i).length : i.length;
630
+ function ie(i, t) {
631
+ const e = [...i, ...t];
632
+ let s = 0;
633
+ for (; e.length > vt; )
634
+ e.splice(w(e), 1), s++;
635
+ const r = e.map((a) => yt(JSON.stringify(a)));
636
+ let n = r.reduce((a, o) => a + o, 0) + Math.max(e.length - 1, 0) + 2;
637
+ for (; n > wt && e.length > 0; ) {
638
+ const a = w(e);
639
+ n -= r[a] + (e.length > 1 ? 1 : 0), r.splice(a, 1), e.splice(a, 1), s++;
640
+ }
641
+ return { json: JSON.stringify(e), dropped: s };
642
+ }
643
+ function re(i) {
644
+ let t;
645
+ return () => t ??= i().finally(() => {
646
+ t = void 0;
647
+ });
648
+ }
649
+ function E(i) {
650
+ try {
651
+ return JSON.stringify(i) ?? void 0;
652
+ } catch {
653
+ return;
654
+ }
655
+ }
656
+ const q = 32, St = 255, bt = /^(task|span|trace|parent|rum)(\.|$)/;
657
+ function C(i) {
658
+ if (!i || typeof i != "object") return;
659
+ const t = {};
660
+ for (const [e, s] of Object.entries(i)) bt.test(e) || (t[e] = s);
661
+ return t;
662
+ }
663
+ function y(i) {
664
+ return typeof i == "string" && i.trim() !== "" ? i.slice(0, St) : void 0;
665
+ }
666
+ class gt {
667
+ constructor() {
668
+ this.open = /* @__PURE__ */ new Map();
669
+ }
670
+ /**
671
+ * Opens `name`, superseding an open span of the same name — dropped without a row, since
672
+ * `abandoned` means "the session ended first" and nothing else. `undefined` past the cap.
673
+ */
674
+ start(t, e, s) {
675
+ if (!this.open.has(t) && this.open.size >= q) return;
676
+ const r = { name: t, start: e, attrs: s };
677
+ return this.open.delete(t), this.open.set(t, r), r;
678
+ }
679
+ /** Close by name. With `only`, a superseded handle cannot close its successor. */
680
+ take(t, e) {
681
+ const s = this.open.get(t);
682
+ if (!(!s || e && s !== e))
683
+ return this.open.delete(t), s;
684
+ }
685
+ /** `disable()` (#172): an opt-out keeps nothing, open journeys included. */
686
+ clear() {
687
+ this.open.clear();
688
+ }
689
+ has(t) {
690
+ return this.open.get(t.name) === t;
691
+ }
692
+ /** Every span frozen to `sessionId`, removed — the ones a finalize owes `abandoned`. */
693
+ takeSession(t) {
694
+ const e = [...this.open.values()].filter((s) => s.sessionId === t);
695
+ for (const s of e) this.open.delete(s.name);
696
+ return e;
697
+ }
698
+ toJSON() {
699
+ return [...this.open.values()].filter((t) => t.sessionId !== void 0).map(({ ready: t, attrs: e, ...s }) => ({ ...s, attrs: e && E(e) }));
700
+ }
701
+ /** Adopt a persisted record's spans. Anything malformed is skipped, never thrown. */
702
+ restore(t) {
703
+ if (this.open.clear(), !!Array.isArray(t))
704
+ for (const e of t.slice(0, q)) {
705
+ if (typeof e?.name != "string" || typeof e.start != "number" || typeof e.sessionId != "string") continue;
706
+ let s;
707
+ try {
708
+ s = e.attrs ? JSON.parse(e.attrs) : void 0;
709
+ } catch {
710
+ s = void 0;
711
+ }
712
+ this.open.set(e.name, { ...e, attrs: s });
713
+ }
714
+ }
715
+ }
716
+ const _t = 255, It = 255, kt = 50, x = 64, U = 64, I = 255;
717
+ let H = !1;
718
+ function S(i, t) {
719
+ if (typeof i != "string") return;
720
+ const e = i.slice(0, t);
721
+ return e.length ? e : void 0;
722
+ }
723
+ function J(i) {
724
+ if (i == null) return;
725
+ if (typeof i == "number" || typeof i == "boolean") return i;
726
+ if (typeof i == "string") return i.slice(0, I) || void 0;
727
+ const t = E(i);
728
+ return t === void 0 ? void 0 : t.slice(0, I) || void 0;
729
+ }
730
+ function At(i) {
731
+ const t = {};
732
+ if (!i) return t;
733
+ const e = S(i.fullName, _t), s = S(i.email, It), r = S(i.phone, kt);
734
+ e !== void 0 && (t["user.name"] = e), s !== void 0 && (t["user.email"] = s), r !== void 0 && (t["user.phone"] = r);
735
+ let n = 0, a = 0;
736
+ for (const o of Object.keys(i.customAttributes || {})) {
737
+ if (o.length > U || a >= x) {
738
+ n++;
739
+ continue;
740
+ }
741
+ const c = J(i.customAttributes[o]);
742
+ if (c === void 0) {
743
+ n++;
744
+ continue;
745
+ }
746
+ t[`user.custom.${o}`] = c, a++;
747
+ }
748
+ return n > 0 && (t["user.custom_dropped"] = n, g() && !H && (H = !0, console.warn(
749
+ `[edge-telemetry] identify(): ${n} custom attribute(s) dropped. user.custom.* is bounded at ${x} keys, ${U}-char keys and ${I}-char values; unserializable values are dropped.`
750
+ ))), t;
751
+ }
752
+ const Et = 64, Tt = 8;
753
+ function Nt(i, t, e = /* @__PURE__ */ new Date()) {
754
+ const s = {};
755
+ if (t && typeof t == "object")
756
+ for (const [r, n] of Object.entries(t).slice(0, Tt)) {
757
+ const a = J(n);
758
+ a !== void 0 && (s[r] = a);
759
+ }
760
+ return s.name = String(i).slice(0, Et), s.timestamp = e.toISOString(), s;
761
+ }
762
+ class Rt {
763
+ constructor(t = 20) {
764
+ this.max = t, this.items = [];
765
+ }
766
+ add(t) {
767
+ this.items.push(t), this.items.length > this.max && this.items.shift();
768
+ }
769
+ list() {
770
+ return [...this.items];
771
+ }
772
+ toJSON() {
773
+ return JSON.stringify(this.items);
774
+ }
775
+ }
776
+ const Dt = /* @__PURE__ */ new Set([
777
+ // `session.sequence` is not in the contract's §3.6 list, which names only `event.sequence`.
778
+ // Both are transmission ordinals with no scrubbing use case: (session.id, session.sequence)
779
+ // orders a session's batches (#92) and (session.id, event.sequence) is the backend's dedup
780
+ // key (#94, §2.4) — a hook that could delete either would break the thing it keys.
781
+ //
782
+ // `event.sequence` is stamped in `enqueue()` *after* this hook runs, so on the way in it is
783
+ // absent and the re-stamp is a no-op; it is listed because the hook must not be able to
784
+ // forge one, and because a re-run over an already-stamped event must leave it alone.
785
+ "session.id",
786
+ "session.start_time",
787
+ "session.sequence",
788
+ "event.sequence",
789
+ "device.platform",
790
+ "trace.id",
791
+ "span.id",
792
+ "parent.span.id",
793
+ "rum.action.id",
794
+ "view.id"
795
+ ]), j = (i) => Dt.has(i) || i.startsWith("sdk.") || i.startsWith("app."), m = "device.id";
796
+ function Mt(i, t) {
797
+ let e;
798
+ try {
799
+ e = t({ ...i, attributes: { ...i.attributes } });
800
+ } catch (s) {
801
+ return h.warn("Telemetry: beforeSend threw — event dropped", s), { kind: "failed" };
802
+ }
803
+ return e === null ? { kind: "dropped" } : typeof e != "object" ? (h.warn("Telemetry: beforeSend returned a non-event — event dropped", e), { kind: "failed" }) : { kind: "kept", event: Pt(i, e) };
804
+ }
805
+ function Pt(i, t) {
806
+ const e = {};
807
+ for (const [n, a] of Object.entries(t.attributes ?? {}))
808
+ j(n) || (e[n] = a);
809
+ for (const [n, a] of Object.entries(i.attributes ?? {}))
810
+ j(n) && (e[n] = a);
811
+ const s = e[m];
812
+ if (typeof s != "string" || s === "") {
813
+ const n = i.attributes?.[m];
814
+ n === void 0 ? delete e[m] : e[m] = n;
815
+ }
816
+ const r = {
817
+ type: i.type,
818
+ timestamp: i.timestamp,
819
+ attributes: e
820
+ };
821
+ return i.eventName !== void 0 && (r.eventName = i.eventName), i.metricName !== void 0 && (r.metricName = i.metricName), i.type === "metric" && (r.value = t.value ?? i.value), r;
822
+ }
823
+ const Ot = "5.0.1", qt = (i) => i ? `react-native-${i}` : "react-native", Ct = Ot, xt = 1800 * 1e3, Ut = 14400 * 1e3, Ht = 8, jt = 500, Vt = 50, zt = 100, Ft = 1e3;
824
+ let V = !1;
825
+ const b = (i) => i.attributes?.["event.sequence"] ?? -1, k = (i) => i === "app.crash" || i === "app.error";
826
+ function w(i) {
827
+ const t = i.findIndex((e) => e.eventName !== "app.crash");
828
+ return t === -1 ? 0 : t;
829
+ }
830
+ const A = "telemetry_device_id", v = "telemetry_session", $t = 255, Lt = /* @__PURE__ */ new Set([
831
+ // `navigation` and `screen.duration` are **removed in v5** (#163, §4.0): the `view` entity
832
+ // is the only screen feed; the processor derives both from it (catalogue `derives:`).
833
+ "session.started",
834
+ "session.finalized",
835
+ "app.lifecycle",
836
+ "http.request",
837
+ "network.change",
838
+ "user.profile.update",
839
+ "app.crash",
840
+ "view",
841
+ "screen.load",
842
+ "app.error",
843
+ "ui.interaction",
844
+ "app.start",
845
+ "task.complete",
846
+ "app.hang",
847
+ "frame.summary",
848
+ "memory.usage",
849
+ "custom.metric",
850
+ "perf.lcp",
851
+ "perf.fcp",
852
+ "perf.cls",
853
+ "perf.inp",
854
+ "perf.ttfb"
855
+ // ⚠ `page_load`, `resource_timing` and `long_task` are **retired, not deferred**
856
+ // (§10.2, #109) — as `user.interaction` was in #102. Do not add them back: `page_load`'s
857
+ // job is done three ways over (`view` + `view.loading_time` + the vitals), `resource_timing`
858
+ // would blow the 500-event queue on one asset-heavy view, and `long_task`'s only APIs are
859
+ // Chromium-only while `frame.summary` detects jank on every runtime.
860
+ ]), z = {
861
+ "perf.lcp": "ms",
862
+ "perf.fcp": "ms",
863
+ "perf.inp": "ms",
864
+ "perf.ttfb": "ms",
865
+ "perf.cls": "score"
866
+ }, Kt = /* @__PURE__ */ new Set(["frame.summary", "memory.usage"]), Bt = /* @__PURE__ */ new Set(["app.crash", "app.error", "custom.event"]), F = (i) => typeof i == "number" && Number.isFinite(i) && i >= 0 && i <= 1;
867
+ function $(i) {
868
+ if (typeof i != "string") return;
869
+ let t;
870
+ try {
871
+ t = JSON.parse(i);
872
+ } catch {
873
+ return;
874
+ }
875
+ if (!(typeof t?.id != "string" || typeof t.start != "number" || typeof t.lastActivity != "number"))
876
+ return t;
877
+ }
878
+ function Jt(i) {
879
+ return i === void 0 ? 1 : !Number.isFinite(i) || i < 0 || i > 1 ? (h.warn(`Telemetry: sessionSampleRate must be a number in [0,1] — got ${i}; using 1`), 1) : i;
880
+ }
881
+ class Wt {
882
+ constructor(t) {
883
+ this.queue = [], this.intervalId = null, this.networkStarted = !1, this.userId = void 0, this.deviceIdEphemeral = !1, this.userProfile = void 0, this.eventCount = 0, this.breadcrumbs = new Rt(20), this.sessionSequence = 0, this.eventSequence = 0, this.sessionEventCount = 0, this.errorCount = 0, this.hookDropped = 0, this.hookFailed = 0, this.eventsDropped = 0, this.crashPersistedThrough = -1, this.appStartEmitted = !1, this.spans = new gt(), this.finalizing = !1, this.pendingStart = !1, this.holdUntil = 0, this.sender = t?.sender, this.batchSize = t?.batchSize ?? 50, this.flushIntervalMs = t?.flushIntervalMs ?? 3e4, this.endpoint = t?.endpoint, this.platform = t?.platform, this.store = t?.store ?? G({ unavailable: !0 }), this.beforeSend = t?.beforeSend, this.buildId = typeof t?.buildId == "string" && t.buildId !== "" ? t.buildId : void 0, this.enabled = t?.enabled !== !1, this.enabled || (this.appStartEmitted = !0), this.configuredSampleRate = Jt(t?.sessionSampleRate), this.sampleRate = this.configuredSampleRate, this.sampled = this.rollSample(), this.sessionId = t?.sessionId ?? this.generateSessionId(), t?.userId && this.setUserId(t.userId), this.sessionStart = Date.now(), this.sdkVersion = t?.sdkVersion ?? Ct, this.enabled && this.startDelivery(), this.trace = new dt(t?.traceLaunchStart, t?.traceHostAllowlist), this.deviceState = t?.deviceStateHandler, this.enabled && this.deviceState?.start?.(), g() || (this.hangs = new pt(this), this.hangs.suspend(!this.enabled)), this.views = new at(this), this.deviceInfoHandler = t?.deviceInfoHandler ?? {
884
+ start: async () => Promise.resolve(),
885
+ collect: async () => Promise.resolve({
886
+ app: { name: "", version: "" },
887
+ device: { platform: "" }
888
+ })
889
+ }, this.networkInfoHandler = t?.networkInfoHandler ?? {
890
+ start: async () => Promise.resolve({}),
891
+ collect: async () => Promise.resolve({})
892
+ }, t?.networkInfoHandler && this.getNetworkInfo(t.networkInfoHandler);
893
+ }
894
+ // ---------- Session & User APIs ----------
895
+ /**
896
+ * §4.7 — report a handled error. Accepts `unknown` on purpose: half of real `catch`
897
+ * blocks receive a string or an axios rejection object, and a consumer should not have
898
+ * to prove to TypeScript that it is an `Error` before reporting it.
899
+ *
900
+ * Emits `app.error`, **never** `app.crash`. There is deliberately no public path to
901
+ * `app.crash` — a consumer's own code must not be able to manufacture rows in the one
902
+ * table an unfiltered crash-free rate is read from.
903
+ *
904
+ * `source` is SDK-internal (`captureConsole` passes `"console"`); the public wrappers
905
+ * forward two arguments, so a consumer can only ever produce `"reported"`. Routing the
906
+ * console path through here rather than through `log()` directly is what keeps the
907
+ * `error.fatal` rule in one place.
908
+ */
909
+ captureError(t, e, s = "reported") {
910
+ const r = this.isNativePlatform() ? { fatal: !1 } : {};
911
+ return this.log("app.error", { ...e, ...Z(s, t, r) });
912
+ }
913
+ /**
914
+ * Extend the breadcrumb trail without emitting anything. §4.7 demotes `console.warn` to
915
+ * exactly this — React's dev-mode warnings were the bulk of v3's `app.crash` volume.
916
+ *
917
+ * Also the public `addBreadcrumb()` (#167) — one path, so the SDK's own crumbs and the
918
+ * host's obey the same bounds (`boundCrumb`). Shows on `app.crash` and `app.hang`.
919
+ */
920
+ addBreadcrumb(t, e) {
921
+ this.breadcrumbs.add(Nt(t, e));
922
+ }
923
+ /**
924
+ * `startNewSession()` (#167) — logout/login. The same finalize + started pair as an idle
925
+ * or max-duration rotation, with `session.reason: manual` on both.
926
+ */
927
+ async startNewSession() {
928
+ await this.rotateSession("manual");
929
+ }
930
+ trackErrors(t, e) {
931
+ this.crashHandler = t, t.attach(e).catch((s) => {
932
+ h.warn("Telemetry crashHandler attach failed:", s);
933
+ });
934
+ }
935
+ getDeviceInfo(t) {
936
+ this.deviceInfoHandler = t, t.start(this).catch((e) => {
937
+ h.warn("Telemetry deviceInfo tracking start failed:", e);
938
+ });
939
+ }
940
+ /** Starts the network tracker once; later calls are no-ops, so listeners never stack. */
941
+ getNetworkInfo(t) {
942
+ this.networkStarted || (this.networkStarted = !0, this.networkInfoHandler = t, t.start(this).catch((e) => {
943
+ h.warn("Telemetry networkInfoHandler start failed:", e);
944
+ }));
945
+ }
946
+ trackFrameDrops(t) {
947
+ this.frameDropsHandler = t, t.start().catch((e) => {
948
+ h.warn("Telemetry frameDropsHandler start failed:", e);
949
+ });
950
+ }
951
+ trackNetworkRequests(t) {
952
+ this.networkHandler = t, t.start().catch((e) => {
953
+ h.warn("Telemetry networkHandler start failed:", e);
954
+ });
955
+ }
956
+ /** The offline replay and the flush timer — at construction, and again at each `enable()`. */
957
+ startDelivery() {
958
+ this.sender?.replayFailed && this.sender.replayFailed().catch((t) => {
959
+ h.warn("Telemetry replay failed Telemetry class:", t);
960
+ }), this.flushIntervalMs > 0 && !this.intervalId && (this.intervalId = setInterval(() => this.flush().catch(() => {
961
+ }), this.flushIntervalMs));
962
+ }
963
+ isEnabled() {
964
+ return this.enabled;
965
+ }
966
+ /**
967
+ * The consent kill-switch (#172). Synchronous: the flag is off before this returns. The
968
+ * in-memory queue, the offline store and the session record are dropped — an opt-out
969
+ * means nothing is sent **and nothing is kept**, open spans included — and every timer
970
+ * stops; the rAF loop keeps running but `logMetric` discards its samples. While off the
971
+ * network patches pass through untouched. `device.id` is kept: it is not telemetry, and
972
+ * minting a new one at re-consent would read as a new install.
973
+ */
974
+ disable() {
975
+ if (this.enabled) {
976
+ this.enabled = !1, this.queue = [], this.intervalId && (clearInterval(this.intervalId), this.intervalId = null), this.memoryHandler?.stop?.(), this.deviceState?.stop?.(), this.hangs?.suspend(!0), this.spans.clear();
977
+ for (const t of [mt, v])
978
+ Promise.resolve(this.store.remove(t)).catch((e) => h.warn("disable: store remove failed:", e));
979
+ }
980
+ }
981
+ /**
982
+ * Resume collection (#172) and run the lazy session-expiry check — a session can expire
983
+ * while disabled. A dark-started process announces its session here (`session.started`,
984
+ * unless a live record resumes) and never emits `app.start`.
985
+ */
986
+ async enable() {
987
+ if (this.enabled) return;
988
+ if (this.enabled = !0, this.startDelivery(), this.memoryHandler && this.memoryHandler.start().catch((e) => h.warn("Telemetry memoryHandler start failed:", e)), this.hangs?.suspend(!1), this.deviceState?.start?.(), this.pendingStart) {
989
+ this.pendingStart = !1, await this.hydrateAndAnnounce();
990
+ return;
991
+ }
992
+ const t = this.expiryReason(Date.now());
993
+ t && await this.rotateSession(t);
994
+ }
995
+ trackMemoryUsage(t) {
996
+ this.memoryHandler?.stop?.(), this.memoryHandler = t, this.enabled && t.start().catch((e) => {
997
+ h.warn("Telemetry memoryHandler start failed:", e);
998
+ });
999
+ }
1000
+ autoTrackNavigation(t) {
1001
+ this.navigationHandler = t, t?.start().catch((e) => {
1002
+ h.warn("Telemetry navigationHandler start failed:", e);
1003
+ });
1004
+ }
1005
+ /**
1006
+ * The per-session sample roll (§3.6). Never per-event: per-event sampling punches
1007
+ * holes that desynchronise the per-view counters by a random factor per view.
1008
+ *
1009
+ * `Math.random()` is deliberate here where `randomHex` refuses it — this decides one
1010
+ * boolean that dies with the session, not an id that persists forever, and a biased
1011
+ * PRNG costs a fraction of a percent of sample accuracy rather than a permanent
1012
+ * identity collision.
1013
+ */
1014
+ rollSample() {
1015
+ return Math.random() < this.sampleRate;
1016
+ }
1017
+ /** §3.3 / §4.7's platform split, from the entry's declared `platform` opt — never a global. */
1018
+ isNativePlatform() {
1019
+ return this.platform === "ios" || this.platform === "android";
1020
+ }
1021
+ generateSessionId() {
1022
+ const t = `session_${Date.now()}_${p(16)}`;
1023
+ return this.platform ? `${t}_${this.platform}` : t;
1024
+ }
1025
+ setSessionId(t) {
1026
+ this.sessionId = t, this.sessionStart = Date.now();
1027
+ }
1028
+ getSessionId() {
1029
+ return this.sessionId;
1030
+ }
1031
+ /**
1032
+ * Freeze the identity a deferred row must report (§4.6). Read **synchronously at the
1033
+ * moment the thing happened**, so a `log()` that lands after a route change or a session
1034
+ * rotation still books the click where it occurred.
1035
+ */
1036
+ snapshot(t) {
1037
+ return {
1038
+ at: t,
1039
+ viewId: this.views.id,
1040
+ sessionId: this.sessionId,
1041
+ sessionStart: this.sessionStart
1042
+ };
1043
+ }
1044
+ /** Collector endpoint, so fetch/XHR adapters can skip self-capturing the SDK's own POST. */
1045
+ getEndpoint() {
1046
+ return this.endpoint;
1047
+ }
1048
+ /**
1049
+ * Sampling stays **session-level** (§6.5): an unsampled session injects no header at
1050
+ * all — not a `flags=00` id. Read by the interceptors, which sit outside `log()`'s own
1051
+ * sampled-out early return and so need the decision directly.
1052
+ */
1053
+ isSampled() {
1054
+ return this.sampled;
1055
+ }
1056
+ // ---------- Session lifecycle (#29) ----------
1057
+ /**
1058
+ * The entry's one call at init (§4.2): resume the durable session when the gap is
1059
+ * inside the idle window, otherwise close the stale one out and start fresh.
1060
+ *
1061
+ * Process death, tab close, hard reload and bfcache restore all land here, and all
1062
+ * four **resume** — which is why a resumed session must not re-emit `session.started`
1063
+ * (§4.1), or `COUNT(session.started)` stops equalling session count.
1064
+ */
1065
+ async resumeOrStartSession() {
1066
+ if (!this.enabled) {
1067
+ this.pendingStart = !0;
1068
+ return;
1069
+ }
1070
+ await this.hydrateAndAnnounce(), await this.emitAppStart();
1071
+ }
1072
+ async hydrateAndAnnounce() {
1073
+ const t = await this.hydrateSession();
1074
+ if (t.kind === "resumed") return;
1075
+ if (t.kind === "expired") {
1076
+ await this.rotateSession(t.reason);
1077
+ return;
1078
+ }
1079
+ if (this.lastActivity === void 0) {
1080
+ await this.startSession("launch");
1081
+ return;
1082
+ }
1083
+ const e = this.expiryReason(Date.now());
1084
+ e && await this.rotateSession(e);
1085
+ }
1086
+ /**
1087
+ * `app.start` (§4.3/§6.2): once per process, a **root** of `trace.root_type = launch`,
1088
+ * carrying the launch root minted in the constructor. Idempotent because the web build
1089
+ * re-runs `resumeOrStartSession()` on a bfcache restore, which is a resumed process and
1090
+ * not a new one.
1091
+ */
1092
+ async emitAppStart() {
1093
+ if (this.appStartEmitted) return;
1094
+ this.appStartEmitted = !0;
1095
+ const t = (s) => {
1096
+ const r = this.jsReadyMs?.();
1097
+ return this.log("app.start", {
1098
+ ...this.trace.launchRootAttributes(),
1099
+ // Cold only by construction: RN's JS context survives backgrounding (§4.3).
1100
+ "app.start.type": "cold",
1101
+ ...s === void 0 ? {} : { "app.start.duration_ms": Math.round(s) },
1102
+ ...r === void 0 ? {} : { "app.start.js_ready_ms": r }
1103
+ });
1104
+ }, e = this.appStartMs?.();
1105
+ if (!e) return t();
1106
+ e.then(t, () => t()).catch((s) => h.warn("app.start failed:", s));
1107
+ }
1108
+ /**
1109
+ * Read the durable record and adopt it. Adoption happens even when the session has
1110
+ * expired: `session.finalized` has to ship under the *old* `session.id` and
1111
+ * `session.start_time` before the fresh one takes over.
1112
+ */
1113
+ async hydrateSession() {
1114
+ const t = await this.store.get(v);
1115
+ if (t.status === "unavailable")
1116
+ return h.warn("Telemetry: session storage unavailable — this session cannot be resumed"), { kind: "nothing" };
1117
+ if (t.status === "miss") return { kind: "nothing" };
1118
+ const e = $(t.value);
1119
+ if (!e) return { kind: "nothing" };
1120
+ this.sessionId = e.id, this.sessionStart = e.start, this.lastActivity = e.lastActivity, this.sessionSequence = e.sequence ?? 0, this.eventSequence = e.eventSequence ?? 0, this.sessionEventCount = e.eventCount ?? 0, this.errorCount = e.errorCount ?? 0, this.spans.restore(e.spans), typeof e.sampled == "boolean" && F(e.sampleRate) && (this.sampled = e.sampled, this.sampleRate = e.sampleRate);
1121
+ const s = this.expiryReason(Date.now());
1122
+ return s ? { kind: "expired", reason: s } : { kind: "resumed" };
1123
+ }
1124
+ /**
1125
+ * Another tab wrote the shared session record (#161, web's `storage` event). Two tabs keep
1126
+ * their own in-memory `lastActivity`, so without this one can idle-expire a session the
1127
+ * other is still using, or both can finalize the same `session.id`.
1128
+ *
1129
+ * Same id: fold in the other tab's progress — activity and the ordinals only ever move
1130
+ * forward, so `max` is the merge. A different id is the other tab's rotation: this tab's
1131
+ * live view is emitted under the session it belongs to, then the successor session is
1132
+ * adopted **silently** — its `session.started` already shipped from the tab that rotated,
1133
+ * and the retired one's `session.finalized` too, which is the whole point.
1134
+ *
1135
+ * Shared core, no platform branch: the entry decides what feeds it.
1136
+ */
1137
+ async adoptSessionRecord(t) {
1138
+ const e = $(t);
1139
+ if (e) {
1140
+ if (e.id === this.sessionId) {
1141
+ this.lastActivity = Math.max(this.lastActivity ?? e.lastActivity, e.lastActivity), this.sessionSequence = Math.max(this.sessionSequence, e.sequence ?? 0), this.eventSequence = Math.max(this.eventSequence, e.eventSequence ?? 0), this.sessionEventCount = Math.max(this.sessionEventCount, e.eventCount ?? 0), this.errorCount = Math.max(this.errorCount, e.errorCount ?? 0);
1142
+ return;
1143
+ }
1144
+ e.start < this.sessionStart || (await this.views.endView(), await this.abandonSpans(), this.sessionId = e.id, this.sessionStart = e.start, this.lastActivity = e.lastActivity, this.sessionSequence = e.sequence ?? 0, this.eventSequence = e.eventSequence ?? 0, this.sessionEventCount = e.eventCount ?? 0, this.errorCount = e.errorCount ?? 0, this.crashPersistedThrough = -1, typeof e.sampled == "boolean" && F(e.sampleRate) && (this.sampled = e.sampled, this.sampleRate = e.sampleRate), this.trace.clear(), await this.views.beginView("session_rotation"));
1145
+ }
1146
+ }
1147
+ /**
1148
+ * Which boundary, if any, the current session has crossed. Idle is checked first:
1149
+ * when a long session has also gone quiet, the reason it ended is that the user left.
1150
+ *
1151
+ * Inert until `lastActivity` is set, so a bare `new Telemetry()` that never started a
1152
+ * session never rotates one.
1153
+ */
1154
+ expiryReason(t) {
1155
+ if (this.lastActivity !== void 0) {
1156
+ if (t - this.lastActivity > xt) return "timeout";
1157
+ if (t - this.sessionStart > Ut) return "max_duration";
1158
+ }
1159
+ }
1160
+ /**
1161
+ * Write the session through the `Store` so the next process can resume it.
1162
+ *
1163
+ * ponytail: one write per event. Web's is a synchronous `localStorage` write; native's
1164
+ * is an AsyncStorage round-trip — debounce here if it ever shows up in a trace.
1165
+ */
1166
+ async persistSession() {
1167
+ if (!this.enabled) return;
1168
+ const t = {
1169
+ id: this.sessionId,
1170
+ start: this.sessionStart,
1171
+ lastActivity: this.lastActivity ?? this.sessionStart,
1172
+ sequence: this.sessionSequence,
1173
+ eventSequence: this.eventSequence,
1174
+ eventCount: this.sessionEventCount,
1175
+ errorCount: this.errorCount,
1176
+ sampled: this.sampled,
1177
+ sampleRate: this.sampleRate,
1178
+ spans: this.spans.toJSON()
1179
+ };
1180
+ (await this.store.set(v, JSON.stringify(t))).status === "unavailable" && h.log("Telemetry: session not persisted (store unavailable)");
1181
+ }
1182
+ /** Emit session.started for the current session. */
1183
+ async startSession(t) {
1184
+ this.lastActivity = Date.now(), await this.persistSession();
1185
+ const e = await this.deviceState?.accessibility().catch(() => ({})) ?? {};
1186
+ await this.log("session.started", {
1187
+ ...e,
1188
+ // Catalogue session.yaml (#179): no `launch` in the enum — a launch start carries no reason.
1189
+ ...t === "launch" ? {} : { "session.reason": t },
1190
+ // §4.1, count only — never the hosts (#99). Ships on every session so a zero is
1191
+ // legible as "nobody opted in" rather than as a stripped header.
1192
+ "sdk.trace_allowlist_size": this.trace.allowlistSize()
1193
+ });
1194
+ }
1195
+ /**
1196
+ * Finalize the current session: journey summary + sdk.error_count, then an immediate flush.
1197
+ *
1198
+ * The backend discards `duration_ms` and `event_count` and derives both (§4.2) — they
1199
+ * stay on the wire because the event survives as the carrier for `session.reason` and
1200
+ * `sdk.error_count`, neither of which is derivable. Duration is stamped from
1201
+ * `lastActivity`, never `now`: a lazily-detected rotation must report 2 minutes of use,
1202
+ * not the 6 idle hours that followed it.
1203
+ */
1204
+ async finalizeSession(t) {
1205
+ await this.abandonSpans(), await this.log("session.finalized", {
1206
+ "session.duration_ms": Math.max(0, (this.lastActivity ?? this.sessionStart) - this.sessionStart),
1207
+ "session.event_count": this.sessionEventCount,
1208
+ "sdk.error_count": this.errorCount,
1209
+ "session.reason": t
1210
+ }), await this.flush();
1211
+ }
1212
+ /** Every span frozen to the session being left ships `abandoned` under it — before the switch. */
1213
+ async abandonSpans() {
1214
+ this.finalizing = !0;
1215
+ try {
1216
+ for (const t of this.spans.takeSession(this.sessionId))
1217
+ await this.emitTask(t, "abandoned", void 0, Math.max(t.start, this.lastActivity ?? t.start));
1218
+ } finally {
1219
+ this.finalizing = !1;
1220
+ }
1221
+ }
1222
+ /** Begin a fresh session: new id/start, reset per-session counters, emit session.started. */
1223
+ async newSession(t) {
1224
+ this.sessionId = this.generateSessionId(), this.sessionStart = Date.now(), this.sessionSequence = 0, this.eventSequence = 0, this.crashPersistedThrough = -1, this.sessionEventCount = 0, this.errorCount = 0, this.sampleRate = this.configuredSampleRate, this.sampled = this.rollSample(), this.appStartEmitted ? this.trace.clear() : this.trace.restartLaunchRoot(), await this.views.beginView("session_rotation"), await this.startSession(t);
1225
+ }
1226
+ // ---------- Manual spans (#164) ----------
1227
+ /**
1228
+ * Open a manual span — **synchronously**, so the trace keys, `view.id` and `session.id`
1229
+ * freeze at the call (§3.1). Inert (`undefined`, reported through `debug()`) for a blank
1230
+ * name or past 32 open spans; never throws. Refreshes `lastActivity` but is not an
1231
+ * action: `view.action_count` counts `ui.interaction` only.
1232
+ *
1233
+ * On a session that has already expired the freeze waits for the rotation the start
1234
+ * itself triggers, so a journey begun after a long idle belongs to the new session
1235
+ * rather than being `abandoned` by the very next row.
1236
+ */
1237
+ startSpan(t, e, s = Date.now()) {
1238
+ if (!this.enabled) return;
1239
+ const r = y(t);
1240
+ if (!r) {
1241
+ h.warn("startSpan: blank name — span is inert");
1242
+ return;
1243
+ }
1244
+ const n = this.spans.start(r, s, C(e));
1245
+ if (!n) {
1246
+ h.warn(`startSpan: ${r} — more than 32 open spans, span is inert`);
1247
+ return;
1248
+ }
1249
+ const a = () => {
1250
+ n.keys = this.trace.manualSpan(s), n.viewId = this.views.id, n.sessionId = this.sessionId, n.sessionStart = this.sessionStart, this.lastActivity = Math.max(this.lastActivity ?? s, s), this.persistSession().catch((c) => h.warn("startSpan: persist failed:", c));
1251
+ }, o = this.expiryReason(s);
1252
+ return o ? n.ready = this.rotateSession(o).catch((c) => h.warn("startSpan: rotation failed:", c)).then(() => {
1253
+ this.spans.has(n) && a();
1254
+ }) : a(), n;
1255
+ }
1256
+ /**
1257
+ * Close a span by name and emit its one `task.complete`. An unknown or already-closed
1258
+ * name is a no-op. With `only`, the close is a handle's, and a superseded handle cannot
1259
+ * close the span that replaced it.
1260
+ */
1261
+ async endSpan(t, e = "completed", s, r = Date.now(), n, a) {
1262
+ const o = y(t), c = o === void 0 ? void 0 : this.spans.take(o, n);
1263
+ if (!c) {
1264
+ h.log(`endSpan: no open span named ${String(t)}`);
1265
+ return;
1266
+ }
1267
+ await c.ready, await this.emitTask(c, e, C(s), r, e === "failed" ? y(a) : void 0);
1268
+ }
1269
+ async emitTask(t, e, s, r, n) {
1270
+ !t.keys || !t.viewId || !t.sessionId || t.sessionStart === void 0 || await this.log("task.complete", {
1271
+ ...t.attrs,
1272
+ ...s,
1273
+ ...t.keys,
1274
+ "task.name": t.name,
1275
+ "task.outcome": e,
1276
+ ...n === void 0 ? {} : { "task.failure_reason": n },
1277
+ // On root *and* child — the flagged §6.3 exception: a declared end is not
1278
+ // derivable from children, so a root's width cannot be left to the server.
1279
+ "span.duration_ms": Math.max(0, r - t.start)
1280
+ }, { at: r, viewId: t.viewId, sessionId: t.sessionId, sessionStart: t.sessionStart });
1281
+ }
1282
+ /** Boundary rotation: finalize the old session then start a fresh one (the pair). */
1283
+ async rotateSession(t) {
1284
+ await this.views.endView(), await this.finalizeSession(t), await this.newSession(t);
1285
+ }
1286
+ /** Truncated at source (§3.2): the collector caps at 255 and we must not be the one over. */
1287
+ setUserId(t) {
1288
+ this.userId = t ? t.slice(0, $t) : void 0;
1289
+ }
1290
+ getUserId() {
1291
+ return this.userId;
1292
+ }
1293
+ /**
1294
+ * The SDK-owned `device.id` (§3.2/§3.3): self-minted, written through the `Store`,
1295
+ * uninstall-scoped, stable across process restarts, and never rotated by login,
1296
+ * logout or a profile clear.
1297
+ *
1298
+ * The platform suffix is the entry's (ios|android|web), not the device-info adapter's:
1299
+ * this id is persisted forever, so it must not depend on a call that can throw on first run.
1300
+ *
1301
+ * `getUniqueId()` is deliberately not used — it already carries two lifetimes on RN
1302
+ * alone (ANDROID_ID survives reinstall, identifierForVendor does not), so one identity
1303
+ * column would mean two things.
1304
+ *
1305
+ * When the Store reports `unavailable` — incognito, a partitioned iframe, ITP
1306
+ * eviction, a full disk — the id lives for one process only and `device.id_ephemeral`
1307
+ * rides the Context block to say so, because that population is otherwise
1308
+ * indistinguishable from real installs and reads as traffic growth.
1309
+ */
1310
+ async getDeviceId() {
1311
+ return this.deviceIdPromise ??= (async () => {
1312
+ const t = await this.store.get(A);
1313
+ if (t.status === "hit") return t.value;
1314
+ const e = this.platform ? `_${this.platform}` : "", s = `device_${Date.now()}_${p(16)}${e}`, r = await this.store.set(A, s);
1315
+ return this.deviceIdEphemeral = t.status === "unavailable" || r.status === "unavailable", s;
1316
+ })(), this.deviceIdPromise;
1317
+ }
1318
+ // ---------- User Profile Management ----------
1319
+ /**
1320
+ * Set complete user profile information
1321
+ */
1322
+ setUserProfile(t) {
1323
+ const e = Date.now(), s = !this.userProfile || t.userId && t.userId !== this.userProfile.userId;
1324
+ this.userProfile = {
1325
+ ...this.userProfile,
1326
+ ...t,
1327
+ updatedAt: e,
1328
+ ...s && { createdAt: e }
1329
+ }, t.userId ? (this.setUserId(t.userId), this.userProfile.userId = this.userId) : this.userProfile && !this.userProfile.userId && (this.userProfile.userId = this.userId), h.log("Telemetry: User profile updated", this.userProfile);
1330
+ }
1331
+ /**
1332
+ * EdgeRum-style identify(): record the host-app profile and emit the one event that
1333
+ * carries it — `user.profile.update` (§4.10, #107). The PII is no longer on the
1334
+ * Context block of every event.
1335
+ *
1336
+ * `userId` is optional and new in v4: the one call that sends a profile should also
1337
+ * set the key that profile attaches to, since `user.id` is consumer-supplied (§3.2)
1338
+ * and an unkeyed profile has nothing to upsert on. Omitting it leaves `user.id`
1339
+ * exactly as it was — identify never mints one.
1340
+ */
1341
+ async identify(t) {
1342
+ t.userId !== void 0 && this.setUserId(t.userId), this.setUserProfile({
1343
+ ...t.name !== void 0 ? { fullName: t.name } : {},
1344
+ ...t.email !== void 0 ? { email: t.email } : {},
1345
+ ...t.phone !== void 0 ? { phone: t.phone } : {},
1346
+ ...t.avatar !== void 0 ? { avatar: t.avatar } : {},
1347
+ ...t.customAttributes !== void 0 ? { customAttributes: t.customAttributes } : {}
1348
+ }), await this.log("user.profile.update", At(this.userProfile));
1349
+ }
1350
+ /**
1351
+ * Set user details with individual parameters
1352
+ */
1353
+ setUserDetails(t) {
1354
+ this.setUserProfile(t);
1355
+ }
1356
+ /**
1357
+ * Update specific user profile fields
1358
+ */
1359
+ updateUserProfile(t) {
1360
+ if (!this.userProfile) {
1361
+ this.setUserProfile(t);
1362
+ return;
1363
+ }
1364
+ this.userProfile = {
1365
+ ...this.userProfile,
1366
+ ...t,
1367
+ updatedAt: Date.now()
1368
+ }, h.log("Telemetry: User profile updated", this.userProfile);
1369
+ }
1370
+ /**
1371
+ * Get current user profile
1372
+ */
1373
+ getUserProfile() {
1374
+ return this.userProfile;
1375
+ }
1376
+ /**
1377
+ * Clear user profile data
1378
+ */
1379
+ clearUserProfile() {
1380
+ this.userProfile = void 0, this.userId = void 0, h.log("Telemetry: User profile cleared");
1381
+ }
1382
+ /**
1383
+ * Set user name (convenience method)
1384
+ */
1385
+ setUserName(t, e, s) {
1386
+ this.setUserProfile({
1387
+ fullName: t,
1388
+ firstName: e,
1389
+ lastName: s
1390
+ });
1391
+ }
1392
+ /**
1393
+ * Set user contact info (convenience method)
1394
+ */
1395
+ setUserContact(t, e) {
1396
+ this.setUserProfile({
1397
+ email: t,
1398
+ phone: e
1399
+ });
1400
+ }
1401
+ // ---------- Logging APIs ----------
1402
+ /**
1403
+ * Log a named event. Keeps existing signature compatibility.
1404
+ * Automatically attaches userId and sessionId to every queued event.
1405
+ */
1406
+ async log(t, e, s) {
1407
+ if (!this.enabled) return;
1408
+ this.eventCount++;
1409
+ let r = !1, n = !1;
1410
+ const a = Kt.has(t);
1411
+ if (a) {
1412
+ const o = this.expiryReason(Date.now());
1413
+ o && await this.rotateSession(o);
1414
+ } else if (!t.startsWith("session.") && t !== "view" && t !== "screen.load" && !this.finalizing) {
1415
+ const o = Date.now(), c = this.expiryReason(o);
1416
+ c && await this.rotateSession(c), this.lastActivity = o, this.sessionEventCount++, k(t) && this.errorCount++, r = !0;
1417
+ }
1418
+ if (this.sampled) {
1419
+ const o = Lt.has(t), c = o ? t : "custom.event", d = await this.collectContext(e);
1420
+ o || (d["event.name"] = t), Bt.has(c) && Object.assign(d, this.trace.annotate()), (c === "app.crash" || c === "app.hang") && (d["error.breadcrumbs"] = this.breadcrumbs.toJSON()), (c === "app.crash" || c === "app.error" || c === "app.hang") && Object.assign(d, this.deviceState?.battery?.()), c === "app.crash" ? n = !0 : a || this.breadcrumbs.add({ name: c, timestamp: (/* @__PURE__ */ new Date()).toISOString() }), k(c) ? this.views.countError() : c === "ui.interaction" && this.views.countAction(), s && (d["view.id"] = s.viewId, d["view.name"] = this.views.nameOf(s.viewId), d["session.id"] = s.sessionId, d["session.start_time"] = new Date(s.sessionStart).toISOString()), this.enqueue({
1421
+ type: "event",
1422
+ eventName: c,
1423
+ timestamp: new Date(s?.at ?? Date.now()).toISOString(),
1424
+ attributes: d
1425
+ }), h.log("Telemetry queued event:", t, "Queue size:", this.queue.length), h.log("Event attributes:", d);
1426
+ }
1427
+ r && await this.persistSession(), n ? await this.flushCrash() : this.queue.length >= this.batchSize && this.flush();
1428
+ }
1429
+ /** §2.5 4xx: drop the batch, book it, and tell a dev once — it is usually a wrong apiKey. */
1430
+ reject(t, e) {
1431
+ this.recordDrop("rejected", e), g() && !V && (V = !0, console.warn(`edge-telemetry: the collector rejected a batch with HTTP ${u(t)} — dropped, not retried. Check the apiKey and endpoint. (Shown once, in dev only.)`));
1432
+ }
1433
+ /** §2.5 429: halt the drain until `X-RateLimit-Reset`, 1 s when the header is absent. */
1434
+ holdFor(t) {
1435
+ const e = t?.resetAt;
1436
+ this.holdUntil = typeof e == "number" ? e : Date.now() + Ft;
1437
+ }
1438
+ /**
1439
+ * The crash path (§2 / §9.4): persist the whole queue, then send **one** batch reordered
1440
+ * so the crash rides in it. Not a drain — a dying process gets one round trip.
1441
+ *
1442
+ * ⚠ The web/native asymmetry is real and is not fixed here. On web the `Store` is
1443
+ * synchronous `localStorage`, so the persist has *landed* by the time the next line runs
1444
+ * and the loss window closes. On native it is an AsyncStorage round-trip that a SIGKILL
1445
+ * can outrun, so the window only narrows. Awaiting harder does not change that; the
1446
+ * asymmetry is the `Store` port's whole point (`core/store.ts`).
1447
+ *
1448
+ * The persisted copy is a safety copy, not a handoff: the queue is left intact, because
1449
+ * an `app.crash` is not always fatal — `window.onerror` fires and the page keeps running
1450
+ * — and the process usually lives on. A successful send therefore
1451
+ * leaves a duplicate on disk to replay next launch — which is what `event.sequence` and
1452
+ * the backend's `(session_id, event_sequence)` dedup exist for (§2.4).
1453
+ *
1454
+ * *One* duplicate. Each row is written at most once by this path, watermarked on
1455
+ * `event.sequence`: a chatty app crash-flushes often, and re-persisting the whole queue
1456
+ * each time would fill the store with copies of
1457
+ * its own backlog and book `store_full` drops that are not loss — corrupting the very
1458
+ * counter this change adds.
1459
+ */
1460
+ async flushCrash() {
1461
+ if (!this.enabled || !this.sender || this.queue.length === 0) return;
1462
+ const t = (r) => r.eventName === "app.crash";
1463
+ this.queue = [...this.queue.filter(t), ...this.queue.filter((r) => !t(r))];
1464
+ const e = this.queue.filter((r) => b(r) > this.crashPersistedThrough);
1465
+ if (e.length > 0 && this.sender.onFailure)
1466
+ try {
1467
+ this.recordDrop("store_full", await this.sender.onFailure(e)), this.crashPersistedThrough = Math.max(this.crashPersistedThrough, ...e.map(b));
1468
+ } catch (r) {
1469
+ h.warn("Telemetry: crash-path persist failed:", r);
1470
+ }
1471
+ const s = this.queue.splice(0, this.batchSize);
1472
+ try {
1473
+ await this.sender.send(s), await this.ackBatch();
1474
+ } catch (r) {
1475
+ if (h.warn("Telemetry: crash-path send failed:", r), _(r)) {
1476
+ this.reject(r, s.length);
1477
+ return;
1478
+ }
1479
+ u(r) === 429 && this.holdFor(r);
1480
+ const n = s.filter((a) => b(a) > this.crashPersistedThrough);
1481
+ n.length > 0 && this.queue.unshift(...n);
1482
+ }
1483
+ }
1484
+ /**
1485
+ * Build the v3 Context block that rides on every event AND metric: the flattened
1486
+ * device/network snapshot, the caller's data, identity + session + sdk fields, and the
1487
+ * user profile. Shared by log() and logMetric() so both carry the identical iOS-clean set.
1488
+ */
1489
+ async collectContext(t) {
1490
+ let e = {}, s = {};
1491
+ try {
1492
+ e = await this.deviceInfoHandler?.collect() || {};
1493
+ } catch (a) {
1494
+ h.warn("Telemetry: failed to fetch device info", a);
1495
+ }
1496
+ try {
1497
+ s = await this.networkInfoHandler?.collect() || {};
1498
+ } catch (a) {
1499
+ h.warn("Telemetry: failed to fetch network info", a);
1500
+ }
1501
+ const r = await this.getDeviceId();
1502
+ return {
1503
+ // deviceInfo already namespaces its own keys (app.*, device.*) — flatten flat
1504
+ ...this.flattenWithPrefix("", e),
1505
+ ...this.flattenWithPrefix("network", s),
1506
+ ...this.flattenWithPrefix("", t || {}),
1507
+ // Identity keys land after caller data: `data` may override app./device./network.*
1508
+ // but must never override these (§3.3).
1509
+ // With the identity keys, not with deviceInfo's `app.*`: it is the symbolication
1510
+ // join key, so a stray `log()` payload must not be able to shift which map a
1511
+ // crash resolves against.
1512
+ ...this.buildId ? { "app.build_id": this.buildId } : {},
1513
+ "device.id": r,
1514
+ ...this.deviceIdEphemeral ? { "device.id_ephemeral": !0 } : {},
1515
+ // Omitted entirely on anonymous traffic (§3.2) — no "", no placeholder.
1516
+ ...this.userId ? { "user.id": this.userId } : {},
1517
+ // Denormalized onto every row (§4.5) so "errors by screen" needs no join. The id
1518
+ // is the join key; the name is the view's current best, resolved here at log time
1519
+ // by lookup on that id, so a row can never carry a name that disagrees with it.
1520
+ "view.id": this.views.id,
1521
+ "view.name": this.views.name,
1522
+ "session.id": this.sessionId,
1523
+ "session.start_time": new Date(this.sessionStart).toISOString(),
1524
+ "session.sequence": this.sessionSequence,
1525
+ // Extrapolation is arithmetic when the rate is on the row: it survives a
1526
+ // consumer retuning mid-quarter, which config-in-a-spreadsheet does not.
1527
+ "session.sample_rate": this.sampleRate,
1528
+ // Monotonic and always present; the reason stays omitted until there is one,
1529
+ // so `sdk.drop_reason IS NOT NULL` is a usable filter for "this install lost data".
1530
+ "sdk.events_dropped": this.eventsDropped,
1531
+ ...this.dropReason ? { "sdk.drop_reason": this.dropReason } : {},
1532
+ "sdk.hook_dropped": this.hookDropped,
1533
+ "sdk.hook_failed": this.hookFailed,
1534
+ "sdk.platform": qt(this.platform),
1535
+ "sdk.version": this.sdkVersion
1536
+ };
1537
+ }
1538
+ /**
1539
+ * Emit a metric on the v3 `type:"metric"` path: { type, metricName, value, timestamp, attributes }.
1540
+ * Carries the same Context block as events. Metrics are samples, not user actions, so they
1541
+ * don't extend the breadcrumb trail and don't count as session activity — a periodic sampler
1542
+ * (memory/frames) must not keep a session alive and defeat the 30-min idle rotation.
1543
+ */
1544
+ async logMetric(t, e, s, r, n) {
1545
+ if (!this.enabled) return;
1546
+ this.eventCount++;
1547
+ const a = this.expiryReason(Date.now());
1548
+ if (a && await this.rotateSession(a), !this.sampled) return;
1549
+ const o = await this.collectContext(s), c = z[t] ?? r;
1550
+ c && (o["metric.unit"] = c), n !== void 0 && (o["metric.name"] = n), this.enqueue({
1551
+ type: "metric",
1552
+ metricName: t,
1553
+ value: e,
1554
+ timestamp: (/* @__PURE__ */ new Date()).toISOString(),
1555
+ attributes: o
1556
+ }), this.queue.length >= this.batchSize && this.flush();
1557
+ }
1558
+ /**
1559
+ * The single enqueue point: neither the sample decision nor `beforeSend` can be
1560
+ * bypassed by a future emit path, and the hook runs *before* the queue — which is
1561
+ * what keeps scrubbed fields off disk when a send fails and the batch is persisted.
1562
+ *
1563
+ * The sample check is repeated by log()/logMetric() ahead of `collectContext()`, so
1564
+ * a sampled-out session does no work per event; this one is the backstop that makes
1565
+ * the guarantee structural rather than a convention two call sites happen to follow.
1566
+ *
1567
+ * The two counters are separate on purpose: "my volume is down 40%" has to
1568
+ * distinguish *my rule is too broad* from *my rule is crashing*, and one merged
1569
+ * counter answers neither.
1570
+ */
1571
+ enqueue(t) {
1572
+ if (!this.sampled || !this.enabled) return;
1573
+ let e = t;
1574
+ if (this.beforeSend) {
1575
+ const s = Mt(t, this.beforeSend);
1576
+ if (s.kind === "failed") {
1577
+ this.hookFailed++;
1578
+ return;
1579
+ }
1580
+ if (s.kind === "dropped") {
1581
+ this.hookDropped++;
1582
+ return;
1583
+ }
1584
+ e = s.event;
1585
+ }
1586
+ (e.attributes ??= {})["event.sequence"] = this.eventSequence++, this.queue.push(e), this.capQueue();
1587
+ }
1588
+ /**
1589
+ * Hold the in-memory queue at its cap (§9.4), booking what it costs.
1590
+ *
1591
+ * The count lands on the *next* event's Context block, not this one's — `collectContext()`
1592
+ * has already run by the time we get here. That is §3.7's stated behaviour, not a bug.
1593
+ */
1594
+ capQueue() {
1595
+ for (; this.queue.length > jt; )
1596
+ this.queue.splice(w(this.queue), 1), this.recordDrop("queue_full");
1597
+ }
1598
+ /**
1599
+ * Book dropped rows against the monotonic counter and the reason that shipped last.
1600
+ * Takes `Sender.onFailure`'s return shape as-is — a sender with no cap returns nothing.
1601
+ */
1602
+ recordDrop(t, e = 1) {
1603
+ !e || e <= 0 || (this.eventsDropped += e, this.dropReason = t);
1604
+ }
1605
+ flattenWithPrefix(t, e, s = 0) {
1606
+ const r = {};
1607
+ for (const n in e) {
1608
+ if (!Object.prototype.hasOwnProperty.call(e, n)) continue;
1609
+ const a = e[n], o = t ? `${t}.${n}` : n;
1610
+ if (a !== void 0)
1611
+ if (typeof a == "object" && a !== null && !Array.isArray(a) && s < Ht)
1612
+ Object.assign(r, this.flattenWithPrefix(o, a, s + 1));
1613
+ else if (typeof a == "object" && a !== null) {
1614
+ const c = E(a);
1615
+ c !== void 0 && (r[o] = c);
1616
+ } else
1617
+ r[o] = a;
1618
+ }
1619
+ return r;
1620
+ }
1621
+ /**
1622
+ * The public metric path (#167), sent as `custom.metric` with the host's name in
1623
+ * `metric.name` (processor #41). The SDK's own names stay **reserved**, and no cap on distinct
1624
+ * names. A non-finite value is dropped, never shipped as a fabricated number. `unit`
1625
+ * becomes `metric.unit`, stamped after `data` so an attribute cannot mislabel it.
1626
+ */
1627
+ recordMetric(t, e, s, r) {
1628
+ if (typeof t != "string" || t.trim() === "") {
1629
+ h.warn("recordMetric: blank name — dropped");
1630
+ return;
1631
+ }
1632
+ if (Object.prototype.hasOwnProperty.call(z, t)) {
1633
+ h.warn(`recordMetric: ${t} is reserved by the SDK — dropped`);
1634
+ return;
1635
+ }
1636
+ if (typeof e != "number" || !Number.isFinite(e)) {
1637
+ h.warn(`recordMetric: ${t} value is not finite — dropped`);
1638
+ return;
1639
+ }
1640
+ const n = typeof r?.unit == "string" && r.unit !== "" ? r.unit : void 0;
1641
+ return this.logMetric("custom.metric", e, s, n, t);
1642
+ }
1643
+ // ---------- Flush / Persistence ----------
1644
+ /**
1645
+ * §2.4's draining flush (#162): batches go **sequentially** until the queue is empty,
1646
+ * stopping at the first failure, at most `DRAIN_MAX_BATCHES` per call and paced to the
1647
+ * collector's 10 req/s burst. Sequential because parallel batches are how a cold backend
1648
+ * gets stampeded by a replay. Retry + backoff live in the Sender (`sendWithRetry`).
1649
+ *
1650
+ * A call landing while a drain is in flight joins it rather than starting a second loop:
1651
+ * the interval and the batch-full trigger both fire `flush()` unawaited, and two loops
1652
+ * would interleave their sends and break the pacing.
1653
+ */
1654
+ flush() {
1655
+ return this.draining ??= this.drain().finally(() => {
1656
+ this.draining = void 0;
1657
+ });
1658
+ }
1659
+ async drain() {
1660
+ for (let t = 0; t < Vt; t++) {
1661
+ if (t > 0 && this.queue.length > 0 && await new Promise((s) => setTimeout(s, zt)), !this.sender || this.queue.length === 0 || Date.now() < this.holdUntil) return;
1662
+ const e = this.queue.splice(0, this.batchSize);
1663
+ try {
1664
+ await this.sender.send(e), await this.ackBatch();
1665
+ } catch (s) {
1666
+ throw await this.onSendFailure(e, s), h.error("Telemetry flush failed:", s), s;
1667
+ }
1668
+ }
1669
+ }
1670
+ /**
1671
+ * §2.5's status table, for a batch the sender gave up on.
1672
+ *
1673
+ * | 4xx | dropped — no persist — booked `rejected`, one `__DEV__` warning per process |
1674
+ * | 429 | requeued at the front; the drain halts until `X-RateLimit-Reset` |
1675
+ * | 5xx / network | persisted through the sender, or requeued when it cannot persist |
1676
+ *
1677
+ * A wrong credential is the realistic 4xx, and persisting it would make it terminal: the
1678
+ * drain halts at batch 1 on every launch forever while the store fills and evicts.
1679
+ */
1680
+ async onSendFailure(t, e) {
1681
+ if (this.enabled) {
1682
+ if (_(e)) {
1683
+ this.reject(e, t.length);
1684
+ return;
1685
+ }
1686
+ if (u(e) === 429) {
1687
+ this.queue.unshift(...t), this.holdFor(e);
1688
+ return;
1689
+ }
1690
+ if (this.sender?.onFailure)
1691
+ try {
1692
+ this.recordDrop("store_full", await this.sender.onFailure(t));
1693
+ } catch (s) {
1694
+ this.queue.unshift(...t), h.warn("Sender.onFailure failed, requeued events:", s);
1695
+ }
1696
+ else
1697
+ this.queue.unshift(...t);
1698
+ }
1699
+ }
1700
+ /**
1701
+ * Book an acknowledged (2xx) batch. `session.sequence` orders a session's batches (#29),
1702
+ * and it is persisted because a resumed session restarting at 0 would emit duplicate
1703
+ * (session.id, session.sequence) pairs and stop ordering anything (#92).
1704
+ */
1705
+ async ackBatch() {
1706
+ this.sessionSequence++, await this.persistSession();
1707
+ }
1708
+ getQueue() {
1709
+ return [...this.queue];
1710
+ }
1711
+ async shutdown() {
1712
+ this.intervalId && clearInterval(this.intervalId), this.memoryHandler?.stop?.(), this.webVitals?.stop(), this.hangs?.stop(), this.deviceState?.stop?.(), await this.flush();
1713
+ }
1714
+ // Expose some internal counters (optional)
1715
+ getEventCount() {
1716
+ return this.eventCount;
1717
+ }
1718
+ /**
1719
+ * A route change (§4.5): rung 2 of the name ladder. The two deprecated feeds it used to
1720
+ * emit alongside — `navigation` and `screen.duration` — are gone in v5 (#163).
1721
+ */
1722
+ async recordRouteChange(t) {
1723
+ await this.enterView(t, "route");
1724
+ }
1725
+ /**
1726
+ * Feed the name ladder (§4.5.1). Rungs 1 and 2 arrive unnormalized; rung 3's caller
1727
+ * normalizes before calling. Whether this re-stamps the current view or mints a
1728
+ * successor is the ladder's decision, not the caller's.
1729
+ */
1730
+ async enterView(t, e) {
1731
+ await this.views.navigate(t, e);
1732
+ }
1733
+ }
1734
+ const ne = /* @__PURE__ */ Object.freeze(/* @__PURE__ */ Object.defineProperty({
1735
+ __proto__: null,
1736
+ DEVICE_ID_KEY: A,
1737
+ SESSION_KEY: v,
1738
+ Telemetry: Wt,
1739
+ evictIndex: w,
1740
+ isErrorName: k
1741
+ }, Symbol.toStringTag, { value: "Module" }));
1742
+ export {
1743
+ ee as D,
1744
+ mt as F,
1745
+ Zt as a,
1746
+ Qt as b,
1747
+ se as d,
1748
+ ie as e,
1749
+ re as g,
1750
+ Gt as r,
1751
+ te as s,
1752
+ ne as t
1753
+ };
1754
+ //# sourceMappingURL=telemetry-60sfWkh0.js.map