failproofai 1.0.12-beta.2 → 1.0.13-beta.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 (374) hide show
  1. package/.next/standalone/.next/BUILD_ID +1 -1
  2. package/.next/standalone/.next/build-manifest.json +13 -13
  3. package/.next/standalone/.next/prerender-manifest.json +3 -3
  4. package/.next/standalone/.next/required-server-files.json +1 -1
  5. package/.next/standalone/.next/server/app/_global-error/page/build-manifest.json +2 -2
  6. package/.next/standalone/.next/server/app/_global-error/page/server-reference-manifest.json +1 -1
  7. package/.next/standalone/.next/server/app/_global-error/page.js +2 -1
  8. package/.next/standalone/.next/server/app/_global-error/page.js.nft.json +1 -1
  9. package/.next/standalone/.next/server/app/_global-error/page_client-reference-manifest.js +1 -1
  10. package/.next/standalone/.next/server/app/_global-error.html +1 -1
  11. package/.next/standalone/.next/server/app/_global-error.rsc +2 -2
  12. package/.next/standalone/.next/server/app/_global-error.segments/__PAGE__.segment.rsc +2 -2
  13. package/.next/standalone/.next/server/app/_global-error.segments/_full.segment.rsc +2 -2
  14. package/.next/standalone/.next/server/app/_global-error.segments/_tree.segment.rsc +1 -1
  15. package/.next/standalone/.next/server/app/_not-found/page/build-manifest.json +2 -2
  16. package/.next/standalone/.next/server/app/_not-found/page/server-reference-manifest.json +1 -1
  17. package/.next/standalone/.next/server/app/_not-found/page.js +4 -3
  18. package/.next/standalone/.next/server/app/_not-found/page.js.nft.json +1 -1
  19. package/.next/standalone/.next/server/app/_not-found/page_client-reference-manifest.js +1 -1
  20. package/.next/standalone/.next/server/app/_not-found.html +1 -1
  21. package/.next/standalone/.next/server/app/_not-found.rsc +3 -3
  22. package/.next/standalone/.next/server/app/_not-found.segments/_full.segment.rsc +3 -3
  23. package/.next/standalone/.next/server/app/_not-found.segments/_not-found/__PAGE__.segment.rsc +2 -2
  24. package/.next/standalone/.next/server/app/_not-found.segments/_tree.segment.rsc +1 -1
  25. package/.next/standalone/.next/server/app/api/audit/invite/route.js +6 -5
  26. package/.next/standalone/.next/server/app/api/audit/invite/route.js.nft.json +1 -1
  27. package/.next/standalone/.next/server/app/api/audit/run/route.js +27 -26
  28. package/.next/standalone/.next/server/app/api/audit/run/route.js.nft.json +1 -1
  29. package/.next/standalone/.next/server/app/api/audit/status/route.js +4 -3
  30. package/.next/standalone/.next/server/app/api/audit/status/route.js.nft.json +1 -1
  31. package/.next/standalone/.next/server/app/api/auth/login-request/route.js +6 -5
  32. package/.next/standalone/.next/server/app/api/auth/login-request/route.js.nft.json +1 -1
  33. package/.next/standalone/.next/server/app/api/auth/login-verify/route.js +6 -5
  34. package/.next/standalone/.next/server/app/api/auth/login-verify/route.js.nft.json +1 -1
  35. package/.next/standalone/.next/server/app/api/auth/logout/route.js +6 -5
  36. package/.next/standalone/.next/server/app/api/auth/logout/route.js.nft.json +1 -1
  37. package/.next/standalone/.next/server/app/api/auth/status/route.js +6 -5
  38. package/.next/standalone/.next/server/app/api/auth/status/route.js.nft.json +1 -1
  39. package/.next/standalone/.next/server/app/api/download/[project]/[session]/route.js +4 -3
  40. package/.next/standalone/.next/server/app/api/download/[project]/[session]/route.js.nft.json +1 -1
  41. package/.next/standalone/.next/server/app/audit/page/build-manifest.json +2 -2
  42. package/.next/standalone/.next/server/app/audit/page/server-reference-manifest.json +2 -2
  43. package/.next/standalone/.next/server/app/audit/page.js +7 -6
  44. package/.next/standalone/.next/server/app/audit/page.js.nft.json +1 -1
  45. package/.next/standalone/.next/server/app/audit/page_client-reference-manifest.js +1 -1
  46. package/.next/standalone/.next/server/app/index.html +1 -1
  47. package/.next/standalone/.next/server/app/index.rsc +3 -3
  48. package/.next/standalone/.next/server/app/index.segments/__PAGE__.segment.rsc +2 -2
  49. package/.next/standalone/.next/server/app/index.segments/_full.segment.rsc +3 -3
  50. package/.next/standalone/.next/server/app/index.segments/_tree.segment.rsc +1 -1
  51. package/.next/standalone/.next/server/app/page/build-manifest.json +2 -2
  52. package/.next/standalone/.next/server/app/page/server-reference-manifest.json +1 -1
  53. package/.next/standalone/.next/server/app/page.js +6 -5
  54. package/.next/standalone/.next/server/app/page.js.nft.json +1 -1
  55. package/.next/standalone/.next/server/app/page_client-reference-manifest.js +1 -1
  56. package/.next/standalone/.next/server/app/policies/page/build-manifest.json +2 -2
  57. package/.next/standalone/.next/server/app/policies/page/server-reference-manifest.json +14 -14
  58. package/.next/standalone/.next/server/app/policies/page.js +5 -4
  59. package/.next/standalone/.next/server/app/policies/page.js.nft.json +1 -1
  60. package/.next/standalone/.next/server/app/policies/page_client-reference-manifest.js +1 -1
  61. package/.next/standalone/.next/server/app/project/[name]/page/build-manifest.json +2 -2
  62. package/.next/standalone/.next/server/app/project/[name]/page/server-reference-manifest.json +1 -1
  63. package/.next/standalone/.next/server/app/project/[name]/page.js +21 -20
  64. package/.next/standalone/.next/server/app/project/[name]/page.js.nft.json +1 -1
  65. package/.next/standalone/.next/server/app/project/[name]/page_client-reference-manifest.js +1 -1
  66. package/.next/standalone/.next/server/app/project/[name]/session/[sessionId]/page/build-manifest.json +2 -2
  67. package/.next/standalone/.next/server/app/project/[name]/session/[sessionId]/page/react-loadable-manifest.json +2 -2
  68. package/.next/standalone/.next/server/app/project/[name]/session/[sessionId]/page/server-reference-manifest.json +2 -2
  69. package/.next/standalone/.next/server/app/project/[name]/session/[sessionId]/page.js +10 -9
  70. package/.next/standalone/.next/server/app/project/[name]/session/[sessionId]/page.js.nft.json +1 -1
  71. package/.next/standalone/.next/server/app/project/[name]/session/[sessionId]/page_client-reference-manifest.js +1 -1
  72. package/.next/standalone/.next/server/app/projects/page/build-manifest.json +2 -2
  73. package/.next/standalone/.next/server/app/projects/page/server-reference-manifest.json +1 -1
  74. package/.next/standalone/.next/server/app/projects/page.js +7 -6
  75. package/.next/standalone/.next/server/app/projects/page.js.nft.json +1 -1
  76. package/.next/standalone/.next/server/app/projects/page_client-reference-manifest.js +1 -1
  77. package/.next/standalone/.next/server/app/settings/page/build-manifest.json +2 -2
  78. package/.next/standalone/.next/server/app/settings/page/server-reference-manifest.json +8 -8
  79. package/.next/standalone/.next/server/app/settings/page.js +6 -5
  80. package/.next/standalone/.next/server/app/settings/page.js.nft.json +1 -1
  81. package/.next/standalone/.next/server/app/settings/page_client-reference-manifest.js +1 -1
  82. package/.next/standalone/.next/server/chunks/{[externals]__0vt9i6fqinjne._.js → [externals]__1h83uo-b1b6-2._.js} +1 -1
  83. package/.next/standalone/.next/server/chunks/[externals]__214wn4wh2x79y._.js +3 -0
  84. package/.next/standalone/.next/server/chunks/{[externals]__1rlxpymm37wel._.js → [root-of-the-server]__031qp1lkow_kc._.js} +2 -2
  85. package/.next/standalone/.next/server/chunks/[root-of-the-server]__038kwryp970nh._.js +3 -0
  86. package/.next/standalone/.next/server/chunks/{[root-of-the-server]__0_hsnj_a2mvl_._.js → [root-of-the-server]__03s1za0hn71yp._.js} +2 -2
  87. package/.next/standalone/.next/server/chunks/{[root-of-the-server]__0wg9dk8x8bnau._.js → [root-of-the-server]__07a0sa6fuw5_b._.js} +2 -2
  88. package/.next/standalone/.next/server/chunks/[root-of-the-server]__08atcie7jzswm._.js +3 -0
  89. package/.next/standalone/.next/server/chunks/[root-of-the-server]__08dchfudh2_4f._.js +1 -1
  90. package/.next/standalone/.next/server/chunks/[root-of-the-server]__0car70pylmvor._.js +3 -0
  91. package/.next/standalone/.next/server/chunks/[root-of-the-server]__0spt0kv8azrpl._.js +1 -1
  92. package/.next/standalone/.next/server/chunks/{[root-of-the-server]__12kq3x-h7t7i1._.js → [root-of-the-server]__0yvyp5b7jmlc4._.js} +2 -2
  93. package/.next/standalone/.next/server/chunks/{[root-of-the-server]__02vous7mpi2xm._.js → [root-of-the-server]__145vo_drnuvas._.js} +2 -2
  94. package/.next/standalone/.next/server/chunks/{[externals]__0h0p9dmv_e7r7._.js → [root-of-the-server]__1a2d0ewycsp6k._.js} +2 -2
  95. package/.next/standalone/.next/server/chunks/{[externals]__1_407huhlmj1m._.js → [root-of-the-server]__1am_1tz0o0aqz._.js} +2 -2
  96. package/.next/standalone/.next/server/chunks/{[root-of-the-server]__03i5o4a840guz._.js → [root-of-the-server]__1gxfzuvpyw30j._.js} +1 -1
  97. package/.next/standalone/.next/server/chunks/[root-of-the-server]__1j6kfp0vzu5rw._.js +3 -0
  98. package/.next/standalone/.next/server/chunks/[root-of-the-server]__1l0ayum_hqqsw._.js +3 -0
  99. package/.next/standalone/.next/server/chunks/[root-of-the-server]__1lh8c0mmhdrbj._.js +3 -0
  100. package/.next/standalone/.next/server/chunks/[root-of-the-server]__1o9rznwc0w7og._.js +3 -0
  101. package/.next/standalone/.next/server/chunks/{[root-of-the-server]__0f_4g-vazrvxv._.js → [root-of-the-server]__1o_622x0fglpr._.js} +1 -1
  102. package/.next/standalone/.next/server/chunks/[root-of-the-server]__1oclamblhzhrf._.js +68 -0
  103. package/.next/standalone/.next/server/chunks/[root-of-the-server]__1v1-l-83czzsr._.js +63 -0
  104. package/.next/standalone/.next/server/chunks/{[root-of-the-server]__1a5zkndjwlc13._.js → [root-of-the-server]__1wwi53kkqhnfi._.js} +1 -1
  105. package/.next/standalone/.next/server/chunks/{_1y590mjzpkbos._.js → _02sa8fcu9_9xo._.js} +2 -2
  106. package/.next/standalone/.next/server/chunks/_0tovk6q0miud6._.js +1 -1
  107. package/.next/standalone/.next/server/chunks/_0trp3ycqv17cl._.js +1 -1
  108. package/.next/standalone/.next/server/chunks/_1-2owkp-1_987._.js +1 -1
  109. package/.next/standalone/.next/server/chunks/_13ltj8a9z92o8._.js +1 -1
  110. package/.next/standalone/.next/server/chunks/_15k37au70vjvg._.js +1 -1
  111. package/.next/standalone/.next/server/chunks/_18rfu4__wjhwb._.js +1 -1
  112. package/.next/standalone/.next/server/chunks/_1ek68lnh2daur._.js +2 -2
  113. package/.next/standalone/.next/server/chunks/_1fz8m31sndkcu._.js +1 -1
  114. package/.next/standalone/.next/server/chunks/_1ogwigfb0163w._.js +1 -1
  115. package/.next/standalone/.next/server/chunks/_1vslkoe35wok6._.js +1 -1
  116. package/.next/standalone/.next/server/chunks/node_modules_@opentelemetry_api_build_esm_index_0oo58a7rymoxh.js +3 -0
  117. package/.next/standalone/.next/server/chunks/node_modules_@opentelemetry_api_build_esm_index_1jp9ij0_ddtgk.js +3 -0
  118. package/.next/standalone/.next/server/chunks/node_modules_posthog-node_dist_entrypoints_index_node_mjs_01r25oigsgz07._.js +2 -2
  119. package/.next/standalone/.next/server/chunks/node_modules_posthog-node_dist_entrypoints_index_node_mjs_09z9-p77cu37y._.js +2 -2
  120. package/.next/standalone/.next/server/chunks/package_json_[json]_cjs_1nxcc4vkpxxu7._.js +1 -1
  121. package/.next/standalone/.next/server/chunks/ssr/{[root-of-the-server]__0ffu2-38y03ic._.js → [root-of-the-server]__021vebe-4il8s._.js} +1 -1
  122. package/.next/standalone/.next/server/chunks/ssr/[root-of-the-server]__075uro8t92s0_._.js +14 -0
  123. package/.next/standalone/.next/server/chunks/ssr/[root-of-the-server]__08ch3staq3ejw._.js +1 -1
  124. package/.next/standalone/.next/server/chunks/ssr/{[externals]__12qr51qgrrt6o._.js → [root-of-the-server]__097i34ct1o88x._.js} +2 -2
  125. package/.next/standalone/.next/server/chunks/ssr/[root-of-the-server]__0alpzjn3450sr._.js +3 -0
  126. package/.next/standalone/.next/server/chunks/ssr/[root-of-the-server]__0aup10z2o8zc1._.js +3 -0
  127. package/.next/standalone/.next/server/chunks/ssr/[root-of-the-server]__0bigvy9xmv2ka._.js +1 -1
  128. package/.next/standalone/.next/server/chunks/ssr/[root-of-the-server]__0bioghlkjf7s7._.js +3 -0
  129. package/.next/standalone/.next/server/chunks/ssr/{[root-of-the-server]__01j58mdcdw0vn._.js → [root-of-the-server]__0ed1zh4scn7-k._.js} +1 -1
  130. package/.next/standalone/.next/server/chunks/ssr/{[root-of-the-server]__0naevg4bcoh54._.js → [root-of-the-server]__0evgy902m9h5e._.js} +2 -2
  131. package/.next/standalone/.next/server/chunks/ssr/[root-of-the-server]__0h86bl2qf0k_o._.js +1 -1
  132. package/.next/standalone/.next/server/chunks/ssr/{[root-of-the-server]__00l2u6j86cb8y._.js → [root-of-the-server]__0mhtkwwx1pxcq._.js} +2 -2
  133. package/.next/standalone/.next/server/chunks/ssr/[root-of-the-server]__0nhm28v58ty9z._.js +3 -0
  134. package/.next/standalone/.next/server/chunks/ssr/[root-of-the-server]__0pia5h3p8re4c._.js +1 -1
  135. package/.next/standalone/.next/server/chunks/ssr/[root-of-the-server]__0vse4qi496ol-._.js +3 -0
  136. package/.next/standalone/.next/server/chunks/ssr/{[root-of-the-server]__17r4zrwanhp6r._.js → [root-of-the-server]__0yb3u36xjy3b9._.js} +1 -1
  137. package/.next/standalone/.next/server/chunks/ssr/{[root-of-the-server]__0g8b0kyorya-t._.js → [root-of-the-server]__0ywj2u6ovfm_5._.js} +1 -1
  138. package/.next/standalone/.next/server/chunks/ssr/[root-of-the-server]__1-ey9fgesfbc0._.js +1 -1
  139. package/.next/standalone/.next/server/chunks/ssr/{[root-of-the-server]__0zn1d4blhd3bu._.js → [root-of-the-server]__10v5cyxvj64j4._.js} +1 -1
  140. package/.next/standalone/.next/server/chunks/ssr/[root-of-the-server]__15usvs-ms-0hf._.js +1 -1
  141. package/.next/standalone/.next/server/chunks/ssr/[root-of-the-server]__16gb3_92zvk5x._.js +1 -1
  142. package/.next/standalone/.next/server/chunks/ssr/[root-of-the-server]__190xwrr5zrfi3._.js +3 -0
  143. package/.next/standalone/.next/server/chunks/ssr/[root-of-the-server]__1avi2kypusyb_._.js +1 -1
  144. package/.next/standalone/.next/server/chunks/ssr/{[root-of-the-server]__1vx7o8ukefudh._.js → [root-of-the-server]__1guwlpkyurdn9._.js} +1 -1
  145. package/.next/standalone/.next/server/chunks/ssr/[root-of-the-server]__1k96jctukf65_._.js +3 -0
  146. package/.next/standalone/.next/server/chunks/ssr/[root-of-the-server]__1r7drlqli-ado._.js +1 -1
  147. package/.next/standalone/.next/server/chunks/ssr/[root-of-the-server]__1sj-wn2jp6va5._.js +3 -0
  148. package/.next/standalone/.next/server/chunks/ssr/[root-of-the-server]__1vofkb2oq7p7e._.js +1 -1
  149. package/.next/standalone/.next/server/chunks/ssr/{[root-of-the-server]__1s2-ck3k3rsoo._.js → [root-of-the-server]__20dt376-socef._.js} +1 -1
  150. package/.next/standalone/.next/server/chunks/ssr/{[root-of-the-server]__1lnfv02ucky7m._.js → [root-of-the-server]__2158020r_amn9._.js} +1 -1
  151. package/.next/standalone/.next/server/chunks/ssr/{_1fw0_nzkae5ao._.js → _0bc4f4quq6w47._.js} +2 -2
  152. package/.next/standalone/.next/server/chunks/ssr/_0bseae9u7g98r._.js +1 -1
  153. package/.next/standalone/.next/server/chunks/ssr/_0eoura3_9gjb-._.js +1 -1
  154. package/.next/standalone/.next/server/chunks/ssr/_0mouhaflye1ro._.js +1 -1
  155. package/.next/standalone/.next/server/chunks/ssr/_0ouu886szh6yj._.js +1 -1
  156. package/.next/standalone/.next/server/chunks/ssr/_0pedwblqdoh58._.js +1 -1
  157. package/.next/standalone/.next/server/chunks/ssr/_1_ozgifqv1ssi._.js +1 -1
  158. package/.next/standalone/.next/server/chunks/ssr/_1djqs9i27e4kg._.js +1 -1
  159. package/.next/standalone/.next/server/chunks/ssr/_20hn4gn87nsjc._.js +1 -1
  160. package/.next/standalone/.next/server/chunks/ssr/_next-internal_server_app_policies_page_actions_1sp2-yo5_vm5f.js +2 -2
  161. package/.next/standalone/.next/server/chunks/ssr/app_actions_get-scheduled-audit_ts_0ei9snixb5fd-._.js +1 -1
  162. package/.next/standalone/.next/server/chunks/ssr/app_audit__components_audit-dashboard_tsx_0p9ud47q0xq5w._.js +1 -1
  163. package/.next/standalone/.next/server/chunks/ssr/app_components_project-list_tsx_1ke6anr0vt64h._.js +1 -1
  164. package/.next/standalone/.next/server/chunks/ssr/app_global-error_tsx_1kp6l3x33jqb6._.js +1 -1
  165. package/.next/standalone/.next/server/chunks/ssr/app_policies_hooks-client_tsx_19dqvpcz0uxur._.js +1 -1
  166. package/.next/standalone/.next/server/chunks/ssr/app_settings_02tf1h47jmhhd._.js +1 -1
  167. package/.next/standalone/.next/server/chunks/ssr/{node_modules_09s4n108bqreq._.js → node_modules_0ptcnmeaxvd_a._.js} +22 -2
  168. package/.next/standalone/.next/server/chunks/ssr/node_modules_@opentelemetry_api_build_esm_index_0ntwr8lzj6p2i.js +3 -0
  169. package/.next/standalone/.next/server/chunks/ssr/{node_modules_html-to-image_es_index_1fv03uigni8s5.js → node_modules_html-to-image_es_index_1jwgv0pf-gy96.js} +1 -1
  170. package/.next/standalone/.next/server/chunks/ssr/node_modules_next_0bz67659f5z-3._.js +32 -0
  171. package/.next/standalone/.next/server/chunks/ssr/node_modules_next_dist_0janj0i6dqko7._.js +3 -3
  172. package/.next/standalone/.next/server/chunks/ssr/node_modules_next_dist_0ocrceo0c9psx._.js +32 -0
  173. package/.next/standalone/.next/server/chunks/ssr/node_modules_next_dist_1alv566ojmz5j._.js +32 -0
  174. package/.next/standalone/.next/server/chunks/ssr/node_modules_next_dist_1khq67j4vo9y4._.js +3 -0
  175. package/.next/standalone/.next/server/chunks/ssr/node_modules_next_dist_shared_lib_0ftnv26hg1lry._.js +3 -0
  176. package/.next/standalone/.next/server/chunks/ssr/node_modules_posthog-node_dist_entrypoints_index_node_mjs_0dagmbznysrc2._.js +1 -1
  177. package/.next/standalone/.next/server/chunks/ssr/node_modules_posthog-node_dist_entrypoints_index_node_mjs_11bnuznb72p7z._.js +2 -2
  178. package/.next/standalone/.next/server/chunks/ssr/package_json_[json]_cjs_013tntikdft59._.js +1 -1
  179. package/.next/standalone/.next/server/middleware-build-manifest.js +13 -13
  180. package/.next/standalone/.next/server/middleware.js +2 -2
  181. package/.next/standalone/.next/server/pages/404.html +1 -1
  182. package/.next/standalone/.next/server/pages/500.html +1 -1
  183. package/.next/standalone/.next/server/preview-props.json +3 -3
  184. package/.next/standalone/.next/server/server-reference-manifest.js +1 -1
  185. package/.next/standalone/.next/server/server-reference-manifest.json +23 -23
  186. package/.next/standalone/.next/static/chunks/0cbom4-ijx_a_.js +1 -0
  187. package/.next/standalone/.next/static/chunks/0u5weo5jdn2s8.js +1 -0
  188. package/.next/standalone/.next/static/chunks/{1c_jf6g5wnslk.js → 18-icoqze51kl.js} +1 -1
  189. package/.next/standalone/.next/static/chunks/2d-u90dt4-8rd.js +6 -0
  190. package/.next/standalone/.next/static/chunks/2n-bzb7pxe7hu.js +1 -0
  191. package/.next/standalone/.next/static/chunks/{2o6d37j425uci.js → 2zc7lg-jq353g.js} +1 -1
  192. package/.next/standalone/.next/static/chunks/{0tbm3vjm62h-2.js → 33djjf12bhcsv.js} +1 -1
  193. package/.next/standalone/.next/static/chunks/{42xptz88mtq3x.js → 38u_i3j5funpi.js} +1 -1
  194. package/.next/standalone/.next/static/chunks/{20py8k1gd_i1m.js → 3symuj7t4js-c.js} +1 -1
  195. package/.next/standalone/.next/static/chunks/{0ay__-d2h1xb5.js → 3vzut6zpdrvtx.js} +1 -1
  196. package/.next/standalone/.next/static/chunks/{063al_q720fkj.js → 3xgxl1s_in776.js} +2 -2
  197. package/.next/standalone/SECURITY.md +20 -4
  198. package/.next/standalone/fp-cloud-cli/CHANGELOG.md +34 -1
  199. package/.next/standalone/fp-cloud-cli/README.md +120 -0
  200. package/.next/standalone/fp-cloud-cli/fp_cli/_version.py +1 -1
  201. package/.next/standalone/fp-cloud-cli/fp_cli/app.py +15 -1
  202. package/.next/standalone/fp-cloud-cli/fp_cli/client.py +198 -7
  203. package/.next/standalone/fp-cloud-cli/fp_cli/cloud_output.py +523 -0
  204. package/.next/standalone/fp-cloud-cli/fp_cli/commands/_cloud.py +45 -0
  205. package/.next/standalone/fp-cloud-cli/fp_cli/commands/_write.py +3 -1
  206. package/.next/standalone/fp-cloud-cli/fp_cli/commands/account_cmds.py +171 -0
  207. package/.next/standalone/fp-cloud-cli/fp_cli/commands/agent_cmds.py +80 -7
  208. package/.next/standalone/fp-cloud-cli/fp_cli/commands/alerts_cmds.py +23 -0
  209. package/.next/standalone/fp-cloud-cli/fp_cli/commands/audits_cmds.py +2 -0
  210. package/.next/standalone/fp-cloud-cli/fp_cli/commands/contracts_cmds.py +67 -0
  211. package/.next/standalone/fp-cloud-cli/fp_cli/commands/dashboards_cmds.py +159 -0
  212. package/.next/standalone/fp-cloud-cli/fp_cli/commands/evaluators_cmds.py +380 -0
  213. package/.next/standalone/fp-cloud-cli/fp_cli/commands/events_cmds.py +14 -1
  214. package/.next/standalone/fp-cloud-cli/fp_cli/commands/incidents_cmds.py +82 -6
  215. package/.next/standalone/fp-cloud-cli/fp_cli/commands/list_cmds.py +4 -1
  216. package/.next/standalone/fp-cloud-cli/fp_cli/commands/orgs_cmds.py +17 -0
  217. package/.next/standalone/fp-cloud-cli/fp_cli/commands/policies_cmds.py +143 -1
  218. package/.next/standalone/fp-cloud-cli/fp_cli/commands/queries_cmds.py +70 -0
  219. package/.next/standalone/fp-cloud-cli/fp_cli/commands/sentiment_cmds.py +49 -0
  220. package/.next/standalone/fp-cloud-cli/fp_cli/commands/sessions_cmds.py +95 -1
  221. package/.next/standalone/fp-cloud-cli/fp_cli/commands/settings_cmds.py +2 -0
  222. package/.next/standalone/fp-cloud-cli/fp_cli/commands/usage_cmds.py +21 -1
  223. package/.next/standalone/fp-cloud-cli/fp_cli/commands/users_cmds.py +14 -0
  224. package/.next/standalone/fp-cloud-cli/fp_cli/errors.py +3 -0
  225. package/.next/standalone/fp-cloud-cli/fp_cli/evaluator_spec.py +266 -0
  226. package/.next/standalone/fp-cloud-cli/fp_cli/output.py +187 -81
  227. package/.next/standalone/fp-cloud-cli/fp_cli/theme.py +21 -24
  228. package/.next/standalone/fp-cloud-cli/skill/SKILL.md +124 -23
  229. package/.next/standalone/fp-cloud-cli/skill/agents/openai.yaml +2 -1
  230. package/.next/standalone/fp-cloud-cli/skill/references/commands.md +168 -16
  231. package/.next/standalone/fp-cloud-cli/tests/fake_cloud_smoke.py +312 -0
  232. package/.next/standalone/fp-cloud-cli/tests/test_cloud_account.py +125 -0
  233. package/.next/standalone/fp-cloud-cli/tests/test_cloud_agent.py +253 -0
  234. package/.next/standalone/fp-cloud-cli/tests/test_cloud_human_views.py +287 -0
  235. package/.next/standalone/fp-cloud-cli/tests/test_cloud_observability.py +116 -0
  236. package/.next/standalone/fp-cloud-cli/tests/test_cloud_transport.py +141 -0
  237. package/.next/standalone/fp-cloud-cli/tests/test_commands.py +3 -3
  238. package/.next/standalone/fp-cloud-cli/tests/test_dashboards_agent.py +3 -3
  239. package/.next/standalone/fp-cloud-cli/tests/test_evaluator_authoring.py +449 -0
  240. package/.next/standalone/fp-cloud-cli/tests/test_facets.py +1 -1
  241. package/.next/standalone/fp-cloud-cli/tests/test_help_table_coverage.py +15 -0
  242. package/.next/standalone/fp-cloud-cli/tests/test_operator.py +1 -1
  243. package/.next/standalone/fp-cloud-cli/tests/test_orgs.py +1 -1
  244. package/.next/standalone/fp-cloud-cli/tests/test_output.py +37 -37
  245. package/.next/standalone/fp-cloud-cli/tests/test_round4_behaviour.py +144 -0
  246. package/.next/standalone/fp-cloud-cli/tests/test_screen_language.py +80 -0
  247. package/.next/standalone/fp-cloud-cli/tests/test_session_reevaluate.py +33 -0
  248. package/.next/standalone/fp-cloud-cli/tests/test_staging_parity.py +198 -0
  249. package/.next/standalone/fp-cloud-cli/tests/test_whoami.py +1 -1
  250. package/.next/standalone/fp-cloud-cli/uv.lock +4 -4
  251. package/.next/standalone/hermes-plugin/plugin.yaml +1 -1
  252. package/.next/standalone/node_modules/@next/env/package.json +1 -1
  253. package/.next/standalone/node_modules/next/dist/build/swc/index.js +1 -1
  254. package/.next/standalone/node_modules/next/dist/compiled/next-server/app-page-turbo-experimental.runtime.prod.js +24 -24
  255. package/.next/standalone/node_modules/next/dist/compiled/next-server/app-page-turbo.runtime.prod.js +26 -26
  256. package/.next/standalone/node_modules/next/dist/compiled/next-server/app-route-turbo.runtime.prod.js +3 -3
  257. package/.next/standalone/node_modules/next/dist/compiled/next-server/pages-turbo.runtime.prod.js +13 -13
  258. package/.next/standalone/node_modules/next/dist/lib/patch-incorrect-lockfile.js +3 -3
  259. package/.next/standalone/node_modules/next/dist/server/app-render/app-render.js +41 -40
  260. package/.next/standalone/node_modules/next/dist/server/app-render/async-local-storage.js +1 -1
  261. package/.next/standalone/node_modules/next/dist/server/app-render/dynamic-rendering-validation.js +814 -0
  262. package/.next/standalone/node_modules/next/dist/server/app-render/dynamic-rendering.js +1 -799
  263. package/.next/standalone/node_modules/next/dist/server/base-server.js +39 -5
  264. package/.next/standalone/node_modules/next/dist/server/config.js +1 -1
  265. package/.next/standalone/node_modules/next/dist/server/dev/hot-reloader-turbopack.js +2 -2
  266. package/.next/standalone/node_modules/next/dist/server/dev/hot-reloader-webpack.js +1 -1
  267. package/.next/standalone/node_modules/next/dist/server/lib/app-info-log.js +1 -1
  268. package/.next/standalone/node_modules/next/dist/server/lib/dedupe-fetch.js +4 -43
  269. package/.next/standalone/node_modules/next/dist/server/lib/patch-fetch-symbol.js +13 -0
  270. package/.next/standalone/node_modules/next/dist/server/lib/patch-fetch.js +3 -7
  271. package/.next/standalone/node_modules/next/dist/server/lib/router-server.js +3 -3
  272. package/.next/standalone/node_modules/next/dist/server/lib/router-utils/instrumentation-globals.external.js +77 -12
  273. package/.next/standalone/node_modules/next/dist/server/lib/start-server.js +1 -1
  274. package/.next/standalone/node_modules/next/dist/server/lib/trace/constants.js +12 -0
  275. package/.next/standalone/node_modules/next/dist/server/lib/trace/tracer.js +30 -14
  276. package/.next/standalone/node_modules/next/dist/server/next-server.js +10 -11
  277. package/.next/standalone/node_modules/next/dist/server/route-modules/pages/pages-handler.js +29 -23
  278. package/.next/standalone/node_modules/next/dist/server/route-modules/route-module.js +85 -8
  279. package/.next/standalone/node_modules/next/dist/server/use-cache/use-cache-wrapper.js +1 -1
  280. package/.next/standalone/node_modules/next/dist/server/web/adapter.js +124 -65
  281. package/.next/standalone/node_modules/next/dist/server/web/forward-trace-context.js +102 -0
  282. package/.next/standalone/node_modules/next/dist/telemetry/anonymous-meta.js +1 -1
  283. package/.next/standalone/node_modules/next/dist/telemetry/events/swc-load-failure.js +1 -1
  284. package/.next/standalone/node_modules/next/dist/telemetry/events/version.js +2 -2
  285. package/.next/standalone/node_modules/next/package.json +10 -10
  286. package/.next/standalone/node_modules/react/cjs/react.production.js +1 -1
  287. package/.next/standalone/node_modules/react/package.json +1 -1
  288. package/.next/standalone/node_modules/react-dom/cjs/react-dom-server-legacy.browser.production.js +1 -1
  289. package/.next/standalone/node_modules/react-dom/cjs/react-dom-server-legacy.node.production.js +1 -1
  290. package/.next/standalone/node_modules/react-dom/cjs/react-dom-server.browser.production.js +31 -27
  291. package/.next/standalone/node_modules/react-dom/cjs/react-dom-server.edge.production.js +33 -27
  292. package/.next/standalone/node_modules/react-dom/cjs/react-dom-server.node.production.js +38 -30
  293. package/.next/standalone/node_modules/react-dom/cjs/react-dom.production.js +1 -1
  294. package/.next/standalone/node_modules/react-dom/package.json +2 -2
  295. package/.next/standalone/package.json +10 -10
  296. package/.next/standalone/sdk/python/CHANGELOG.md +8 -4
  297. package/.next/standalone/sdk/python/failproofai_sdk/evaluator/source.py +2 -2
  298. package/.next/standalone/sdk/python/pyproject.toml +2 -7
  299. package/.next/standalone/sdk/python/skill/references/frameworks.md +0 -15
  300. package/.next/standalone/sdk/python/tests/test_docs.py +1 -4
  301. package/.next/standalone/sdk/python/tests/test_evaluator_source.py +1 -1
  302. package/.next/standalone/sdk/python/tests/test_packaging.py +4 -7
  303. package/.next/standalone/sdk/python/tests/test_zero_dependencies.py +2 -13
  304. package/.next/standalone/sdk/python/uv.lock +43 -905
  305. package/.next/standalone/sdk/typescript/CHANGELOG.md +52 -0
  306. package/.next/standalone/sdk/typescript/integration/fixtures/ai-5/package-lock.json +7 -7
  307. package/.next/standalone/sdk/typescript/integration/fixtures/ai-5/package.json +2 -2
  308. package/.next/standalone/sdk/typescript/integration/fixtures/ai-6/package-lock.json +7 -7
  309. package/.next/standalone/sdk/typescript/integration/fixtures/ai-6/package.json +1 -1
  310. package/.next/standalone/sdk/typescript/integration/fixtures/ai-7/package-lock.json +7 -7
  311. package/.next/standalone/sdk/typescript/integration/fixtures/ai-7/package.json +1 -1
  312. package/.next/standalone/sdk/typescript/integration/fixtures/langchain-1/package-lock.json +4 -4
  313. package/.next/standalone/sdk/typescript/integration/fixtures/langchain-1/package.json +1 -1
  314. package/.next/standalone/sdk/typescript/integration/fixtures/langchain-dup-core/package-lock.json +4 -4
  315. package/.next/standalone/sdk/typescript/integration/fixtures/langchain-dup-core/package.json +1 -1
  316. package/.next/standalone/sdk/typescript/integration/fixtures/llamaindex-0.11/package-lock.json +3 -3
  317. package/.next/standalone/sdk/typescript/integration/fixtures/llamaindex-0.11/package.json +3 -0
  318. package/.next/standalone/sdk/typescript/integration/fixtures/llamaindex-0.12/package-lock.json +4 -4
  319. package/.next/standalone/sdk/typescript/integration/fixtures/llamaindex-0.12/package.json +1 -1
  320. package/.next/standalone/sdk/typescript/integration/fixtures/mastra-0/package-lock.json +25 -25
  321. package/.next/standalone/sdk/typescript/integration/fixtures/mastra-0/package.json +1 -1
  322. package/.next/standalone/sdk/typescript/integration/fixtures/mastra-1/package-lock.json +34 -22
  323. package/.next/standalone/sdk/typescript/integration/fixtures/mastra-1/package.json +3 -2
  324. package/.next/standalone/sdk/typescript/integration/fixtures/nextjs/package-lock.json +10 -10
  325. package/.next/standalone/sdk/typescript/integration/fixtures/nextjs/package.json +1 -1
  326. package/.next/standalone/sdk/typescript/integration/fixtures/runtimes/deno-npm.ts +1 -1
  327. package/.next/standalone/sdk/typescript/integration/fixtures/runtimes/package-lock.json +7 -7
  328. package/.next/standalone/sdk/typescript/integration/fixtures/runtimes/package.json +1 -1
  329. package/.next/standalone/server.js +1 -1
  330. package/README.md +0 -6
  331. package/dist/cli.mjs +87 -38
  332. package/dist/worker.mjs +73 -28
  333. package/hermes-plugin/plugin.yaml +1 -1
  334. package/openclaw-plugin/daemon-client.js +254 -0
  335. package/openclaw-plugin/hooks.js +187 -0
  336. package/openclaw-plugin/index.js +17 -211
  337. package/package.json +10 -10
  338. package/scripts/sync-agent-cli-harnesses-prompt.md +26 -31
  339. package/src/hooks/agent-skill.ts +3 -0
  340. package/src/hooks/enforcement-capability.ts +1 -1
  341. package/src/hooks/fp-home.ts +1 -1
  342. package/src/hooks/handler.ts +22 -3
  343. package/src/hooks/integrations.ts +5 -2
  344. package/src/hooks/semantic/intent.ts +127 -24
  345. package/src/hooks/semantic/jev-review.ts +21 -2
  346. package/.next/standalone/.codex/hooks.json +0 -76
  347. package/.next/standalone/.cursor/hooks.json +0 -47
  348. package/.next/standalone/.factory/hooks.json +0 -112
  349. package/.next/standalone/.next/server/chunks/[externals]__1x24dzcbbq6-g._.js +0 -3
  350. package/.next/standalone/.next/server/chunks/[root-of-the-server]__0__a_je8fsn65._.js +0 -3
  351. package/.next/standalone/.next/server/chunks/[root-of-the-server]__0l-oi4gdtmlo5._.js +0 -3
  352. package/.next/standalone/.next/server/chunks/[root-of-the-server]__0t9ufnv5hi2hq._.js +0 -327
  353. package/.next/standalone/.next/server/chunks/[root-of-the-server]__1aaw59g-5uty7._.js +0 -322
  354. package/.next/standalone/.next/server/chunks/[root-of-the-server]__1hqpg6vgmfexv._.js +0 -3
  355. package/.next/standalone/.next/server/chunks/ssr/[externals]__0ilfh9mfnzsth._.js +0 -3
  356. package/.next/standalone/.next/server/chunks/ssr/[externals]__0ohnuzsaozaca._.js +0 -3
  357. package/.next/standalone/.next/server/chunks/ssr/[root-of-the-server]__0pwj2h2efe5f-._.js +0 -14
  358. package/.next/standalone/.next/server/chunks/ssr/node_modules_next_0zuikgt2xho-v._.js +0 -271
  359. package/.next/standalone/.next/server/chunks/ssr/node_modules_next_dist_158jo-9mwvgad._.js +0 -291
  360. package/.next/standalone/.next/server/chunks/ssr/node_modules_next_dist_19r82zsxo2jj1._.js +0 -291
  361. package/.next/standalone/.next/server/chunks/ssr/node_modules_next_dist_1dupwucoqt5qm._.js +0 -3
  362. package/.next/standalone/.next/server/chunks/ssr/node_modules_next_dist_shared_lib_03w27x2kh17_8._.js +0 -23
  363. package/.next/standalone/.next/static/chunks/1my3-5p47t7r-.js +0 -1
  364. package/.next/standalone/.next/static/chunks/21hckpmsc4g70.js +0 -6
  365. package/.next/standalone/.next/static/chunks/2hmex93ppj1ke.js +0 -1
  366. package/.next/standalone/.next/static/chunks/40oworn_-x12p.js +0 -1
  367. package/.next/standalone/.opencode/opencode.json +0 -4
  368. package/.next/standalone/.opencode/plugins/failproofai.mjs +0 -210
  369. package/.next/standalone/.pi/settings.json +0 -5
  370. package/.next/standalone/node_modules/react/cjs/react.development.js +0 -1330
  371. package/scripts/dev-hook.mjs +0 -333
  372. /package/.next/standalone/.next/static/{LHCtFxVG0mdvd4lsXAOFC → 1n2dyfTQb0MDajeqlipJy}/_buildManifest.js +0 -0
  373. /package/.next/standalone/.next/static/{LHCtFxVG0mdvd4lsXAOFC → 1n2dyfTQb0MDajeqlipJy}/_clientMiddlewareManifest.js +0 -0
  374. /package/.next/standalone/.next/static/{LHCtFxVG0mdvd4lsXAOFC → 1n2dyfTQb0MDajeqlipJy}/_ssgManifest.js +0 -0
@@ -1,4 +1,4 @@
1
- module.exports=[39702,e=>{"use strict";let t,r,i,s,n,a;var o,l=e.i(14747);function u(e){return e.replace(/^[A-Z]:/,"").replace(/\\/g,"/")}var c=((o={}).AnonymousId="anonymous_id",o.DistinctId="distinct_id",o.Props="props",o.EnablePersonProcessing="enable_person_processing",o.PersonMode="person_mode",o.FeatureFlagDetails="feature_flag_details",o.FeatureFlags="feature_flags",o.FeatureFlagPayloads="feature_flag_payloads",o.BootstrapFeatureFlagDetails="bootstrap_feature_flag_details",o.BootstrapFeatureFlags="bootstrap_feature_flags",o.BootstrapFeatureFlagPayloads="bootstrap_feature_flag_payloads",o.OverrideFeatureFlags="override_feature_flags",o.Queue="queue",o.AiQueue="ai_queue",o.AiCaptureQueue="ai_capture_queue",o.LogsQueue="logs_queue",o.OptedOut="opted_out",o.SessionId="session_id",o.SessionStartTimestamp="session_start_timestamp",o.SessionLastTimestamp="session_timestamp",o.PersonProperties="person_properties",o.GroupProperties="group_properties",o.InstalledAppBuild="installed_app_build",o.InstalledAppVersion="installed_app_version",o.SessionReplay="session_replay",o.PushRegistered="push_registered",o.SessionReplayEventTriggerActivatedSession="session_replay_event_trigger_activated_session",o.SurveyLastSeenDate="survey_last_seen_date",o.SurveysInProgress="surveys_in_progress",o.SurveysSeen="surveys_seen",o.Surveys="surveys",o.RemoteConfig="remote_config",o.FlagsEndpointWasHit="flags_endpoint_was_hit",o.DeviceId="device_id",o);let h={ERRORS_WHILE_COMPUTING:"errors_while_computing_flags",FLAG_MISSING:"flag_missing",QUOTA_LIMITED:"quota_limited",TIMEOUT:"timeout",CONNECTION_ERROR:"connection_error",UNKNOWN_ERROR:"unknown_error",apiError:e=>`api_error_${e}`};function d(e){let t=[];return JSON.stringify(e,function(e,r){if("bigint"==typeof r)return r.toString();if("function"!=typeof r&&"symbol"!=typeof r){if(r instanceof Error)return{name:r.name,message:r.message,stack:r.stack};if(r&&"object"==typeof r){for(;t.length>0&&t[t.length-1]!==this;)t.pop();if(t.includes(r))return"[Circular]";t.push(r)}return r}})??"null"}let p=Array.isArray,g=Object.prototype;g.hasOwnProperty;let f=g.toString,m=p||function(e){return"[object Array]"===f.call(e)},y=e=>e===Object(e)&&!m(e),_=e=>void 0===e,v=e=>"[object String]"==f.call(e),b=e=>v(e)&&0===e.trim().length,w=e=>null===e,x=e=>_(e)||w(e),S=e=>"[object Number]"==f.call(e)&&e==e;function E(e){return null===e||"object"!=typeof e}function F(e,t){return Object.prototype.toString.call(e)===`[object ${t}]`}function P(e){switch(Object.prototype.toString.call(e)){case"[object Error]":case"[object Exception]":case"[object DOMException]":case"[object DOMError]":case"[object WebAssembly.Exception]":return!0;default:return A(e,Error)}}function I(e){return"u">typeof Event&&A(e,Event)}function A(e,t){try{return e instanceof t}catch{return!1}}let C="Android",k="BlackBerry",$="Nintendo",O="PlayStation",M="Xbox",T="Windows",R="(\\d+(\\.\\d+)?)";RegExp("Version/"+R),RegExp("(Claude|Codex|ChatGPT)\\/"+R),RegExp(M,"i"),RegExp(O+" \\w+","i"),RegExp($+" \\w+","i"),RegExp(k+"|PlayBook|BB10","i");RegExp("rv:"+R),RegExp("Edge?\\/"+R),RegExp("(Chrome|CrMo)\\/"+R),RegExp("CriOS\\/"+R),RegExp("(UCBrowser|UCWEB)\\/"+R),RegExp("(Opera|OPR)\\/"+R),RegExp("Firefox\\/"+R),RegExp("FxiOS\\/"+R),RegExp("Konqueror[:/]?"+R,"i"),RegExp(k+" "+R),RegExp("android\\s"+R,"i"),RegExp("SamsungBrowser\\/"+R),RegExp("OculusBrowser\\/"+R),RegExp("Vivaldi\\/"+R),RegExp("YaBrowser\\/"+R),RegExp("Whale\\/"+R),RegExp("Brave\\/"+R),RegExp("(DuckDuckGo|Ddg)\\/"+R),RegExp("PaleMoon\\/"+R),RegExp("Waterfox\\/"+R),RegExp("GSA\\/"+R),RegExp("(rv:|MSIE )"+R),RegExp("rv:"+R),RegExp(M+"; "+M+" (.*?)[);]","i"),RegExp($,"i"),RegExp(O,"i"),RegExp(T,"i"),RegExp("("+C+" (\\d+)\\.(\\d+)\\.?(\\d+)?|"+C+")","i");let D=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;function j(e,t){return"string"==typeof e&&D.test(e)?e:t()}function B(e,t){let r=Error(t);try{Object.defineProperty(r,"name",{value:e,writable:!0,enumerable:!0,configurable:!0})}catch{}return r}function L(e){return e?e.split("#")[0]:e}async function N(e,t){let r=null;for(let i=0;i<t.retryCount+1;i++){i>0&&await new Promise(e=>setTimeout(e,t.retryDelay));try{return await e()}catch(e){if(r=e,!t.retryCheck(e))throw e}}throw r}function q(){return new Date().toISOString()}function U(e,t){let r=setTimeout(e,t);return r?.unref&&r?.unref(),r}async function z(e,t,r){let i;try{return await Promise.race([e,new Promise((e,s)=>{i=U(()=>{try{r?.(),e()}catch(e){s(e)}},t)})])}finally{clearTimeout(i)}}function H(e){return Promise.all(e.map(e=>(e??Promise.resolve()).then(e=>({status:"fulfilled",value:e}),e=>({status:"rejected",reason:e}))))}function V(e,t,r){return e&&r?t.length===Object.keys(r).length&&t.every(t=>e[t]===r[t]):e===r}class W{constructor(e,t,r=[]){this.coercers=e,this.stackParser=t,this.modifiers=r}buildFromUnknown(e,t={}){let r=t&&t.mechanism||{handled:!0,type:"generic"},i=this.buildCoercingContext(r,t,0).apply(e),s=this.buildParsingContext(t),n=this.parseStacktrace(i,s);return{$exception_list:this.convertToExceptionList(n,r),$exception_level:"error"}}async modifyFrames(e){for(let t of e)t.stacktrace&&t.stacktrace.frames&&m(t.stacktrace.frames)&&(t.stacktrace.frames=await this.applyModifiers(t.stacktrace.frames));return e}coerceFallback(e){return{type:"Error",value:"Unknown error",stack:e.syntheticException?.stack,synthetic:!0}}parseStacktrace(e,t){let r,i;if(null!=e.cause&&(r=this.parseStacktrace(e.cause,t)),""!=e.stack&&null!=e.stack)try{i=this.applyChunkIds(this.stackParser(e.stack,e.synthetic?t.skipFirstLines:0),t.chunkIdMap)}catch{}return{...e,cause:r,stack:i,errors:e.errors?.map(e=>this.parseStacktrace(e,t))}}applyChunkIds(e,t){return e.map(e=>(e.filename&&t&&(e.chunk_id=t[e.filename]),e))}applyCoercers(e,t){for(let r of this.coercers)if(r.match(e))return r.coerce(e,t);return this.coerceFallback(t)}async applyModifiers(e){let t=e;for(let e of this.modifiers)t=await e(t);return t}convertToExceptionList(e,t){let r=[],i=(e,s,n)=>{let a=r.length,o=void 0===s?{type:"string"==typeof t.type&&t.type.length>0?t.type:"generic",..."boolean"==typeof t.handled?{handled:t.handled}:void 0===t.handled?{handled:!0}:{},synthetic:"boolean"==typeof t.synthetic?t.synthetic:e.synthetic,exception_id:a}:{type:"chained",source:n,synthetic:e.synthetic,exception_id:a,parent_id:s},l={type:e.type,value:e.value,mechanism:o};for(let t of(e.stack&&(l.stacktrace={type:"raw",frames:e.stack}),r.push(l),e.cause&&i(e.cause,a,"cause"),e.errors??[]))i(t,a,"member")};return i(e),r}buildParsingContext(e){return{chunkIdMap:function(e){let n=globalThis._posthogChunkIds,a=globalThis._debugIds;if(!n&&!a)return;let o=n?Object.keys(n):[],l=a?Object.keys(a):[];if(s&&V(n,o,r)&&V(a,l,i))return s;r=n?{...n}:void 0,i=a?{...a}:void 0,s={},t??={};let u=(r,i)=>{for(let n of r){let r=i[n];if(!r)continue;let a=t?.[n];if(a){s[a]=r;continue}let o=e(n);for(let e=o.length-1;e>=0;e--){let i=o[e]?.filename;if(i){s[i]=r,t[n]=i;break}}}};return a&&u(l,a),n&&u(o,n),s}(this.stackParser),skipFirstLines:e.skipFirstLines??1}}getAggregateErrors(e){try{if(P(e)){let t=Object.getPrototypeOf(e);for(let r=0;t&&r<100;r++){let r=Object.getOwnPropertyDescriptor(t,"constructor")?.value;if("function"==typeof r&&"AggregateError"===r.name){let t=e.errors;return m(t)?t:void 0}t=Object.getPrototypeOf(t)}}}catch{}}buildCoercingContext(e,t,r=0){let i=0,s=0,n=!1,a=new Set,o=[],l={},u=(e,t,r=0)=>{let u,h,d=c(t,r),p=d.apply;if(d.apply=t=>{o.push(e);try{return p(t)}finally{o.pop()}},r>4||r>0&&-1!==o.indexOf(e))return this.coerceFallback(d);let g="object"==typeof e&&null!==e||"function"==typeof e;if(0===r&&i>=50||g&&a.has(e))return;g&&a.add(e),0===r&&i++;let f=this.getAggregateErrors(e);n||=!!f;try{if(!(u=this.applyCoercers(e,d)))throw l}catch(e){if(e===l){0===r&&i--;return}if(!n)throw e;u=this.coerceFallback(d)}if(!f||i>=50)return u;try{h=f.length}catch{return u}if(!Number.isInteger(h)||h<0||h>0xffffffff)return u;let m=[];for(let e=0;i<50&&s<1e3&&e<h;e++){let r;s++;try{r=d.next(f[e])}catch{i++,r=this.coerceFallback(c(t+1))}r&&m.push(r)}return{...u,errors:m}},c=(r,i=0)=>({...t,syntheticException:0==r?t.syntheticException:void 0,mechanism:0==r?e:{},apply:e=>{let t=u(e,r,i+1);if(!t)throw l;return t},next:e=>u(e,r+1)}),h=c(r);return{...h,apply:e=>u(e,r)??this.coerceFallback(h)}}}e.s(["ErrorPropertiesBuilder",0,W],69309);let K=/^([a-z][a-z0-9.+-]+):/i,G=["http","https","file","blob","app","capacitor","ionic","webpack","webpack-internal","ng"];function Q(e,t,r,i,s){let n={platform:e,filename:t,function:"<anonymous>"===r?"?":r,in_app:function(e){if(!e||"<anonymous>"===e)return!1;let t=K.exec(e);return!t||G.includes(t[1].toLowerCase())}(t)};return _(i)||(n.lineno=i),_(s)||(n.colno=s),n}let J=(e,t)=>{let r=-1!==e.indexOf("safari-extension"),i=-1!==e.indexOf("safari-web-extension");return r||i?[-1!==e.indexOf("@")?e.split("@")[0]:"?",r?`safari-extension:${t}`:`safari-web-extension:${t}`]:[e,t]},Z=/^\s*at (\S+?)(?::(\d+))(?::(\d+))\s*$/i,Y=/^\s*at (?:(.+?\)(?: \[.+\])?|.*?) ?\((?:address at )?)?(?:async )?((?:<anonymous>|[-a-z]+:|.*bundle|\/)?.*?)(?::(\d+))?(?::(\d+))?\)?\s*$/i,X=/\((\S*)(?::(\d+))(?::(\d+))\)/,ee=(e,t)=>{let r=Z.exec(e);if(r){let[,e,i,s]=r;return Q(t,e,"?",+i,+s)}let i=Y.exec(e);if(i){if(i[2]&&0===i[2].indexOf("eval")){let e=X.exec(i[2]);e&&(i[2]=e[1],i[3]=e[2],i[4]=e[3])}let[e,r]=J(i[1]||"?",i[2]);return Q(t,r,e,i[3]?+i[3]:void 0,i[4]?+i[4]:void 0)}},et=/^\s*(.*?)(?:\((.*?)\))?(?:^|@)?((?:[-a-z]+)?:\/.*?|\[native code\]|[^@]*(?:bundle|\d+\.js)|\/[\w\-. /=]+)(?::(\d+))?(?::(\d+))?\s*$/i,er=/(\S+) line (\d+)(?: > eval line \d+)* > eval/i,ei=(e,t)=>{let r=et.exec(e);if(r){if(r[3]&&r[3].indexOf(" > eval")>-1){let e=er.exec(r[3]);e&&(r[1]=r[1]||"eval",r[3]=e[1],r[4]=e[2],r[5]="")}let e=r[3],i=r[1]||"?";return[i,e]=J(i,e),Q(t,e,i,r[4]?+r[4]:void 0,r[5]?+r[5]:void 0)}},es=/^\s*at (?:((?:\[object object\])?.+) )?\(?((?:[-a-z]+):.*?):(\d+)(?::(\d+))?\)?\s*$/i,en=(e,t)=>{let r=es.exec(e);return r?Q(t,r[2],r[1]||"?",+r[3],r[4]?+r[4]:void 0):void 0},ea=/ line (\d+).*script (?:in )?(\S+)(?:: in function (\S+))?$/i,eo=(e,t)=>{let r=ea.exec(e);return r?Q(t,r[2],r[3]||"?",+r[1]):void 0},el=/ line (\d+), column (\d+)\s*(?:in (?:<anonymous function: ([^>]+)>|([^)]+))\(.*\))? in (.*):\s*$/i,eu=(e,t)=>{let r=el.exec(e);return r?Q(t,r[5],r[3]||r[4]||"?",+r[1],+r[2]):void 0},ec=/^\s*[-]{4,}$/,eh=/at (?:async )?(?:(.+?)\s+\()?(?:(.+):(\d+):(\d+)?|([^)]+))\)?/,ed=/^Promise\.(?:all|any)$/,ep=/^index \d+$/,eg=(e,t)=>{let r=e.match(eh);if(r){let e,i,s,n,a;if(r[1]){let t=(s=r[1]).lastIndexOf(".");if("."===s[t-1]&&t--,t>0){e=s.slice(0,t),i=s.slice(t+1);let r=e.indexOf(".Module");r>0&&(s=s.slice(r+1),e=e.slice(0,r))}n=void 0}i&&(n=e,a=i),"<anonymous>"===i&&(a=void 0,s=void 0),void 0===s&&(a=a||"?",s=n?`${n}.${a}`:a);let o=r[2]?.startsWith("file://")?r[2].slice(7):r[2],l="native"===r[5];return o?.match(/\/[A-Z]:/)&&(o=o.slice(1)),o||!r[5]||l||(o=r[5]),ed.test(s)&&ep.test(o||"")&&(o="node:internal/promise"),{filename:o?decodeURI(o):void 0,module:void 0,function:s,lineno:ef(r[3]),colno:ef(r[4]),in_app:function(e,t=!1){return!(t||e&&!e.startsWith("/")&&!e.match(/^[A-Z]:/)&&!e.startsWith(".")&&!e.match(/^[a-zA-Z]([a-zA-Z0-9.\-+])*:\/\//))&&void 0!==e&&!e.includes("node_modules/")}(o||"",l),platform:t}}if(e.match(ec))return{filename:e,platform:t}};function ef(e){return parseInt(e||"",10)||void 0}let em=/\(error: (.*)\)/;function ey(e,t){return e.filename===t.filename&&e.function===t.function&&e.module===t.module&&e.lineno===t.lineno&&e.colno===t.colno}function e_(e,t){let r=t.start;for(;r>0&&ey(e[r-1],e[r-1+t.length]);)r--;return t.start-r}function ev(e,t){let r=t.start+t.length,i=r;for(;i<e.length&&ey(e[i],e[i-t.length]);)i++;return i-r}function eb(e){if(!e.length)return[];let t=Array.from(e);return t.reverse(),t.slice(0,50).map(e=>{var r;return{...e,filename:e.filename||((r=t)[r.length-1]||{}).filename,function:e.function||"?"}})}function ew(){return ex("web:javascript",ee,ei)}function ex(e,...t){return(r,i=0)=>{let s=[],n=r.split("\n"),a=Math.min(n.length,i+1e3),o=[];for(let r=i;r<a;r++){let i=n[r];if(i.length>1024)continue;let a=em.test(i)?i.replace(em,"$1"):i;if(!a.match(/\S*Error: /)){for(let r of t){let t=r(a,e);if(t){s.push(t);let e=function(e){for(let t=1;t<=10;t++){let r=e.length-2*t;if(r<0)break;let i=!0;for(let s=0;s<t;s++)if(!ey(e[r+s],e[r+t+s])){i=!1;break}if(i){for(let i=0;i<t;i++)e[r+i]=e[r+t+i];return e.length=r+t,{start:r,length:t}}}}(s);if(e){for(let t=o.length-1;t>=0;t--){let r=o[t];if(r.start+r.length<=e.start)break;o.pop()}o.push(e)}break}}if(function(e,t){let r=t[0],i=e.length-(r?e_(e,r):0);for(let r of t)i-=ev(e,r);return i}(s,o)>=50)break}}let l=[...o].sort((e,t)=>t.start-e.start),u=l[l.length-1];if(u){let e=e_(s,u);for(let t of(s.splice(u.start-e,e),l))t.start-=e}for(let e of l)!function(e,t){let r=t.start+t.length,i=ev(e,t);i&&e.splice(r+i===e.length?r:t.start,i)}(s,e);return o.some(e=>0===e.start&&s.length===e.length)&&function(e){let t=e.map(e=>`${e.function}|${e.filename}|${e.lineno}|${e.colno}|${e.module}`),r=0;for(let e=1;e<t.length;e++)(function(e,t,r){for(let i=0;i<e.length;i++){let s=e[(t+i)%e.length],n=e[(r+i)%e.length];if(s!==n)return s<n}return!1})(t,e,r)&&(r=e);e.push(...e.splice(0,r))}(s),eb(s)}}class eS{match(e){return this.isDOMException(e)||this.isDOMError(e)}coerce(e,t){let r=v(e.stack);return{type:this.getType(e),value:this.getValue(e),stack:r?e.stack:void 0,cause:e.cause?t.next(e.cause):void 0,synthetic:!1}}getType(e){return this.isDOMError(e)?"DOMError":"DOMException"}getValue(e){let t=e.name||(this.isDOMError(e)?"DOMError":"DOMException");return e.message?`${t}: ${e.message}`:t}isDOMException(e){return F(e,"DOMException")}isDOMError(e){return F(e,"DOMError")}}e.s(["DOMExceptionCoercer",0,eS],33603);class eE{match(e){return!!F(e,"ErrorEvent")&&(void 0!=e.error||this._hasUsableMessage(e))}coerce(e,t){if(void 0!=e.error)return t.apply(e.error);let r=t.apply(e.message);return{...r,stack:this._buildLocationStack(e)??r.stack,synthetic:!0}}_hasUsableMessage(e){return v(e.message)&&e.message.length>0}_buildLocationStack(e){let t=e.lineno??0,r=e.colno??0;if(v(e.filename)&&0!==e.filename.length&&0!==t)return`Error
2
- at ${e.filename}:${t}:${r}`}}e.s(["ErrorEventCoercer",0,eE],60887);let eF=["fatal","error","warning","log","info","debug"];function eP(e,t=40){let r=Object.keys(e);if(r.sort(),!r.length)return"[object has no keys]";for(let e=r.length;e>0;e--){let i=r.slice(0,e).join(", ");if(!(i.length>t)){if(e===r.length)return i;return i.length<=t?i:`${i.slice(0,t)}...`}}return""}class eI{match(e){return"object"==typeof e&&null!==e}coerce(e,t){let r=this.getErrorPropertyFromObject(e);return r?t.apply(r):{type:this.getType(e),value:this.getValue(e),stack:this.getStack(e)??t.syntheticException?.stack,level:this.isSeverityLevel(e.level)?e.level:"error",synthetic:!0}}getType(e){if(I(e))return e.constructor.name;let t="name"in e?e.name:void 0;return v(t)&&!b(t)?t:"Error"}getValue(e){if("name"in e&&"string"==typeof e.name){let t=`'${e.name}' captured as exception`;return"message"in e&&"string"==typeof e.message&&(t+=` with message: '${e.message}'`),t}if("message"in e&&"string"==typeof e.message)return e.message;let t=this.getObjectClassName(e),r=eP(e);return`${t&&"Object"!==t?`'${t}'`:"Object"} captured as exception with keys: ${r}`}isSeverityLevel(e){return v(e)&&!b(e)&&eF.indexOf(e)>=0}getStack(e){try{if(v(e.stacktrace)&&e.stacktrace.length>0)return e.stacktrace;return v(e.stack)&&e.stack.length>0?e.stack:void 0}catch{return}}getErrorPropertyFromObject(e){for(let t in e)if(Object.prototype.hasOwnProperty.call(e,t)){let r=e[t];if(P(r))return r}}getObjectClassName(e){try{let t=Object.getPrototypeOf(e);return t?t.constructor.name:void 0}catch(e){return}}}e.s(["ObjectCoercer",0,eI],12154);class eA{match(e){return I(e)}coerce(e,t){let r=e.constructor.name;return{type:r,value:`${r} captured as exception with keys: ${eP(e)}`,stack:t.syntheticException?.stack,synthetic:!0}}}e.s(["EventCoercer",0,eA],41324);class eC{match(e){return E(e)}coerce(e,t){return{type:"Error",value:`Primitive value captured as exception: ${String(e)}`,stack:t.syntheticException?.stack,synthetic:!0}}}e.s(["PrimitiveCoercer",0,eC],79478);class ek{match(e){return F(e,"PromiseRejectionEvent")||this.isCustomEventWrappingRejection(e)}isCustomEventWrappingRejection(e){if(!I(e))return!1;try{let t=e.detail;return null!=t&&"object"==typeof t&&"reason"in t}catch{return!1}}coerce(e,t){let r=this.getUnhandledRejectionReason(e);return E(r)?{type:"UnhandledRejection",value:`Non-Error promise rejection captured with value: ${String(r)}`,stack:t.syntheticException?.stack,synthetic:!0}:t.apply(r)}getUnhandledRejectionReason(e){try{if("reason"in e)return e.reason;if("detail"in e&&null!=e.detail&&"object"==typeof e.detail&&"reason"in e.detail)return e.detail.reason}catch{}return e}}e.s(["PromiseRejectionEventCoercer",0,ek],1802);let e$={MESSAGE:"$message",TIMESTAMP:"$timestamp"},eO=new Set([e$.MESSAGE,e$.TIMESTAMP]),eM={enabled:!0,max_bytes:32768};function eT(e){return e?{enabled:e.enabled??eM.enabled,max_bytes:function(e,t){if(!S(e)||1/0===e||-1/0===e)return t;let r=Math.floor(e);return r<0?t:r}(e.max_bytes,eM.max_bytes)}:{...eM}}function eR(e){if(!e)return{sanitizedProperties:{},droppedKeys:[]};let t=[];return{sanitizedProperties:Object.keys(e).reduce((r,i)=>(eO.has(i)?t.push(i):r[i]=e[i],r),{}),droppedKeys:t}}class eD{constructor(e){this._entries=[],this._totalBytes=0,this._config=eT(e)}setConfig(e){this._config=eT(e),this._trimToMaxBytes()}add(e){let t=function(e){let t;try{t=d(e)}catch{return}try{let e=JSON.parse(t);if(!y(e))return;let r=e[e$.MESSAGE],i=e[e$.TIMESTAMP];if(!v(r)||0===r.trim().length||!v(i)&&!S(i))return;return{step:e,json:t}}catch{return}}(e);if(!t)return;let r=ej(t.json);r>this._config.max_bytes||(this._entries.push({step:t.step,bytes:r}),this._totalBytes+=r,this._trimToMaxBytes())}getAttachable(){return this._entries.map(e=>e.step)}clear(){this._entries=[],this._totalBytes=0}size(){return this._entries.length}_trimToMaxBytes(){for(;this._totalBytes>this._config.max_bytes&&this._entries.length>0;){let e=this._entries.shift();e&&(this._totalBytes-=e.bytes)}}}function ej(e){if("u">typeof TextEncoder)return new TextEncoder().encode(e).length;let t=encodeURIComponent(e),r=0;for(let e=0;e<t.length;e++)"%"===t[e]?(r+=1,e+=2):r+=1;return r}e.s(["DEFAULT_EXCEPTION_STEPS_CONFIG",0,eM,"EXCEPTION_STEP_INTERNAL_FIELDS",0,e$,"ExceptionStepsBuffer",0,eD,"getUtf8ByteLength",0,ej,"resolveExceptionStepsConfig",0,eT,"stripReservedExceptionStepFields",0,eR],45162),e.i(69309),e.s(["chromeStackLineParser",0,ee,"createDefaultStackParser",0,ew,"createStackParser",0,ex,"geckoStackLineParser",0,ei,"nodeStackLineParser",0,eg,"opera10StackLineParser",0,eo,"opera11StackLineParser",0,eu,"reverseAndStripFrames",0,eb,"winjsStackLineParser",0,en],22546),e.i(22546),e.i(33603);class eB{match(e){return P(e)}coerce(e,t){let r=this.getStack(e),i=void 0===r?t.syntheticException?.stack:void 0;return{type:this.getType(e),value:this.getMessage(e,t),stack:r??i,cause:e.cause?t.next(e.cause):void 0,synthetic:!!i}}getType(e){return e.name||e.constructor.name}getMessage(e,t){let r=e.message;return r.error&&"string"==typeof r.error.message?String(r.error.message):String(r)}getStack(e){try{let t=e.stacktrace;if("string"==typeof t&&t.length>0)return t;let r=e.stack;return"string"==typeof r&&r.length>0?r:void 0}catch{return}}}e.s(["ErrorCoercer",0,eB],13446),e.i(13446),e.i(60887);let eL=/^(?:[Uu]ncaught (?:exception: )?)?(?:((?:Eval|Internal|Range|Reference|Syntax|Type|URI|)Error): )?(.*)$/i;class eN{match(e){return"string"==typeof e}coerce(e,t){let[r,i]=this.getInfos(e);return{type:r??"Error",value:i??e,stack:t.syntheticException?.stack,synthetic:!0}}getInfos(e){let t="Error",r=e,i=e.match(eL);return i&&(t=i[1],r=i[2]),[t,r]}}e.s(["StringCoercer",0,eN],22175),e.i(22175),e.i(12154),e.i(41324),e.i(79478),e.i(1802),e.s(["DOMExceptionCoercer",0,eS,"ErrorCoercer",0,eB,"ErrorEventCoercer",0,eE,"EventCoercer",0,eA,"ObjectCoercer",0,eI,"PrimitiveCoercer",0,eC,"PromiseRejectionEventCoercer",0,ek,"StringCoercer",0,eN],90166),e.i(90166);class eq{constructor(e){this._maxSize=e,this._cache=new Map}get(e){let t=this._cache.get(e);if(void 0!==t)return this._cache.delete(e),this._cache.set(e,t),t}set(e,t){this._cache.set(e,t)}reduce(){for(;this._cache.size>=this._maxSize;){let e=this._cache.keys().next().value;e&&this._cache.delete(e)}}}function eU(){if("u">typeof process){let e=process.env.POSTHOG_RELEASE_ID?.trim();if(e)return e}let e=globalThis._posthogReleaseId;return"string"==typeof e&&e.length>0?e:void 0}e.s(["ReduceableCache",0,eq],45294),e.i(45294),e.i(45162),e.s(["getInjectedReleaseId",0,eU],56168),e.i(56168),e.s(["DEFAULT_EXCEPTION_STEPS_CONFIG",0,eM,"DOMExceptionCoercer",0,eS,"EXCEPTION_STEP_INTERNAL_FIELDS",0,e$,"ErrorCoercer",0,eB,"ErrorEventCoercer",0,eE,"ErrorPropertiesBuilder",0,W,"EventCoercer",0,eA,"ExceptionStepsBuffer",0,eD,"ObjectCoercer",0,eI,"PrimitiveCoercer",0,eC,"PromiseRejectionEventCoercer",0,ek,"ReduceableCache",0,eq,"StringCoercer",0,eN,"chromeStackLineParser",0,ee,"createDefaultStackParser",0,ew,"createStackParser",0,ex,"geckoStackLineParser",0,ei,"getInjectedReleaseId",0,eU,"getUtf8ByteLength",0,ej,"nodeStackLineParser",0,eg,"opera10StackLineParser",0,eo,"opera11StackLineParser",0,eu,"resolveExceptionStepsConfig",0,eT,"reverseAndStripFrames",0,eb,"stripReservedExceptionStepFields",0,eR,"winjsStackLineParser",0,en],11168);var ez=e.i(11168);let eH="0123456789abcdef";class eV{constructor(e){this.bytes=e}static ofInner(e){if(16===e.length)return new eV(e);throw TypeError("not 128-bit length")}static fromFieldsV7(e,t,r,i){if(!Number.isInteger(e)||!Number.isInteger(t)||!Number.isInteger(r)||!Number.isInteger(i)||e<0||t<0||r<0||i<0||e>0xffffffffffff||t>4095||r>0x3fffffff||i>0xffffffff)throw RangeError("invalid field value");let s=new Uint8Array(16);return s[0]=e/0x10000000000,s[1]=e/0x100000000,s[2]=e/0x1000000,s[3]=e/65536,s[4]=e/256,s[5]=e,s[6]=112|t>>>8,s[7]=t,s[8]=128|r>>>24,s[9]=r>>>16,s[10]=r>>>8,s[11]=r,s[12]=i>>>24,s[13]=i>>>16,s[14]=i>>>8,s[15]=i,new eV(s)}static parse(e){let t;switch(e.length){case 32:t=/^[0-9a-f]{32}$/i.exec(e)?.[0];break;case 36:t=/^([0-9a-f]{8})-([0-9a-f]{4})-([0-9a-f]{4})-([0-9a-f]{4})-([0-9a-f]{12})$/i.exec(e)?.slice(1,6).join("");break;case 38:t=/^\{([0-9a-f]{8})-([0-9a-f]{4})-([0-9a-f]{4})-([0-9a-f]{4})-([0-9a-f]{12})\}$/i.exec(e)?.slice(1,6).join("");break;case 45:t=/^urn:uuid:([0-9a-f]{8})-([0-9a-f]{4})-([0-9a-f]{4})-([0-9a-f]{4})-([0-9a-f]{12})$/i.exec(e)?.slice(1,6).join("")}if(t){let e=new Uint8Array(16);for(let r=0;r<16;r+=4){let i=parseInt(t.substring(2*r,2*r+8),16);e[r+0]=i>>>24,e[r+1]=i>>>16,e[r+2]=i>>>8,e[r+3]=i}return new eV(e)}throw SyntaxError("could not parse UUID string")}toString(){let e="";for(let t=0;t<this.bytes.length;t++)e+=eH.charAt(this.bytes[t]>>>4),e+=eH.charAt(15&this.bytes[t]),(3===t||5===t||7===t||9===t)&&(e+="-");return e}toHex(){let e="";for(let t=0;t<this.bytes.length;t++)e+=eH.charAt(this.bytes[t]>>>4),e+=eH.charAt(15&this.bytes[t]);return e}toJSON(){return this.toString()}getVariant(){let e=this.bytes[8]>>>4;if(e<0)throw Error("unreachable");if(e<=7)return this.bytes.every(e=>0===e)?"NIL":"VAR_0";if(e<=11)return"VAR_10";if(e<=13)return"VAR_110";if(e<=15)return this.bytes.every(e=>255===e)?"MAX":"VAR_RESERVED";throw Error("unreachable")}getVersion(){return"VAR_10"===this.getVariant()?this.bytes[6]>>>4:void 0}clone(){return new eV(this.bytes.slice(0))}equals(e){return 0===this.compareTo(e)}compareTo(e){for(let t=0;t<16;t++){let r=this.bytes[t]-e.bytes[t];if(0!==r)return Math.sign(r)}return 0}}class eW{constructor(e){this.timestamp=0,this.counter=0,this.random=e??eK()}generate(){return this.generateOrResetCore(Date.now(),1e4)}generateOrAbort(){return this.generateOrAbortCore(Date.now(),1e4)}generateOrResetCore(e,t){let r=this.generateOrAbortCore(e,t);return void 0===r&&(this.timestamp=0,r=this.generateOrAbortCore(e,t)),r}generateOrAbortCore(e,t){if(!Number.isInteger(e)||e<1||e>0xffffffffffff)throw RangeError("`unixTsMs` must be a 48-bit positive integer");if(t<0||t>0xffffffffffff)throw RangeError("`rollbackAllowance` out of reasonable range");if(e>this.timestamp)this.timestamp=e,this.resetCounter();else{if(!(e+t>=this.timestamp))return;this.counter++,this.counter>0x3ffffffffff&&(this.timestamp++,this.resetCounter())}return eV.fromFieldsV7(this.timestamp,Math.trunc(this.counter/0x40000000),0x3fffffff&this.counter,this.random.nextUint32())}resetCounter(){this.counter=1024*this.random.nextUint32()+(1023&this.random.nextUint32())}generateV4(){let e=new Uint8Array(Uint32Array.of(this.random.nextUint32(),this.random.nextUint32(),this.random.nextUint32(),this.random.nextUint32()).buffer);return e[6]=64|e[6]>>>4,e[8]=128|e[8]>>>2,eV.ofInner(e)}}let eK=()=>({nextUint32:()=>65536*Math.trunc(65536*Math.random())+Math.trunc(65536*Math.random())>>>0}),eG=()=>eQ().toString(),eQ=()=>(n||(n=new eW)).generate();function eJ(e){let t={};if(e)for(let r of e.split(";")){let[e,...i]=r.trim().split("=");if(e){let r=i.join("=").trim();try{t[e.trim()]=decodeURIComponent(r)}catch{t[e.trim()]=r}}}return{get:e=>e in t?{value:t[e]}:void 0}}function eZ(e){let t=e.replace(/\+/g,"PL").replace(/\//g,"SL").replace(/=/g,"EQ");return`ph_${t}_posthog`}function eY(e){let t=Date.now();return JSON.stringify({distinct_id:e,$device_id:e,$user_state:"anonymous",$sesid:[t,eG(),t]})}function eX(e,t){let r=eZ(t),i=e.get(r);return i?e1(i.value):null}function e0(e){if(!e)return;let t={};return e.sessionId&&(t.$session_id=e.sessionId),e.deviceId&&(t.$device_id=e.deviceId),Object.keys(t).length>0?t:void 0}function e1(e){if(!e)return null;try{let t=JSON.parse(e);if(!t||"object"!=typeof t||!t.distinct_id)return null;let r=m(t.$sesid)?t.$sesid[1]:void 0;return{distinctId:String(t.distinct_id),isIdentified:"identified"===t.$user_state,sessionId:"string"==typeof r?r:void 0,deviceId:"string"==typeof t.$device_id?t.$device_id:void 0}}catch{return null}}let e2=e=>void 0===e?void 0:e.variant??e.enabled,e3=e=>{if("string"!=typeof e)return e;try{return JSON.parse(e)}catch{return e}},e5=["$feature_flag","$feature_flag_response","$feature_flag_has_experiment","$feature_flag_id","$feature_flag_version","$feature_flag_reason","$feature_flag_request_id","$feature_flag_evaluated_at","$feature_flag_error","locally_evaluated","$groups","$process_person_profile","$geoip_disable","$current_url","$pathname","$referring_domain","utm_source","utm_medium","utm_campaign","utm_content","utm_term","gad_source","mc_cid","gclid","gclsrc","dclid","gbraid","wbraid","fbclid","msclkid","twclid","li_fat_id","igshid","ttclid","rdt_cid","epik","qclid","sccid","oppref","irclid","_kx","$session_id","$window_id","$lib","$lib_version","$device_id","$is_server"],e4=(e,t=[])=>{let r={},i=t=>{void 0!==e[t]&&(r[t]=e[t])};return e5.forEach(i),t.forEach(i),r};class e6{constructor(){this.events={},this.events={}}on(e,t){return this.events[e]||(this.events[e]=[]),this.events[e].push(t),()=>{this.events[e]=this.events[e].filter(e=>e!==t)}}emit(e,t){for(let r of this.events[e]||[])r(t);for(let r of this.events["*"]||[])r(e,t)}}let e8=e=>{throw B("NativeGzipValidationError",`Native gzip produced invalid output: ${e}`)},e9=async(e,t)=>{e.size<18&&e8("too-short");let r=new Uint8Array(await e.slice(0,10).arrayBuffer());r.length>=2&&31===r[0]&&139===r[1]&&8===r[2]||e8("invalid-header");let i=new DataView(await e.slice(e.size-8).arrayBuffer());i.getUint32(0,!0)!==(e=>{let t=(()=>{if(a)return a;a=[];for(let e=0;e<256;e++){let t=e;for(let e=0;e<8;e++)t=1&t?0xedb88320^t>>>1:t>>>1;a[e]=t>>>0}return a})(),r=0xffffffff;for(let i=0;i<e.length;i++)r=t[(r^e[i])&255]^r>>>8;return(0xffffffff^r)>>>0})(t)&&e8("invalid-crc");let s=t.length>>>0;i.getUint32(4,!0)!==s&&e8("invalid-size")};async function e7(e,t=!0,r){try{let t=new TextEncoder().encode(e),r=new globalThis.CompressionStream("gzip"),i=r.writable.getWriter(),s=i.write(t).then(()=>i.close()).catch(async e=>{try{await i.abort(e)}catch{}throw e}),n=new Response(r.readable).blob(),[a]=await Promise.all([n,s]);return await e9(a,t),a}catch(e){if(r?.rethrow)throw e;return t&&console.error("Failed to gzip compress data",e),null}}class te{add(e){let t=eG(),r=++this.nextId;return this.promiseByIds[t]={id:r,promise:e},e.catch(()=>{}).finally(()=>{delete this.promiseByIds[t]}),e}async join(){let e=Object.values(this.promiseByIds).map(e=>e.promise),t=e.length;for(;t>0;)await Promise.all(e),t=(e=Object.values(this.promiseByIds).map(e=>e.promise)).length}getPromises(e=[],t=this.nextId){let r=new Set(e);return Object.values(this.promiseByIds).filter(e=>e.id<=t&&!r.has(e.promise)).map(e=>e.promise)}get maxId(){return this.nextId}get length(){return Object.keys(this.promiseByIds).length}constructor(){this.promiseByIds={},this.nextId=0}}let tt=(e,t,r)=>{function i(s,...n){t(()=>{(0,r[s])(e,...n)})}return{debug:(...e)=>{i("debug",...e)},info:(...e)=>{i("log",...e)},warn:(...e)=>{i("warn",...e)},error:(...e)=>{i("error",...e)},critical:(...t)=>{r.error(e,...t)},createLogger:i=>tt(`${e} ${i}`,t,r)}};class tr{record(e){if("too-large"===e.kind)return;if("retry-later"!==e.kind)return void this.reset();if(!e.retryAfterMs)return;let t=this.isOpen(),r=Date.now(),i=Math.min(e.retryAfterMs,3e5);if(!t){this._installedAt=r,this._until=r+i;return}this._until=Math.max(this._until,Math.min(r+i,this._installedAt+3e5))}remainingMs(){let e=Date.now();if(e<this._installedAt-5e3)return this.reset(),0;let t=Math.min(3e5,Math.max(0,this._until-e));return 0===t&&this.reset(),t}isOpen(){return this.remainingMs()>0}reset(){this._until=0,this._installedAt=0}constructor(){this._until=0,this._installedAt=0}}class ti extends Error{constructor(e,t,r,i){super("HTTP error while fetching PostHog: status="+e.status+", reqByteLength="+t),this.response=e,this.reqByteLength=t,this.responseBodyDeadline=r,this.abortController=i,this.name="PostHogFetchHttpError",this._bodyReadTimedOut=!1}get status(){return this.response.status}get retryAfterMs(){try{return function(e,t=Date.now()){if("string"!=typeof e||!e)return;let r=e.trim(),i=/^\d+\s*,/.test(r)?r.slice(0,r.indexOf(",")).trim():r;if(/^\d+$/.test(i)){let e=1e3*Math.min(Number(i),300);return e>0?e:void 0}if(!/^(Mon|Tue|Wed|Thu|Fri|Sat|Sun)[a-z]*[ ,]/.test(i))return;let s=Date.parse(/^\w{3} \w{3} /.test(i)?i+" GMT":i)-t;if(Number.isFinite(s)&&!(s<=0))return Math.min(s,3e5)}(this.response.headers?.get("retry-after"))}catch{return}}get bodyReadTimedOut(){return this._bodyReadTimedOut}get text(){if(!this.responseBodyTextPromise)if(Date.now()>=this.responseBodyDeadline){this._bodyReadTimedOut=!0;let e=B("AbortError","Response body read timed out");this.cancelResponseBody(e),this.responseBodyTextPromise=Promise.reject(e)}else{let e,t=new Promise((e,t)=>{this.responseBodyTimer=U(()=>{this._bodyReadTimedOut=!0;let e=B("AbortError","Response body read timed out");t(e),this.cancelResponseBody(e)},this.responseBodyDeadline-Date.now())});try{e=Promise.resolve(this.response.text())}catch(t){e=Promise.reject(t)}this.responseBodyTextPromise=Promise.race([e,t]).finally(()=>clearTimeout(this.responseBodyTimer))}return this.responseBodyTextPromise}get json(){return this.text.then(e=>JSON.parse(e))}cancelResponseBody(e){clearTimeout(this.responseBodyTimer),this.abortController.signal.aborted||this.abortController.abort(e),(async()=>{try{await this.response.body?.cancel()}catch{}})()}}class ts extends Error{constructor(e){super("Network error while fetching PostHog",e instanceof Error?{cause:e}:{}),this.error=e,this.name="PostHogFetchNetworkError"}}async function tn(e){if(e instanceof ti){let t="";try{t=await e.text}catch{e.bodyReadTimedOut&&(t="<response body read timed out>")}console.error(`Error while flushing PostHog: message=${e.message}, response body=${t}`,e)}else console.error("Error while flushing PostHog",e);return Promise.resolve()}function ta(e){return e instanceof ts}function to(e){if(e instanceof ti)return 502===e.status||504===e.status;if(!(e instanceof ts))return!1;let t=e.error;return"ECONNREFUSED"!==(t?.code??t?.cause?.code)}function tl(e){try{if("string"!=typeof e)return e instanceof Uint8Array?e.byteLength:e.size;if("u">typeof Buffer)return Buffer.byteLength(e,"utf8");return new TextEncoder().encode(e).length}catch{return 0}}function tu(e){return"object"==typeof e&&e instanceof ti&&413===e.status}function tc(e){return e instanceof ti?408===e.status||429===e.status||e.status>=500:ta(e)}function th(e){return null!==e&&"object"==typeof e&&!Array.isArray(e)}let td="default";class tp{getErrorPropertiesBuilder(){return this._errorPropertiesBuilder||(this._errorPropertiesBuilder=this.createErrorPropertiesBuilder()),this._errorPropertiesBuilder}createErrorPropertiesBuilder(){return new W([new eB,new eI,new eN,new eC],ew())}getEvaluationRuntime(){}constructor(e,t={}){var r;this.flushPromise=null,this.pendingFlushPromise=null,this.flushPromises=new Set,this._dequeuedMessagesCount=0,this.shutdownPromise=null,this.promiseQueue=new te,this._events=new e6,this._isInitialized=!1;let i="string"==typeof e?e.trim():"",s="string"==typeof t.host?t.host.trim():"",n=!i;this._logger=function(e,t=e=>e()){return tt(e,t,function(e=console){return{log:e.log.bind(e),warn:e.warn.bind(e),error:e.error.bind(e),debug:e.debug.bind(e)}}())}("[PostHog]",this.logMsgIfDebug.bind(this)),n&&this._logger.error("You must pass your PostHog project's api key. The client will be disabled."),this.apiKey=i,this.host=(r=s||"https://us.i.posthog.com",r?.replace(/\/+$/,"")),this.flushAt=t.flushAt?Math.max(t.flushAt,1):20,this.maxBatchSize=Math.max(this.flushAt,t.maxBatchSize??100),this.maxQueueSize=Math.max(this.flushAt,t.maxQueueSize??1e3),this.flushInterval=t.flushInterval??1e4,this.preloadFeatureFlags=t.preloadFeatureFlags??!0,this.defaultOptIn=t.defaultOptIn??!0,this.disableSurveys=t.disableSurveys??!1,this._retryOptions={retryCount:t.fetchRetryCount??3,retryDelay:t.fetchRetryDelay??3e3,retryCheck:tc},this.requestTimeout=t.requestTimeout??1e4,this.featureFlagsRequestTimeoutMs=t.featureFlagsRequestTimeoutMs??3e3,this.featureFlagsRequestMaxRetries=t.featureFlagsRequestMaxRetries??1,this.remoteConfigRequestTimeoutMs=t.remoteConfigRequestTimeoutMs??3e3,this.disableGeoip=t.disableGeoip??!0,this.disabled=(t.disabled??!1)||n,this.historicalMigration=t?.historicalMigration??!1,this._initPromise=Promise.resolve(),this._isInitialized=!0,this.evaluationContexts=t?.evaluationContexts??t?.evaluationEnvironments,t?.evaluationEnvironments&&!t?.evaluationContexts&&this._logger.warn("evaluationEnvironments is deprecated. Use evaluationContexts instead. This property will be removed in a future version."),this.disableCompression=!("CompressionStream"in globalThis&&"TextEncoder"in globalThis&&"Response"in globalThis&&"function"==typeof Response.prototype.blob)||(t?.disableCompression??!1)}logMsgIfDebug(e){this.isDebug&&e()}wrap(e){return this.disabled?void this._logger.warn("The client is disabled"):this._isInitialized?e():void this._initPromise.then(()=>e())}getCommonEventProperties(){return{$lib:this.getLibraryId(),$lib_version:this.getLibraryVersion()}}get optedOut(){return this.getPersistedProperty(c.OptedOut)??!this.defaultOptIn}async optIn(){this.wrap(()=>{this.setPersistedProperty(c.OptedOut,!1)})}async optOut(){this.wrap(()=>{this.setPersistedProperty(c.OptedOut,!0)})}on(e,t){return this._events.on(e,t)}debug(e=!0){if(this.removeDebugCallback?.(),e){let e=this.on("*",(e,t)=>this._logger.info(e,t));this.removeDebugCallback=()=>{e(),this.removeDebugCallback=void 0}}}get isDebug(){return!!this.removeDebugCallback}get isDisabled(){return this.disabled}buildPayload(e){let t=e.properties||{},r=this.mergeCommonEventProperties(t);var i=r;for(let e of Object.keys(t))(e.startsWith("$feature/")||"$active_feature_flags"===e)&&(i[e]=t[e]);return"$feature_flag_called"===e.event&&!1===r.$feature_flag_has_experiment&&this.isMinimalFlagCalledEventsEnabled()&&(r=e4(r)),{distinct_id:e.distinct_id,event:e.event,properties:r}}mergeCommonEventProperties(e){return{...e,...this.getCommonEventProperties()}}isMinimalFlagCalledEventsEnabled(){return!1}addPendingPromise(e){return this.promiseQueue.add(e)}identifyStateless(e,t,r){this.wrap(()=>{let i={...this.buildPayload({distinct_id:e,event:"$identify",properties:t})};this.enqueue("identify",i,r)})}async identifyStatelessImmediate(e,t,r){let i={...this.buildPayload({distinct_id:e,event:"$identify",properties:t})};await this.sendImmediate("identify",i,r)}captureStateless(e,t,r,i){this.wrap(()=>{let s=this.buildPayload({distinct_id:e,event:t,properties:r});this.enqueue("capture",s,i)})}async captureStatelessImmediate(e,t,r,i){let s=this.buildPayload({distinct_id:e,event:t,properties:r});await this.sendImmediate("capture",s,i)}aliasStateless(e,t,r,i){this.wrap(()=>{let s=this.buildPayload({event:"$create_alias",distinct_id:t,properties:{...r||{},distinct_id:t,alias:e}});this.enqueue("alias",s,i)})}async aliasStatelessImmediate(e,t,r,i){let s=this.buildPayload({event:"$create_alias",distinct_id:t,properties:{...r||{},distinct_id:t,alias:e}});await this.sendImmediate("alias",s,i)}groupIdentifyStateless(e,t,r,i,s,n){this.wrap(()=>{let a=this.buildPayload({distinct_id:s||`$${e}_${t}`,event:"$groupidentify",properties:{$group_type:e,$group_key:t,$group_set:r||{},...n||{}}});this.enqueue("capture",a,i)})}async groupIdentifyStatelessImmediate(e,t,r,i,s,n){let a=this.buildPayload({distinct_id:s||`$${e}_${t}`,event:"$groupidentify",properties:{$group_type:e,$group_key:t,$group_set:r||{},...n||{}}});await this.sendImmediate("capture",a,i)}async getRemoteConfig(){await this._initPromise;let e=this.host;"https://us.i.posthog.com"===e?e="https://us-assets.i.posthog.com":"https://eu.i.posthog.com"===e&&(e="https://eu-assets.i.posthog.com");let t=`${e}/array/${this.apiKey}/config`,r={method:"GET",headers:{...this.getCustomHeaders(),"Content-Type":"application/json"}};return this.fetchWithRetry(t,r,{type:"required",consume:e=>e.json()},{retryCount:0},this.remoteConfigRequestTimeoutMs).catch(e=>{this._logger.error("Remote config could not be loaded",e),this._events.emit("error",e)})}async getFlags(e,t={},r={},i={},s={},n=!1){await this._initPromise;let a=`${this.host}/flags/?v=2${n?"&config=true":""}`,o={token:this.apiKey,distinct_id:e,groups:t,person_properties:r,group_properties:i,...s};r.$device_id&&(o.$device_id=r.$device_id),this.evaluationContexts&&this.evaluationContexts.length>0&&(o.evaluation_contexts=this.evaluationContexts);let l=this.getEvaluationRuntime();l&&(o.evaluation_runtime=l);let u={method:"POST",headers:{...this.getCustomHeaders(),"Content-Type":"application/json"},body:JSON.stringify(o)};return this._logger.info("Flags URL",a),this.fetchWithRetry(a,u,{type:"required",consume:e=>e.json()},{retryCount:this.featureFlagsRequestMaxRetries,retryCheck:to},this.featureFlagsRequestTimeoutMs).then(e=>({success:!0,response:(e=>{if("flags"in e){let t,r=Object.fromEntries(Object.entries(e.flags??{}).map(([e,t])=>[e,e2(t)]).filter(([,e])=>void 0!==e)),i=Object.fromEntries(Object.keys(t=e.flags??{}).filter(e=>{let r=t[e];return r.enabled&&r.metadata&&void 0!==r.metadata.payload}).map(e=>{let r=t[e].metadata?.payload;return[e,r?e3(r):void 0]}));return{...e,featureFlags:r,featureFlagPayloads:i}}{let t=e.featureFlags??{},r=Object.fromEntries(Object.entries(e.featureFlagPayloads||{}).map(([e,t])=>[e,e3(t)])),i=Object.fromEntries(Object.entries(t).map(([e,t])=>{var i,s;return[e,{key:e,enabled:"string"==typeof(i=t)||i,variant:"string"==typeof i?i:void 0,reason:void 0,metadata:{id:void 0,version:void 0,payload:(s=r[e])?JSON.stringify(s):void 0,description:void 0}}]}));return{...e,featureFlags:t,featureFlagPayloads:r,flags:i}}})(e)})).catch(e=>(this._events.emit("error",e),{success:!1,error:this.categorizeRequestError(e)}))}categorizeRequestError(e){if(e instanceof ti)return{type:"api_error",statusCode:e.status};if(e instanceof ts){let t=e.error;return t instanceof Error&&("AbortError"===t.name||"TimeoutError"===t.name)?{type:"timeout"}:{type:"connection_error"}}return{type:"unknown_error"}}async getFeatureFlagStateless(e,t,r={},i={},s={},n){await this._initPromise;let a=await this.getFeatureFlagDetailStateless(e,t,r,i,s,n);if(void 0===a)return{response:void 0,requestId:void 0};let o=e2(a.response);return void 0===o&&(o=!1),{response:o,requestId:a.requestId}}async getFeatureFlagDetailStateless(e,t,r={},i={},s={},n){await this._initPromise;let a=await this.getFeatureFlagDetailsStateless(t,r,i,s,n,[e]);if(void 0!==a)return{response:a.flags[e],requestId:a.requestId,evaluatedAt:a.evaluatedAt}}async getFeatureFlagPayloadStateless(e,t,r={},i={},s={},n){await this._initPromise;let a=await this.getFeatureFlagPayloadsStateless(t,r,i,s,n,[e]);if(!a)return;let o=a[e];return void 0===o?null:o}async getFeatureFlagPayloadsStateless(e,t={},r={},i={},s,n){return await this._initPromise,(await this.getFeatureFlagsAndPayloadsStateless(e,t,r,i,s,n)).payloads}async getFeatureFlagsStateless(e,t={},r={},i={},s,n){return await this._initPromise,await this.getFeatureFlagsAndPayloadsStateless(e,t,r,i,s,n)}async getFeatureFlagsAndPayloadsStateless(e,t={},r={},i={},s,n){await this._initPromise;let a=await this.getFeatureFlagDetailsStateless(e,t,r,i,s,n);return a?{flags:a.featureFlags,payloads:a.featureFlagPayloads,requestId:a.requestId}:{flags:void 0,payloads:void 0,requestId:void 0}}async getFeatureFlagDetailsStateless(e,t={},r={},i={},s,n){await this._initPromise;let a={geoip_disable:s??this.disableGeoip};n&&(a.flag_keys_to_evaluate=n);let o=await this.getFlags(e,t,r,i,a);if(!o.success)return;let l=o.response;return(l.errorsWhileComputingFlags&&console.error("[FEATURE FLAGS] Error while computing feature flags, some flags may be missing or incorrect. Learn more at https://posthog.com/docs/feature-flags/best-practices"),l.quotaLimited?.includes("feature_flags"))?(console.warn("[FEATURE FLAGS] Feature flags quota limit exceeded - feature flags unavailable. Learn more about billing limits at https://posthog.com/docs/billing/limits-alerts"),{flags:{},featureFlags:{},featureFlagPayloads:{},requestId:l?.requestId,quotaLimited:l.quotaLimited}):l}async getSurveysStateless(){if(await this._initPromise,this.disabled)return[];if(!0===this.disableSurveys)return this._logger.info("Loading surveys is disabled."),[];let e=`${this.host}/api/surveys/?token=${this.apiKey}`,t={method:"GET",headers:{...this.getCustomHeaders(),"Content-Type":"application/json"}},r=await this.fetchWithRetry(e,t,{type:"required",consume:e=>{if(200!==e.status||!e.json){let t=`Surveys API could not be loaded: ${e.status}`,r=Error(t);return this._logger.error(r),this._events.emit("error",Error(t)),Promise.resolve(void 0)}return e.json()}}).catch(e=>{this._logger.error("Surveys API could not be loaded",e),this._events.emit("error",e)}),i=r?.surveys;return i&&this._logger.info("Surveys fetched from API: ",JSON.stringify(i)),i??[]}get props(){return this._props||(this._props=this.getPersistedProperty(c.Props)),this._props||{}}set props(e){this._props=e}async register(e){this.wrap(()=>{this.props={...this.props,...e},this.setPersistedProperty(c.Props,this.props)})}async unregister(e){this.wrap(()=>{delete this.props[e],this.setPersistedProperty(c.Props,this.props)})}processBeforeEnqueue(e){return e}async flushStorage(){}getQueueRouteKey(e){return td}persistedQueueKeyForRoute(e){return c.Queue}getActiveQueueRoutes(){return[td]}getRouteQueue(e){return this.getPersistedProperty(this.persistedQueueKeyForRoute(e))||[]}enqueue(e,t,r,i){this.wrap(()=>{if(this.optedOut)return void this._events.emit(e,"Library is disabled. Not sending event. To re-enable, call posthog.optIn()");let s=this.prepareMessage(t,r);if(null===(s=this.processBeforeEnqueue(s)))return;s=this.normalizeMessage(s);let n=this.persistedQueueKeyForRoute(i??this.getQueueRouteKey(s)),a=this.getPersistedProperty(n)||[];a.length>=this.maxQueueSize&&(a.shift(),this._logger.warn("Queue is full, the oldest event is dropped.")),a.push({message:s}),this.setPersistedProperty(n,a),this._events.emit(e,s),a.length>=this.flushAt&&this.flushBackground(),this.flushInterval&&!this._flushTimer&&(this._flushTimer=U(()=>this.flushBackground(),this.flushInterval))})}async sendImmediate(e,t,r,i){if(this.disabled)return void this._logger.warn("The client is disabled");if(this._isInitialized||await this._initPromise,this.optedOut)return void this._events.emit(e,"Library is disabled. Not sending event. To re-enable, call posthog.optIn()");let s=this.prepareMessage(t,r);if(null!==(s=this.processBeforeEnqueue(s))){s=this.normalizeMessage(s);try{await this.sendBatch([s],void 0,i??this.getQueueRouteKey(s))}catch(e){this._events.emit("error",e)}}}normalizeMessage(e){let{type:t,library:r,library_version:i,...s}=e,n=th(s.properties)?s.properties:void 0;return void 0!==r&&n?.$lib===void 0&&(n={...n||{},$lib:r}),void 0!==i&&n?.$lib_version===void 0&&(n={...n||{},$lib_version:i}),n&&(s.properties=n),s.uuid=j(s.uuid,eG),s}normalizeTimestampForWire(e){let t=e instanceof Date?e:"string"==typeof e?new Date(e):null;if(!t||Number.isNaN(t.getTime()))return e;let r=t.toISOString(),i="string"==typeof e?e.match(/\.(\d+)(?:Z|[+-]\d{2}:?\d{2})?$/i)?.[1]:void 0;return i&&i.length>3?r.replace(/\.\d{3}Z$/,`.${i}Z`):r}prepareMessage(e,t){let r={...e,timestamp:t?.timestamp?t?.timestamp:q(),uuid:j(t?.uuid,eG)};return(t?.disableGeoip??this.disableGeoip)&&(th(r.properties)||(r.properties={}),r.properties.$geoip_disable=!0),r.distinctId&&(r.distinct_id=r.distinctId,delete r.distinctId),r}clearFlushTimer(){this._flushTimer&&(clearTimeout(this._flushTimer),this._flushTimer=void 0)}flushBackground(){this.pendingFlushPromise||this.flushAutomatic().catch(async e=>{await tn(e)})}flushAutomatic(){return this.flush()}async waitForPendingPromises(e,t=[]){let r=t.filter(e=>!!e),i=0;for(;;){let t=this.promiseQueue.getPromises([...r,...this.flushPromises],e);if(0===t.length)return;i>0&&this._logger.debug(`flush() re-checking ${t.length} pending promise(s) before flushing`),await Promise.all(t.map(e=>e.catch(()=>{}))),i++}}flushWithPendingPromises(){return this.flushInternal(!0)}flush(){return this.flushInternal(!1)}flushInternal(e){if(this.disabled)return Promise.resolve();if(!e&&this.pendingFlushPromise)return this.pendingFlushPromise;let t=this.flushPromise,r=this.promiseQueue.maxId,i=Promise.resolve().then(()=>{if(e)return this.waitForPendingPromises(r,[t,i])}).then(()=>H([t])).then(()=>(this.pendingFlushPromise===i&&(this.pendingFlushPromise=null),this._flush()));return this.pendingFlushPromise=i,this.flushPromise=i,this.flushPromises.add(i),this.addPendingPromise(i),H([i]).then(()=>{this.flushPromises.delete(i),this.pendingFlushPromise===i&&(this.pendingFlushPromise=null),this.flushPromise===i&&(this.flushPromise=null)}),i}getCustomHeaders(){let e=this.getCustomUserAgent(),t={};return e&&""!==e&&(t["User-Agent"]=e),t}compressPayload(e){return e7(e,this.isDebug)}getBatchEndpointPath(e){return"/batch/"}async sendBatch(e,t,r=td){let i={api_key:this.apiKey,batch:e.map(e=>{if(!e)return e;let t=this.normalizeTimestampForWire(e.timestamp);return t===e.timestamp?e:{...e,timestamp:t}}),sent_at:q()};this.historicalMigration&&(i.historical_migration=!0);let s=d(i),n=`${this.host}${this.getBatchEndpointPath(r)}`,a=this.disableCompression?null:await this.compressPayload(s),o={method:"POST",headers:{...this.getCustomHeaders(),"Content-Type":"application/json",...null!==a&&{"Content-Encoding":"gzip"}},body:a||s};await this.fetchWithRetry(n,o,{type:"successful-write"},t)}async _flush(){let e;this.clearFlushTimer(),await this._initPromise;let t=this.getActiveQueueRoutes();if(!t.some(e=>this.getRouteQueue(e).length>0))return;let r=[];for(let i of t)try{await this._flushRoute(i,r)}catch(t){void 0===e&&(e=t)}if(void 0!==e)throw e;this._events.emit("flush",r)}async _flushRoute(e,t){let r=this.persistedQueueKeyForRoute(e),i=this.getPersistedProperty(r)||[];if(!i.length)return;let s=i.length,n=0;for(;i.length>0&&n<s;){let s=i.slice(0,this.maxBatchSize),a=s.map(e=>void 0===e.message?e.message:this.normalizeMessage(e.message)),o=async()=>{let e=this.getPersistedProperty(r)||[],t=[...s],n=e.filter(e=>{let r=e.message?.uuid,i=t.findIndex(t=>t===e||"string"==typeof r&&r.length>0&&t.message?.uuid===r);return -1===i||(t.splice(i,1),!1)});this.setPersistedProperty(r,n),i=n,this._dequeuedMessagesCount+=s.length,await this.flushStorage()},l={retryCheck:e=>!tu(e)&&tc(e)};try{await this.sendBatch(a,l,e)}catch(e){if(tu(e)&&a.length>1){this.maxBatchSize=Math.max(1,Math.floor(a.length/2)),this._logger.warn(`Received 413 when sending batch of size ${a.length}, reducing batch size to ${this.maxBatchSize}`);continue}throw e instanceof ts||await o(),this._events.emit("error",e),e}await o(),t.push(...a),n+=a.length}}async _sendOtlpBatch({path:e,auth:t,payload:r}){let i;if(this.disabled)return{kind:"fatal",error:Error("The client is disabled")};try{i=JSON.stringify(r)}catch(t){return this.logMsgIfDebug(()=>console.warn(`[PostHog] Could not serialize a ${e} batch; reporting it as too large`,t)),{kind:"too-large",measuredLocally:!0}}let s=tl(i);if(s>0xa00000)return this.logMsgIfDebug(()=>console.warn(`[PostHog] Not sending a ${e} batch of ${s} bytes: the endpoint accepts at most 10485760`)),{kind:"too-large",measuredLocally:!0};let n="bearer"===t?`${this.host}/i/v1/${e}`:`${this.host}/i/v1/${e}?token=${encodeURIComponent(this.apiKey)}`,a=this.disableCompression?null:await this.compressPayload(i),o=a||i,l={method:"POST",headers:{...this.getCustomHeaders(),"Content-Type":"application/json",..."bearer"===t&&{Authorization:`Bearer ${this.apiKey}`},...null!==a&&{"Content-Encoding":"gzip"}},body:o};try{return await this.fetchWithRetry(n,l,{type:"successful-write"},{retryCheck:e=>!tu(e)&&(!(e instanceof ti)||void 0===e.retryAfterMs)&&tc(e)}),{kind:"ok"}}catch(e){if(tu(e))return{kind:"too-large"};if(tc(e)){let t=e instanceof ti?e.retryAfterMs:void 0;return{kind:"retry-later",error:e,...void 0!==t&&{retryAfterMs:t}}}return{kind:"fatal",error:e}}}async _sendLogsBatch(e){return this._sendOtlpBatch({path:"logs",auth:"query-token",payload:e})}async _sendMetricsBatch(e){return this._sendOtlpBatch({path:"metrics",auth:"query-token",payload:e})}async _sendTracesBatch(e){return this._sendOtlpBatch({path:"traces",auth:"bearer",payload:e})}async fetchWithRetry(e,t,r,i,s){let n=tl(t.body?t.body:""),a={...this._retryOptions,...i},o=0;return await N(async()=>{let i,a,l;o++;let u=new AbortController,c=s??this.requestTimeout,h=Date.now()+c,d=new Promise((e,t)=>{i=U(()=>{let e=B("AbortError",`Request timed out after ${c}ms`);t(e),u.abort(e)},c)}),p=!1,g=()=>l??=(async()=>{try{await a?.body?.cancel()}catch{}})();try{let i;try{i=this.fetch(e,{signal:u.signal,...t})}catch(e){throw new ts(e)}i.then(e=>{u.signal.aborted&&!p&&Promise.resolve(e.body?.cancel()).catch(()=>{})}).catch(()=>{});try{a=await Promise.race([i,d]),p=!0}catch(e){throw new ts(e)}let s="no-cors"===t.mode,o="successful-write"===r.type?300:400;if(!s&&(a.status<200||a.status>=o))throw new ti(a,n,h,u);if("successful-write"===r.type){try{await Promise.race([g(),d])}catch{}return}try{return await Promise.race([r.consume(a),d])}catch(e){if(u.signal.aborted)throw new ts(e);throw e}}finally{clearTimeout(i),u.signal.aborted&&a&&g()}},{...a,retryCheck:e=>{let t=a.retryCheck(e);return t&&o<=a.retryCount&&e instanceof ti&&e.cancelResponseBody(),t}})}async _shutdown(e=3e4){await this._initPromise;let t=!1;if(this.clearFlushTimer(),!this.disabled)return z((async()=>{try{for(await this.promiseQueue.join();this.getActiveQueueRoutes().some(e=>this.getRouteQueue(e).length>0);){let e=this._dequeuedMessagesCount;if(await this.flush(),t)break;if(this._dequeuedMessagesCount===e){this._logger.warn("Shutdown flush completed but did not send any queued events. Stopping drain to avoid a loop.");break}}}catch(e){if(!("object"==typeof e&&(e instanceof ti||ta(e))))throw e;await tn(e)}})(),e,()=>{this._logger.critical("Timeout while shutting down PostHog. Some events may not have been sent.",{shutdownTimeoutMs:e}),t=!0})}async shutdown(e=3e4){return this.shutdownPromise?this._logger.warn("shutdown() called while already shutting down. shutdown() is meant to be called once before process exit - use flush() for per-request cleanup"):this.shutdownPromise=this._shutdown(e).finally(()=>{this.shutdownPromise=null}),this.shutdownPromise}}let tg="[Circular]",tf="[Truncated]",tm="[Unserializable]";function ty(e){let t="";for(let r=0;r<e.length;r++){let i=e.charCodeAt(r);if(i>=55296&&i<=56319){let i=e.charCodeAt(r+1);i>=56320&&i<=57343?(t+=e[r]+e[r+1],r++):t+="�"}else t+=i>=56320&&i<=57343?"�":e[r]}return t}function t_(e,t){if(!t)return e;let r=[];try{r=Object.keys(t)}catch{r=[]}for(let i of r){let r;try{r=t[i]}catch{r=tm}Object.defineProperty(e,i,{value:r,enumerable:!0,writable:!0,configurable:!0})}return e}Date.prototype.getTime,Date.prototype.toISOString,Object.prototype.propertyIsEnumerable;let tv=Object.prototype.propertyIsEnumerable;function tb(e,t){try{return tw(e,t,{ancestors:new WeakSet,remainingNodes:1e4},0)}catch{return[]}}function tw(e,t,r,i){let s=[];for(let n in e)if(tv.call(e,n)){if(!n){t?.debug("Dropping an attribute with an empty key");continue}if(s.length>=1e3||r.remainingNodes<=0){t?.debug("Attributes truncated: the value exceeds the OTLP encoder budget");break}try{let a=e[n];if(w(a)||_(a))continue;s.push({key:ty(n),value:function e(t,r,i,s){if(i.remainingNodes<=0)return{stringValue:tf};if(i.remainingNodes--,"[object Boolean]"===f.call(t))return{boolValue:t};if("bigint"==typeof t){let e,i;return e=t.toString(),t>=(i=BigInt("9223372036854775808"))||t<-i?(r?.debug(`Attribute ${e} is outside the int64 range; encoding it as a string`),{stringValue:e}):{intValue:e}}if("number"==typeof t){if(!Number.isFinite(t))return{stringValue:String(t)};if(Number.isInteger(t)){if(Number.isSafeInteger(t))return{intValue:String(t)};if("u"<typeof BigInt)return{stringValue:String(t)};let e=BigInt(t).toString();return t>=0x8000000000000000||t<-0x8000000000000000?(r?.debug(`Attribute ${e} is outside the int64 range; encoding it as a string`),{stringValue:e}):{intValue:e}}return{doubleValue:t}}if("string"==typeof t)return{stringValue:ty(t)};if("function"==typeof t)return{stringValue:"[Function]"};if("symbol"==typeof t)return{stringValue:String(t)};if("object"==typeof t&&null!==t){if(i.ancestors.has(t))return{stringValue:tg};if(s>=20)return{stringValue:tf};if(t instanceof Date){let e=Number.isFinite(t.getTime())?t.toISOString():String(t);return{stringValue:"string"==typeof e?ty(e):String(e)}}i.ancestors.add(t);try{try{let n=t.toJSON;if("function"==typeof n)return e(n.call(t),r,i,s+1)}catch{}if(m(t))return{arrayValue:{values:function(t,r,i,s){let n=[],a=Math.min(t.length,1e3),o=0;for(;o<a&&i.remainingNodes>0;o++)try{let a=o in t?t[o]:void 0;if(x(a))continue;n.push(e(a,r,i,s))}catch{n.push({stringValue:tm})}return t.length>o&&n.push({stringValue:tf}),n}(t,r,i,s+1)}};return{kvlistValue:{values:tw(t,r,i,s+1)}}}finally{i.ancestors.delete(t)}}return{stringValue:ty(String(t))}}(a,t,r,i)})}catch{s.push({key:ty(n),value:{stringValue:tm}})}}return s}function tx(e,t,r){return{...t_({},e.resourceAttributes),"service.name":e.serviceName||"unknown_service",...e.environment&&{"deployment.environment":e.environment},...e.serviceVersion&&{"service.version":e.serviceVersion},"telemetry.sdk.name":t,"telemetry.sdk.version":r}}let tS=["service.name","deployment.environment","service.version","telemetry.sdk.name","telemetry.sdk.version"];function tE(e,t){let r=t_({},e),i={};for(let e of tS)Object.prototype.hasOwnProperty.call(r,e)&&(i[e]=r[e],delete r[e]);return[...tb(r,t),...tb(i,t)]}let tF={darwin:"macOS",win32:"Windows",cygwin:"Windows",linux:"Linux",android:"Android",freebsd:"FreeBSD",openbsd:"OpenBSD",netbsd:"NetBSD",sunos:"SunOS",aix:"AIX",haiku:"Haiku","Mac OS X":"macOS"};class tP{constructor(e){this._onFire=e,this._firesAt=0}get pending(){return!!this._timer}arm(e){this.clear(),this._firesAt=Date.now()+e,this._timer=U(()=>{this._timer=void 0,this._onFire()},e)}armNoEarlierThan(e){this._timer&&Date.now()+e<=this._firesAt||this.arm(e)}clear(){this._timer&&(clearTimeout(this._timer),this._timer=void 0)}}function tI(){return .75+.25*Math.random()*2}function tA(e,t,r,i){let s=Math.min(Math.max(0,t-1),6),n=e*2**s;return Math.round((void 0===i?n:Math.min(n,Math.max(i,e)))*r)}let tC="0000000000000000",tk=tC+tC,t$=/^[0-9a-f]+$/;function tO(e){let t=function(e){let t="";for(let r=0;r<e.length;r++)t+=e[r].toString(16).padStart(2,"0");return t}(function(e){let t=new Uint8Array(e),r=globalThis.crypto;if(r&&"function"==typeof r.getRandomValues)try{return r.getRandomValues(t),t}catch{}for(let r=0;r<e;r++)t[r]=Math.floor(256*Math.random());return t}(e));return/[^0]/.test(t)?t:t.slice(0,-1)+"1"}function tM(e,t,r){return"string"==typeof e&&e.length===t&&e!==r&&t$.test(e)}let tT=/^([0-9a-f]{2})-([0-9a-f]{32})-([0-9a-f]{16})-([0-9a-f]{2})(-.*)?$/;function tR(e){let t=tD(e);return t&&{traceId:t.traceId,spanId:t.spanId,flags:1&parseInt(t.flags,16)?tB:tL}}function tD(e){if("string"!=typeof e)return;let t=tT.exec(e.trim());if(!t)return;let[,r,i,s,n,a]=t;if("ff"!==r&&("00"!==r||!a)&&tM(i,32,tk)&&tM(s,16,tC))return{version:r,traceId:i,spanId:s,flags:n}}function tj(e){return Array.isArray(e)&&1===e.length?e[0]:e}let tB="01",tL="00";function tN(e){if("string"!=typeof e)return;let t=e.trim();if(!t||/[^\x20-\x7e\t]/.test(t))return;let r=t.split(",");if(!(r.length>32)){for(let e of r)if(e.trim()&&!e.includes("="))return;return t.length<=512?t:function(e){let t=[...e],r=()=>t.reduce((e,t)=>e+t.length,0)+t.length-1;for(let e=t.length-1;e>=0&&r()>512;e--)t[e].length>128&&t.splice(e,1);for(;t.length&&r()>512;)t.pop();return t.length?t.join(","):void 0}(r)}}let tq=[0,5,10,25,50,75,100,250,500,750,1e3,2500,5e3,7500,1e4];function tU(e){return String(e)+"000000"}function tz(e,t,r,i){let s="";return i&&(s=Object.keys(i).sort().map(e=>`${JSON.stringify(e)}:${JSON.stringify(i[e])}`).join(",")),`${e}\0${t}\0${r??""}\0${s}`}class tH{constructor(e,t,r){this._instance=e,this._config=t,this._logger=r,this._series=new Map,this._flushTimer=new tP(()=>this.flush().catch(e=>{this._logger.error("Metrics flush failed:",e)})),this._flushPromise=null,this._seriesCapWarned=!1,this._typeByName=new Map,this._typeCollisionWarned=new Set,this._retryAfter=new tr,this._consecutiveFlushFailures=0,this._flushJitter=1,this._generation=0}count(e,t=1,r){this._capture({name:e,type:"count",value:t,unit:r?.unit,attributes:r?.attributes})}gauge(e,t,r){this._capture({name:e,type:"gauge",value:t,unit:r?.unit,attributes:r?.attributes})}histogram(e,t,r){this._capture({name:e,type:"histogram",value:t,unit:r?.unit,attributes:r?.attributes})}flush(){let e=this._flushPromise,t=(async()=>{e&&await e.catch(()=>{}),await this._doFlush()})().finally(()=>{this._flushPromise===t&&(this._flushPromise=null)});return this._flushPromise=t,t}drainWindow(){if(0===this._series.size)return null;let e=this._series;return this._series=new Map,this._seriesCapWarned=!1,this._typeByName=new Map,this._typeCollisionWarned=new Set,this._buildPayload(e)}reset(){this._generation++,this._retryAfter.reset(),this._consecutiveFlushFailures=0,this._flushJitter=1,this._flushTimer.clear(),this._series=new Map,this._flushPromise=null,this._seriesCapWarned=!1,this._typeByName=new Map,this._typeCollisionWarned=new Set}_capture(e){let t,r;if(this._instance.isDisabled||this._instance.optedOut)return;let i=this._runBeforeSend(e);if(null===i)return;if(!i.name||"string"!=typeof i.name)return void this._logger.warn("Dropping metric with empty name");if("number"!=typeof i.value||!Number.isFinite(i.value))return void this._logger.warn(`Dropping metric '${i.name}': value must be a finite number`);if("count"===i.type&&i.value<0)return void this._logger.warn(`Dropping count '${i.name}': counters are monotonic, value must be >= 0`);try{t=i.attributes?{...i.attributes}:void 0,r=tz(i.type,i.name,i.unit,t)}catch(e){this._logger.warn(`Dropping metric '${i.name}': attributes could not be serialized`,e);return}let s=this._series.get(r);if(!s){if(!this._admitNewSeries())return;s={name:i.name,type:i.type,unit:i.unit,attributes:t,windowStartMs:Date.now()},this._series.set(r,s)}let n=this._typeByName.get(i.name);void 0===n?this._typeByName.set(i.name,i.type):n===i.type||this._typeCollisionWarned.has(i.name)||(this._typeCollisionWarned.add(i.name),this._logger.warn(`Metric name '${i.name}' is already used as a ${n}; recording it as a ${i.type} too will blend both series in charts. Use a distinct name.`)),this._fold(s,i.value);let a=this._activeTraceContext();a&&(s.exemplar={...a,value:i.value,timeMs:Date.now()}),this._armFlushTimer()}_activeTraceContext(){try{let e=tR(this._instance.getActiveSpan?.()?.traceparent());if(e&&e.flags===tB)return{traceId:e.traceId,spanId:e.spanId}}catch{}}_admitNewSeries(){return this._series.size<this._config.maxSeriesPerFlush||(this._seriesCapWarned||(this._seriesCapWarned=!0,this._logger.warn(`Metric series cap reached (${this._config.maxSeriesPerFlush} per flush window); dropping new series until the next flush. Reduce attribute cardinality.`)),!1)}_fold(e,t){switch(e.type){case"count":e.total=(e.total??0)+t;break;case"gauge":e.last=t;break;case"histogram":{e.hist||(e.hist={count:0,sum:0,min:t,max:t,bucketCounts:Array(tq.length+1).fill(0)});let r=e.hist;r.count+=1,r.sum+=t,r.min=Math.min(r.min,t),r.max=Math.max(r.max,t),r.bucketCounts[function(e,t){for(let r=0;r<t.length;r++)if(e<=t[r])return r;return t.length}(t,tq)]+=1}}}_runBeforeSend(e){let t=this._config.beforeSend;if(!t)return e;let r=m(t)?t:[t],i=e;for(let e of r)try{let t=e(i);if(!t)return this._logger.info("Metric was rejected in beforeSend function"),null;i=t}catch(e){return this._logger.error("Error in beforeSend function for metric:",e),null}return i}_armFlushTimer(){this._flushTimer.pending||this._flushTimer.arm(this._nextFlushDelay())}_nextFlushDelay(){return Math.max(tA(this._config.flushIntervalMs,this._consecutiveFlushFailures,this._flushJitter,3e4),this._retryAfter.remainingMs())}async _doFlush(){if(this._flushTimer.clear(),0===this._series.size)return;let e=this._series;this._series=new Map,this._seriesCapWarned=!1,this._typeByName=new Map,this._typeCollisionWarned=new Set;let t=this._generation,r=await this._instance._sendMetricsBatch(this._buildPayload(e));if(t===this._generation)switch(this._retryAfter.record(r),"retry-later"===r.kind?(this._consecutiveFlushFailures++,this._flushJitter=tI()):(this._consecutiveFlushFailures=0,this._flushJitter=1),this._flushTimer.pending&&this._flushTimer.arm(this._nextFlushDelay()),r.kind){case"ok":return;case"retry-later":this._mergeWindowBack(e),this._flushTimer.armNoEarlierThan(this._nextFlushDelay());return;case"too-large":this._logger.warn("Metrics batch exceeded the server size limit and was dropped");return;case"fatal":this._logger.error("Failed to send metrics batch:",r.error);return}}_buildPayload(e){var t,r,i,s;return t=this._buildMetrics(e),r=tx(this._config,this._instance.getLibraryId(),this._instance.getLibraryVersion()),i=this._instance.getLibraryId(),s=this._instance.getLibraryVersion(),{resourceMetrics:[{resource:{attributes:tE(r)},scopeMetrics:[{scope:{name:i,version:s},metrics:t}]}]}}_buildMetrics(e){let t=tU(Date.now()),r=new Map;for(let s of e.values()){var i;let e=tz(s.type,s.name,s.unit,void 0),n=r.get(e);n||(n={name:s.name,...s.unit&&{unit:s.unit}},"count"===s.type?n.sum={aggregationTemporality:1,isMonotonic:!0,dataPoints:[]}:"gauge"===s.type?n.gauge={dataPoints:[]}:n.histogram={aggregationTemporality:1,dataPoints:[]},r.set(e,n));let a=tb(s.attributes??{},this._logger),o=tU(s.windowStartMs),l=(i=s.exemplar)?{exemplars:[{filteredAttributes:[],timeUnixNano:tU(i.timeMs),asDouble:i.value,traceId:i.traceId,spanId:i.spanId}]}:{};if("count"===s.type){let e={attributes:a,startTimeUnixNano:o,timeUnixNano:t,asDouble:s.total??0,...l};n.sum.dataPoints.push(e)}else if("gauge"===s.type){let e={attributes:a,timeUnixNano:t,asDouble:s.last??0,...l};n.gauge.dataPoints.push(e)}else if(s.hist){let e={attributes:a,startTimeUnixNano:o,timeUnixNano:t,count:s.hist.count,sum:s.hist.sum,min:s.hist.min,max:s.hist.max,bucketCounts:s.hist.bucketCounts,explicitBounds:tq,...l};n.histogram.dataPoints.push(e)}}return Array.from(r.values())}_mergeWindowBack(e){for(let[t,r]of e){let e=this._series.get(t);if(!e){this._admitNewSeries()&&this._series.set(t,r);continue}switch(e.windowStartMs=Math.min(e.windowStartMs,r.windowStartMs),e.exemplar=e.exemplar??r.exemplar,e.type){case"count":e.total=(e.total??0)+(r.total??0);break;case"gauge":break;case"histogram":if(r.hist)if(e.hist){e.hist.count+=r.hist.count,e.hist.sum+=r.hist.sum,e.hist.min=Math.min(e.hist.min,r.hist.min),e.hist.max=Math.max(e.hist.max,r.hist.max);for(let t=0;t<e.hist.bucketCounts.length;t++)e.hist.bucketCounts[t]+=r.hist.bucketCounts[t]}else e.hist=r.hist}}}}let tV="unknown";function tW(e,t,r,i){return"string"==typeof e&&e.trim()?e.length>r?e.slice(0,r):e:(i?.debug(`${t} must be a non-empty string; using "${tV}"`),tV)}function tK(e){if(null==e)return;let t=e;if(e instanceof Date)try{t=e.getTime()}catch{return}if("number"==typeof t&&Number.isFinite(t)&&!(t<0)&&!(t>0x8637bd05af6))return t}function tG(e,t,r,i){let s=tK(e);return void 0===s?(void 0!==e&&i?.debug(`Span ${r} is out of range or not a valid time; using the derived time`),t):s}function tQ(){let e=globalThis.performance;return"function"==typeof e?.now?e.now():void 0}class tJ{constructor(e,t,r){for(let i of(this._onEnd=t,this._logger=r,this._events=[],this._ended=!1,this._userAttributeCount=0,this._userEventCount=0,this._droppedAttributes=0,this._droppedEvents=0,this._traceId=e.traceId,this._spanId=e.spanId,this._parentSpanId=e.parentSpanId,this._traceState=e.traceState,this._traceFlags=e.traceFlags??tB,this._parentIsRemote=e.parentIsRemote??!1,this._name=e.name,this._kind=e.kind,this._autoKeys=new Set(e.autoAttributeKeys),this._maxAttributes=e.maxAttributes,this._maxEvents=e.maxEvents,this._maxAttributesPerEvent=e.maxAttributesPerEvent,this._maxAttributeValueLength=e.maxAttributeValueLength,this._attributes=Object.create(null),Object.keys(e.attributes)))this._writeAttribute(i,e.attributes[i]);this._startMono=e.backdated?void 0:tQ(),this._startTime=e.clockAnchor&&void 0!==this._startMono?e.clockAnchor.wall+(this._startMono-e.clockAnchor.mono):e.startTime,void 0!==this._startMono&&(this._clockAnchor=e.clockAnchor??{wall:this._startTime,mono:this._startMono})}_now(){if(void 0!==this._startMono){let e=tQ();if(void 0!==e)return this._startTime+Math.max(0,e-this._startMono)}return Date.now()}_mutable(e){return!this._ended||(this._logger?.debug(`Ignoring ${e} on a span that has already ended`),!1)}_writeAttribute(e,t){if(x(t)){e in this._attributes&&!this._autoKeys.has(e)&&this._userAttributeCount--,delete this._attributes[e];return}if(!this._autoKeys.has(e)&&!(e in this._attributes)){if(this._userAttributeCount>=this._maxAttributes)return void this._droppedAttributes++;this._userAttributeCount++}this._attributes[e]=t4(t,this._maxAttributeValueLength)}setAttribute(e,t){return this._mutable("setAttribute")&&this._writeAttribute(e,t),this}setAttributes(e){if(this._mutable("setAttributes")){let t=t_({},e);for(let e of Object.keys(t))this._writeAttribute(e,t[e])}return this}addEvent(e,t,r){if(this._mutable("addEvent")){if(this._userEventCount>=this._maxEvents)return this._droppedEvents++,this;this._userEventCount++;let i=t&&t6(t,this._maxAttributesPerEvent,this._maxAttributeValueLength);this._events.push({name:tW(e,"Span event name",this._maxAttributeValueLength,this._logger),timestamp:tG(r,this._now(),"event timestamp",this._logger),...i&&{attributes:i.attributes,...i.dropped&&{droppedAttributesCount:i.dropped}}})}return this}setStatus(e,t){if(this._mutable("setStatus")){if("ok"!==e&&"error"!==e)return this._logger?.debug(`Ignoring unknown span status "${String(e)}"; expected "ok" or "error"`),this;this._status={code:e,...t&&{message:t5(t,this._maxAttributeValueLength)}}}return this}get statusIsExplicitlyOk(){return this._status?.code==="ok"}recordException(e){if(!this._mutable("recordException"))return this;let{type:t,message:r,stack:i}=t9(e);return this.addEvent(tZ,{"exception.type":t,"exception.message":r,...i&&{"exception.stacktrace":i}}),this.setStatus("error",r)}updateName(e){return this._mutable("updateName")&&(this._name=tW(e,"Span name",this._maxAttributeValueLength,this._logger)),this}traceparent(){return function(e,t,r=tB){return`00-${e}-${t}-${r}`}(this._traceId,this._spanId,this._traceFlags)}tracestate(){return this._traceState??null}childContext(){return{traceId:this._traceId,parentSpanId:this._spanId,traceState:this._traceState,traceFlags:this._traceFlags,clockAnchor:this._clockAnchor}}end(e){var t;if(this._ended)return void this._logger?.debug("Ignoring end() on a span that has already ended");this._ended=!0;let r=tG(e,this._now(),"end time",this._logger);this._onEnd({traceId:this._traceId,spanId:this._spanId,...this._parentSpanId&&{parentSpanId:this._parentSpanId},...this._traceState&&{traceState:this._traceState},traceFlags:this._traceFlags,parentIsRemote:this._parentIsRemote,name:this._name,kind:this._kind,...this._status&&{status:this._status},attributes:{...this._attributes},events:this._events,startTime:this._startTime,endTime:r<(t=this._startTime)?t:r,...this._droppedAttributes&&{droppedAttributesCount:this._droppedAttributes},...this._droppedEvents&&{droppedEventsCount:this._droppedEvents}},this._autoKeys)}}let tZ="exception";function tY(e){return"number"!=typeof e||!Number.isFinite(e)||e<=0?0:Math.min(Math.floor(e),0xffffffff)}class tX{setAttribute(){return this}setAttributes(){return this}addEvent(){return this}setStatus(){return this}recordException(){return this}updateName(){return this}traceparent(){return null}tracestate(){return null}end(){}}let t0=new tX;class t1 extends tX{constructor(e,t){super(),this._traceparent=e,this._tracestate=t}traceparent(){return this._traceparent}tracestate(){return this._tracestate??null}}function t2(e,t){var r;let i=tj(e?.parent)??t,s=tD(r="string"==typeof i||null==i?i:t3(i,"traceparent"))&&r.trim();return s?new t1(s,tN("string"==typeof i||null==i?e?.tracestate:t3(i,"tracestate"))):t0}function t3(e,t){try{let r=e[t];return"function"==typeof r?r.call(e):void 0}catch{return}}function t5(e,t){return e.length>t?e.slice(0,t):e}function t4(e,t){return function e(t,r,i,s){if(null===t||"object"!=typeof t)return x(t)||i.remainingNodes<=0?t:(i.remainingNodes--,"string"==typeof t?t5(t,r):t);if(i.ancestors.has(t))return tg;if(i.remainingNodes<=0||s>=20)return t;i.remainingNodes--,i.ancestors.add(t);try{if(t instanceof Date)return t;let n=function(e){try{let t=e.toJSON;if("function"==typeof t)return{selfDescribed:!0,value:t.call(e)}}catch{}return{selfDescribed:!1}}(t);if(n.selfDescribed)return x(n.value)?String(n.value):e(n.value,r,i,s+1);if(m(t)){let n=Math.min(t.length,1e3),a=[];for(let o=0;o<n;o++)try{a.push(e(t[o],r,i,s+1))}catch{a.push(tm)}return t.length>n&&(a.length=t.length),a}let a={},o=0;for(let n of Object.keys(t)){let l;if(o>=1e3)break;try{l=e(t[n],r,i,s+1)}catch{l=tm}n&&!x(l)&&o++,Object.defineProperty(a,n,{value:l,enumerable:!0,writable:!0,configurable:!0})}return a}catch{return t}finally{i.ancestors.delete(t)}}(e,t,{ancestors:new WeakSet,remainingNodes:1e4},0)}function t6(e,t,r){let i;try{i=Object.keys(e)}catch{return{attributes:{},dropped:0}}let s={},n=0,a=0;for(let o of i){let i;if(n>=t){a++;continue}try{i=t4(e[o],r)}catch{i=tm}x(i)||(n++,Object.defineProperty(s,o,{value:i,enumerable:!0,writable:!0,configurable:!0}))}return{attributes:s,dropped:a}}function t8(e,t,r){return t===t0?r(t):e.with(t,()=>r(t))}function t9(e){try{let t=function(e){try{let t=e.stack;return"string"==typeof t&&t?{stack:t}:{}}catch{return{}}}(e);if(P(e))return{type:e.name||"Error",message:e.message||"",...t};if("string"==typeof e)return{type:"string",message:e};if(e&&"object"==typeof e&&"string"==typeof e.message)return{type:"string"==typeof e.name?e.name:"Object",message:e.message,...t};return{type:typeof e,message:String(e)}}catch{return{type:typeof e,message:""}}}let t7={internal:1,server:2,client:3,producer:4,consumer:5},re={ok:1,error:2};function rt(e){if("string"==typeof e)return ty(e);try{return ty(String(e))}catch{return tm}}function rr(e){let t=Math.floor(e),r=Math.round((e-t)*1e6);return r>=1e6&&(t+=1,r=0),String(t)+String(r).padStart(6,"0")}function ri(){return tQ()??Date.now()}function rs(e){try{return e instanceof tJ}catch{return!1}}function rn(e,t){let r=tR(e);if(r)return{traceId:r.traceId,parentSpanId:r.spanId,traceState:tN(t),traceFlags:r.flags,isRemote:!0}}function ra(e,t,r){e[t]!==r&&(e[t]=r)}class ro{constructor(e,t,r,i,s,n){this._instance=e,this._config=t,this._logger=r,this._getContext=i,this._contextManager=s,this._onSpanQueued=n,this._queue=[],this._flushTimer=new tP(()=>this._flushInBackground()),this._flushPromise=null,this._droppedSinceWarning=0,this._lastDropWarningAt=0,this._dropReasons=new Set,this._consecutiveFlushFailures=0,this._flushJitter=1,this._retryAfter=new tr,this._headBatchFailures=0,this._headBatchSize=0,this._headBatchChargeableAt=0,this._generation=0,this._liveSpans=new Map,this._maxExportBatchSize=t.maxExportBatchSize}startSpan(e,t){var r,i;let s;if(this._instance.isDisabled||this._instance.optedOut)return t2(t,this._contextManager.active());let n=tj(t?.parent);if(n&&"string"!=typeof n&&!rs(n)){if(function(e){try{return"function"==typeof e.traceparent}catch{return!1}}(n))return this._logger.debug("Span parent is not a span from this SDK; returning an inert span"),t2(t,this._contextManager.active());this._logger.debug("Ignoring an unusable span parent")}let a=this._resolveParent(n,t);if(this._liveSpans.size>=this._config.maxLiveSpans&&this._evictAgedSpans(),this._liveSpans.size>=this._config.maxLiveSpans)return this._recordDrop(1,`the live-span limit (${this._config.maxLiveSpans}) was reached — spans are being started and never ended`),t2(t,this._contextManager.active());let o=Date.now(),l=(r=t?.startTime,i=this._logger,void 0===(s=tK(r))?(void 0!==r&&i?.debug("Span startTime is out of range or not a valid time; using the current time"),o):(o-s>864e5?i?.debug("Span startTime is more than 24 hours in the past; the server will clamp it to receive time and keep the original in $originalTimestamp"):s>o&&i?.debug("Span startTime is in the future; the span may export with a zero duration"),s)),u=tO(8);this._liveSpans.set(u,ri());let c=this._autoContextAttributes();return new tJ({traceId:a?.traceId??tO(16),spanId:u,parentSpanId:a?.parentSpanId,traceState:a?.traceState,traceFlags:a?.traceFlags,parentIsRemote:a?.isRemote,name:tW(e,"Span name",this._config.maxAttributeValueLength,this._logger),kind:t?.kind??"internal",attributes:t_({...c},t?.attributes),autoAttributeKeys:Object.keys(c),maxAttributes:this._config.maxAttributesPerSpan,maxEvents:this._config.maxEventsPerSpan,maxAttributesPerEvent:this._config.maxAttributesPerEvent,maxAttributeValueLength:this._config.maxAttributeValueLength,startTime:l,backdated:l!==o,clockAnchor:void 0===tK(t?.startTime)?a?.clockAnchor:void 0},(e,t)=>this._onSpanEnd(e,t),this._logger)}withSpan(e,t,r){let i=this.startSpan(e,"function"==typeof t?void 0:t);try{let e=t8(this._contextManager,i,"function"==typeof t?t:r);if(e&&"function"==typeof e.then)return e.then(e=>(i.end(),e),e=>{throw this._recordCallbackError(i,e),i.end(),e});return i.end(),e}catch(e){throw this._recordCallbackError(i,e),i.end(),e}}getActiveSpan(){return this._contextManager.active()??null}get throttled(){return this._retryAfter.isOpen()}async flush(){for(;;){if(!this._queue.length)return;let e=this._flushPromise;if(!await (e??this._startFlush()))return}}_startFlush(){this._flushTimer.clear();let e=this._generation,t=Promise.resolve().then(()=>e===this._generation?this._flushInner():0).finally(()=>{this._flushPromise===t&&(this._flushPromise=null),this._armFlushTimerIfQueuedNoEarlierThan()});return this._flushPromise=t,t}reset(){this._flushTimer.clear(),this._queue.length&&this._logger.critical(`Discarding ${this._queue.length} span(s) that were still queued when tracing was shut down. Raise the shutdown timeout or flush earlier if they matter.`),this._queue=[],this._liveSpans.clear(),this._flushPromise=null,this._generation++,this._maxExportBatchSize=this._config.maxExportBatchSize,this._droppedSinceWarning=0,this._dropReasons.clear(),this._lastDropWarningAt=0,this._consecutiveFlushFailures=0,this._flushJitter=1,this._retryAfter.reset(),this._resetHeadBatchBudget()}_resetHeadBatchBudget(){this._headBatchFailures=0,this._headBatchChargeableAt=0}_resolveParent(e,t){if("string"==typeof e){let r=rn(e,t?.tracestate);return r||this._logger.debug("Ignoring malformed traceparent; starting a new trace"),r}if(rs(e))return e.childContext();let r=this._contextManager.active();return rs(r)?r.childContext():r instanceof t1?rn(r.traceparent(),r.tracestate()??void 0):void 0}_autoContextAttributes(){let e;try{e=this._getContext()}catch(e){return this._logger.debug("Failed to read tracing context; span will carry no PostHog attributes",e),{}}let t={};return e.distinctId&&(t.posthogDistinctId=e.distinctId),e.sessionId&&(t.sessionId=e.sessionId),e.currentUrl&&(t["url.full"]=e.currentUrl),e.screenName&&(t["screen.name"]=e.screenName),e.appState&&(t["app.state"]=e.appState),t}_recordCallbackError(e,t){if(!(e instanceof tJ))return;let{type:r,message:i,stack:s}=t9(t);e.addEvent("exception",{"exception.type":r,"exception.message":i,...s&&{"exception.stacktrace":s}}),e.statusIsExplicitlyOk||e.setStatus("error",i)}_evictAgedSpans(){let e=ri()-this._config.maxSpanAgeMs,t=0;for(let[r,i]of this._liveSpans){if(i>e)break;this._liveSpans.delete(r),t++}t&&this._recordDrop(t,`they were still live after ${this._config.maxSpanAgeMs}ms`)}_onSpanEnd(e,t){if(!this._liveSpans.delete(e.spanId))return;if(this._instance.isDisabled||this._instance.optedOut)return void this._recordDrop(1,"the user has opted out");let r=this._runBeforeSpanSend(e,t);if(r){if(this._reportLimitDrops(r),this._queue.length>=this._config.maxQueueSize)return void this._recordDrop(1,`the queue is full (${this._config.maxQueueSize}) — raise the flush frequency or reduce span volume`);this._queue.push(r);try{this._onSpanQueued?.()}catch(e){this._logger.debug("Span queue notification failed",e)}!(this._queue.length>=this._maxExportBatchSize)||this._consecutiveFlushFailures||this._retryAfter.isOpen()?this._armFlushTimerIfQueued():this._flushInBackground()}}_reportLimitDrops(e){let t=e.droppedAttributesCount??0,r=e.droppedEventsCount??0,i=0;for(let t of e.events)i+=t.droppedAttributesCount??0;(t||r||i)&&this._logger.debug(`Span limits discarded data from "${e.name}": ${t} attributes, ${r} events, ${i} event attributes`)}_runBeforeSpanSend(e,t){if(!this._config.beforeSpanSend.length)return e;let r={traceId:e.traceId,spanId:e.spanId,parentSpanId:e.parentSpanId,traceState:e.traceState},i={startTime:e.startTime,endTime:e.endTime},s={attributes:e.droppedAttributesCount,events:e.droppedEventsCount},n=Object.keys(e.attributes),a={traceFlags:e.traceFlags,parentIsRemote:e.parentIsRemote},o=e.status&&{...e.status},l=e,u=e;try{var c,h,d;for(let e of this._config.beforeSpanSend){let t=e(l);if(!t)return this._recordDrop(1,"beforeSpanSend dropped it"),null;l=this._keepSpanIdentity(t,r)}if(!((c=u={traceId:r.traceId,spanId:r.spanId,parentSpanId:r.parentSpanId,traceState:r.traceState,name:l.name,kind:l.kind,status:l.status,attributes:l.attributes,events:l.events,startTime:l.startTime,endTime:l.endTime,traceFlags:a.traceFlags,parentIsRemote:a.parentIsRemote,droppedAttributesCount:s.attributes,droppedEventsCount:s.events}).attributes&&"object"==typeof c.attributes&&!Array.isArray(c.attributes)&&Array.isArray(c.events)&&void 0!==c.name&&void 0!==c.kind&&void 0!==c.startTime&&void 0!==c.endTime))return this._logger.debug("beforeSpanSend did not return a span record; dropping the span"),this._recordDrop(1,"beforeSpanSend returned an unusable record"),null;u.name=tW(u.name,"Span name",this._config.maxAttributeValueLength,this._logger),u.status&&"ok"!==u.status.code&&"error"!==u.status.code&&(this._logger.debug("beforeSpanSend set an unknown span status; keeping the original"),u.status=o),u.startTime=tK(u.startTime)??i.startTime,u.endTime=(h=tK(u.endTime)??i.endTime,d=u.startTime,h<d?d:h);let e=[];for(let t of u.events)try{e.push({...t,name:tW(t.name,"Span event name",this._config.maxAttributeValueLength,this._logger),timestamp:tG(t.timestamp,u.startTime,"event timestamp",this._logger)})}catch{this._logger.debug("beforeSpanSend left an unreadable span event; dropping it")}return u.events=e,!function(e,t,r,i,s,n,a=[]){let o=0,l=0,u={};for(let i of function(e,t){if(!t.length)return Object.keys(e);let r=t.filter(t=>Object.prototype.propertyIsEnumerable.call(e,t)),i=new Set(r);return[...r,...Object.keys(e).filter(e=>!i.has(e))]}(e.attributes,a)){let s=e.attributes[i];if(!x(s)){if(!t.has(i)){if(o>=r){l++;continue}o++}Object.defineProperty(u,i,{value:t4(s,n),enumerable:!0,writable:!0,configurable:!0})}}e.attributes=u,l&&(e.droppedAttributesCount=tY(e.droppedAttributesCount)+l);let c=0,h=0,d=[];for(let t of e.events){if(c>=i){h++;continue}if(c++,t.attributes){let e=t6(t.attributes,s,n);t.attributes=e.attributes,e.dropped&&(t.droppedAttributesCount=tY(t.droppedAttributesCount)+e.dropped)}d.push(t)}e.events=d,h&&(e.droppedEventsCount=tY(e.droppedEventsCount)+h),e.status?.message&&(e.status={...e.status,message:t5(function(e){try{return"string"==typeof e?e:String(e)}catch{return tm}}(e.status.message),n)})}(u,t,this._config.maxAttributesPerSpan,this._config.maxEventsPerSpan,this._config.maxAttributesPerEvent,this._config.maxAttributeValueLength,n),u}catch(e){return this._logger.debug("beforeSpanSend failed; dropping the span rather than exporting it unscrubbed",e),this._recordDrop(1,"beforeSpanSend failed"),null}}_keepSpanIdentity(e,t){(e.traceId!==t.traceId||e.spanId!==t.spanId||e.parentSpanId!==t.parentSpanId)&&this._logger.debug("beforeSpanSend changed a span identity field; keeping the original ids");try{ra(e,"traceId",t.traceId),ra(e,"spanId",t.spanId),ra(e,"parentSpanId",t.parentSpanId),ra(e,"traceState",t.traceState)}catch{try{let r=Object.getOwnPropertyDescriptors(e);for(let e of["traceId","spanId","parentSpanId","traceState"])r[e]={value:t[e],enumerable:!0,writable:!0,configurable:!0};return Object.create(Object.getPrototypeOf(e),r)}catch{;}}return e}_recordDrop(e,t){this._droppedSinceWarning+=e,this._dropReasons.add(t),Date.now()-this._lastDropWarningAt>=this._config.flushIntervalMs&&this._warnAboutDrops()}_warnAboutDrops(){this._droppedSinceWarning&&(this._lastDropWarningAt=Date.now(),this._logger.warn(`Dropping ${this._droppedSinceWarning} span(s): ${[...this._dropReasons].join("; ")}`),this._droppedSinceWarning=0,this._dropReasons.clear())}_encodeBatch(e){let t=[];for(let r of e)try{t.push(function(e,t){var r;let i,s={traceId:e.traceId,spanId:e.spanId,name:rt(e.name),kind:(r=e.kind)&&Object.prototype.hasOwnProperty.call(t7,r)?t7[r]:t7.internal,startTimeUnixNano:rr(e.startTime),endTimeUnixNano:rr(e.endTime),flags:(Number.isFinite(i=parseInt(e.traceFlags,16))?255&i:1)|256|512*!!e.parentIsRemote};e.parentSpanId&&(s.parentSpanId=e.parentSpanId),e.traceState&&(s.traceState=rt(e.traceState));let n=tb(e.attributes,t);n.length&&(s.attributes=n),e.events.length&&(s.events=e.events.map(e=>(function(e,t){let r={name:rt(e.name),timeUnixNano:rr(e.timestamp)};if(e.attributes){let i=tb(e.attributes,t);i.length&&(r.attributes=i)}let i=tY(e.droppedAttributesCount);return i&&(r.droppedAttributesCount=i),r})(e,t)));let a=tY(e.droppedAttributesCount);a&&(s.droppedAttributesCount=a);let o=tY(e.droppedEventsCount);return o&&(s.droppedEventsCount=o),e.status&&(s.status={code:re[e.status.code],...e.status.message&&{message:rt(e.status.message)}}),s}(r,this._logger))}catch(e){this._logger.debug("Failed to encode a span; dropping it",e),this._recordDrop(1,"its attributes could not be encoded")}return t}_discardQueueIfConsentWithdrawn(){if(!this._instance.isDisabled&&!this._instance.optedOut)return 0;let e=this._queue.length;return this._queue=[],this._resetHeadBatchBudget(),this._recordDrop(e,"the user has opted out"),this._warnAboutDrops(),e}async _flushInner(){var e,t;if(!this._queue.length)return 0;let r=this._discardQueueIfConsentWithdrawn();if(r)return r;let i=function(e,t){for(let r of Object.keys(e))e[r]=t4(e[r],t);return e}((e=this._config,tx(e,this._instance.getLibraryId(),this._instance.getLibraryVersion())),this._config.maxAttributeValueLength),s=this._instance.getLibraryId(),n=this._instance.getLibraryVersion(),a=this._queue.length,o=0,l=1/0,u=this._generation;try{for(;a>0&&this._queue.length>0;){let e=this._discardQueueIfConsentWithdrawn();if(e)return o+e;let r=this._headBatchFailures>0?Math.min(this._maxExportBatchSize,this._headBatchSize):this._maxExportBatchSize,c=Math.max(1,Math.min(r,l,a,this._queue.length)),h=this._queue.slice(0,c),d=this._encodeBatch(h);if(!d.length){this._queue.splice(0,c),a-=c,o+=c,this._resetHeadBatchBudget();continue}let p=ri()>=this._headBatchChargeableAt&&!this._retryAfter.isOpen(),g=await this._instance._sendTracesBatch((t=this._logger,{resourceSpans:[{resource:{attributes:tE(i,t)},scopeSpans:[{scope:{name:s,version:n},spans:d}]}]}));if(u!==this._generation)break;if(this._retryAfter.record(g),"ok"===g.kind){this._consecutiveFlushFailures=0,this._flushJitter=1,this._resetHeadBatchBudget(),this._queue.splice(0,c),a-=c,o+=c,this._maxExportBatchSize<this._config.maxExportBatchSize&&this._maxExportBatchSize++;continue}if("too-large"===g.kind){if(1===c){this._queue.splice(0,1),a-=1,o+=1,this._recordDrop(1,"it is too large for the ingestion endpoint"),this._consecutiveFlushFailures=0,this._flushJitter=1,this._resetHeadBatchBudget();continue}let e=Math.max(1,Math.floor(c/2));g.measuredLocally?l=e:this._maxExportBatchSize=e,this._resetHeadBatchBudget(),this._logger.debug(`Batch too large; retrying the same spans in batches of ${e}`);continue}if("retry-later"===g.kind){if(this._consecutiveFlushFailures++,this._flushJitter=tI(),this._headBatchSize=c,p&&(this._headBatchFailures++,this._headBatchChargeableAt=ri()+this._nextFlushDelay()),this._headBatchFailures<8)return this._logger.debug("Span export failed; retrying on the next flush",g.error),o;if(this._queue.splice(0,c),a-=c,o+=c,this._consecutiveFlushFailures=0,this._flushJitter=1,this._resetHeadBatchBudget(),this._recordDrop(c,"the ingestion endpoint failed 8 times in a row"),this._retryAfter.isOpen())return o;continue}this._logger.debug("Dropping a span batch the ingestion endpoint rejected",g.error),this._queue.splice(0,c),a-=c,o+=c,this._consecutiveFlushFailures=0,this._flushJitter=1,this._resetHeadBatchBudget(),this._recordDrop(c,"the ingestion endpoint rejected the batch")}return o}finally{this._warnAboutDrops()}}_flushInBackground(){this._backgroundFlush||(this._backgroundFlush=this.flush().catch(e=>{this._logger.debug("Background span flush failed",e)}).finally(()=>{this._backgroundFlush=void 0,this._armFlushTimerIfQueuedNoEarlierThan()}))}_armFlushTimerIfQueued(){!this._flushTimer.pending&&this._queue.length&&this._flushTimer.arm(this._nextFlushDelay())}_armFlushTimerIfQueuedNoEarlierThan(){this._queue.length&&this._flushTimer.armNoEarlierThan(this._nextFlushDelay())}_nextFlushDelay(){return Math.max(tA(this._config.flushIntervalMs,this._consecutiveFlushFailures,this._flushJitter,3e4),this._retryAfter.remainingMs())}}var rl=e.i(2157),ru=e.i(12714),rc=e.i(50227),rh=e.i(1457);let rd=new ez.ReduceableCache(25),rp=new ez.ReduceableCache(20);async function rg(e,t=ru.open,r){let i,s={};try{i=process.cwd()}catch{}for(let t=e.length-1;t>=0;t--){var n,a;let r=e[t],o=r?.filename;!(!r||"string"!=typeof o||"number"!=typeof r.lineno||(n=o).startsWith("node:")||n.endsWith(".min.js")||n.endsWith(".min.cjs")||n.endsWith(".min.mjs")||n.startsWith("data:")||void 0!==(a=r).lineno&&a.lineno>1e4||void 0!==a.colno&&a.colno>1e3)&&((0,rc.isAbsolute)(o)||void 0!==i)&&(s[o]||(s[o]=[]),s[o].push(r.lineno))}let o=Object.keys(s);if(0==o.length)return e;let l=[];for(let e of o){let n=r_(e,i);if(void 0===n||rp.get(n))continue;let a=s[e];if(!a)continue;a.sort((e,t)=>e-t);let o=function(e){if(!e.length)return[];let t=0,r=e[0];if("number"!=typeof r)return[];let i=rv(r),s=[];for(;;){if(t===e.length-1){s.push(i);break}let r=e[t+1];if("number"!=typeof r)break;r<=i[1]?i[1]=r+7:(s.push(i),i=rv(r)),t++}return s}(a);if(o.every(e=>(function(e,t){let r=rd.get(e);if(void 0===r)return!1;for(let e=t[0];e<=t[1];e++)if(void 0===r[e])return!1;return!0})(n,e)))continue;let u=function(e,t,r){let i=e.get(t);return void 0===i?(e.set(t,r),r):i}(rd,n,{});l.push(rm(e,o,u,n,t,r))}return await Promise.all(l).catch(()=>{}),e&&e.length>0&&function(e,t,r){for(let i of e)if(i.filename&&void 0===i.context_line&&"number"==typeof i.lineno){let e=r_(i.filename,r),s=void 0===e?void 0:t.get(e);if(void 0===s)continue;!function(e,t,r){if(void 0===t.lineno||void 0===r)return;t.pre_context=[];for(let i=rb(e);i<e;i++){let e=r[i];if(void 0===e)return void ry(t);t.pre_context.push(e)}if(void 0===r[e])return ry(t);t.context_line=r[e];let i=function(e){return e+7}(e);t.post_context=[];for(let s=e+1;s<=i;s++){let e=r[s];if(void 0===e)break;t.post_context.push(e)}}(i.lineno,i,s)}}(e,rd,i),rd.reduce(),e}async function rf(e,t,r){let i,s=!1;try{i=await t(e,rl.constants.O_RDONLY|rl.constants.O_NONBLOCK);let n=await i.stat();if(!n.isFile())return;if(n.size>0xa00000)return void r?.debug(`Skipping source context for oversized file ${e}: ${n.size} bytes exceeds 10485760`);return s=!0,i}catch{return}finally{i&&!s&&await i.close().catch(()=>{})}}async function rm(e,t,r,i,s,n){let a=await rf(e,s,n);return void 0===a?void rp.set(i,1):new Promise(e=>{let s,n,o=!1;function l(t){o||(o=!0,t?.destroy(),a.close().then(e,e))}try{s=a.createReadStream({autoClose:!1,start:0,end:0x9fffff})}catch{rp.set(i,1),l();return}try{n=(0,rh.createInterface)({input:s})}catch{rp.set(i,1),l(s);return}let u=0,c=0,h=t[0];if(void 0===h)return void l(s);let d=h[0],p=h[1];function g(){rp.set(i,1),n.close(),n.removeAllListeners(),l(s)}s.on("error",g),n.on("error",g),n.on("close",()=>l(s)),n.on("line",e=>{if(!(++u<d)&&(r[u]=function(e,t){let r=e,i=r.length;if(i<=150)return r;t>i&&(t=i);let s=Math.max(t-60,0);s<5&&(s=0);let n=Math.min(s+140,i);return n>i-5&&(n=i),n===i&&(s=Math.max(n-140,0)),r=r.slice(s,n),s>0&&(r=`...${r}`),n<i&&(r+="..."),r}(e,0),u>=p)){if(c===t.length-1){n.close(),n.removeAllListeners();return}let e=t[++c];if(void 0===e){n.close(),n.removeAllListeners();return}d=e[0],p=e[1]}})})}function ry(e){delete e.pre_context,delete e.context_line,delete e.post_context}function r_(e,t){return(0,rc.isAbsolute)(e)?JSON.stringify([null,e]):void 0===t?void 0:JSON.stringify([t,e])}function rv(e){return[rb(e),e+7]}function rb(e){return Math.max(1,e-7)}class rw{active(){return this._active}with(e,t){let r=this._active;this._active=e;try{return t()}finally{this._active=r}}}let rx=["amazonbot","amazonproductbot","app.hypefactors.com","applebot","archive.org_bot","awariobot","backlinksextendedbot","baiduspider","bingbot","bingpreview","chrome-lighthouse","dataforseobot","deepscan","duckduckbot","facebookexternal","facebookcatalog","http://yandex.com/bots","hubspot","ia_archiver","leikibot","linkedinbot","meta-externalagent","mj12bot","msnbot","nessus","petalbot","pinterestbot","prerender","rogerbot","screaming frog","sebot-wa","sitebulb","slackbot","slurp","trendictionbot","turnitin","twitterbot","vercel-screenshot","vercelbot","yahoo! slurp","yandexbot","zoombot","bot.htm","bot.php","(bot;","bot/","crawler","ahrefsbot","ahrefssiteaudit","semrushbot","siteauditbot","splitsignalbot","gptbot","oai-searchbot","chatgpt-user","perplexitybot","better uptime bot","sentryuptimebot","uptimerobot","headlesschrome","cypress","google-hoteladsverifier","adsbot-google","apis-google","duplexweb-google","feedfetcher-google","google favicon","google web preview","google-read-aloud","googlebot","googleother","google-cloudvertexbot","googleweblight","mediapartners-google","storebot-google","google-inspectiontool","bytespider"],rS=new Map,rE=function(e,t=[]){if(!e)return!1;let r=function(e,t){let r="";for(let e=0;e<t.length;e++){let i=t[e];r+=i.length+":"+i}return e.length+":"+e+"|"+t.length+":"+r}(e,t),i=rS.get(r);if(void 0!==i)return i;let s=e.toLowerCase(),n=rx.concat(t).some(e=>-1!==s.indexOf(e.toLowerCase()));return rS.size>=256&&rS.clear(),rS.set(r,n),n};function rF(e,t){return"number"==typeof e&&Number.isInteger(e)&&e>=1?e:t}let rP=["service.name","service.version","deployment.environment"],rI={ERRORS_WHILE_COMPUTING:"errors_while_computing_flags",FLAG_MISSING:"flag_missing",QUOTA_LIMITED:"quota_limited",UNKNOWN_ERROR:"unknown_error"};e.s(["FeatureFlagError",0,rI],88096);class rA{constructor(e){this._host=e.host,this._distinctId=e.distinctId,this._groups=e.groups,this._disableGeoip=e.disableGeoip,this._flags=e.flags,this._requestId=e.requestId,this._evaluatedAt=e.evaluatedAt,this._flagDefinitionsLoadedAt=e.flagDefinitionsLoadedAt,this._errorsWhileComputing=e.errorsWhileComputing??!1,this._quotaLimited=e.quotaLimited??!1,this._accessed=e.accessed??new Set,this._isSlice=e.isSlice??!1}isEnabled(e,t={}){let r=this._flags[e];return this._recordAccess(e),r?.enabled??t.defaultValue??!1}getFlag(e){let t=this._flags[e];if(this._recordAccess(e),t)return!!t.enabled&&(t.variant??!0)}getFlagPayload(e){return this._flags[e]?.payload}onlyAccessed(){let e={};for(let t of this._accessed){let r=this._flags[t];r&&(e[t]=r)}return this._cloneWith(e)}only(e){let t={},r=[];for(let i of e){let e=this._flags[i];e?t[i]=e:r.push(i)}return r.length>0&&this._host.logWarning(`FeatureFlagEvaluations.only() was called with flag keys that are not in the evaluation set and will be dropped: ${r.join(", ")}`),this._cloneWith(t)}get keys(){return Object.keys(this._flags)}_getEventProperties(){let e={},t=[];for(let[r,i]of Object.entries(this._flags)){let s=!1!==i.enabled&&(i.variant??!0);e[`$feature/${r}`]=s,i.enabled&&t.push(r)}return t.length>0&&(t.sort(),e.$active_feature_flags=t),e}_cloneWith(e){return new rA({host:this._host,distinctId:this._distinctId,groups:this._groups,disableGeoip:this._disableGeoip,flags:e,requestId:this._requestId,evaluatedAt:this._evaluatedAt,flagDefinitionsLoadedAt:this._flagDefinitionsLoadedAt,errorsWhileComputing:this._errorsWhileComputing,quotaLimited:this._quotaLimited,accessed:new Set(this._accessed),isSlice:!0})}_recordAccess(e){if(this._accessed.add(e),""===this._distinctId||this._isSlice&&!(e in this._flags))return;let t=this._flags[e],r=void 0===t?void 0:!1!==t.enabled&&(t.variant??!0),i={$feature_flag:e,$feature_flag_response:r,$feature_flag_id:t?.id,$feature_flag_version:t?.version,$feature_flag_reason:t?.reason,locally_evaluated:t?.locallyEvaluated??!1,[`$feature/${e}`]:r,$feature_flag_request_id:this._requestId,$feature_flag_evaluated_at:t?.locallyEvaluated?Date.now():this._evaluatedAt};t?.hasExperiment!==void 0&&(i.$feature_flag_has_experiment=t.hasExperiment),t?.locallyEvaluated&&void 0!==this._flagDefinitionsLoadedAt&&(i.$feature_flag_definitions_loaded_at=this._flagDefinitionsLoadedAt);let s=[];this._errorsWhileComputing&&s.push(rI.ERRORS_WHILE_COMPUTING),this._quotaLimited&&s.push(rI.QUOTA_LIMITED),void 0===t&&s.push(rI.FLAG_MISSING),s.length>0&&(i.$feature_flag_error=s.join(",")),this._host.captureFlagCalledEventIfNeeded({distinctId:this._distinctId,key:e,response:r,groups:this._groups,disableGeoip:this._disableGeoip,properties:i})}}let rC=["is_not","is_set"];class rk extends Error{constructor(e){super(e),this.name=this.constructor.name,Object.setPrototypeOf(this,rk.prototype)}}function r$(e){if("boolean"==typeof e)return!0;if("string"==typeof e){let t=e.toLowerCase();return"true"===t||"false"===t}if(!Array.isArray(e))return!1;for(let t=0;t<e.length;t++)if(!r$(t in e?e[t]:null))return!1;return!0}function rO(e){if("boolean"==typeof e)return e;if("string"==typeof e)return"true"===e.toLowerCase();if(!Array.isArray(e))return!1;for(let t=0;t<e.length;t++)if(!rO(t in e?e[t]:null))return!1;return!0}function rM(e){for(let t=0;t<e.length;t++){let r=e.charCodeAt(t);if(r>=55296&&r<=56319){let r=e.charCodeAt(t+1);if(t+1>=e.length||r<56320||r>57343)throw new rk("Cannot stringify an unpaired surrogate like the flags service");t++}else if(r>=56320&&r<=57343)throw new rk("Cannot stringify an unpaired surrogate like the flags service")}}function rT(e,t=new Set){if(null!==e&&"boolean"!=typeof e){if("string"==typeof e)return void rM(e);if("number"==typeof e){if(!Number.isFinite(e))throw new rk(`Cannot represent non-finite number ${e} like the flags service`);return}if(Array.isArray(e)){if(t.has(e))throw new rk("Cannot represent a circular array during local evaluation");t.add(e);try{for(let r=0;r<e.length;r++)r in e&&rT(e[r],t)}finally{t.delete(e)}return}if("object"==typeof e){let r=Object.getPrototypeOf(e);if(r!==Object.prototype&&null!==r)throw new rk("Cannot represent a non-JSON object like the flags service");if(t.has(e))throw new rk("Cannot represent a circular object during local evaluation");t.add(e);try{for(let r of Object.keys(e))rM(r),rT(e[r],t)}finally{t.delete(e)}return}throw new rk(`Cannot represent ${typeof e} like the flags service`)}}function rR(e,t){let r=0,i=0;for(;r<e.length&&i<t.length;){let s=e.charCodeAt(r),n=t.charCodeAt(i),a=s>=55296&&s<=56319,o=n>=55296&&n<=56319,l=a?e.charCodeAt(r+1):0,u=o?t.charCodeAt(i+1):0,c=a?(s-55296)*1024+l-56320+65536:s,h=o?(n-55296)*1024+u-56320+65536:n;if(c!==h)return c-h;r+=a?2:1,i+=o?2:1}return e.length-t.length}function rD(e){return"string"==typeof e?(rM(e),e):function e(t,r=new Set){if(null===t)return"null";if("string"==typeof t)return rM(t),JSON.stringify(t);if("boolean"==typeof t)return t?"true":"false";if("number"==typeof t){if(!Number.isFinite(t))throw new rk(`Cannot stringify non-finite number ${t} like the flags service`);if(Number.isInteger(t))throw new rk(`Cannot distinguish integer ${t} from an integral JSON float during local evaluation`);return String(t)}if(Array.isArray(t)){if(r.has(t))throw new rk("Cannot stringify a circular array during local evaluation");r.add(t);try{let i=[];for(let s=0;s<t.length;s++)i.push(s in t?e(t[s],r):"null");return`[${i.join(",")}]`}finally{r.delete(t)}}if("object"==typeof t){let i=Object.getPrototypeOf(t);if(i!==Object.prototype&&null!==i)throw new rk("Cannot stringify a non-JSON object like the flags service");if(r.has(t))throw new rk("Cannot stringify a circular object during local evaluation");r.add(t);try{let i=Object.keys(t);return i.forEach(rM),`{${i.sort(rR).map(i=>`${JSON.stringify(i)}:${e(t[i],r)}`).join(",")}}`}finally{r.delete(t)}}throw new rk(`Cannot stringify ${typeof t} like the flags service`)}(e)}function rj(e){try{return new RegExp(e),!0}catch{return!1}}function rB(e){return String(e).replace(/[A-Z]/g,e=>e.toLowerCase())}function rL(e,t,r){if(!/^\d+$/.test(e)||"strict"===r&&e.length>1&&"0"===e[0])throw new rk(`Invalid semver: ${t}`);return parseInt(e,10)}function rN(e,t="strict"){let r=String(e).trim().replace(/^[vV]/,"").split("-")[0].split("+")[0];if(!r||r.startsWith("."))throw new rk(`Invalid semver: ${e}`);let i=r.split("."),s=r=>void 0===r||""===r?0:rL(r,e,t);return[s(i[0]),s(i[1]),s(i[2])]}function rq(e,t){for(let r=0;r<3;r++){if(e[r]<t[r])return -1;if(e[r]>t[r])return 1}return 0}function rU(e){if(e instanceof Date)return e;if("string"==typeof e||"number"==typeof e){let t=new Date(e);if(!isNaN(t.valueOf()))return t;throw new rk(`${e} is in an invalid date format`)}throw new rk(`The date provided ${e} must be a string, number, or date object`)}async function rz(e){let t=globalThis.crypto?.subtle;if(!t)throw Error("SubtleCrypto API not available");return Array.from(new Uint8Array(await t.digest("SHA-1",new TextEncoder().encode(e)))).map(e=>e.toString(16).padStart(2,"0")).join("")}async function rH(e,t,r="",i="."){return parseInt((await rz(`${e}${i}${t}${r}`)).slice(0,15),16)/0x1000000000000000}async function rV(e,t){if(null==e||null==e.id||null==e.exclusion_percentage)return;let r=Number(e.exclusion_percentage);if(!Number.isFinite(r))return;let i=Math.min(Math.max(r,0),100);if(!(100!==i&&await rH("holdout",t,"","-")>i/100))return`holdout-${e.id}`}function rW(e){let t=[],r=0;for(let i of e){let e=r+i.rollout_percentage/100;t.push({valueMin:r,valueMax:e,key:i.key}),r=e}return t}async function rK(e,t,r){let i=await rH(e,t,"variant");return rW(r).find(e=>i>=e.valueMin&&i<e.valueMax)?.key}function rG(e){return"client"===e||"server"===e?e:"all"}class rQ extends Error{constructor(e){super(),Error.captureStackTrace(this,this.constructor),this.name="ClientError",this.message=e,Object.setPrototypeOf(this,rQ.prototype)}}class rJ extends Error{constructor(e){super(e),this.name=rJ.name,Error.captureStackTrace(this,rJ),Object.setPrototypeOf(this,rJ.prototype)}}class rZ{constructor({pollingInterval:e,personalApiKey:t,projectApiKey:r,timeout:i,host:s,customHeaders:n,...a}){this.debugMode=!1,this.shouldBeginExponentialBackoff=!1,this.backOffCount=0,this.pollerStopped=!1,this.filteredOutFlagKeys=new Set,this.pollingInterval=e,this.personalApiKey=t,this.featureFlags=[],this.featureFlagsByKey={},this.groupTypeMapping={},this.cohorts={},this.loadedSuccessfullyOnce=!1,this.timeout=i,this.projectApiKey=r,this.host=s,this.poller=void 0,this.fetch=a.fetch||fetch,this.onError=a.onError,this.customHeaders=n,this.onLoad=a.onLoad,this.onMinimalFlagCalledEvents=a.onMinimalFlagCalledEvents,this.cacheProvider=a.cacheProvider,this.strictLocalEvaluation=a.strictLocalEvaluation??!1,this.evaluationContexts=a.evaluationContexts,this.loadFeatureFlags()}debug(e=!0){this.debugMode=e}logMsgIfDebug(e){this.debugMode&&e()}withEvaluationSnapshot(e){return e.definitions?e:{...e,evaluationCache:{},definitions:{featureFlagsByKey:this.featureFlagsByKey,groupTypeMapping:this.groupTypeMapping,cohorts:this.cohorts,filteredOutFlagKeys:this.filteredOutFlagKeys,propertyMatchingVersion:this.propertyMatchingVersion}}}createEvaluationContext(e,t={},r={},i={},s={}){return{distinctId:e,groups:t,personProperties:r,groupProperties:i,evaluationCache:s}}async getFeatureFlag(e,t,r={},i={},s={}){let n,a;if(await this.loadFeatureFlags(),!this.loadedSuccessfullyOnce)return n;if(void 0!==(a=this.featureFlagsByKey[e])){let o=this.createEvaluationContext(t,r,i,s);try{n=(await this.computeFlagAndPayloadLocally(a,o)).value,this.logMsgIfDebug(()=>console.debug(`Successfully computed flag locally: ${e} -> ${n}`))}catch(t){t instanceof rJ||t instanceof rk?this.logMsgIfDebug(()=>console.debug(`${t.name} when computing flag locally: ${e}: ${t.message}`)):t instanceof Error&&this.onError?.(Error(`Error computing flag locally: ${e}: ${t}`))}}return n}async getAllFlagsAndPayloads(e,t){await this.loadFeatureFlags();let r={},i={},s=0==this.featureFlags.length,n=t?t.map(e=>this.featureFlagsByKey[e]).filter(Boolean):this.featureFlags,a=this.withEvaluationSnapshot({...e,definitions:void 0});return await Promise.all(n.map(async e=>{try{let{value:t,payload:s}=await this.computeFlagAndPayloadLocally(e,a,{skipLoadCheck:!0});r[e.key]=t,s&&(i[e.key]=s)}catch(t){t instanceof rJ||t instanceof rk?this.logMsgIfDebug(()=>console.debug(`${t.name} when computing flag locally: ${e.key}: ${t.message}`)):t instanceof Error&&this.onError?.(Error(`Error computing flag locally: ${e.key}: ${t}`)),s=!0}})),{response:r,payloads:i,fallbackToFlags:s}}async computeFlagAndPayloadLocally(e,t,r={}){let i,{matchValue:s,skipLoadCheck:n=!1}=r;if(this.loadedSuccessfullyOnce&&(t=this.withEvaluationSnapshot(t)),n||await this.loadFeatureFlags(),!this.loadedSuccessfullyOnce)return{value:!1,payload:null};e=(t=this.withEvaluationSnapshot(t)).definitions.featureFlagsByKey[e.key]??e,i=void 0!==s?s:await this.computeFlagValueLocally(e,t);let a=function(e,t){if(!1===t||null==t||!e)return null;let r=e["boolean"==typeof t?t.toString():t]||null;return null==r?null:e3(r)}(e.filters?.payloads,i);return{value:i,payload:a}}async computeFlagValueLocally(e,t){let{distinctId:r,groups:i,personProperties:s,groupProperties:n}=t;if(!e.active)return!1;if(e.ensure_experience_continuity)throw new rk("Flag has experience continuity enabled");let a=(e.filters||{}).aggregation_group_type_index;if(void 0!=a){let r=t.definitions.groupTypeMapping[String(a)];if(!r)throw this.logMsgIfDebug(()=>console.warn(`[FEATURE FLAGS] Unknown group type index ${a} for feature flag ${e.key}`)),new rk("Flag has unknown group type index");if(!(r in i))return this.logMsgIfDebug(()=>console.warn(`[FEATURE FLAGS] Can't compute group feature flag: ${e.key} without group names passed in`)),!1;"device_id"===e.bucketing_identifier&&(s?.$device_id===void 0||s?.$device_id===null||s?.$device_id==="")&&this.logMsgIfDebug(()=>console.warn(`[FEATURE FLAGS] Ignoring bucketing_identifier for group flag: ${e.key}`));let o=n[r];return await this.matchFeatureFlagProperties(e,i[r],o,t)}{let i=this.getBucketingValueForFlag(e,r,s);if(void 0===i)throw this.logMsgIfDebug(()=>console.warn(`[FEATURE FLAGS] Can't compute feature flag: ${e.key} without $device_id, falling back to server evaluation`)),new rk(`Can't compute feature flag: ${e.key} without $device_id`);return await this.matchFeatureFlagProperties(e,i,s,t)}}getBucketingValueForFlag(e,t,r){if(e.filters?.aggregation_group_type_index!=void 0)return t;if("device_id"===e.bucketing_identifier){let e=r?.$device_id;if(null==e||""===e)return;return e}return t}async evaluateFlagDependency(e,t,r){let{evaluationCache:i}=r,s=e.key;if(!r.definitions.featureFlagsByKey)throw new rk("Feature flags not available for dependency evaluation");if(!("dependency_chain"in e))throw new rk(`Flag dependency property for '${s}' is missing required 'dependency_chain' field`);let n=e.dependency_chain;if(!Array.isArray(n))throw new rk(`Flag dependency property for '${s}' has an invalid 'dependency_chain' (expected array, got ${typeof n})`);if(0===n.length)throw new rk(`Circular dependency detected for flag '${s}' (empty dependency chain)`);for(let e of n){if(!(e in i)){let t=r.definitions.featureFlagsByKey[e];if(t)if(t.active)try{let s=await this.computeFlagValueLocally(t,r);i[e]=s}catch(t){throw new rk(`Error evaluating flag dependency '${e}' for flag '${s}': ${t}`)}else i[e]=!1;else if(r.definitions.filteredOutFlagKeys.has(e))i[e]=!1;else throw new rk(`Missing flag dependency '${e}' for flag '${s}'`)}if(null==i[e])throw new rk(`Dependency '${e}' could not be evaluated`)}let a=i[s];return this.flagEvaluatesToExpectedValue(e.value,a)}flagEvaluatesToExpectedValue(e,t){return"boolean"==typeof e?e===t||"string"==typeof t&&""!==t&&!0===e:"string"==typeof e&&t===e}async matchFeatureFlagProperties(e,t,r,i){let s;i=this.withEvaluationSnapshot(i);let n=e.filters||{},a=await rV(n.holdout,t);if(void 0!==a)return a;let o=n.groups||[],l=n.aggregation_group_type_index,u=n.early_exit??!1,{groups:c,groupProperties:h}=i,d=!1;for(let a of o)try{let o=void 0!==a.aggregation_group_type_index?a.aggregation_group_type_index:l,p=r,g=t;if(o!==l&&null!=o){let t=i.definitions.groupTypeMapping[String(o)];if(!t||!(t in c)){this.logMsgIfDebug(()=>console.debug(`[FEATURE FLAGS] Skipping group condition for flag '${e.key}': group type index ${o} not available`));continue}if(!(t in h)){d=!0;continue}p=h[t],g=c[t]}let f=await this.isConditionMatch(e,g,a,p,i);if("match"===f){let t=a.variant,r=n.multivariate?.variants||[];s=t&&r.some(e=>e.key===t)?t:await this.getMatchingVariant(e,g)||!0;break}if(u&&"out_of_rollout_bound"===f){if(d)break;return!1}}catch(e){if(e instanceof rJ)throw e;if(e instanceof rk)d=!0;else throw e}if(void 0!==s)return s;if(d)throw new rk("Can't determine if feature flag is enabled or not with given properties");return!1}async isConditionMatch(e,t,r,i,s){let n=(s=this.withEvaluationSnapshot(s)).definitions,a=r.rollout_percentage,o=e=>{this.logMsgIfDebug(()=>console.warn(e))};if((r.properties||[]).length>0){for(let e of r.properties){let t=e.type,r=!1;if("cohort"===t){let t=await rX(e,i,n.cohorts,this.debugMode,e=>this.evaluateFlagDependency(e,i,s),n.propertyMatchingVersion);r="not_in"===e.operator?!t:t}else r="flag"===t?await this.evaluateFlagDependency(e,i,s):rY(e,i,o,n.propertyMatchingVersion);if(!r)return"no_match"}if(void 0==a)return"match"}return void 0!=a&&await rH(e.key,t)>a/100?"out_of_rollout_bound":"match"}async getMatchingVariant(e,t){return rK(e.key,t,e.filters?.multivariate?.variants||[])}variantLookupTable(e){return rW(e.filters?.multivariate?.variants||[])}filterFlagsByEvaluationContexts(e){if(!this.evaluationContexts||0===this.evaluationContexts.length)return e;let t=new Set(this.evaluationContexts);return e.filter(e=>{let r=e.evaluation_contexts??e.evaluation_tags;return!r||0===r.length||r.some(e=>t.has(e))})}getEvaluationRuntimeForFlag(e){let t=this.featureFlagsByKey[e];return t?rG(t.evaluation_runtime):void 0}getFlagKeysByEvaluationRuntime(e){return this.featureFlags.filter(t=>{var r;return(r=rG(t.evaluation_runtime))===e||"all"===r||"all"===e}).map(e=>e.key)}updateFlagState(e){let t=this.filterFlagsByEvaluationContexts(e.flags);this.featureFlags=t,this.featureFlagsByKey=t.reduce((e,t)=>(e[t.key]=t,e),{});let r=new Set(t.map(e=>e.key));this.filteredOutFlagKeys=new Set(e.flags.filter(e=>!r.has(e.key)).map(e=>e.key)),this.groupTypeMapping=e.group_type_mapping??e.groupTypeMapping??{},this.cohorts=e.cohorts,this.propertyMatchingVersion=e.property_matching_version??e.propertyMatchingVersion,this.loadedSuccessfullyOnce=!0,this.onMinimalFlagCalledEvents?.((e.minimal_flag_called_events??e.minimalFlagCalledEvents)===!0)}warnAboutExperienceContinuityFlags(e){if(this.strictLocalEvaluation)return;let t=e.filter(e=>e.ensure_experience_continuity);t.length>0&&console.warn(`[PostHog] You are using local evaluation but ${t.length} flag(s) have experience continuity enabled: ${t.map(e=>e.key).join(", ")}. Experience continuity is incompatible with local evaluation and will cause a server request on every flag evaluation, negating local evaluation cost savings. To avoid server requests and unexpected costs, either disable experience continuity on these flags in PostHog, use strictLocalEvaluation: true in client init, or pass onlyEvaluateLocally: true per flag call (flags that cannot be evaluated locally will return undefined).`)}async loadFromCache(e){if(!this.cacheProvider)return!1;try{let t=await this.cacheProvider.getFlagDefinitions();if(t)return this.updateFlagState(t),this.logMsgIfDebug(()=>console.debug(`[FEATURE FLAGS] ${e} (${t.flags.length} flags)`)),this.onLoad?.(this.featureFlags.length),this.warnAboutExperienceContinuityFlags(this.featureFlags),!0;return!1}catch(e){return this.onError?.(Error(`Failed to load from cache: ${e}`)),!1}}async loadFeatureFlags(e=!1){if(!this.loadedSuccessfullyOnce||e)return!e&&this.nextFetchAllowedAt&&Date.now()<this.nextFetchAllowedAt?void this.logMsgIfDebug(()=>console.debug("[FEATURE FLAGS] Skipping fetch, in backoff period")):(this.loadingPromise||(this.loadingPromise=this._loadFeatureFlags().catch(e=>this.logMsgIfDebug(()=>console.debug(`[FEATURE FLAGS] Failed to load feature flags: ${e}`))).finally(()=>{this.loadingPromise=void 0})),this.loadingPromise)}isLocalEvaluationReady(){return(this.loadedSuccessfullyOnce??!1)&&(this.featureFlags?.length??0)>0}getFlagDefinitionsLoadedAt(){return this.flagDefinitionsLoadedAt}getPollingInterval(){let e=this.pollingInterval??3e4;return this.shouldBeginExponentialBackoff?Math.min(6e4,e*2**this.backOffCount):e}beginBackoff(){this.shouldBeginExponentialBackoff=!0,this.backOffCount+=1,this.nextFetchAllowedAt=Date.now()+this.getPollingInterval()}clearBackoff(){this.shouldBeginExponentialBackoff=!1,this.backOffCount=0,this.nextFetchAllowedAt=void 0}async _loadFeatureFlags(){this.poller&&(clearTimeout(this.poller),this.poller=void 0);try{let e=!0;if(this.cacheProvider)try{e=await this.cacheProvider.shouldFetchFlagDefinitions()}catch(e){this.onError?.(Error(`Error in shouldFetchFlagDefinitions: ${e}`))}if(!e&&(await this.loadFromCache("Loaded flags from cache (skipped fetch)")||this.loadedSuccessfullyOnce))return;let t=await this._requestFeatureFlagDefinitions();if(!t)return;switch(t.status){case 304:this.logMsgIfDebug(()=>console.debug("[FEATURE FLAGS] Flags not modified (304), using cached data")),this.flagsEtag=t.headers?.get("ETag")??this.flagsEtag,this.loadedSuccessfullyOnce=!0,this.clearBackoff();return;case 401:throw this.beginBackoff(),new rQ(`Your project key or secret key is invalid. Setting next polling interval to ${this.getPollingInterval()}ms. More information: https://posthog.com/docs/api#rate-limiting`);case 402:console.warn("[FEATURE FLAGS] Feature flags quota limit exceeded - unsetting all local flags. Learn more about billing limits at https://posthog.com/docs/billing/limits-alerts"),this.featureFlags=[],this.featureFlagsByKey={},this.filteredOutFlagKeys=new Set,this.groupTypeMapping={},this.cohorts={},this.propertyMatchingVersion=void 0,this.onMinimalFlagCalledEvents?.(!1);return;case 403:throw this.beginBackoff(),new rQ(`Your secret key does not have permission to fetch feature flag definitions for local evaluation. Setting next polling interval to ${this.getPollingInterval()}ms. Are you sure you're using the correct secret and Project API key pair? More information: https://posthog.com/docs/api/overview`);case 429:throw this.beginBackoff(),new rQ(`You are being rate limited. Setting next polling interval to ${this.getPollingInterval()}ms. More information: https://posthog.com/docs/api#rate-limiting`);case 200:{let r=await t.json()??{};if(!("flags"in r))return void this.onError?.(Error(`Invalid response when getting feature flags: ${JSON.stringify(r)}`));this.flagsEtag=t.headers?.get("ETag")??void 0;let i=r.group_type_mapping||{},s=!0===r.minimal_flag_called_events,n={flags:r.flags??[],group_type_mapping:i,cohorts:r.cohorts||{},minimal_flag_called_events:s,property_matching_version:r.property_matching_version,propertyMatchingVersion:r.property_matching_version,groupTypeMapping:i,minimalFlagCalledEvents:s};if(this.updateFlagState(n),this.flagDefinitionsLoadedAt=Date.now(),this.clearBackoff(),this.cacheProvider&&e)try{await this.cacheProvider.onFlagDefinitionsReceived(n)}catch(e){this.onError?.(Error(`Failed to store in cache: ${e}`))}this.onLoad?.(this.featureFlags.length),this.warnAboutExperienceContinuityFlags(this.featureFlags);break}default:return}}catch(e){e instanceof rQ&&this.onError?.(e)}finally{this.pollerStopped||null===this.pollingInterval||(this.poller=setTimeout(()=>this.loadFeatureFlags(!0),this.getPollingInterval()))}}getPersonalApiKeyRequestOptions(e="GET",t){let r={...this.customHeaders,"Content-Type":"application/json",Authorization:`Bearer ${this.personalApiKey}`};return t&&(r["If-None-Match"]=t),{method:e,headers:r}}async _requestFeatureFlagDefinitions(){let e=`${this.host}/flags/definitions?token=${this.projectApiKey}&send_cohorts`,t=this.getPersonalApiKeyRequestOptions("GET",this.flagsEtag),r=null;if(this.timeout&&"number"==typeof this.timeout){let e=new AbortController;r=U(()=>{e.abort()},this.timeout),t.signal=e.signal}try{let i=this.fetch,s=await i(e,t);if(200!==s.status)return clearTimeout(r),s;return{status:s.status,headers:s.headers,body:s.body,text:async()=>{try{return await s.text()}finally{clearTimeout(r)}},json:async()=>{try{return await s.json()}finally{clearTimeout(r)}}}}catch(e){throw clearTimeout(r),e}}async stopPoller(e=3e4){if(this.pollerStopped=!0,clearTimeout(this.poller),this.poller=void 0,this.cacheProvider)try{let t=this.cacheProvider.shutdown();t instanceof Promise&&await z(t,e,()=>{throw Error(`Cache shutdown timeout after ${e}ms`)})}catch(e){this.onError?.(Error(`Error during cache shutdown: ${e}`))}}}function rY(e,t,r,i){return function(e,t,r={}){let i=e.key,s=e.value,n=e.operator||"exact",a=r.semverParsingPolicy??"strict";if(Object.prototype.hasOwnProperty.call(t,i)){if("is_not_set"===n)return!1;else if("is_set"===n)return!0}else throw new rk(`Property ${i} not found in propertyValues`);let o=t[i];if(void 0===o)return r.warnFunction?.(`Property ${i} cannot have a value of undefined with the ${n} operator`),"is_not"===n;if(null===o&&!rC.includes(n)&&"exact"!==n&&"is_not"!==n)return r.warnFunction?.(`Property ${i} cannot have a value of null with the ${n} operator`),!1;let l=(e,t)=>{if(2!==r.propertyMatchingVersion&&r$(e)||Array.isArray(e)&&0===e.length)return rT(t),rO(e)===rO(t);if(2===r.propertyMatchingVersion&&"number"==typeof t&&r$(e))return rT(t),!1;if(Array.isArray(e)){let r=rD(t).toLowerCase();return e.some(e=>rD(e).toLowerCase()===r)}return rD(e).toLowerCase()===rD(t).toLowerCase()},u=(e,t,r)=>{if("gt"===r)return e>t;if("gte"===r)return e>=t;if("lt"===r)return e<t;if("lte"===r)return e<=t;throw Error(`Invalid operator: ${r}`)};switch(n){case"exact":return l(s,o);case"is_not":return!l(s,o);case"is_set":return!0;case"icontains":return rB(o).includes(rB(s));case"not_icontains":return!rB(o).includes(rB(s));case"starts_with":return rB(o).startsWith(rB(s));case"not_starts_with":return!rB(o).startsWith(rB(s));case"ends_with":return rB(o).endsWith(rB(s));case"not_ends_with":return!rB(o).endsWith(rB(s));case"regex":return rj(String(s))&&null!==String(o).match(String(s));case"not_regex":return rj(String(s))&&null===String(o).match(String(s));case"gt":case"gte":case"lt":case"lte":{let e="number"==typeof s?s:parseFloat(String(s)),t="number"==typeof o?o:null!=o?parseFloat(String(o)):0/0;if(Number.isFinite(e)&&Number.isFinite(t))return u(t,e,n);return u(String(o),String(s),n)}case"is_date_after":case"is_date_before":{if("boolean"==typeof s)throw new rk("Date operations cannot be performed on boolean values");let e=function(e){let t=e.match(/^-?(?<number>[0-9]+)(?<interval>[a-z])$/),r=new Date(new Date().toISOString());if(!t||!t.groups)return null;let i=parseInt(t.groups.number);if(i>=1e4)return null;let s=t.groups.interval;if("h"===s)r.setUTCHours(r.getUTCHours()-i);else if("d"===s)r.setUTCDate(r.getUTCDate()-i);else if("w"===s)r.setUTCDate(r.getUTCDate()-7*i);else if("m"===s)r.setUTCMonth(r.getUTCMonth()-i);else{if("y"!==s)return null;r.setUTCFullYear(r.getUTCFullYear()-i)}return r}(String(s));null==e&&(e=rU(s));let t=rU(o);return"is_date_before"===n?t<e:t>e}case"semver_eq":return 0===rq(rN(String(o),a),rN(String(s),a));case"semver_neq":return 0!==rq(rN(String(o),a),rN(String(s),a));case"semver_gt":return rq(rN(String(o),a),rN(String(s),a))>0;case"semver_gte":return rq(rN(String(o),a),rN(String(s),a))>=0;case"semver_lt":return 0>rq(rN(String(o),a),rN(String(s),a));case"semver_lte":return 0>=rq(rN(String(o),a),rN(String(s),a));case"semver_tilde":{let e,t=rN(String(o),a),{lower:r,upper:i}={lower:[(e=rN(String(s),a))[0],e[1],e[2]],upper:[e[0],e[1]+1,0]};return rq(t,r)>=0&&0>rq(t,i)}case"semver_caret":{let e=rN(String(o),a),{lower:t,upper:r}=function(e,t){let[r,i,s]=rN(e,t);return{lower:[r,i,s],upper:r>0?[r+1,0,0]:i>0?[0,i+1,0]:[0,0,s+1]}}(String(s),a);return rq(e,t)>=0&&0>rq(e,r)}case"semver_wildcard":{let e=rN(String(o),a),{lower:t,upper:r}=function(e,t){let r=String(e).trim().replace(/^[vV]/,"").replace(/\.\*$/,"").replace(/\*$/,"");if(!r)throw new rk(`Invalid wildcard semver: ${e}`);let i=r.split("."),s=r=>{if("legacy-permissive"===t){let e=parseInt(r,10);if(!isNaN(e))return e}else try{return rL(r,e,t)}catch{}throw new rk(`Invalid wildcard semver: ${e}`)},n=s(i[0]);if(1===i.length)return{lower:[n,0,0],upper:[n+1,0,0]};let a=s(i[1]);return{lower:[n,a,0],upper:[n,a+1,0]}}(String(s),a);return rq(e,t)>=0&&0>rq(e,r)}default:throw new rk(`Unknown operator: ${n}`)}}(e,t,{warnFunction:r,propertyMatchingVersion:i})}async function rX(e,t,r,i=!1,s,n){let a=String(e.value);if(!(a in r))throw new rJ(`cohort ${a} not found in local cohorts - likely a static cohort that requires server evaluation`);return r0(r[a],t,r,i,s,n)}async function r0(e,t,r,i=!1,s,n){if(!e)return!0;let a=e.type,o=e.values;if(!o||0===o.length)return!0;let l=!1;if("values"in o[0]){for(let e of o)try{let o=await r0(e,t,r,i,s,n);if("AND"===a){if(!o)return!1}else if(o)return!0}catch(t){if(t instanceof rJ)throw t;if(t instanceof rk)i&&console.debug(`Failed to compute property ${e} locally: ${t}`),l=!0;else throw t}if(l)throw new rk("Can't match cohort without a given cohort property value");return"AND"===a}for(let e of o)try{let o;if("cohort"===e.type)o=await rX(e,t,r,i,s,n);else if("flag"===e.type){if(!s)throw new rk(`Flag dependency '${e.key||"unknown"}' cannot be evaluated without a flag dependency evaluator`);o=await s(e)}else o=rY(e,t,void 0,n);let l=e.negation||!1;if("AND"===a){if(!o&&!l||o&&l)return!1}else if(o&&!l||!o&&l)return!0}catch(t){if(t instanceof rJ)throw t;if(t instanceof rk)i&&console.debug(`Failed to compute property ${e} locally: ${t}`),l=!0;else throw t}if(l)throw new rk("can't match cohort without a given cohort property value");return"AND"===a}let r1=["--unhandled-rejections","--unhandled_rejections"],r2=new Set(["throw","strict","warn","warn-with-error-code","none"]),r3=[...globalThis.process?.execArgv??[]],r5=globalThis.process?.env?.NODE_OPTIONS;function r4(e){let t;for(let r=0;r<e.length;r++){let i=e[r],s=r1.find(e=>i===e||i.startsWith(`${e}=`));if(!s)continue;let n=i===s?e[++r]:i.slice(s.length+1);r2.has(n)&&(t=n)}return t}let r6=function(e=r3,t=r5){return r4(e)??r4(function(e){let t=[],r="",i=!1;for(let s=0;s<e.length;s++){let n=e[s];"\\"===n&&i&&s+1<e.length?r+=e[++s]:" "!==n||i?'"'===n?i=!i:r+=n:r&&(t.push(r),r="")}return r&&t.push(r),t}(t??""))??"throw"}();function r8(e,t,r){e(t,{mechanism:{type:"unhandledRejection"===r?"onunhandledrejection":"onuncaughtexception",handled:!1}})}function r9(e,t,r,i,s){if(t>r&&(i.warn("min cannot be greater than max."),t=r),S(e))if(e>r)return i.warn(" cannot be greater than max: "+r+". Using max value instead."),r;else return e<t?(i.warn(" cannot be less than min: "+t+". Using min value instead."),t):e;return i.warn(" must be a number. using max or fallback. max: "+r+", fallback: "+s),r9(s??r,t,r,i)}class r7{constructor(e){this._buckets={},this._onBucketRateLimited=e._onBucketRateLimited,this._bucketSize=r9(e.bucketSize,0,100,e._logger),this._refillRate=r9(e.refillRate,0,this._bucketSize,e._logger),this._refillInterval=r9(e.refillInterval,0,864e5,e._logger)}_applyRefill(e,t){let r=Math.floor((t-e.lastAccess)/this._refillInterval);if(r>0){let t=r*this._refillRate;e.tokens=Math.min(e.tokens+t,this._bucketSize),e.lastAccess=e.lastAccess+r*this._refillInterval}}consumeRateLimit(e){let t=Date.now(),r=String(e),i=this._buckets[r];return i?this._applyRefill(i,t):(i={tokens:this._bucketSize,lastAccess:t},this._buckets[r]=i),0===i.tokens||(i.tokens--,0===i.tokens&&this._onBucketRateLimited?.(e),0===i.tokens)}stop(){this._buckets={}}}var ie=ez;let it=class t{constructor(e,t,r){this.client=e,this._exceptionAutocaptureEnabled=t.enableExceptionAutocapture||!1,this._logger=r,this._rateLimiter=new r7({...function(e={}){return{refillRate:e.exceptionRateLimiterRefillRate??e.__exceptionRateLimiterRefillRate??1,bucketSize:e.exceptionRateLimiterBucketSize??e.__exceptionRateLimiterBucketSize??10}}(t),refillInterval:1e4,_logger:this._logger}),this.startAutocaptureIfEnabled()}static isPreviouslyCapturedError(e){return y(e)&&"__posthog_previously_captured_error"in e&&!0===e.__posthog_previously_captured_error}static async buildEventMessage(e,t,r,i,s){let n={...s},a=e.buildFromUnknown(t,r);a.$exception_list=await e.modifyFrames(a.$exception_list);let o=ie.getInjectedReleaseId();return o&&(n.$release_id=o),{event:"$exception",distinctId:i,properties:{...a,...n},_originatedFromCaptureException:!0}}startAutocaptureIfEnabled(){this.isEnabled()&&(!function(t,r,i=r6){let s=globalThis.process;if(s){let n;if("strict"===i)return s.on("uncaughtExceptionMonitor",(e,r)=>r8(t,e,r));s.on("uncaughtException",(n=!1,Object.assign((i,s)=>{let a=e.g.process.listeners("uncaughtException").filter(e=>"domainUncaughtExceptionClear"!==e.name&&!0!==e._posthogErrorHandler).length;r8(t,i,s),n||0!==a||(n=!0,r(i))},{_posthogErrorHandler:!0})))}}(this.onException.bind(this),this.onFatalError.bind(this)),function(e,t=r6){let r=globalThis.process;r&&"throw"!==t&&"strict"!==t&&"warn-with-error-code"!==t&&r.on("unhandledRejection",t=>{e(t,{mechanism:{type:"onunhandledrejection",handled:!1}})})}(this.onException.bind(this)))}onException(e,r){this.client.addPendingPromise((async()=>{if(!t.isPreviouslyCapturedError(e)){let i=await t.buildEventMessage(this.client.getErrorPropertiesBuilder(),e,r),s=i.properties,n=s?.$exception_list[0]?.type??"Exception";return this._rateLimiter.consumeRateLimit(n)?void this._logger.info("Skipping exception capture because of client rate limiting.",{exception:n}):this.client._capturePreparedEvent(i,!1)}})())}async onFatalError(e){console.error(e),await this.client.shutdown(2e3),globalThis.process.exit(1)}isEnabled(){return!this.client.isDisabled&&this._exceptionAutocaptureEnabled}shutdown(){this._rateLimiter.stop()}};class ir{getProperty(e){return this._memoryStorage[e]}setProperty(e,t){this._memoryStorage[e]=null!==t?t:void 0}constructor(){this._memoryStorage={}}}let ii="analytics";class is extends Error{constructor({requestId:e,drops:t,retryExhausted:r,cause:i}){super(is.buildMessage(e,t,r,i)),this.name="CaptureV1Error",this.requestId=e,this.drops=t,this.retryExhausted=r,this.cause=i}static buildMessage(e,t,r,i){let s=`Capture V1 batch ${e} did not fully deliver: ${t.length} dropped, ${r.length} undelivered`;return i instanceof Error&&(s+=` (${i.message})`),s}}function ia(e){if("boolean"==typeof e)return e;if("number"==typeof e)return 0!==e;if("string"==typeof e){let t=e.trim().toLowerCase();if("true"===t||"1"===t)return!0;if("false"===t||"0"===t)return!1}}let io=[{property:"$cookieless_mode",optionKey:"cookieless_mode",coerce:ia},{property:"$ignore_sent_at",optionKey:"disable_skew_correction",coerce:ia},{property:"$process_person_profile",optionKey:"process_person_profile",coerce:ia},{property:"$product_tour_id",optionKey:"product_tour_id",coerce:function(e){return"string"==typeof e?e:void 0}}],il=[{property:"$session_id",field:"session_id"},{property:"$window_id",field:"window_id"}];function iu(e,t,r){void 0===r||t in e||(e[t]=r)}function ic(e){var t;let r={..."object"==typeof(t=e.properties)&&null!==t&&!Array.isArray(t)?e.properties:{}},i={};for(let{property:e,optionKey:t,coerce:s}of io)if(e in r){let n=s(r[e]);void 0!==n&&(i[t]=n),delete r[e]}let s={};for(let{property:e,field:t}of il)if(e in r){let i=r[e];"string"==typeof i&&(s[t]=i),delete r[e]}return delete r.$lib,delete r.$lib_version,iu(r,"$set",e.$set),iu(r,"$set_once",e.$set_once),{event:String(e.event??""),uuid:String(e.uuid??""),distinct_id:String(e.distinct_id??""),timestamp:function(e){if("string"==typeof e){let t=new Date(e);if(Number.isNaN(t.getTime()))return new Date().toISOString();let r=t.toISOString(),i=e.match(/\.(\d+)(?:Z|[+-]\d{2}:?\d{2})?$/i)?.[1];return i&&i.length>3?r.replace(/\.\d{3}Z$/,`.${i}Z`):r}if(e instanceof Date)return Number.isNaN(e.getTime())?new Date().toISOString():e.toISOString();let t=null==e?new Date:new Date(e);return Number.isNaN(t.getTime())?new Date().toISOString():t.toISOString()}(e.timestamp),...s,options:i,properties:r}}let ih=new Set([408,500,502,503,504]);class id{constructor(e,t){this.config=e,this.maxBackoffMs=e.maxBackoffMs??3e4,this.fetchFn=t.fetch,this.onError=t.onError,this.now=t.now??Date.now,this.sleep=t.sleep??(e=>new Promise(t=>U(t,e))),this.generateRequestId=t.generateRequestId??eG,this.compress=t.compress??e7}async sendV1Batch(e){if(0===e.length)return;let t=this.generateRequestId(),r=new Date(this.now()).toISOString(),{batch:i}=function(e,{createdAt:t,historicalMigration:r}){let i={created_at:t,batch:e.map(ic)};return r&&(i.historical_migration=!0),i}(e,{createdAt:r,historicalMigration:this.config.historicalMigration}),s=`${this.config.host}/i/v1/analytics/events`,n=[],a=i,o=Math.max(1,this.config.maxAttempts);for(let e=1;e<=o;e++){let i,l,u=e===o,c=d({created_at:r,...this.config.historicalMigration?{historical_migration:!0}:{},batch:a});try{let{response:r,signal:o}=i=await this.sendOnce(s,c,e,t),{status:h}=r;if(h<200||h>=300)if(!u&&ih.has(h)){let t=this.parseRetryAfter(r);await i.waitFor(i.cancelBody()).catch(()=>{}),l=this.backoffDelay(e,t)}else{let e=await this.buildHttpError(r,h,i.waitFor);return this.surfaceBatchFailure(t,n,a,e)}else{let s;try{s=await i.waitFor(this.parseResponse(r))}catch(e){if(o.aborted)throw e;return this.surfaceBatchFailure(t,n,a,Error(`Capture V1 returned an unparseable ${h} response body`))}let c=this.classify(a,s,n);if(0===c.length)return this.surfacePartialDrops(t,n);if(u)return void this.onError(new is({requestId:t,drops:n,retryExhausted:c.map(e=>e.uuid)}));a=c;let d=this.parseRetryAfter(r);l=this.backoffDelay(e,d)}}catch(r){if(i&&!i.signal.aborted)throw r;if(u)return this.surfaceBatchFailure(t,n,a,r);l=this.backoffDelay(e)}finally{i?.cleanup()}void 0!==l&&await this.sleep(l)}}async sendOnce(e,t,r,i){let s,n=this.buildHeaders(r,i),a=t;if(this.config.compressionEnabled){let e=await this.compress(t,this.config.isDebug);null!==e&&(a=e,n["Content-Encoding"]="gzip")}let o=new AbortController,l="waiting for response headers",u=new Promise((e,t)=>{s=U(()=>{let e=Error(`Capture V1 request timed out ${l} after ${this.config.requestTimeoutMs}ms`);e.name="AbortError",t(e),o.abort(e)},this.config.requestTimeoutMs)});try{let t,r=this.fetchFn(e,{method:"POST",headers:n,body:a,signal:o.signal}),i=!1;r.then(e=>{o.signal.aborted&&!i&&this.cancelBody(e)}).catch(()=>{});let c=await Promise.race([r,u]);i=!0,l="while reading the response body";let h=!1,d=()=>t??=this.cancelBody(c);return{response:c,signal:o.signal,waitFor:e=>Promise.race([e,u]),cancelBody:d,cleanup:()=>{!h&&(h=!0,clearTimeout(s),o.signal.aborted&&d())}}}catch(e){throw clearTimeout(s),e}}buildHeaders(e,t){let r=`${this.config.libraryId}/${this.config.libraryVersion}`,i={"Content-Type":"application/json",Authorization:`Bearer ${this.config.apiKey}`,"PostHog-Sdk-Info":r,"PostHog-Attempt":String(e),"PostHog-Request-Id":t,"PostHog-Request-Timestamp":new Date(this.now()).toISOString()};return this.config.userAgent&&(i["User-Agent"]=this.config.userAgent),i}classify(e,t,r){let i=t.results??{},s=[];for(let t of e){let e=i[t.uuid];e&&("drop"===e.result?r.push({uuid:t.uuid,details:e.details??void 0}):"retry"===e.result&&s.push(t))}return s}backoffDelay(e,t){let r=Math.min(this.config.initialRetryDelayMs*2**(e-1),this.maxBackoffMs);return void 0===t?r:Math.max(r,Math.min(t,this.maxBackoffMs))}parseRetryAfter(e){let t=e.headers?.get("Retry-After");if(!t)return;let r=t.trim();if(/^\d+$/.test(r)){let e=parseInt(r,10);return Number.isFinite(e)&&e>0?1e3*e:void 0}let i=Date.parse(r);if(Number.isNaN(i))return;let s=i-this.now();return s>0?s:void 0}async parseResponse(e){let t=JSON.parse(await e.text());if("object"!=typeof t||null===t||Array.isArray(t))throw Error("unexpected response shape");let r=t.results;if(void 0!==r&&("object"!=typeof r||null===r||Array.isArray(r)))throw Error("unexpected results shape");return{results:r??{}}}async buildHttpError(e,t,r){let i="";try{i=(await r(e.text())).slice(0,512)}catch{}let s=i?`: ${i}`:"";return Error(`Capture V1 request failed with HTTP ${t}${s}`)}surfaceBatchFailure(e,t,r,i){this.onError(new is({requestId:e,drops:t,retryExhausted:r.map(e=>e.uuid),cause:i}))}surfacePartialDrops(e,t){t.length>0&&this.onError(new is({requestId:e,drops:t,retryExhausted:[]}))}async cancelBody(e){try{await e.body?.cancel()}catch{}}}let ip="ai-capture",ig="/i/v0/ai/batch/",im=new TextEncoder;function iy(e){return im.encode(d(e)).length}let i_=new Set;function iv(e,t){i_.has(e)||(i_.add(e),console.warn(`[PostHog] ${t}`))}class ib extends tp{get distinctIdHasSentFlagCalls(){return Object.fromEntries(this._distinctIdHasSentFlagCalls)}set distinctIdHasSentFlagCalls(e){this._distinctIdHasSentFlagCalls=new Map(Object.entries(e??{}))}constructor(e,t={}){var r,i;let s,n="string"==typeof e?e.trim():"",a={...t,maxQueueSize:t.maxQueueSize??1e4,flushInterval:t.flushInterval??5e3,host:("string"==typeof(r=t.host)?r.trim():"")||"https://us.i.posthog.com",personalApiKey:("string"==typeof(i=t.secretKey??t.personalApiKey)?i.trim():"")||void 0};if(super(n,a),this._memoryStorage=new ir,this._aiCaptureRouteActive=!1,this._minimalFlagCalledEvents=!1,this.options=a,this.captureMode="v0"===(s="u">typeof process?process.env?.POSTHOG_CAPTURE_MODE:void 0)||"v1"===s?s:"v0",this.enableFullAiCapture=!0===a.enableFullAiCapture,this.context=this.initializeContext(),this.options.featureFlagsPollingInterval="number"==typeof a.featureFlagsPollingInterval?Math.max(a.featureFlagsPollingInterval,100):null===a.featureFlagsPollingInterval?null:3e4,"number"==typeof a.waitUntilDebounceMs&&(this.options.waitUntilDebounceMs=Math.max(a.waitUntilDebounceMs,0)),"number"==typeof a.waitUntilMaxWaitMs&&(this.options.waitUntilMaxWaitMs=Math.max(a.waitUntilMaxWaitMs,0)),!this.disabled&&a.personalApiKey){if(a.personalApiKey.includes("phc_"))throw Error('Your Personal API key is invalid. These keys are prefixed with "phx_" and can be created in PostHog project settings.');!1!==a.enableLocalEvaluation&&(this.featureFlagsPoller=new rZ({pollingInterval:this.options.featureFlagsPollingInterval,personalApiKey:a.personalApiKey,projectApiKey:n,timeout:a.requestTimeout??1e4,host:this.host,fetch:a.fetch,onError:e=>{this._events.emit("error",e)},onLoad:e=>{this._events.emit("localEvaluationFlagsLoaded",e)},onMinimalFlagCalledEvents:e=>{this._minimalFlagCalledEvents=e},customHeaders:this.getCustomHeaders(),cacheProvider:a.flagDefinitionCacheProvider,strictLocalEvaluation:a.strictLocalEvaluation,evaluationContexts:a.evaluationContexts??a.evaluationEnvironments}))}this.errorTracking=new it(this,a,this._logger),this._distinctIdHasSentFlagCalls=new Map,this.maxCacheSize=a.maxCacheSize||5e4}enqueue(e,t,r,i){super.enqueue(e,t,r,i),this.scheduleDebouncedFlush()}_flushEventsAndSpans(e=!1){let t=this.flushWithPendingPromises();return!this._traces||e&&this._traces.throttled?t:H([t,this._traces.flush().catch(()=>{})]).then(([e])=>{if("rejected"===e.status)throw e.reason})}flushAutomatic(){return this._flushKeepingRuntimeAlive(!0)}async flush(){return this._flushKeepingRuntimeAlive(!1)}_flushKeepingRuntimeAlive(e){let t=this._flushEventsAndSpans(e),r=this.options.waitUntil;if(r&&!this._waitUntilCycle)try{r(t.catch(()=>{}))}catch{}return t}scheduleDebouncedFlush(){let e=this.options.waitUntil;if(!e||this.disabled||this.optedOut)return;if(!this._waitUntilCycle){let t,r=new Promise(e=>{t=e});try{e(r)}catch{return}this._waitUntilCycle={resolve:t,startedAt:Date.now(),timer:void 0}}let t=Date.now()-this._waitUntilCycle.startedAt,r=this.options.waitUntilMaxWaitMs??500;if(void 0!==this._waitUntilCycle.timer&&clearTimeout(this._waitUntilCycle.timer),t>=r)return void this.resolveWaitUntilFlush();let i=this.options.waitUntilDebounceMs??50;this._waitUntilCycle.timer=U(()=>{this.resolveWaitUntilFlush()},i)}_consumeWaitUntilCycle(){let e=this._waitUntilCycle;return e&&(clearTimeout(e.timer),this._waitUntilCycle=void 0),e?.resolve}async resolveWaitUntilFlush(){let e=this._consumeWaitUntilCycle();try{await this._flushEventsAndSpans()}catch{}finally{e?.()}}getPersistedProperty(e){return this._memoryStorage.getProperty(e)}setPersistedProperty(e,t){return this._memoryStorage.setProperty(e,t)}fetch(e,t){return this.options.fetch?this.options.fetch(e,t):fetch(e,t)}getQueueRouteKey(e){var t;return"v1"===this.captureMode&&"string"==typeof(t=e).event&&t.event.startsWith("$ai_")?"ai":ii}persistedQueueKeyForRoute(e){return e===ip?c.AiCaptureQueue:"ai"===e?c.AiQueue:c.Queue}getActiveQueueRoutes(){let e="v1"===this.captureMode?[ii,"ai"]:[ii];return this._aiCaptureRouteActive&&e.push(ip),e}getBatchEndpointPath(e){return e===ip?ig:super.getBatchEndpointPath(e)}async sendBatch(e,t,r=ii){if(r===ip)return this.sendAiCaptureBatch(e,t);if("v1"!==this.captureMode||"ai"===r)return super.sendBatch(e,t,r);let i=e.filter(e=>void 0!==e);await this.getV1Sender().sendV1Batch(i)}async sendAiCaptureBatch(e,t){let{batches:r,dropped:i}=function(e,t=8388608,r=5242880){let i=[],s=[],n=[],a=0;for(let o of e){if(void 0===o)continue;let e=iy(o);if(e>t){s.push({event:"string"==typeof o.event?o.event:"unknown",bytes:e});continue}n.length>0&&a+e>r&&(i.push(n),n=[],a=0),n.push(o),a+=e}return n.length>0&&i.push(n),{batches:i,dropped:s}}(e);for(let{event:e,bytes:t}of i){let r=`Event ${e} (${t} bytes) exceeds the 8MiB limit for ${ig}, dropping.`;this._logger.error(r),this._events.emit("error",Error(r))}for(let e of r)await this.sendAiSubBatch(e,t)}async sendAiSubBatch(e,t){try{await super.sendBatch(e,t,ip)}catch(i){if(!tu(i))throw i;if(1===e.length){let[t]=e,r="string"==typeof t.event?t.event:"unknown",i=`Event ${r} (${iy(t)} bytes) was rejected with 413 by ${ig} on its own, dropping.`;this._logger.error(i),this._events.emit("error",Error(i));return}let r=Math.ceil(e.length/2);await this.sendAiSubBatch(e.slice(0,r),t),await this.sendAiSubBatch(e.slice(r),t)}}getV1Sender(){return this._v1Sender||(this._v1Sender=new id({host:this.host,apiKey:this.apiKey,libraryId:this.getLibraryId(),libraryVersion:this.getLibraryVersion(),userAgent:this.getCustomUserAgent()||void 0,historicalMigration:this.historicalMigration,compressionEnabled:!this.disableCompression,requestTimeoutMs:this.requestTimeout,maxAttempts:(this.options.fetchRetryCount??3)+1,initialRetryDelayMs:this.options.fetchRetryDelay??3e3,isDebug:this.isDebug},{fetch:(e,t)=>this.fetch(e,t),onError:e=>this._events.emit("error",e),compress:e=>this.compressPayload(e)})),this._v1Sender}getLibraryVersion(){return"5.55.1"}get metrics(){var e;let t;return this._metrics||(this._metrics=new tH(this,(e=this.options.metrics,t=e?.resourceAttributes,{serviceName:t?.["service.name"]??e?.serviceName,serviceVersion:t?.["service.version"]??e?.serviceVersion,environment:t?.["deployment.environment"]??e?.environment,resourceAttributes:t,beforeSend:e?.beforeSend,flushIntervalMs:e?.flushIntervalMs??1e4,maxSeriesPerFlush:e?.maxSeriesPerFlush??1e3}),this._logger)),this._metrics}initializeSpanContextManager(){return new rw}hostResourceAttributes(){return{}}get _spanContextManager(){return this._spanContext||(this._spanContext=this.initializeSpanContextManager()),this._spanContext}get _tracesPipeline(){if(this.options.traces){var e,t,r;let i,s;return this._traces||(this._traces=new ro(this,(e=this.options.traces,t=this.hostResourceAttributes(),r=this._logger,i=t_({...t},function(e){if(!(!e||"object"!=typeof e||Array.isArray(e)))try{if(rP.every(t=>!(t in e)||"string"==typeof e[t]))return e;let t={...e};for(let e of rP)e in t&&"string"!=typeof t[e]&&delete t[e];return t}catch{return}}(e?.resourceAttributes)),s=rF(e?.maxExportBatchSize,512),{serviceName:i?.["service.name"]??e?.serviceName,serviceVersion:i?.["service.version"]??e?.serviceVersion,environment:i?.["deployment.environment"]??e?.environment,resourceAttributes:i,beforeSpanSend:function(e,t){if(!e)return[];let r=[e].flat().filter(e=>!!e),i=r.filter(e=>"function"==typeof e);return i.length!==r.length&&t?.critical(`beforeSpanSend: ignoring ${r.length-i.length} of ${r.length} entries that are not functions. Spans export without them, so whatever they were redacting is not redacted.`),i}(e?.beforeSpanSend,r),maxAttributesPerSpan:rF(e?.maxAttributesPerSpan,128),maxEventsPerSpan:rF(e?.maxEventsPerSpan,128),maxAttributesPerEvent:128,maxAttributeValueLength:rF(e?.maxAttributeValueLength,8192),flushIntervalMs:rF(e?.flushIntervalMs,5e3),maxExportBatchSize:s,maxQueueSize:Math.max(rF(e?.maxQueueSize,2048),s),maxLiveSpans:rF(e?.maxLiveSpans,1e4),maxSpanAgeMs:rF(e?.maxSpanAgeMs,36e5)}),this._logger,()=>this._tracingContext(),this._spanContextManager,()=>this.scheduleDebouncedFlush())),this._traces}}_tracingContext(){let e=this.context?.get();return{distinctId:e?.distinctId,sessionId:e?.sessionId}}startSpan(e,t){return this._tracesPipeline?.startSpan(e,t)??t2(t,this._spanContextManager.active())}withSpan(e,t,r){let i="function"==typeof t?void 0:t,s="function"==typeof t?t:r,n=this._tracesPipeline;return n?i?n.withSpan(e,i,s):n.withSpan(e,s):t8(this._spanContextManager,t2(i,this._spanContextManager.active()),s)}getActiveSpan(){return this._spanContextManager.active()??null}getCustomUserAgent(){return`${this.getLibraryId()}/${this.getLibraryVersion()}`}getEvaluationRuntime(){return"server"}getCommonEventProperties(){let e=super.getCommonEventProperties();return(this.options.isServer??!0)&&(e.$is_server=!0),e}enable(){return super.optIn()}disable(){return super.optOut()}debug(e=!0){super.debug(e),this.featureFlagsPoller?.debug(e)}_warnIfInvalidCapture(e,t,r){"string"==typeof e&&this._logger.warn(t),"$exception"!==e.event||e._originatedFromCaptureException||this._logger.warn(r)}_sendPreparedEvent(e,t,r,i,s){return this.addPendingPromise(this._prepareEventMessage(t,i).then(({distinctId:t,event:i,properties:n,options:a})=>{let o={timestamp:a.timestamp,disableGeoip:a.disableGeoip,uuid:a.uuid},l={distinctId:t,event:i,properties:{...n,...this.getCommonEventProperties()}};return r?this.sendImmediate(e,l,o,s):this.enqueue(e,l,o,s)}).catch(e=>{e&&console.error(e)}))}_capturePreparedEvent(e,t){return this._sendPreparedEvent("capture",e,t)}capture(e){this._warnIfInvalidCapture(e,"Called capture() with a string as the first argument when an object was expected.","Using `posthog.capture('$exception')` is unreliable because it does not attach required metadata. Use `posthog.captureException(error)` instead, which attaches required metadata automatically."),this._capturePreparedEvent(e,!1)}async captureImmediate(e){return this._warnIfInvalidCapture(e,"Called captureImmediate() with a string as the first argument when an object was expected.","Capturing a `$exception` event via `posthog.captureImmediate('$exception')` is unreliable because it does not attach required metadata. Use `posthog.captureExceptionImmediate(error)` instead, which attaches this metadata by default."),this._capturePreparedEvent(e,!0)}captureAi(e){if(this.disabled)return;let t=j(e.uuid,eG);return this._sendPreparedAiEvent({...e,uuid:t},!1),t}async captureAiImmediate(e){if(this.disabled)return;let t=j(e.uuid,eG);return await this._sendPreparedAiEvent({...e,uuid:t},!0),t}_sendPreparedAiEvent(e,t){return"string"!=typeof e?.event||e.event.startsWith("$ai_")||this._logger.debug(`captureAi called with non-AI event ${e.event}; routing it to the AI endpoint anyway.`),this._aiCaptureRouteActive=!0,this._sendPreparedEvent("capture",e,t,void 0,ip)}identify({distinctId:e,properties:t={},disableGeoip:r}){let{$set:i,$set_once:s,$anon_distinct_id:n,...a}=t;this._sendPreparedEvent("identify",{distinctId:e,event:"$identify",properties:{$set:i||a,$set_once:s||{},$anon_distinct_id:n??void 0},disableGeoip:r},!1,{includeContextProperties:!1})}async identifyImmediate({distinctId:e,properties:t={},disableGeoip:r}){let{$set:i,$set_once:s,$anon_distinct_id:n,...a}=t;await this._sendPreparedEvent("identify",{distinctId:e,event:"$identify",properties:{$set:i||a,$set_once:s||{},$anon_distinct_id:n??void 0},disableGeoip:r},!0,{includeContextProperties:!1})}setPersonProperties({distinctId:e,properties:t={},propertiesOnce:r={}}){if(0===Object.keys(t).length&&0===Object.keys(r).length)return;let i={};Object.keys(t).length>0&&(i.$set=t),Object.keys(r).length>0&&(i.$set_once=r),this.capture({distinctId:e,event:"$set",properties:i})}unsetPersonProperties({distinctId:e,properties:t}){let r=(Array.isArray(t)?t:[t]).filter(e=>"string"==typeof e&&e.trim().length>0);0!==r.length&&this.capture({distinctId:e,event:"$set",properties:{$unset:r}})}alias(e){this._sendPreparedEvent("alias",{distinctId:e.distinctId,event:"$create_alias",properties:{distinct_id:e.distinctId,alias:e.alias},disableGeoip:e.disableGeoip},!1,{includeContextProperties:!1})}async aliasImmediate(e){await this._sendPreparedEvent("alias",{distinctId:e.distinctId,event:"$create_alias",properties:{distinct_id:e.distinctId,alias:e.alias},disableGeoip:e.disableGeoip},!0,{includeContextProperties:!1})}isLocalEvaluationReady(){return this.featureFlagsPoller?.isLocalEvaluationReady()??!1}getFeatureFlagEvaluationRuntime(e){return this.featureFlagsPoller?.getEvaluationRuntimeForFlag(e)}getFeatureFlagKeysByEvaluationRuntime(e){return this.featureFlagsPoller?.getFlagKeysByEvaluationRuntime(e)??[]}async waitForLocalEvaluationReady(e=3e4){return!!this.isLocalEvaluationReady()||void 0!==this.featureFlagsPoller&&new Promise(t=>{let r=setTimeout(()=>{i(),t(!1)},e),i=this._events.on("localEvaluationFlagsLoaded",e=>{clearTimeout(r),i(),t(e>0)})})}_resolveDistinctId(e,t){return"string"==typeof e?{distinctId:e,options:t}:{distinctId:this.context?.get()?.distinctId,options:e}}async _getFeatureFlagResult(e,t,r={},i){let s,n,a,o,l,u,c,h;if(this.disabled)return void this._logger.warn("The client is disabled");let d=r.sendFeatureFlagEvents??!0;if(void 0!==this._flagOverrides&&e in this._flagOverrides){let t=this._flagOverrides[e];if(void 0===t)return;let r=this._payloadOverrides?.[e];return{key:e,enabled:!1!==t,variant:"string"==typeof t?t:void 0,payload:r}}let{groups:p,disableGeoip:g}=r,{onlyEvaluateLocally:f,personProperties:m,groupProperties:y}=r,_=this.addLocalPersonAndGroupProperties(t,p,m,y);m=_.allPersonProperties,y=_.allGroupProperties;let v=this.createFeatureFlagEvaluationContext(t,p,this.personPropertiesForLocalEvaluation(t,m),y);void 0==f&&(f=this.options.strictLocalEvaluation??!1);let b=!1;if(void 0!==this.featureFlagsPoller){await this.featureFlagsPoller?.loadFeatureFlags();let t=this.featureFlagsPoller?.featureFlagsByKey[e];if(t)try{let r=await this.featureFlagsPoller?.computeFlagAndPayloadLocally(t,v,{matchValue:i});if(r){b=!0;let i=r.value;l=t.id,c="Evaluated locally",h=t.has_experiment,s={key:e,enabled:!1!==i,variant:"string"==typeof i?i:void 0,payload:r.payload??void 0,reason:c,reasonCode:!1===t.active?"flag_disabled":void 0}}}catch(t){if(t instanceof rJ||t instanceof rk)this._logger?.info(`${t.name} when computing flag locally: ${e}: ${t.message}`);else throw t}}if(!b&&!f){let t=await super.getFeatureFlagDetailsStateless(v.distinctId,v.groups,m,y,g,[e]);if(void 0===t)o=rI.UNKNOWN_ERROR;else{this._minimalFlagCalledEvents=!0===t.minimalFlagCalledEvents,n=t.requestId,a=t.evaluatedAt;let r=[];t.errorsWhileComputingFlags&&r.push(rI.ERRORS_WHILE_COMPUTING),t.quotaLimited?.includes("feature_flags")&&r.push(rI.QUOTA_LIMITED);let i=t.flags[e];if(void 0===i)r.push(rI.FLAG_MISSING);else{let t;if(l=i.metadata?.id,u=i.metadata?.version,c=i.reason?.description??i.reason?.code,h=i.metadata?.has_experiment,i.metadata?.payload!==void 0)try{t=JSON.parse(i.metadata.payload)}catch{t=i.metadata.payload}s={key:e,enabled:i.enabled,variant:i.variant??void 0,payload:t,reason:c,reasonCode:i.reason?.code}}r.length>0&&(o=r.join(","))}}if(d){let r=void 0===s?void 0:!1!==s.enabled&&(s.variant??!0),i={$feature_flag:e,$feature_flag_response:r,$feature_flag_id:l,$feature_flag_version:u,$feature_flag_reason:c,locally_evaluated:b,[`$feature/${e}`]:r,$feature_flag_request_id:n,$feature_flag_evaluated_at:b?Date.now():a};if(void 0!==h&&(i.$feature_flag_has_experiment=h),b&&this.featureFlagsPoller){let e=this.featureFlagsPoller.getFlagDefinitionsLoadedAt();void 0!==e&&(i.$feature_flag_definitions_loaded_at=e)}o&&(i.$feature_flag_error=o),this._captureFlagCalledEventIfNeeded({distinctId:t,key:e,response:r,groups:p,disableGeoip:g,properties:i})}return void 0!==s&&void 0!==this._payloadOverrides&&e in this._payloadOverrides&&(s={...s,payload:this._payloadOverrides[e]}),s}async getFeatureFlag(e,t,r){iv("getFeatureFlag","`getFeatureFlag` is deprecated and will be removed in a future major version. Use `posthog.evaluateFlags(distinctId, ...)` and call `flags.getFlag(key)` instead — this consolidates flag evaluation into a single `/flags` request per incoming request.");let i=await this._getFeatureFlagResult(e,t,{...r,sendFeatureFlagEvents:r?.sendFeatureFlagEvents??this.options.sendFeatureFlagEvent??!0});if(void 0!==i)return!1!==i.enabled&&(i.variant??!0)}async getFeatureFlagPayload(e,t,r,i){if(iv("getFeatureFlagPayload","`getFeatureFlagPayload` is deprecated and will be removed in a future major version. Use `posthog.evaluateFlags(distinctId, ...)` and call `flags.getFlagPayload(key)` instead — this consolidates flag evaluation into a single `/flags` request per incoming request."),void 0!==this._payloadOverrides&&e in this._payloadOverrides)return this._payloadOverrides[e];let s=await this._getFeatureFlagResult(e,t,{...i,sendFeatureFlagEvents:!1},r);if(void 0!==s)return s.payload??null}async getFeatureFlagResult(e,t,r){let{distinctId:i,options:s}=this._resolveDistinctId(t,r);return i?this._getFeatureFlagResult(e,i,{...s,sendFeatureFlagEvents:s?.sendFeatureFlagEvents??this.options.sendFeatureFlagEvent??!0}):void this._logger.warn("[PostHog] distinctId is required — pass it explicitly or use withContext()")}async getRemoteConfigPayload(e){if(this.disabled)return void this._logger.warn("The client is disabled");if(!this.options.personalApiKey)throw Error("Personal API key is required for remote config payload decryption");let t=await this._requestRemoteConfigPayload(e);if(!t)return;let r=await t.json();if("string"==typeof r)try{return JSON.parse(r)}catch(e){}return r}async isFeatureEnabled(e,t,r){iv("isFeatureEnabled","`isFeatureEnabled` is deprecated and will be removed in a future major version. Use `posthog.evaluateFlags(distinctId, ...)` and call `flags.isEnabled(key)` instead — this consolidates flag evaluation into a single `/flags` request per incoming request.");let i=await this._getFeatureFlagResult(e,t,{...r,sendFeatureFlagEvents:r?.sendFeatureFlagEvents??this.options.sendFeatureFlagEvent??!0});return void 0===i?void 0:!1!==i.enabled&&!!(i.variant??!0)}async getAllFlags(e,t){let{distinctId:r,options:i}=this._resolveDistinctId(e,t);return r?(await this.getAllFlagsAndPayloads(r,i)).featureFlags||{}:(this._logger.warn("[PostHog] distinctId is required to get feature flags — pass it explicitly or use withContext()"),{})}async getAllFlagsAndPayloads(e,t){let{distinctId:r,options:i}=this._resolveDistinctId(e,t);if(!r)return this._logger.warn("[PostHog] distinctId is required to get feature flags and payloads — pass it explicitly or use withContext()"),{featureFlags:{},featureFlagPayloads:{}};if(this.disabled)return this._logger.warn("The client is disabled"),{featureFlags:{},featureFlagPayloads:{}};let{groups:s,disableGeoip:n,flagKeys:a}=i||{},{onlyEvaluateLocally:o,personProperties:l,groupProperties:u}=i||{},c=this.addLocalPersonAndGroupProperties(r,s,l,u);l=c.allPersonProperties,u=c.allGroupProperties;let h=this.createFeatureFlagEvaluationContext(r,s,this.personPropertiesForLocalEvaluation(r,l),u);void 0==o&&(o=this.options.strictLocalEvaluation??!1);let d=await this.featureFlagsPoller?.getAllFlagsAndPayloads(h,a),p={},g={},f=!0;if(d&&(p=d.response,g=d.payloads,f=d.fallbackToFlags),f&&!o){let e=await super.getFeatureFlagsAndPayloadsStateless(h.distinctId,h.groups,l,u,n,a);p={...p,...e.flags||{}},g={...g,...e.payloads||{}}}return void 0!==this._flagOverrides&&(p={...p,...this._flagOverrides}),void 0!==this._payloadOverrides&&(g={...g,...this._payloadOverrides}),{featureFlags:p,featureFlagPayloads:g}}async evaluateFlags(e,t){let r,i,{distinctId:s,options:n}=this._resolveDistinctId(e,t);if(!s)return this._logger.warn("[PostHog] distinctId is required to evaluate feature flags — pass it explicitly or use withContext()"),new rA({host:this._getFeatureFlagEvaluationsHost(),distinctId:"",flags:{}});if(this.disabled)return this._logger.warn("The client is disabled"),new rA({host:this._getFeatureFlagEvaluationsHost(),distinctId:s,flags:{}});let{groups:a,disableGeoip:o}=n||{},l=n?.flagKeys??void 0;if(l?.length===0)return new rA({host:this._getFeatureFlagEvaluationsHost(),distinctId:s,groups:a,disableGeoip:o,flags:{}});let{onlyEvaluateLocally:u,personProperties:c,groupProperties:h}=n||{},d=this.addLocalPersonAndGroupProperties(s,a,c,h);c=d.allPersonProperties,h=d.allGroupProperties;let p=this.createFeatureFlagEvaluationContext(s,a,this.personPropertiesForLocalEvaluation(s,c),h);void 0==u&&(u=this.options.strictLocalEvaluation??!1);let g=l?new Set(l):void 0,f={},m=!1,y=!1,_=await this.featureFlagsPoller?.getAllFlagsAndPayloads(p,l),v=new Set;if(_)for(let[e,t]of Object.entries(_.response)){let r=this.featureFlagsPoller?.featureFlagsByKey[e];f[e]={key:e,enabled:!1!==t,variant:"string"==typeof t?t:void 0,payload:_.payloads[e],id:r?.id,version:void 0,reason:"Evaluated locally",locallyEvaluated:!0,hasExperiment:r?.has_experiment},v.add(e)}let b=void 0!==g&&Array.from(g).some(e=>this.featureFlagsPoller?.featureFlagsByKey[e]===void 0);if((!_||_.fallbackToFlags||b)&&!u){let e=await super.getFeatureFlagDetailsStateless(p.distinctId,p.groups,c,h,o,l);if(e)for(let[t,s]of(this._minimalFlagCalledEvents=!0===e.minimalFlagCalledEvents,r=e.requestId,i=e.evaluatedAt,m=!!e.errorsWhileComputingFlags,y=Array.isArray(e.quotaLimited)&&e.quotaLimited.includes("feature_flags"),Object.entries(e.flags))){let e;if(!v.has(t)){if(s.metadata?.payload!==void 0)try{e=JSON.parse(s.metadata.payload)}catch{e=s.metadata.payload}f[t]={key:t,enabled:s.enabled,variant:s.variant,payload:e,id:s.metadata?.id,version:s.metadata?.version,reason:s.reason?.description??s.reason?.code,locallyEvaluated:!1,hasExperiment:s.metadata?.has_experiment}}}}if(void 0!==this._flagOverrides)for(let[e,t]of Object.entries(this._flagOverrides)){if(void 0===t){delete f[e];continue}let r=f[e];f[e]={key:e,enabled:!1!==t,variant:"string"==typeof t?t:void 0,payload:r?.payload,id:r?.id,version:r?.version,reason:r?.reason,locallyEvaluated:r?.locallyEvaluated??!1,hasExperiment:r?.hasExperiment}}if(void 0!==this._payloadOverrides)for(let[e,t]of Object.entries(this._payloadOverrides)){let r=f[e];r&&(f[e]={...r,payload:t})}if(void 0!==g)for(let e of Object.keys(f))g.has(e)||delete f[e];return new rA({host:this._getFeatureFlagEvaluationsHost(),distinctId:s,groups:a,disableGeoip:o,flags:f,requestId:r,evaluatedAt:i,flagDefinitionsLoadedAt:this.featureFlagsPoller?.getFlagDefinitionsLoadedAt(),errorsWhileComputing:m,quotaLimited:y})}_shouldSendMinimalFlagCalledEvent(e,t){return"$feature_flag_called"===e&&this._minimalFlagCalledEvents&&!1===t.$feature_flag_has_experiment}_captureFlagCalledEventIfNeeded(e){let{distinctId:t,key:r,response:i,groups:s,disableGeoip:n,properties:a}=e,o=s&&Object.keys(s).length>0?`_${JSON.stringify(Object.entries(s).sort(([e],[t])=>e<t?-1:+(e>t)))}`:"",l=`${r}_${i}${o}`,u=this._distinctIdHasSentFlagCalls.get(t)??new Set;if(this._distinctIdHasSentFlagCalls.delete(t),this._distinctIdHasSentFlagCalls.set(t,u),!u.has(l)){for(u.add(l);this._distinctIdHasSentFlagCalls.size>Math.max(this.maxCacheSize,1);){let e=this._distinctIdHasSentFlagCalls.keys().next().value;if(void 0===e)break;this._distinctIdHasSentFlagCalls.delete(e)}this.capture({distinctId:t,event:"$feature_flag_called",properties:a,groups:s,disableGeoip:n})}}_getFeatureFlagEvaluationsHost(){return this._featureFlagEvaluationsHost||(this._featureFlagEvaluationsHost={captureFlagCalledEventIfNeeded:e=>this._captureFlagCalledEventIfNeeded(e),logWarning:e=>{!1!==this.options.featureFlagsLogWarnings&&console.warn(`[PostHog] ${e}`)}}),this._featureFlagEvaluationsHost}groupIdentify({groupType:e,groupKey:t,properties:r,distinctId:i,disableGeoip:s}){this._sendPreparedEvent("capture",{distinctId:i||`$${e}_${t}`,event:"$groupidentify",properties:{$group_type:e,$group_key:t,$group_set:r||{}},disableGeoip:s},!1,{includeContextProperties:!1})}async groupIdentifyImmediate({groupType:e,groupKey:t,properties:r,distinctId:i,disableGeoip:s}){await this._sendPreparedEvent("capture",{distinctId:i||`$${e}_${t}`,event:"$groupidentify",properties:{$group_type:e,$group_key:t,$group_set:r||{}},disableGeoip:s},!0,{includeContextProperties:!1})}async reloadFeatureFlags(){await this.featureFlagsPoller?.loadFeatureFlags(!0)}overrideFeatureFlags(e){let t=e=>Object.fromEntries(e.map(e=>[e,!0]));if(!1===e){this._flagOverrides=void 0,this._payloadOverrides=void 0;return}if(Array.isArray(e)){this._flagOverrides=t(e);return}if(this._isFeatureFlagOverrideOptions(e)){"flags"in e&&(!1===e.flags?this._flagOverrides=void 0:Array.isArray(e.flags)?this._flagOverrides=t(e.flags):void 0!==e.flags&&(this._flagOverrides={...e.flags})),"payloads"in e&&(!1===e.payloads?this._payloadOverrides=void 0:void 0!==e.payloads&&(this._payloadOverrides={...e.payloads}));return}this._flagOverrides={...e}}_isFeatureFlagOverrideOptions(e){if("object"!=typeof e||null===e||Array.isArray(e))return!1;if("flags"in e){let t=e.flags;if(!1===t||Array.isArray(t)||"object"==typeof t&&null!==t)return!0}if("payloads"in e){let t=e.payloads;if(!1===t||"object"==typeof t&&null!==t)return!0}return!1}withContext(e,t,r){return this.context?this.context.run(e,t,r):t()}getContext(){return this.context?.get()}enterContext(e,t){this.context?.enter(e,t)}async _shutdown(e){let t=Date.now()+(e??3e4),r=this._consumeWaitUntilCycle();await this.featureFlagsPoller?.stopPoller(e),this.errorTracking.shutdown(),this._metrics&&(await z(this._metrics.flush().catch(()=>{}),Math.max(0,t-Date.now())),this._metrics.reset()),this._traces&&(await z(this._traces.flush().catch(()=>{}),Math.max(0,t-Date.now())),this._traces.reset());try{return await super._shutdown(Math.max(0,t-Date.now()))}finally{this._distinctIdHasSentFlagCalls.clear(),r?.()}}async _requestRemoteConfigPayload(e){if(this.disabled||!this.apiKey||!this.options.personalApiKey)return;let t=`${this.host}/api/projects/@current/feature_flags/${e}/remote_config?token=${encodeURIComponent(this.apiKey)}`,r={method:"GET",headers:{...this.getCustomHeaders(),"Content-Type":"application/json",Authorization:`Bearer ${this.options.personalApiKey}`}},i=null;if(this.options.requestTimeout&&"number"==typeof this.options.requestTimeout){let e=new AbortController;i=U(()=>{e.abort()},this.options.requestTimeout),r.signal=e.signal}try{return await this.fetch(t,r)}catch(e){this._events.emit("error",e);return}finally{i&&clearTimeout(i)}}extractPropertiesFromEvent(e,t){if(!e)return{personProperties:{},groupProperties:{}};let r={},i={};for(let[s,n]of Object.entries(e))if(F(n,"Object")&&t&&s in t){let e={};for(let[t,r]of Object.entries(n))e[String(t)]=String(r);i[String(s)]=e}else r[String(s)]=String(n);return{personProperties:r,groupProperties:i}}async getFeatureFlagsForEvent(e,t,r,i){if(this.disabled||!this.apiKey)return void this._logger.warn("The client is disabled");let s=i?.personProperties||{},n=i?.groupProperties||{},a=i?.flagKeys;if(i?.onlyEvaluateLocally??this.options.strictLocalEvaluation)if(!((this.featureFlagsPoller?.featureFlags?.length||0)>0))return{};else{let i={};for(let[e,r]of Object.entries(t||{}))i[e]=String(r);return await this.getAllFlags(e,{groups:i,personProperties:s,groupProperties:n,disableGeoip:r,onlyEvaluateLocally:!0,flagKeys:a})}if((this.featureFlagsPoller?.featureFlags?.length||0)>0){let i={};for(let[e,r]of Object.entries(t||{}))i[e]=String(r);return await this.getAllFlags(e,{groups:i,personProperties:s,groupProperties:n,disableGeoip:r,onlyEvaluateLocally:!0,flagKeys:a})}return(await super.getFeatureFlagsStateless(e,t,s,n,r)).flags}addLocalPersonAndGroupProperties(e,t,r,i){let s={...r||{}},n={};if(t)for(let e of Object.keys(t))n[e]={$group_key:t[e],...i?.[e]||{}};return{allPersonProperties:s,allGroupProperties:n}}personPropertiesForLocalEvaluation(e,t){return{distinct_id:e,...t||{}}}createFeatureFlagEvaluationContext(e,t,r,i){return{distinctId:e,groups:t||{},personProperties:r||{},groupProperties:i||{},evaluationCache:{}}}captureException(e,t,r,i,s){if(!it.isPreviouslyCapturedError(e)){let n=Error("PostHog syntheticException");this.addPendingPromise(it.buildEventMessage(this.getErrorPropertiesBuilder(),e,{syntheticException:n},t,r).then(e=>this._capturePreparedEvent({...e,uuid:i,flags:s},!1)))}}async captureExceptionImmediate(e,t,r,i){if(!it.isPreviouslyCapturedError(e)){let s=Error("PostHog syntheticException");return this.addPendingPromise(it.buildEventMessage(this.getErrorPropertiesBuilder(),e,{syntheticException:s},t,r).then(e=>this.captureImmediate({...e,flags:i})))}}async prepareEventMessage(e){return this._prepareEventMessage(e)}async _prepareEventMessage(e,t={}){let{distinctId:r,event:i,properties:s,groups:n,flags:a,sendFeatureFlags:o,timestamp:l,disableGeoip:u,uuid:c}=e,h=this.context?.get(),d=t.includeContextProperties??!0,p=r||h?.distinctId,g=d?{...this.props,...h?.properties||{},...s||{}}:{...s||{}};p||(p=eG(),g.$process_person_profile=!1),d&&h?.sessionId&&!g.$session_id&&(g.$session_id=h.sessionId);let f=this._shouldSendMinimalFlagCalledEvent(i,g)?e4(g):g,m=this._runBeforeSend({distinctId:p,event:i,properties:f,groups:n,flags:a,sendFeatureFlags:o,timestamp:l,disableGeoip:u,uuid:c});if(!m)return Promise.reject(null);let y=await Promise.resolve().then(async()=>{if(a)return o&&console.warn("[PostHog] Both `flags` and `sendFeatureFlags` were passed to capture(); using `flags` and ignoring `sendFeatureFlags`."),a._getEventProperties();if(o){iv("sendFeatureFlags","`sendFeatureFlags` is deprecated and will be removed in a future major version. Pass a `flags` snapshot from `posthog.evaluateFlags(...)` instead — it avoids a second `/flags` request per capture and guarantees the event carries the exact flag values your code branched on.");var e=await this.getFeatureFlagsForEvent(m.distinctId,n,u,"object"==typeof o?o:void 0);if(!e)return{};let t={};for(let[r,i]of Object.entries(e))t[`$feature/${r}`]=i;let r=Object.keys(e).filter(t=>!1!==e[t]).sort();return r.length>0&&(t.$active_feature_flags=r),t}return{}}).catch(()=>({})).then(e=>{let t=m.groups||n;return{...e,...m.properties||{},...void 0!==t&&Object.keys(t).length>0?{$groups:t}:{}}});return"$pageview"===m.event&&this.options.__preview_capture_bot_pageviews&&"string"==typeof y.$raw_user_agent&&rE(y.$raw_user_agent,this.options.custom_blocked_useragents||[])&&(m.event="$bot_pageview",y.$browser_type="bot"),{distinctId:m.distinctId,event:m.event,properties:y,options:{timestamp:m.timestamp,disableGeoip:m.disableGeoip,uuid:m.uuid}}}_runBeforeSend(e){let t=this.options.before_send;if(!t)return e;let r=Array.isArray(t)?t:[t],i=e;for(let t of r)try{if(!(i=t(i)))return this._logger.info(`Event '${e.event}' was rejected in beforeSend function`),null;if(!i.properties||0===Object.keys(i.properties).length){let e=`Event '${i.event}' has no properties after beforeSend function, this is likely an error.`;this._logger.warn(e)}}catch(t){return this._logger.error(`Error in before_send function for event '${e.event}':`,t),null}return i}}var iw=e.i(78500);class ix{constructor(){this.storage=new iw.AsyncLocalStorage}get(){return this.storage.getStore()}run(e,t,r){return this.storage.run(this.resolve(e,r),t)}enter(e,t){this.storage.enterWith(this.resolve(e,t))}resolve(e,t){if(t?.fresh===!0)return e;let r=this.get()||{};return{distinctId:e.distinctId??r.distinctId,sessionId:e.sessionId??r.sessionId,properties:{...r.properties||{},...e.properties||{}}}}}class iS{active(){return this._storage.getStore()}with(e,t){return this._storage.run(e,t)}constructor(){this._storage=new iw.AsyncLocalStorage}}var iE=e.i(27028);let iF=(0,e.i(12057).promisify)(iE.gzip);async function iP(e,t=!0){try{let t=await iF(e);return new Uint8Array(t)}catch(e){return t&&console.error("Failed to gzip compress data",e),null}}var iI=e.i(60526),ie=ez;let iA="posthog-node";function iC(e,{organization:t,projectId:r,prefix:i,severityAllowList:s=["error"],sendExceptionsToPostHog:n=!0}={}){return a=>{if(!("*"===s||s.includes(a.level)))return a;a.tags||(a.tags={});let o=a.tags[i$.POSTHOG_ID_TAG];if(void 0===o)return a;let l=e.options.host??"https://us.i.posthog.com",u=new URL(`/project/${e.apiKey}/person/${o}`,l).toString();a.tags["PostHog Person URL"]=u;let c=a.exception?.values||[],h=c.map(e=>({...e,stacktrace:e.stacktrace?{...e.stacktrace,type:"raw",frames:(e.stacktrace.frames||[]).map(e=>({...e,platform:"node:javascript"}))}:void 0})),d={$exception_message:c[0]?.value||a.message,$exception_type:c[0]?.type,$exception_level:a.level,$exception_list:h,$sentry_event_id:a.event_id,$sentry_exception:a.exception,$sentry_exception_message:c[0]?.value||a.message,$sentry_exception_type:c[0]?.type,$sentry_tags:a.tags},p=ie.getInjectedReleaseId();return p&&(d.$release_id=p),t&&r&&(d.$sentry_url=(i||"https://sentry.io/organizations/")+t+"/issues/?project="+r+"&query="+a.event_id),n&&e.capture({event:"$exception",distinctId:o,properties:d}),a}}function ik(e,t){let r=iC(e,t);return{name:iA,processEvent:e=>r(e)}}class i${static{this.POSTHOG_ID_TAG="posthog_distinct_id"}constructor(e,t,r,i,s){this.name=iA,this.name=iA,this.setupOnce=function(n,a){n(iC(e,{organization:t,projectId:a()?.getClient()?.getDsn()?.projectId,prefix:r,severityAllowList:i,sendExceptionsToPostHog:s??!0}))}}}e.s(["PostHogSentryIntegration",0,i$,"createEventProcessor",0,iC,"sentryIntegration",0,ik],92164);let iO=/[\x00-\x1f\x7f-\x9f]/g;function iM(e,t,r){null!=r&&""!==r&&(e[t]=r)}function iT(e){return Array.isArray(e)?e[0]:e}function iR(e){if(Array.isArray(e)){for(let t of e){let e=iR(t);if(void 0!==e)return e}return}if("string"!=typeof e)return;let t=e.replace(iO,"").trim();if(t)return t.length>1e3?t.slice(0,1e3):t}function iD(e,t){var r,i;let s,{sessionId:n,distinctId:a}=function(e){if(!e)return{};let t=iR(e["x-posthog-session-id"]),r=iR(e["x-posthog-distinct-id"]);return{...void 0!==t?{sessionId:t}:{},...void 0!==r?{distinctId:r}:{}}}(t.headers),o={},l=!0===e.options.disable_capture_url_hashes;return iM(o,"$current_url",(r=t.originalUrl||t.url,l?L(r):r)),iM(o,"$request_method",t.method),iM(o,"$request_path",(i=t.path,s=function(e){if(!e)return e;let t=e.indexOf("?"),r=e.indexOf("#");return -1===t||-1!==r&&r<t?e:`${e.slice(0,t)}${-1===r?"":e.slice(r)}`}(i),l?L(s):s)),iM(o,"$user_agent",iT(t.headers["user-agent"])),iM(o,"$ip",function(e){let t=iT(e.headers["x-forwarded-for"]);if(t){let e=t.split(",")[0].trim();if(e)return e}return e.socket?.remoteAddress}(t)),{...void 0!==n?{sessionId:n}:{},...void 0!==a?{distinctId:a}:{},properties:o}}function ij(e,t){var r;t.use((r=e,(e,t,i)=>{r.withContext(iD(r,e),()=>i())}))}function iB(e,t){var r;t.use((r=e,(e,t,i,s)=>{if(it.isPreviouslyCapturedError(e))return void s(e);let n=iD(r,t),a=Error("Synthetic exception"),o={...void 0!==n.sessionId?{$session_id:n.sessionId}:{},...n.properties||{}};r.addPendingPromise(Promise.all([it.buildEventMessage(r.getErrorPropertiesBuilder(),e,{mechanism:{type:"middleware",handled:!1},syntheticException:a},n.distinctId,o),i.headersSent||i.destroyed?Promise.resolve(i.headersSent?i.statusCode:void 0):new Promise(e=>{let t=t=>{clearTimeout(s),i.removeListener("finish",r),i.removeListener("close",r),e(t)},r=()=>t(i.headersSent?i.statusCode:void 0),s=setTimeout(()=>t(void 0),1e3);s.unref(),i.once("finish",r),i.once("close",r)})]).then(([e,t])=>(void 0!==t&&(e.properties={...e.properties,$response_status_code:t}),r._capturePreparedEvent(e,!1)))),s(e)}))}e.s(["setupExpressErrorHandler",0,iB,"setupExpressRequestContext",0,ij],88512),e.i(92164),e.i(88512),e.i(88096),e.s(["FeatureFlagError",0,h,"FeatureFlagEvaluations",0,rA,"PostHogSentryIntegration",0,i$,"cookieStateToProperties",0,e0,"cookieStoreFromHeader",0,eJ,"createEventProcessor",0,iC,"getPostHogCookieName",0,eZ,"parsePostHogCookie",0,e1,"readPostHogCookie",0,eX,"sentryIntegration",0,ik,"serializePostHogCookie",0,eY,"setupExpressErrorHandler",0,iB,"setupExpressRequestContext",0,ij,"uuidv7",0,eG],92349),e.i(92349),e.s(["FeatureFlagError",0,h,"FeatureFlagEvaluations",0,rA,"PostHog",0,class extends ib{getLibraryId(){return"posthog-node"}compressPayload(e){return iP(e,this.isDebug)}initializeContext(){return new ix}initializeSpanContextManager(){return new iS}hostResourceAttributes(){return function(){var e,t;let r,i,s;try{r=(0,iI.platform)(),i=(0,iI.release)()}catch{}return e=r,t=i,{...(s=function(e){if(e)return Object.prototype.hasOwnProperty.call(tF,e)?tF[e]:e}(e))?{"os.name":s}:{},...t?{"os.version":t}:{}}}()}createErrorPropertiesBuilder(){let e;return new ez.ErrorPropertiesBuilder([new ez.EventCoercer,new ez.ErrorCoercer,new ez.ObjectCoercer,new ez.StringCoercer,new ez.PrimitiveCoercer],ez.createStackParser("node:javascript",ez.nodeStackLineParser),[(e=function(e=process.argv[1]?(0,l.dirname)(process.argv[1]):process.cwd(),t="\\"===l.sep){let r=t?u(e):e;return e=>{if(!e)return;let i=t?u(e):e,{dir:s,base:n,ext:a}=l.posix.parse(i);(".js"===a||".mjs"===a||".cjs"===a)&&(n=n.slice(0,-1*a.length));let o=decodeURIComponent(n);s||(s=".");let c=s.lastIndexOf("/node_modules");if(c>-1)return`${s.slice(c+14).replace(/\//g,".")}:${o}`;if(s.startsWith(r)){let e=s.slice(r.length+1).replace(/\//g,".");return e?`${e}:${o}`:o}return o}}(),async t=>{for(let r of t)r.module=e(r.filename);return t}),e=>rg(e,void 0,this._logger),function(e=process.cwd()){l.sep;let t=e=>e,r=t(e);return async e=>{for(let i of e)!(!i.filename||i.filename.startsWith("node:")||i.filename.startsWith("data:"))&&(0,l.isAbsolute)(i.filename)&&(i.filename=t((0,l.relative)(r,t(i.filename))));return e}}()])}},"PostHogSentryIntegration",0,i$,"cookieStateToProperties",0,e0,"cookieStoreFromHeader",0,eJ,"createEventProcessor",0,iC,"getPostHogCookieName",0,eZ,"parsePostHogCookie",0,e1,"readPostHogCookie",0,eX,"sentryIntegration",0,ik,"serializePostHogCookie",0,eY,"setupExpressErrorHandler",0,iB,"setupExpressRequestContext",0,ij,"uuidv7",0,eG],39702)}];
1
+ module.exports=[39702,e=>{"use strict";let t,r,i,s,n,a,o;var l,u=e.i(14747);function c(e){return e.replace(/^[A-Z]:/,"").replace(/\\/g,"/")}var h=((l={}).AnonymousId="anonymous_id",l.DistinctId="distinct_id",l.Props="props",l.EnablePersonProcessing="enable_person_processing",l.PersonMode="person_mode",l.FeatureFlagDetails="feature_flag_details",l.FeatureFlags="feature_flags",l.FeatureFlagPayloads="feature_flag_payloads",l.BootstrapFeatureFlagDetails="bootstrap_feature_flag_details",l.BootstrapFeatureFlags="bootstrap_feature_flags",l.BootstrapFeatureFlagPayloads="bootstrap_feature_flag_payloads",l.OverrideFeatureFlags="override_feature_flags",l.Queue="queue",l.AiQueue="ai_queue",l.AiCaptureQueue="ai_capture_queue",l.LogsQueue="logs_queue",l.OptedOut="opted_out",l.SessionId="session_id",l.SessionStartTimestamp="session_start_timestamp",l.SessionLastTimestamp="session_timestamp",l.PersonProperties="person_properties",l.GroupProperties="group_properties",l.InstalledAppBuild="installed_app_build",l.InstalledAppVersion="installed_app_version",l.SessionReplay="session_replay",l.PushRegistered="push_registered",l.SessionReplayEventTriggerActivatedSession="session_replay_event_trigger_activated_session",l.SurveyLastSeenDate="survey_last_seen_date",l.SurveysInProgress="surveys_in_progress",l.SurveysSeen="surveys_seen",l.Surveys="surveys",l.RemoteConfig="remote_config",l.FlagsEndpointWasHit="flags_endpoint_was_hit",l.DeviceId="device_id",l);let d={ERRORS_WHILE_COMPUTING:"errors_while_computing_flags",FLAG_MISSING:"flag_missing",LOCAL_EVALUATION_INCONCLUSIVE:"local_evaluation_inconclusive",QUOTA_LIMITED:"quota_limited",TIMEOUT:"timeout",CONNECTION_ERROR:"connection_error",UNKNOWN_ERROR:"unknown_error",apiError:e=>`api_error_${e}`};function f(e){let t=[];return JSON.stringify(e,function(e,r){if("bigint"==typeof r)return r.toString();if("function"!=typeof r&&"symbol"!=typeof r){if(r instanceof Error)return{name:r.name,message:r.message,stack:r.stack};if(r&&"object"==typeof r){for(;t.length>0&&t[t.length-1]!==this;)t.pop();if(t.includes(r))return"[Circular]";t.push(r)}return r}})??"null"}let p=Array.isArray,g=Object.prototype;g.hasOwnProperty;let m=g.toString,y=p||function(e){return"[object Array]"===m.call(e)},_=e=>e===Object(e)&&!y(e),v=e=>void 0===e,b=e=>"[object String]"==m.call(e),w=e=>b(e)&&0===e.trim().length,x=e=>null===e,E=e=>v(e)||x(e),S=e=>"[object Number]"==m.call(e)&&e==e;function F(e){return null===e||"object"!=typeof e}function P(e,t){return Object.prototype.toString.call(e)===`[object ${t}]`}function I(e){switch(Object.prototype.toString.call(e)){case"[object Error]":case"[object Exception]":case"[object DOMException]":case"[object DOMError]":case"[object WebAssembly.Exception]":return!0;default:return C(e,Error)}}function A(e){return"u">typeof Event&&C(e,Event)}function C(e,t){try{return e instanceof t}catch{return!1}}let k="Android",$="BlackBerry",O="Nintendo",M="PlayStation",T="Xbox",R="Windows",j="(\\d+(\\.\\d+)?)";RegExp("Version/"+j),RegExp("(Claude|Codex|ChatGPT)\\/"+j),RegExp(T,"i"),RegExp(M+" \\w+","i"),RegExp(O+" \\w+","i"),RegExp($+"|PlayBook|BB10","i");RegExp("rv:"+j),RegExp("Edge?\\/"+j),RegExp("(Chrome|CrMo)\\/"+j),RegExp("CriOS\\/"+j),RegExp("(UCBrowser|UCWEB)\\/"+j),RegExp("(Opera|OPR)\\/"+j),RegExp("Firefox\\/"+j),RegExp("FxiOS\\/"+j),RegExp("Konqueror[:/]?"+j,"i"),RegExp($+" "+j),RegExp("android\\s"+j,"i"),RegExp("SamsungBrowser\\/"+j),RegExp("OculusBrowser\\/"+j),RegExp("Vivaldi\\/"+j),RegExp("YaBrowser\\/"+j),RegExp("Whale\\/"+j),RegExp("Brave\\/"+j),RegExp("(DuckDuckGo|Ddg)\\/"+j),RegExp("PaleMoon\\/"+j),RegExp("Waterfox\\/"+j),RegExp("GSA\\/"+j),RegExp("(rv:|MSIE )"+j),RegExp("rv:"+j),RegExp(T+"; "+T+" (.*?)[);]","i"),RegExp(O,"i"),RegExp(M,"i"),RegExp(R,"i"),RegExp("("+k+" (\\d+)\\.(\\d+)\\.?(\\d+)?|"+k+")","i");let D=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;function B(e,t){return"string"==typeof e&&D.test(e)?e:t()}function L(e,t){let r=Error(t);try{Object.defineProperty(r,"name",{value:e,writable:!0,enumerable:!0,configurable:!0})}catch{}return r}function N(e){return e?e.split("#")[0]:e}async function q(e,t){let r=null;for(let i=0;i<t.retryCount+1;i++){i>0&&await new Promise(e=>setTimeout(e,t.retryDelay));try{return await e()}catch(e){if(r=e,!t.retryCheck(e))throw e}}throw r}function U(){return new Date().toISOString()}function V(e,t){let r=setTimeout(e,t);return r?.unref&&r?.unref(),r}async function z(e,t,r){let i;try{return await Promise.race([e,new Promise((e,s)=>{i=V(()=>{try{r?.(),e()}catch(e){s(e)}},t)})])}finally{clearTimeout(i)}}function H(e){return Promise.all(e.map(e=>(e??Promise.resolve()).then(e=>({status:"fulfilled",value:e}),e=>({status:"rejected",reason:e}))))}function W(e,t,r){return e&&r?t.length===Object.keys(r).length&&t.every(t=>e[t]===r[t]):e===r}class K{constructor(e,t,r=[]){this.coercers=e,this.stackParser=t,this.modifiers=r}buildFromUnknown(e,t={}){let r=t&&t.mechanism||{handled:!0,type:"generic"},i=this.buildCoercingContext(r,t,0).apply(e),s=this.buildParsingContext(t),n=this.parseStacktrace(i,s);return{$exception_list:this.convertToExceptionList(n,r),$exception_level:"error"}}async modifyFrames(e){for(let t of e)t.stacktrace&&t.stacktrace.frames&&y(t.stacktrace.frames)&&(t.stacktrace.frames=await this.applyModifiers(t.stacktrace.frames));return e}coerceFallback(e){return{type:"Error",value:"Unknown error",stack:e.syntheticException?.stack,synthetic:!0}}parseStacktrace(e,t){let r,i;if(null!=e.cause&&(r=this.parseStacktrace(e.cause,t)),""!=e.stack&&null!=e.stack)try{i=this.applyChunkIds(this.stackParser(e.stack,e.synthetic?t.skipFirstLines:0),t.chunkIdMap)}catch{}return{...e,cause:r,stack:i,errors:e.errors?.map(e=>this.parseStacktrace(e,t))}}applyChunkIds(e,t){return e.map(e=>(e.filename&&t&&(e.chunk_id=t[e.filename]),e))}applyCoercers(e,t){for(let r of this.coercers)if(r.match(e))return r.coerce(e,t);return this.coerceFallback(t)}async applyModifiers(e){let t=e;for(let e of this.modifiers)t=await e(t);return t}convertToExceptionList(e,t){let r=[],i=(e,s,n)=>{let a=r.length,o=void 0===s?{type:"string"==typeof t.type&&t.type.length>0?t.type:"generic",..."boolean"==typeof t.handled?{handled:t.handled}:void 0===t.handled?{handled:!0}:{},synthetic:"boolean"==typeof t.synthetic?t.synthetic:e.synthetic,exception_id:a}:{type:"chained",source:n,synthetic:e.synthetic,exception_id:a,parent_id:s},l={type:e.type,value:e.value,mechanism:o};for(let t of(e.stack&&(l.stacktrace={type:"raw",frames:e.stack}),r.push(l),e.cause&&i(e.cause,a,"cause"),e.errors??[]))i(t,a,"member")};return i(e),r}buildParsingContext(e){return{chunkIdMap:function(e){let n=globalThis._posthogChunkIds,a=globalThis._debugIds;if(!n&&!a)return;let o=n?Object.keys(n):[],l=a?Object.keys(a):[];if(s&&W(n,o,r)&&W(a,l,i))return s;r=n?{...n}:void 0,i=a?{...a}:void 0,s={},t??={};let u=(r,i)=>{for(let n of r){let r=i[n];if(!r)continue;let a=t?.[n];if(a){s[a]=r;continue}let o=e(n);for(let e=o.length-1;e>=0;e--){let i=o[e]?.filename;if(i){s[i]=r,t[n]=i;break}}}};return a&&u(l,a),n&&u(o,n),s}(this.stackParser),skipFirstLines:e.skipFirstLines??1}}getAggregateErrors(e){try{if(I(e)){let t=Object.getPrototypeOf(e);for(let r=0;t&&r<100;r++){let r=Object.getOwnPropertyDescriptor(t,"constructor")?.value;if("function"==typeof r&&"AggregateError"===r.name){let t=e.errors;return y(t)?t:void 0}t=Object.getPrototypeOf(t)}}}catch{}}buildCoercingContext(e,t,r=0){let i=0,s=0,n=!1,a=new Set,o=[],l={},u=(e,t,r=0)=>{let u,h,d=c(t,r),f=d.apply;if(d.apply=t=>{o.push(e);try{return f(t)}finally{o.pop()}},r>4||r>0&&-1!==o.indexOf(e))return this.coerceFallback(d);let p="object"==typeof e&&null!==e||"function"==typeof e;if(0===r&&i>=50||p&&a.has(e))return;p&&a.add(e),0===r&&i++;let g=this.getAggregateErrors(e);n||=!!g;try{if(!(u=this.applyCoercers(e,d)))throw l}catch(e){if(e===l){0===r&&i--;return}if(!n)throw e;u=this.coerceFallback(d)}if(!g||i>=50)return u;try{h=g.length}catch{return u}if(!Number.isInteger(h)||h<0||h>0xffffffff)return u;let m=[];for(let e=0;i<50&&s<1e3&&e<h;e++){let r;s++;try{r=d.next(g[e])}catch{i++,r=this.coerceFallback(c(t+1))}r&&m.push(r)}return{...u,errors:m}},c=(r,i=0)=>({...t,syntheticException:0==r?t.syntheticException:void 0,mechanism:0==r?e:{},apply:e=>{let t=u(e,r,i+1);if(!t)throw l;return t},next:e=>u(e,r+1)}),h=c(r);return{...h,apply:e=>u(e,r)??this.coerceFallback(h)}}}e.s(["ErrorPropertiesBuilder",0,K],69309);let G=/^([a-z][a-z0-9.+-]+):/i,Q=["http","https","file","blob","app","capacitor","ionic","webpack","webpack-internal","ng"];function J(e,t,r,i,s){let n={platform:e,filename:t,function:"<anonymous>"===r?"?":r,in_app:function(e){if(!e||"<anonymous>"===e)return!1;let t=G.exec(e);return!t||Q.includes(t[1].toLowerCase())}(t)};return v(i)||(n.lineno=i),v(s)||(n.colno=s),n}let Z=(e,t)=>{let r=-1!==e.indexOf("safari-extension"),i=-1!==e.indexOf("safari-web-extension");return r||i?[-1!==e.indexOf("@")?e.split("@")[0]:"?",r?`safari-extension:${t}`:`safari-web-extension:${t}`]:[e,t]},Y=/^\s*at (\S+?)(?::(\d+))(?::(\d+))\s*$/i,X=/^\s*at (?:(.+?\)(?: \[.+\])?|.*?) ?\((?:address at )?)?(?:async )?((?:<anonymous>|[-a-z]+:|.*bundle|\/)?.*?)(?::(\d+))?(?::(\d+))?\)?\s*$/i,ee=/\((\S*)(?::(\d+))(?::(\d+))\)/,et=(e,t)=>{let r=Y.exec(e);if(r){let[,e,i,s]=r;return J(t,e,"?",+i,+s)}let i=X.exec(e);if(i){if(i[2]&&0===i[2].indexOf("eval")){let e=ee.exec(i[2]);e&&(i[2]=e[1],i[3]=e[2],i[4]=e[3])}let[e,r]=Z(i[1]||"?",i[2]);return J(t,r,e,i[3]?+i[3]:void 0,i[4]?+i[4]:void 0)}},er=/^\s*(.*?)(?:\((.*?)\))?(?:^|@)?((?:[-a-z]+)?:\/.*?|\[native code\]|[^@]*(?:bundle|\d+\.js)|\/[\w\-. /=]+)(?::(\d+))?(?::(\d+))?\s*$/i,ei=/(\S+) line (\d+)(?: > eval line \d+)* > eval/i,es=(e,t)=>{let r=er.exec(e);if(r){if(r[3]&&r[3].indexOf(" > eval")>-1){let e=ei.exec(r[3]);e&&(r[1]=r[1]||"eval",r[3]=e[1],r[4]=e[2],r[5]="")}let e=r[3],i=r[1]||"?";return[i,e]=Z(i,e),J(t,e,i,r[4]?+r[4]:void 0,r[5]?+r[5]:void 0)}},en=/^\s*at (?:((?:\[object object\])?.+) )?\(?((?:[-a-z]+):.*?):(\d+)(?::(\d+))?\)?\s*$/i,ea=(e,t)=>{let r=en.exec(e);return r?J(t,r[2],r[1]||"?",+r[3],r[4]?+r[4]:void 0):void 0},eo=/ line (\d+).*script (?:in )?(\S+)(?:: in function (\S+))?$/i,el=(e,t)=>{let r=eo.exec(e);return r?J(t,r[2],r[3]||"?",+r[1]):void 0},eu=/ line (\d+), column (\d+)\s*(?:in (?:<anonymous function: ([^>]+)>|([^)]+))\(.*\))? in (.*):\s*$/i,ec=(e,t)=>{let r=eu.exec(e);return r?J(t,r[5],r[3]||r[4]||"?",+r[1],+r[2]):void 0},eh=/^\s*[-]{4,}$/,ed=/at (?:async )?(?:(.+?)\s+\()?(?:(.+):(\d+):(\d+)?|([^)]+))\)?/,ef=/^Promise\.(?:all|any)$/,ep=/^index \d+$/,eg=(e,t)=>{let r=e.match(ed);if(r){let e,i,s,n,a;if(r[1]){let t=(s=r[1]).lastIndexOf(".");if("."===s[t-1]&&t--,t>0){e=s.slice(0,t),i=s.slice(t+1);let r=e.indexOf(".Module");r>0&&(s=s.slice(r+1),e=e.slice(0,r))}n=void 0}i&&(n=e,a=i),"<anonymous>"===i&&(a=void 0,s=void 0),void 0===s&&(a=a||"?",s=n?`${n}.${a}`:a);let o=r[2]?.startsWith("file://")?r[2].slice(7):r[2],l="native"===r[5];return o?.match(/\/[A-Z]:/)&&(o=o.slice(1)),o||!r[5]||l||(o=r[5]),ef.test(s)&&ep.test(o||"")&&(o="node:internal/promise"),{filename:o?decodeURI(o):void 0,module:void 0,function:s,lineno:em(r[3]),colno:em(r[4]),in_app:function(e,t=!1){return!(t||e&&!e.startsWith("/")&&!e.match(/^[A-Z]:/)&&!e.startsWith(".")&&!e.match(/^[a-zA-Z]([a-zA-Z0-9.\-+])*:\/\//))&&void 0!==e&&!e.includes("node_modules/")}(o||"",l),platform:t}}if(e.match(eh))return{filename:e,platform:t}};function em(e){return parseInt(e||"",10)||void 0}let ey=/\(error: (.*)\)/;function e_(e,t){return e.filename===t.filename&&e.function===t.function&&e.module===t.module&&e.lineno===t.lineno&&e.colno===t.colno}function ev(e,t){let r=t.start;for(;r>0&&e_(e[r-1],e[r-1+t.length]);)r--;return t.start-r}function eb(e,t){let r=t.start+t.length,i=r;for(;i<e.length&&e_(e[i],e[i-t.length]);)i++;return i-r}function ew(e){if(!e.length)return[];let t=Array.from(e);return t.reverse(),t.slice(0,50).map(e=>{var r;return{...e,filename:e.filename||((r=t)[r.length-1]||{}).filename,function:e.function||"?"}})}function ex(){return eE("web:javascript",et,es)}function eE(e,...t){return(r,i=0)=>{let s=[],n=r.split("\n"),a=Math.min(n.length,i+1e3),o=[];for(let r=i;r<a;r++){let i=n[r];if(i.length>1024)continue;let a=ey.test(i)?i.replace(ey,"$1"):i;if(!a.match(/\S*Error: /)){for(let r of t){let t=r(a,e);if(t){s.push(t);let e=function(e){for(let t=1;t<=10;t++){let r=e.length-2*t;if(r<0)break;let i=!0;for(let s=0;s<t;s++)if(!e_(e[r+s],e[r+t+s])){i=!1;break}if(i){for(let i=0;i<t;i++)e[r+i]=e[r+t+i];return e.length=r+t,{start:r,length:t}}}}(s);if(e){for(let t=o.length-1;t>=0;t--){let r=o[t];if(r.start+r.length<=e.start)break;o.pop()}o.push(e)}break}}if(function(e,t){let r=t[0],i=e.length-(r?ev(e,r):0);for(let r of t)i-=eb(e,r);return i}(s,o)>=50)break}}let l=[...o].sort((e,t)=>t.start-e.start),u=l[l.length-1];if(u){let e=ev(s,u);for(let t of(s.splice(u.start-e,e),l))t.start-=e}for(let e of l)!function(e,t){let r=t.start+t.length,i=eb(e,t);i&&e.splice(r+i===e.length?r:t.start,i)}(s,e);return o.some(e=>0===e.start&&s.length===e.length)&&function(e){let t=e.map(e=>`${e.function}|${e.filename}|${e.lineno}|${e.colno}|${e.module}`),r=0;for(let e=1;e<t.length;e++)(function(e,t,r){for(let i=0;i<e.length;i++){let s=e[(t+i)%e.length],n=e[(r+i)%e.length];if(s!==n)return s<n}return!1})(t,e,r)&&(r=e);e.push(...e.splice(0,r))}(s),ew(s)}}class eS{match(e){return this.isDOMException(e)||this.isDOMError(e)}coerce(e,t){let r=b(e.stack);return{type:this.getType(e),value:this.getValue(e),stack:r?e.stack:void 0,cause:e.cause?t.next(e.cause):void 0,synthetic:!1}}getType(e){return this.isDOMError(e)?"DOMError":"DOMException"}getValue(e){let t=e.name||(this.isDOMError(e)?"DOMError":"DOMException");return e.message?`${t}: ${e.message}`:t}isDOMException(e){return P(e,"DOMException")}isDOMError(e){return P(e,"DOMError")}}e.s(["DOMExceptionCoercer",0,eS],33603);class eF{match(e){return!!P(e,"ErrorEvent")&&(void 0!=e.error||this._hasUsableMessage(e))}coerce(e,t){if(void 0!=e.error)return t.apply(e.error);let r=t.apply(e.message);return{...r,stack:this._buildLocationStack(e)??r.stack,synthetic:!0}}_hasUsableMessage(e){return b(e.message)&&e.message.length>0}_buildLocationStack(e){let t=e.lineno??0,r=e.colno??0;if(b(e.filename)&&0!==e.filename.length&&0!==t)return`Error
2
+ at ${e.filename}:${t}:${r}`}}e.s(["ErrorEventCoercer",0,eF],60887);let eP=["fatal","error","warning","log","info","debug"];function eI(e,t=40){let r=Object.keys(e);if(r.sort(),!r.length)return"[object has no keys]";for(let e=r.length;e>0;e--){let i=r.slice(0,e).join(", ");if(!(i.length>t)){if(e===r.length)return i;return i.length<=t?i:`${i.slice(0,t)}...`}}return""}class eA{match(e){return"object"==typeof e&&null!==e}coerce(e,t){let r=this.getErrorPropertyFromObject(e);return r?t.apply(r):{type:this.getType(e),value:this.getValue(e),stack:this.getStack(e)??t.syntheticException?.stack,level:this.isSeverityLevel(e.level)?e.level:"error",synthetic:!0}}getType(e){if(A(e))return e.constructor.name;let t="name"in e?e.name:void 0;return b(t)&&!w(t)?t:"Error"}getValue(e){if("name"in e&&"string"==typeof e.name){let t=`'${e.name}' captured as exception`;return"message"in e&&"string"==typeof e.message&&(t+=` with message: '${e.message}'`),t}if("message"in e&&"string"==typeof e.message)return e.message;let t=this.getObjectClassName(e),r=eI(e);return`${t&&"Object"!==t?`'${t}'`:"Object"} captured as exception with keys: ${r}`}isSeverityLevel(e){return b(e)&&!w(e)&&eP.indexOf(e)>=0}getStack(e){try{if(b(e.stacktrace)&&e.stacktrace.length>0)return e.stacktrace;return b(e.stack)&&e.stack.length>0?e.stack:void 0}catch{return}}getErrorPropertyFromObject(e){for(let t in e)if(Object.prototype.hasOwnProperty.call(e,t)){let r=e[t];if(I(r))return r}}getObjectClassName(e){try{let t=Object.getPrototypeOf(e);return t?t.constructor.name:void 0}catch(e){return}}}e.s(["ObjectCoercer",0,eA],12154);class eC{match(e){return A(e)}coerce(e,t){let r=e.constructor.name;return{type:r,value:`${r} captured as exception with keys: ${eI(e)}`,stack:t.syntheticException?.stack,synthetic:!0}}}e.s(["EventCoercer",0,eC],41324);class ek{match(e){return F(e)}coerce(e,t){return{type:"Error",value:`Primitive value captured as exception: ${String(e)}`,stack:t.syntheticException?.stack,synthetic:!0}}}e.s(["PrimitiveCoercer",0,ek],79478);class e${match(e){return P(e,"PromiseRejectionEvent")||this.isCustomEventWrappingRejection(e)}isCustomEventWrappingRejection(e){if(!A(e))return!1;try{let t=e.detail;return null!=t&&"object"==typeof t&&"reason"in t}catch{return!1}}coerce(e,t){let r=this.getUnhandledRejectionReason(e);return F(r)?{type:"UnhandledRejection",value:`Non-Error promise rejection captured with value: ${String(r)}`,stack:t.syntheticException?.stack,synthetic:!0}:t.apply(r)}getUnhandledRejectionReason(e){try{if("reason"in e)return e.reason;if("detail"in e&&null!=e.detail&&"object"==typeof e.detail&&"reason"in e.detail)return e.detail.reason}catch{}return e}}e.s(["PromiseRejectionEventCoercer",0,e$],1802);let eO={MESSAGE:"$message",TIMESTAMP:"$timestamp"},eM=new Set([eO.MESSAGE,eO.TIMESTAMP]),eT={enabled:!0,max_bytes:32768};function eR(e){return e?{enabled:e.enabled??eT.enabled,max_bytes:function(e,t){if(!S(e)||1/0===e||-1/0===e)return t;let r=Math.floor(e);return r<0?t:r}(e.max_bytes,eT.max_bytes)}:{...eT}}function ej(e){if(!e)return{sanitizedProperties:{},droppedKeys:[]};let t=[];return{sanitizedProperties:Object.keys(e).reduce((r,i)=>(eM.has(i)?t.push(i):r[i]=e[i],r),{}),droppedKeys:t}}class eD{constructor(e){this._entries=[],this._totalBytes=0,this._config=eR(e)}setConfig(e){this._config=eR(e),this._trimToMaxBytes()}add(e){let t=function(e){let t;try{t=f(e)}catch{return}try{let e=JSON.parse(t);if(!_(e))return;let r=e[eO.MESSAGE],i=e[eO.TIMESTAMP];if(!b(r)||0===r.trim().length||!b(i)&&!S(i))return;return{step:e,json:t}}catch{return}}(e);if(!t)return;let r=eB(t.json);r>this._config.max_bytes||(this._entries.push({step:t.step,bytes:r}),this._totalBytes+=r,this._trimToMaxBytes())}getAttachable(){return this._entries.map(e=>e.step)}clear(){this._entries=[],this._totalBytes=0}size(){return this._entries.length}_trimToMaxBytes(){for(;this._totalBytes>this._config.max_bytes&&this._entries.length>0;){let e=this._entries.shift();e&&(this._totalBytes-=e.bytes)}}}function eB(e){if("u">typeof TextEncoder)return new TextEncoder().encode(e).length;let t=encodeURIComponent(e),r=0;for(let e=0;e<t.length;e++)"%"===t[e]?(r+=1,e+=2):r+=1;return r}e.s(["DEFAULT_EXCEPTION_STEPS_CONFIG",0,eT,"EXCEPTION_STEP_INTERNAL_FIELDS",0,eO,"ExceptionStepsBuffer",0,eD,"getUtf8ByteLength",0,eB,"resolveExceptionStepsConfig",0,eR,"stripReservedExceptionStepFields",0,ej],45162),e.i(69309),e.s(["chromeStackLineParser",0,et,"createDefaultStackParser",0,ex,"createStackParser",0,eE,"geckoStackLineParser",0,es,"nodeStackLineParser",0,eg,"opera10StackLineParser",0,el,"opera11StackLineParser",0,ec,"reverseAndStripFrames",0,ew,"winjsStackLineParser",0,ea],22546),e.i(22546),e.i(33603);class eL{match(e){return I(e)}coerce(e,t){let r=this.getStack(e),i=void 0===r?t.syntheticException?.stack:void 0;return{type:this.getType(e),value:this.getMessage(e,t),stack:r??i,cause:e.cause?t.next(e.cause):void 0,synthetic:!!i}}getType(e){return e.name||e.constructor.name}getMessage(e,t){let r=e.message;return r.error&&"string"==typeof r.error.message?String(r.error.message):String(r)}getStack(e){try{let t=e.stacktrace;if("string"==typeof t&&t.length>0)return t;let r=e.stack;return"string"==typeof r&&r.length>0?r:void 0}catch{return}}}e.s(["ErrorCoercer",0,eL],13446),e.i(13446),e.i(60887);let eN=/^(?:[Uu]ncaught (?:exception: )?)?(?:((?:Eval|Internal|Range|Reference|Syntax|Type|URI|)Error): )?(.*)$/i;class eq{match(e){return"string"==typeof e}coerce(e,t){let[r,i]=this.getInfos(e);return{type:r??"Error",value:i??e,stack:t.syntheticException?.stack,synthetic:!0}}getInfos(e){let t="Error",r=e,i=e.match(eN);return i&&(t=i[1],r=i[2]),[t,r]}}e.s(["StringCoercer",0,eq],22175),e.i(22175),e.i(12154),e.i(41324),e.i(79478),e.i(1802),e.s(["DOMExceptionCoercer",0,eS,"ErrorCoercer",0,eL,"ErrorEventCoercer",0,eF,"EventCoercer",0,eC,"ObjectCoercer",0,eA,"PrimitiveCoercer",0,ek,"PromiseRejectionEventCoercer",0,e$,"StringCoercer",0,eq],90166),e.i(90166);class eU{constructor(e){this._maxSize=e,this._cache=new Map}get(e){let t=this._cache.get(e);if(void 0!==t)return this._cache.delete(e),this._cache.set(e,t),t}set(e,t){this._cache.set(e,t)}reduce(){for(;this._cache.size>=this._maxSize;){let e=this._cache.keys().next().value;e&&this._cache.delete(e)}}}function eV(){if("u">typeof process){let e=process.env.POSTHOG_RELEASE_ID?.trim();if(e)return e}let e=globalThis._posthogReleaseId;return"string"==typeof e&&e.length>0?e:void 0}e.s(["ReduceableCache",0,eU],45294),e.i(45294),e.i(45162),e.s(["getInjectedReleaseId",0,eV],56168),e.i(56168),e.s(["DEFAULT_EXCEPTION_STEPS_CONFIG",0,eT,"DOMExceptionCoercer",0,eS,"EXCEPTION_STEP_INTERNAL_FIELDS",0,eO,"ErrorCoercer",0,eL,"ErrorEventCoercer",0,eF,"ErrorPropertiesBuilder",0,K,"EventCoercer",0,eC,"ExceptionStepsBuffer",0,eD,"ObjectCoercer",0,eA,"PrimitiveCoercer",0,ek,"PromiseRejectionEventCoercer",0,e$,"ReduceableCache",0,eU,"StringCoercer",0,eq,"chromeStackLineParser",0,et,"createDefaultStackParser",0,ex,"createStackParser",0,eE,"geckoStackLineParser",0,es,"getInjectedReleaseId",0,eV,"getUtf8ByteLength",0,eB,"nodeStackLineParser",0,eg,"opera10StackLineParser",0,el,"opera11StackLineParser",0,ec,"resolveExceptionStepsConfig",0,eR,"reverseAndStripFrames",0,ew,"stripReservedExceptionStepFields",0,ej,"winjsStackLineParser",0,ea],11168);var ez=e.i(11168);let eH="0123456789abcdef";class eW{constructor(e){this.bytes=e}static ofInner(e){if(16===e.length)return new eW(e);throw TypeError("not 128-bit length")}static fromFieldsV7(e,t,r,i){if(!Number.isInteger(e)||!Number.isInteger(t)||!Number.isInteger(r)||!Number.isInteger(i)||e<0||t<0||r<0||i<0||e>0xffffffffffff||t>4095||r>0x3fffffff||i>0xffffffff)throw RangeError("invalid field value");let s=new Uint8Array(16);return s[0]=e/0x10000000000,s[1]=e/0x100000000,s[2]=e/0x1000000,s[3]=e/65536,s[4]=e/256,s[5]=e,s[6]=112|t>>>8,s[7]=t,s[8]=128|r>>>24,s[9]=r>>>16,s[10]=r>>>8,s[11]=r,s[12]=i>>>24,s[13]=i>>>16,s[14]=i>>>8,s[15]=i,new eW(s)}static parse(e){let t;switch(e.length){case 32:t=/^[0-9a-f]{32}$/i.exec(e)?.[0];break;case 36:t=/^([0-9a-f]{8})-([0-9a-f]{4})-([0-9a-f]{4})-([0-9a-f]{4})-([0-9a-f]{12})$/i.exec(e)?.slice(1,6).join("");break;case 38:t=/^\{([0-9a-f]{8})-([0-9a-f]{4})-([0-9a-f]{4})-([0-9a-f]{4})-([0-9a-f]{12})\}$/i.exec(e)?.slice(1,6).join("");break;case 45:t=/^urn:uuid:([0-9a-f]{8})-([0-9a-f]{4})-([0-9a-f]{4})-([0-9a-f]{4})-([0-9a-f]{12})$/i.exec(e)?.slice(1,6).join("")}if(t){let e=new Uint8Array(16);for(let r=0;r<16;r+=4){let i=parseInt(t.substring(2*r,2*r+8),16);e[r+0]=i>>>24,e[r+1]=i>>>16,e[r+2]=i>>>8,e[r+3]=i}return new eW(e)}throw SyntaxError("could not parse UUID string")}toString(){let e="";for(let t=0;t<this.bytes.length;t++)e+=eH.charAt(this.bytes[t]>>>4),e+=eH.charAt(15&this.bytes[t]),(3===t||5===t||7===t||9===t)&&(e+="-");return e}toHex(){let e="";for(let t=0;t<this.bytes.length;t++)e+=eH.charAt(this.bytes[t]>>>4),e+=eH.charAt(15&this.bytes[t]);return e}toJSON(){return this.toString()}getVariant(){let e=this.bytes[8]>>>4;if(e<0)throw Error("unreachable");if(e<=7)return this.bytes.every(e=>0===e)?"NIL":"VAR_0";if(e<=11)return"VAR_10";if(e<=13)return"VAR_110";if(e<=15)return this.bytes.every(e=>255===e)?"MAX":"VAR_RESERVED";throw Error("unreachable")}getVersion(){return"VAR_10"===this.getVariant()?this.bytes[6]>>>4:void 0}clone(){return new eW(this.bytes.slice(0))}equals(e){return 0===this.compareTo(e)}compareTo(e){for(let t=0;t<16;t++){let r=this.bytes[t]-e.bytes[t];if(0!==r)return Math.sign(r)}return 0}}class eK{constructor(e){this.timestamp=0,this.counter=0,this.random=e??eG()}generate(){return this.generateOrResetCore(Date.now(),1e4)}generateOrAbort(){return this.generateOrAbortCore(Date.now(),1e4)}generateOrResetCore(e,t){let r=this.generateOrAbortCore(e,t);return void 0===r&&(this.timestamp=0,r=this.generateOrAbortCore(e,t)),r}generateOrAbortCore(e,t){if(!Number.isInteger(e)||e<1||e>0xffffffffffff)throw RangeError("`unixTsMs` must be a 48-bit positive integer");if(t<0||t>0xffffffffffff)throw RangeError("`rollbackAllowance` out of reasonable range");if(e>this.timestamp)this.timestamp=e,this.resetCounter();else{if(!(e+t>=this.timestamp))return;this.counter++,this.counter>0x3ffffffffff&&(this.timestamp++,this.resetCounter())}return eW.fromFieldsV7(this.timestamp,Math.trunc(this.counter/0x40000000),0x3fffffff&this.counter,this.random.nextUint32())}resetCounter(){this.counter=1024*this.random.nextUint32()+(1023&this.random.nextUint32())}generateV4(){let e=new Uint8Array(Uint32Array.of(this.random.nextUint32(),this.random.nextUint32(),this.random.nextUint32(),this.random.nextUint32()).buffer);return e[6]=64|e[6]>>>4,e[8]=128|e[8]>>>2,eW.ofInner(e)}}let eG=()=>({nextUint32:()=>65536*Math.trunc(65536*Math.random())+Math.trunc(65536*Math.random())>>>0}),eQ=()=>eJ().toString(),eJ=()=>(n||(n=new eK)).generate();function eZ(e){let t={};if(e)for(let r of e.split(";")){let[e,...i]=r.trim().split("=");if(e){let r=i.join("=").trim();try{t[e.trim()]=decodeURIComponent(r)}catch{t[e.trim()]=r}}}return{get:e=>e in t?{value:t[e]}:void 0}}function eY(e){let t=e.replace(/\+/g,"PL").replace(/\//g,"SL").replace(/=/g,"EQ");return`ph_${t}_posthog`}function eX(e){let t=Date.now();return JSON.stringify({distinct_id:e,$device_id:e,$user_state:"anonymous",$sesid:[t,eQ(),t]})}function e0(e,t){let r=eY(t),i=e.get(r);return i?e2(i.value):null}function e1(e){if(!e)return;let t={};return e.sessionId&&(t.$session_id=e.sessionId),e.deviceId&&(t.$device_id=e.deviceId),Object.keys(t).length>0?t:void 0}function e2(e){if(!e)return null;try{let t=JSON.parse(e);if(!t||"object"!=typeof t||!t.distinct_id)return null;let r=y(t.$sesid)?t.$sesid[1]:void 0;return{distinctId:String(t.distinct_id),isIdentified:"identified"===t.$user_state,sessionId:"string"==typeof r?r:void 0,deviceId:"string"==typeof t.$device_id?t.$device_id:void 0}}catch{return null}}let e3=e=>void 0===e?void 0:e.variant??e.enabled,e5=e=>{if("string"!=typeof e)return e;try{return JSON.parse(e)}catch{return e}},e4=["$feature_flag","$feature_flag_response","$feature_flag_has_experiment","$feature_flag_id","$feature_flag_version","$feature_flag_reason","$feature_flag_request_id","$feature_flag_evaluated_at","$feature_flag_error","locally_evaluated","$groups","$process_person_profile","$geoip_disable","$current_url","$pathname","$referring_domain","utm_source","utm_medium","utm_campaign","utm_content","utm_term","gad_source","mc_cid","gclid","gclsrc","dclid","gbraid","wbraid","fbclid","msclkid","twclid","li_fat_id","igshid","ttclid","rdt_cid","epik","qclid","sccid","oppref","bfcid","irclid","_kx","$session_id","$window_id","$lib","$lib_version","$device_id","$is_server"],e6=(e,t=[])=>{let r={},i=t=>{void 0!==e[t]&&(r[t]=e[t])};return e4.forEach(i),t.forEach(i),r};class e8{constructor(){this.events={},this.events={}}on(e,t){return this.events[e]||(this.events[e]=[]),this.events[e].push(t),()=>{this.events[e]=this.events[e].filter(e=>e!==t)}}emit(e,t){for(let r of this.events[e]||[])r(t);for(let r of this.events["*"]||[])r(e,t)}}let e9=e=>{throw L("NativeGzipValidationError",`Native gzip produced invalid output: ${e}`)},e7=async(e,t)=>{e.size<18&&e9("too-short");let r=new Uint8Array(await e.slice(0,10).arrayBuffer());r.length>=2&&31===r[0]&&139===r[1]&&8===r[2]||e9("invalid-header");let i=new DataView(await e.slice(e.size-8).arrayBuffer());i.getUint32(0,!0)!==(e=>{let t=(()=>{if(a)return a;a=[];for(let e=0;e<256;e++){let t=e;for(let e=0;e<8;e++)t=1&t?0xedb88320^t>>>1:t>>>1;a[e]=t>>>0}return a})(),r=0xffffffff;for(let i=0;i<e.length;i++)r=t[(r^e[i])&255]^r>>>8;return(0xffffffff^r)>>>0})(t)&&e9("invalid-crc");let s=t.length>>>0;i.getUint32(4,!0)!==s&&e9("invalid-size")};async function te(e,t=!0,r){try{let t=new TextEncoder().encode(e),r=new globalThis.CompressionStream("gzip"),i=r.writable.getWriter(),s=i.write(t).then(()=>i.close()).catch(async e=>{try{await i.abort(e)}catch{}throw e}),n=new Response(r.readable).blob(),[a]=await Promise.all([n,s]);return await e7(a,t),a}catch(e){if(r?.rethrow)throw e;return t&&console.error("Failed to gzip compress data",e),null}}class tt{add(e){let t=eQ(),r=++this.nextId;return this.promiseByIds[t]={id:r,promise:e},e.catch(()=>{}).finally(()=>{delete this.promiseByIds[t]}),e}async join(){let e=Object.values(this.promiseByIds).map(e=>e.promise),t=e.length;for(;t>0;)await Promise.all(e),t=(e=Object.values(this.promiseByIds).map(e=>e.promise)).length}getPromises(e=[],t=this.nextId){let r=new Set(e);return Object.values(this.promiseByIds).filter(e=>e.id<=t&&!r.has(e.promise)).map(e=>e.promise)}get maxId(){return this.nextId}get length(){return Object.keys(this.promiseByIds).length}constructor(){this.promiseByIds={},this.nextId=0}}let tr=(e,t,r)=>{function i(s,...n){t(()=>{(0,r[s])(e,...n)})}return{debug:(...e)=>{i("debug",...e)},info:(...e)=>{i("log",...e)},warn:(...e)=>{i("warn",...e)},error:(...e)=>{i("error",...e)},critical:(...t)=>{r.error(e,...t)},createLogger:i=>tr(`${e} ${i}`,t,r)}};class ti{record(e){if("too-large"===e.kind)return;if("retry-later"!==e.kind)return void this.reset();if(!e.retryAfterMs)return;let t=this.isOpen(),r=Date.now(),i=Math.min(e.retryAfterMs,3e5);if(!t){this._installedAt=r,this._until=r+i;return}this._until=Math.max(this._until,Math.min(r+i,this._installedAt+3e5))}remainingMs(){let e=Date.now();if(e<this._installedAt-5e3)return this.reset(),0;let t=Math.min(3e5,Math.max(0,this._until-e));return 0===t&&this.reset(),t}isOpen(){return this.remainingMs()>0}reset(){this._until=0,this._installedAt=0}constructor(){this._until=0,this._installedAt=0}}class ts extends Error{constructor(e,t,r,i){super("HTTP error while fetching PostHog: status="+e.status+", reqByteLength="+t),this.response=e,this.reqByteLength=t,this.responseBodyDeadline=r,this.abortController=i,this.name="PostHogFetchHttpError",this._bodyReadTimedOut=!1}get status(){return this.response.status}get retryAfterMs(){try{return function(e,t=Date.now()){if("string"!=typeof e||!e)return;let r=e.trim(),i=/^\d+\s*,/.test(r)?r.slice(0,r.indexOf(",")).trim():r;if(/^\d+$/.test(i)){let e=1e3*Math.min(Number(i),300);return e>0?e:void 0}if(!/^(Mon|Tue|Wed|Thu|Fri|Sat|Sun)[a-z]*[ ,]/.test(i))return;let s=Date.parse(/^\w{3} \w{3} /.test(i)?i+" GMT":i)-t;if(Number.isFinite(s)&&!(s<=0))return Math.min(s,3e5)}(this.response.headers?.get("retry-after"))}catch{return}}get bodyReadTimedOut(){return this._bodyReadTimedOut}get text(){if(!this.responseBodyTextPromise)if(Date.now()>=this.responseBodyDeadline){this._bodyReadTimedOut=!0;let e=L("AbortError","Response body read timed out");this.cancelResponseBody(e),this.responseBodyTextPromise=Promise.reject(e)}else{let e,t=new Promise((e,t)=>{this.responseBodyTimer=V(()=>{this._bodyReadTimedOut=!0;let e=L("AbortError","Response body read timed out");t(e),this.cancelResponseBody(e)},this.responseBodyDeadline-Date.now())});try{e=Promise.resolve(this.response.text())}catch(t){e=Promise.reject(t)}this.responseBodyTextPromise=Promise.race([e,t]).finally(()=>clearTimeout(this.responseBodyTimer))}return this.responseBodyTextPromise}get json(){return this.text.then(e=>JSON.parse(e))}cancelResponseBody(e){clearTimeout(this.responseBodyTimer),this.abortController.signal.aborted||this.abortController.abort(e),(async()=>{try{await this.response.body?.cancel()}catch{}})()}}class tn extends Error{constructor(e){super("Network error while fetching PostHog",e instanceof Error?{cause:e}:{}),this.error=e,this.name="PostHogFetchNetworkError"}}async function ta(e){if(e instanceof ts){let t="";try{t=await e.text}catch{e.bodyReadTimedOut&&(t="<response body read timed out>")}console.error(`Error while flushing PostHog: message=${e.message}, response body=${t}`,e)}else console.error("Error while flushing PostHog",e);return Promise.resolve()}function to(e){return e instanceof tn}function tl(e){if(e instanceof ts)return 502===e.status||504===e.status;if(!(e instanceof tn))return!1;let t=e.error;return"ECONNREFUSED"!==(t?.code??t?.cause?.code)}function tu(e){try{if("string"!=typeof e)return e instanceof Uint8Array?e.byteLength:e.size;if("u">typeof Buffer)return Buffer.byteLength(e,"utf8");return new TextEncoder().encode(e).length}catch{return 0}}function tc(e){return"object"==typeof e&&e instanceof ts&&413===e.status}function th(e){return e instanceof ts?408===e.status||429===e.status||e.status>=500:to(e)}function td(e){return null!==e&&"object"==typeof e&&!Array.isArray(e)}let tf="default";class tp{getErrorPropertiesBuilder(){return this._errorPropertiesBuilder||(this._errorPropertiesBuilder=this.createErrorPropertiesBuilder()),this._errorPropertiesBuilder}createErrorPropertiesBuilder(){return new K([new eL,new eA,new eq,new ek],ex())}getEvaluationRuntime(){}get apiKey(){return this.projectToken}constructor(e,t={}){var r;this.flushPromise=null,this.pendingFlushPromise=null,this.flushPromises=new Set,this._dequeuedMessagesCount=0,this.shutdownPromise=null,this.promiseQueue=new tt,this._events=new e8,this._isInitialized=!1;let i="string"==typeof e?e.trim():"",s="string"==typeof t.host?t.host.trim():"",n=!i;this._logger=function(e,t=e=>e()){return tr(e,t,function(e=console){return{log:e.log.bind(e),warn:e.warn.bind(e),error:e.error.bind(e),debug:e.debug.bind(e)}}())}("[PostHog]",this.logMsgIfDebug.bind(this)),n&&this._logger.error("You must pass your PostHog project token. The client will be disabled."),this.projectToken=i,this.host=(r=s||"https://us.i.posthog.com",r?.replace(/\/+$/,"")),this.flushAt=t.flushAt?Math.max(t.flushAt,1):20,this.maxBatchSize=Math.max(this.flushAt,t.maxBatchSize??100),this.maxQueueSize=Math.max(this.flushAt,t.maxQueueSize??1e3),this.flushInterval=t.flushInterval??1e4,this.preloadFeatureFlags=t.preloadFeatureFlags??!0,this.defaultOptIn=t.defaultOptIn??!0,this.disableSurveys=t.disableSurveys??!1,this._retryOptions={retryCount:t.fetchRetryCount??3,retryDelay:t.fetchRetryDelay??3e3,retryCheck:th},this.requestTimeout=t.requestTimeout??1e4,this.featureFlagsRequestTimeoutMs=t.featureFlagsRequestTimeoutMs??3e3,this.featureFlagsRequestMaxRetries=t.featureFlagsRequestMaxRetries??1,this.remoteConfigRequestTimeoutMs=t.remoteConfigRequestTimeoutMs??3e3,this.disableGeoip=t.disableGeoip??!0,this.disabled=(t.disabled??!1)||n,this.historicalMigration=t?.historicalMigration??!1,this._initPromise=Promise.resolve(),this._isInitialized=!0,this.evaluationContexts=t?.evaluationContexts??t?.evaluationEnvironments,t?.evaluationEnvironments&&!t?.evaluationContexts&&this._logger.warn("evaluationEnvironments is deprecated. Use evaluationContexts instead. This property will be removed in a future version."),this.disableCompression=!("CompressionStream"in globalThis&&"TextEncoder"in globalThis&&"Response"in globalThis&&"function"==typeof Response.prototype.blob)||(t?.disableCompression??!1)}logMsgIfDebug(e){this.isDebug&&e()}wrap(e){return this.disabled?void this._logger.warn("The client is disabled"):this._isInitialized?e():void this._initPromise.then(()=>e())}getCommonEventProperties(){return{$lib:this.getLibraryId(),$lib_version:this.getLibraryVersion()}}get optedOut(){return this.getPersistedProperty(h.OptedOut)??!this.defaultOptIn}async optIn(){this.wrap(()=>{this.setPersistedProperty(h.OptedOut,!1)})}async optOut(){this.wrap(()=>{this.setPersistedProperty(h.OptedOut,!0)})}on(e,t){return this._events.on(e,t)}debug(e=!0){if(this.removeDebugCallback?.(),e){let e=this.on("*",(e,t)=>this._logger.info(e,t));this.removeDebugCallback=()=>{e(),this.removeDebugCallback=void 0}}}get isDebug(){return!!this.removeDebugCallback}get isDisabled(){return this.disabled}buildPayload(e){let t=e.properties||{},r=this.mergeCommonEventProperties(t);var i=r;for(let e of Object.keys(t))(e.startsWith("$feature/")||"$active_feature_flags"===e)&&(i[e]=t[e]);return"$feature_flag_called"===e.event&&!1===r.$feature_flag_has_experiment&&this.isMinimalFlagCalledEventsEnabled()&&(r=e6(r)),{distinct_id:e.distinct_id,event:e.event,properties:r}}mergeCommonEventProperties(e){return{...e,...this.getCommonEventProperties()}}isMinimalFlagCalledEventsEnabled(){return!1}addPendingPromise(e){return this.promiseQueue.add(e)}identifyStateless(e,t,r){this.wrap(()=>{let i={...this.buildPayload({distinct_id:e,event:"$identify",properties:t})};this.enqueue("identify",i,r)})}async identifyStatelessImmediate(e,t,r){let i={...this.buildPayload({distinct_id:e,event:"$identify",properties:t})};await this.sendImmediate("identify",i,r)}captureStateless(e,t,r,i){this.wrap(()=>{let s=this.buildPayload({distinct_id:e,event:t,properties:r});this.enqueue("capture",s,i)})}async captureStatelessImmediate(e,t,r,i){let s=this.buildPayload({distinct_id:e,event:t,properties:r});await this.sendImmediate("capture",s,i)}aliasStateless(e,t,r,i){this.wrap(()=>{let s=this.buildPayload({event:"$create_alias",distinct_id:t,properties:{...r||{},distinct_id:t,alias:e}});this.enqueue("alias",s,i)})}async aliasStatelessImmediate(e,t,r,i){let s=this.buildPayload({event:"$create_alias",distinct_id:t,properties:{...r||{},distinct_id:t,alias:e}});await this.sendImmediate("alias",s,i)}groupIdentifyStateless(e,t,r,i,s,n){this.wrap(()=>{let a=this.buildPayload({distinct_id:s||`$${e}_${t}`,event:"$groupidentify",properties:{$group_type:e,$group_key:t,$group_set:r||{},...n||{}}});this.enqueue("capture",a,i)})}async groupIdentifyStatelessImmediate(e,t,r,i,s,n){let a=this.buildPayload({distinct_id:s||`$${e}_${t}`,event:"$groupidentify",properties:{$group_type:e,$group_key:t,$group_set:r||{},...n||{}}});await this.sendImmediate("capture",a,i)}async getRemoteConfig(){await this._initPromise;let e=this.host;"https://us.i.posthog.com"===e?e="https://us-assets.i.posthog.com":"https://eu.i.posthog.com"===e&&(e="https://eu-assets.i.posthog.com");let t=`${e}/array/${this.projectToken}/config`,r={method:"GET",headers:{...this.getCustomHeaders(),"Content-Type":"application/json"}};return this.fetchWithRetry(t,r,{type:"required",consume:e=>e.json()},{retryCount:0},this.remoteConfigRequestTimeoutMs).catch(e=>{this._logger.error("Remote config could not be loaded",e),this._events.emit("error",e)})}async getFlags(e,t={},r={},i={},s={},n=!1){await this._initPromise;let a=`${this.host}/flags/?v=2${n?"&config=true":""}`,o={token:this.projectToken,distinct_id:e,groups:t,person_properties:r,group_properties:i,...s};r.$device_id&&(o.$device_id=r.$device_id),this.evaluationContexts&&this.evaluationContexts.length>0&&(o.evaluation_contexts=this.evaluationContexts);let l=this.getEvaluationRuntime();l&&(o.evaluation_runtime=l);let u={method:"POST",headers:{...this.getCustomHeaders(),"Content-Type":"application/json"},body:JSON.stringify(o)};return this._logger.info("Flags URL",a),this.fetchWithRetry(a,u,{type:"required",consume:e=>e.json()},{retryCount:this.featureFlagsRequestMaxRetries,retryCheck:tl},this.featureFlagsRequestTimeoutMs).then(e=>({success:!0,response:(e=>{if("flags"in e){let t,r=Object.fromEntries(Object.entries(e.flags??{}).map(([e,t])=>[e,e3(t)]).filter(([,e])=>void 0!==e)),i=Object.fromEntries(Object.keys(t=e.flags??{}).filter(e=>{let r=t[e];return r.enabled&&r.metadata&&void 0!==r.metadata.payload}).map(e=>{let r=t[e].metadata?.payload;return[e,r?e5(r):void 0]}));return{...e,featureFlags:r,featureFlagPayloads:i}}{let t=e.featureFlags??{},r=Object.fromEntries(Object.entries(e.featureFlagPayloads||{}).map(([e,t])=>[e,e5(t)])),i=Object.fromEntries(Object.entries(t).map(([e,t])=>{var i,s;return[e,{key:e,enabled:"string"==typeof(i=t)||i,variant:"string"==typeof i?i:void 0,reason:void 0,metadata:{id:void 0,version:void 0,payload:(s=r[e])?JSON.stringify(s):void 0,description:void 0}}]}));return{...e,featureFlags:t,featureFlagPayloads:r,flags:i}}})(e)})).catch(e=>(this._events.emit("error",e),{success:!1,error:this.categorizeRequestError(e)}))}categorizeRequestError(e){if(e instanceof ts)return{type:"api_error",statusCode:e.status};if(e instanceof tn){let t=e.error;return t instanceof Error&&("AbortError"===t.name||"TimeoutError"===t.name)?{type:"timeout"}:{type:"connection_error"}}return{type:"unknown_error"}}async getFeatureFlagStateless(e,t,r={},i={},s={},n){await this._initPromise;let a=await this.getFeatureFlagDetailStateless(e,t,r,i,s,n);if(void 0===a)return{response:void 0,requestId:void 0};let o=e3(a.response);return void 0===o&&(o=!1),{response:o,requestId:a.requestId}}async getFeatureFlagDetailStateless(e,t,r={},i={},s={},n){await this._initPromise;let a=await this.getFeatureFlagDetailsStateless(t,r,i,s,n,[e]);if(void 0!==a)return{response:a.flags[e],requestId:a.requestId,evaluatedAt:a.evaluatedAt}}async getFeatureFlagPayloadStateless(e,t,r={},i={},s={},n){await this._initPromise;let a=await this.getFeatureFlagPayloadsStateless(t,r,i,s,n,[e]);if(!a)return;let o=a[e];return void 0===o?null:o}async getFeatureFlagPayloadsStateless(e,t={},r={},i={},s,n){return await this._initPromise,(await this.getFeatureFlagsAndPayloadsStateless(e,t,r,i,s,n)).payloads}async getFeatureFlagsStateless(e,t={},r={},i={},s,n){return await this._initPromise,await this.getFeatureFlagsAndPayloadsStateless(e,t,r,i,s,n)}async getFeatureFlagsAndPayloadsStateless(e,t={},r={},i={},s,n){await this._initPromise;let a=await this.getFeatureFlagDetailsStateless(e,t,r,i,s,n);return a?{flags:a.featureFlags,payloads:a.featureFlagPayloads,requestId:a.requestId}:{flags:void 0,payloads:void 0,requestId:void 0}}async getFeatureFlagDetailsStateless(e,t={},r={},i={},s,n){await this._initPromise;let a={geoip_disable:s??this.disableGeoip};n&&(a.flag_keys_to_evaluate=n);let o=await this.getFlags(e,t,r,i,a);if(!o.success)return;let l=o.response;return(l.errorsWhileComputingFlags&&console.error("[FEATURE FLAGS] Error while computing feature flags, some flags may be missing or incorrect. Learn more at https://posthog.com/docs/feature-flags/best-practices"),l.quotaLimited?.includes("feature_flags"))?(console.warn("[FEATURE FLAGS] Feature flags quota limit exceeded - feature flags unavailable. Learn more about billing limits at https://posthog.com/docs/billing/limits-alerts"),{flags:{},featureFlags:{},featureFlagPayloads:{},requestId:l?.requestId,quotaLimited:l.quotaLimited}):l}async getSurveysStateless(){if(await this._initPromise,this.disabled)return[];if(!0===this.disableSurveys)return this._logger.info("Loading surveys is disabled."),[];let e=`${this.host}/api/surveys/?token=${this.projectToken}`,t={method:"GET",headers:{...this.getCustomHeaders(),"Content-Type":"application/json"}},r=await this.fetchWithRetry(e,t,{type:"required",consume:e=>{if(200!==e.status||!e.json){let t=`Surveys API could not be loaded: ${e.status}`,r=Error(t);return this._logger.error(r),this._events.emit("error",Error(t)),Promise.resolve(void 0)}return e.json()}}).catch(e=>{this._logger.error("Surveys API could not be loaded",e),this._events.emit("error",e)}),i=r?.surveys;return i&&this._logger.info("Surveys fetched from API: ",JSON.stringify(i)),i??[]}get props(){return this._props||(this._props=this.getPersistedProperty(h.Props)),this._props||{}}set props(e){this._props=e}async register(e){this.wrap(()=>{this.props={...this.props,...e},this.setPersistedProperty(h.Props,this.props)})}async unregister(e){this.wrap(()=>{delete this.props[e],this.setPersistedProperty(h.Props,this.props)})}processBeforeEnqueue(e){return e}async flushStorage(){}getQueueRouteKey(e){return tf}persistedQueueKeyForRoute(e){return h.Queue}getActiveQueueRoutes(){return[tf]}getRouteQueue(e){return this.getPersistedProperty(this.persistedQueueKeyForRoute(e))||[]}enqueue(e,t,r,i){this.wrap(()=>{if(this.optedOut)return void this._events.emit(e,"Library is disabled. Not sending event. To re-enable, call posthog.optIn()");let s=this.prepareMessage(t,r);if(null===(s=this.processBeforeEnqueue(s)))return;s=this.normalizeMessage(s);let n=this.persistedQueueKeyForRoute(i??this.getQueueRouteKey(s)),a=this.getPersistedProperty(n)||[];a.length>=this.maxQueueSize&&(a.shift(),this._logger.warn("Queue is full, the oldest event is dropped.")),a.push({message:s}),this.setPersistedProperty(n,a),this._events.emit(e,s),a.length>=this.flushAt&&this.flushBackground(),this.flushInterval&&!this._flushTimer&&(this._flushTimer=V(()=>this.flushBackground(),this.flushInterval))})}async sendImmediate(e,t,r,i){if(this.disabled)return void this._logger.warn("The client is disabled");if(this._isInitialized||await this._initPromise,this.optedOut)return void this._events.emit(e,"Library is disabled. Not sending event. To re-enable, call posthog.optIn()");let s=this.prepareMessage(t,r);if(null!==(s=this.processBeforeEnqueue(s))){s=this.normalizeMessage(s);try{await this.sendBatch([s],void 0,i??this.getQueueRouteKey(s))}catch(e){this._events.emit("error",e)}}}normalizeMessage(e){let{type:t,library:r,library_version:i,...s}=e,n=td(s.properties)?s.properties:void 0;return void 0!==r&&n?.$lib===void 0&&(n={...n||{},$lib:r}),void 0!==i&&n?.$lib_version===void 0&&(n={...n||{},$lib_version:i}),n&&(s.properties=n),s.uuid=B(s.uuid,eQ),s}normalizeTimestampForWire(e){let t=e instanceof Date?e:"string"==typeof e?new Date(e):null;if(!t||Number.isNaN(t.getTime()))return e;let r=t.toISOString(),i="string"==typeof e?e.match(/\.(\d+)(?:Z|[+-]\d{2}:?\d{2})?$/i)?.[1]:void 0;return i&&i.length>3?r.replace(/\.\d{3}Z$/,`.${i}Z`):r}prepareMessage(e,t){let r={...e,timestamp:t?.timestamp?t?.timestamp:U(),uuid:B(t?.uuid,eQ)};return(t?.disableGeoip??this.disableGeoip)&&(td(r.properties)||(r.properties={}),r.properties.$geoip_disable=!0),r.distinctId&&(r.distinct_id=r.distinctId,delete r.distinctId),r}clearFlushTimer(){this._flushTimer&&(clearTimeout(this._flushTimer),this._flushTimer=void 0)}flushBackground(){this.pendingFlushPromise||this.flushAutomatic().catch(async e=>{await ta(e)})}flushAutomatic(){return this.flush()}async waitForPendingPromises(e,t=[]){let r=t.filter(e=>!!e),i=0;for(;;){let t=this.promiseQueue.getPromises([...r,...this.flushPromises],e);if(0===t.length)return;i>0&&this._logger.debug(`flush() re-checking ${t.length} pending promise(s) before flushing`),await Promise.all(t.map(e=>e.catch(()=>{}))),i++}}flushWithPendingPromises(){return this.flushInternal(!0)}flush(){return this.flushInternal(!1)}flushInternal(e){if(this.disabled)return Promise.resolve();if(!e&&this.pendingFlushPromise)return this.pendingFlushPromise;let t=this.flushPromise,r=this.promiseQueue.maxId,i=Promise.resolve().then(()=>{if(e)return this.waitForPendingPromises(r,[t,i])}).then(()=>H([t])).then(()=>(this.pendingFlushPromise===i&&(this.pendingFlushPromise=null),this._flush()));return this.pendingFlushPromise=i,this.flushPromise=i,this.flushPromises.add(i),this.addPendingPromise(i),H([i]).then(()=>{this.flushPromises.delete(i),this.pendingFlushPromise===i&&(this.pendingFlushPromise=null),this.flushPromise===i&&(this.flushPromise=null)}),i}getCustomHeaders(){let e=this.getCustomUserAgent(),t={};return e&&""!==e&&(t["User-Agent"]=e),t}compressPayload(e){return te(e,this.isDebug)}getBatchEndpointPath(e){return"/batch/"}async sendBatch(e,t,r=tf){let i={api_key:this.projectToken,batch:e.map(e=>{if(!e)return e;let t=this.normalizeTimestampForWire(e.timestamp);return t===e.timestamp?e:{...e,timestamp:t}}),sent_at:U()};this.historicalMigration&&(i.historical_migration=!0);let s=f(i),n=`${this.host}${this.getBatchEndpointPath(r)}`,a=this.disableCompression?null:await this.compressPayload(s),o={method:"POST",headers:{...this.getCustomHeaders(),"Content-Type":"application/json",...null!==a&&{"Content-Encoding":"gzip"}},body:a||s};await this.fetchWithRetry(n,o,{type:"successful-write"},t)}async _flush(){let e;this.clearFlushTimer(),await this._initPromise;let t=this.getActiveQueueRoutes();if(!t.some(e=>this.getRouteQueue(e).length>0))return;let r=[];for(let i of t)try{await this._flushRoute(i,r)}catch(t){void 0===e&&(e=t)}if(void 0!==e)throw e;this._events.emit("flush",r)}async _flushRoute(e,t){let r=this.persistedQueueKeyForRoute(e),i=this.getPersistedProperty(r)||[];if(!i.length)return;let s=i.length,n=0;for(;i.length>0&&n<s;){let s=i.slice(0,this.maxBatchSize),a=s.map(e=>void 0===e.message?e.message:this.normalizeMessage(e.message)),o=async()=>{let e=this.getPersistedProperty(r)||[],t=[...s],n=e.filter(e=>{let r=e.message?.uuid,i=t.findIndex(t=>t===e||"string"==typeof r&&r.length>0&&t.message?.uuid===r);return -1===i||(t.splice(i,1),!1)});this.setPersistedProperty(r,n),i=n,this._dequeuedMessagesCount+=s.length,await this.flushStorage()},l={retryCheck:e=>!tc(e)&&th(e)};try{await this.sendBatch(a,l,e)}catch(e){if(tc(e)&&a.length>1){this.maxBatchSize=Math.max(1,Math.floor(a.length/2)),this._logger.warn(`Received 413 when sending batch of size ${a.length}, reducing batch size to ${this.maxBatchSize}`);continue}throw e instanceof tn||await o(),this._events.emit("error",e),e}await o(),t.push(...a),n+=a.length}}async _sendOtlpBatch({path:e,auth:t,payload:r}){let i;if(this.disabled)return{kind:"fatal",error:Error("The client is disabled")};try{i=JSON.stringify(r)}catch(t){return this.logMsgIfDebug(()=>console.warn(`[PostHog] Could not serialize a ${e} batch; reporting it as too large`,t)),{kind:"too-large",measuredLocally:!0}}let s=tu(i);if(s>0xa00000)return this.logMsgIfDebug(()=>console.warn(`[PostHog] Not sending a ${e} batch of ${s} bytes: the endpoint accepts at most 10485760`)),{kind:"too-large",measuredLocally:!0};let n="bearer"===t?`${this.host}/i/v1/${e}`:`${this.host}/i/v1/${e}?token=${encodeURIComponent(this.projectToken)}`,a=this.disableCompression?null:await this.compressPayload(i),o=a||i,l={method:"POST",headers:{...this.getCustomHeaders(),"Content-Type":"application/json",..."bearer"===t&&{Authorization:`Bearer ${this.projectToken}`},...null!==a&&{"Content-Encoding":"gzip"}},body:o};try{return await this.fetchWithRetry(n,l,{type:"successful-write"},{retryCheck:e=>!tc(e)&&(!(e instanceof ts)||void 0===e.retryAfterMs)&&th(e)}),{kind:"ok"}}catch(e){if(tc(e))return{kind:"too-large"};if(th(e)){let t=e instanceof ts?e.retryAfterMs:void 0;return{kind:"retry-later",error:e,...void 0!==t&&{retryAfterMs:t}}}return{kind:"fatal",error:e}}}async _sendLogsBatch(e){return this._sendOtlpBatch({path:"logs",auth:"query-token",payload:e})}async _sendMetricsBatch(e){return this._sendOtlpBatch({path:"metrics",auth:"query-token",payload:e})}async _sendTracesBatch(e){return this._sendOtlpBatch({path:"traces",auth:"bearer",payload:e})}async fetchWithRetry(e,t,r,i,s){let n=tu(t.body?t.body:""),a={...this._retryOptions,...i},o=0;return await q(async()=>{let i,a,l;o++;let u=new AbortController,c=s??this.requestTimeout,h=Date.now()+c,d=new Promise((e,t)=>{i=V(()=>{let e=L("AbortError",`Request timed out after ${c}ms`);t(e),u.abort(e)},c)}),f=!1,p=()=>l??=(async()=>{try{await a?.body?.cancel()}catch{}})();try{let i;try{i=this.fetch(e,{signal:u.signal,...t})}catch(e){throw new tn(e)}i.then(e=>{u.signal.aborted&&!f&&Promise.resolve(e.body?.cancel()).catch(()=>{})}).catch(()=>{});try{a=await Promise.race([i,d]),f=!0}catch(e){throw new tn(e)}let s="no-cors"===t.mode,o="successful-write"===r.type?300:400;if(!s&&(a.status<200||a.status>=o))throw new ts(a,n,h,u);if("successful-write"===r.type){try{await Promise.race([p(),d])}catch{}return}try{return await Promise.race([r.consume(a),d])}catch(e){if(u.signal.aborted)throw new tn(e);throw e}}finally{clearTimeout(i),u.signal.aborted&&a&&p()}},{...a,retryCheck:e=>{let t=a.retryCheck(e);return t&&o<=a.retryCount&&e instanceof ts&&e.cancelResponseBody(),t}})}async _shutdown(e=3e4){await this._initPromise;let t=!1;if(this.clearFlushTimer(),!this.disabled)return z((async()=>{try{for(await this.promiseQueue.join();this.getActiveQueueRoutes().some(e=>this.getRouteQueue(e).length>0);){let e=this._dequeuedMessagesCount;if(await this.flush(),t)break;if(this._dequeuedMessagesCount===e){this._logger.warn("Shutdown flush completed but did not send any queued events. Stopping drain to avoid a loop.");break}}}catch(e){if(!("object"==typeof e&&(e instanceof ts||to(e))))throw e;await ta(e)}})(),e,()=>{this._logger.critical("Timeout while shutting down PostHog. Some events may not have been sent.",{shutdownTimeoutMs:e}),t=!0})}async shutdown(e=3e4){return this.shutdownPromise?this._logger.warn("shutdown() called while already shutting down. shutdown() is meant to be called once before process exit - use flush() for per-request cleanup"):this.shutdownPromise=this._shutdown(e).finally(()=>{this.shutdownPromise=null}),this.shutdownPromise}}let tg="[Circular]",tm="[Truncated]",ty="[Unserializable]";function t_(e){let t="";for(let r=0;r<e.length;r++){let i=e.charCodeAt(r);if(i>=55296&&i<=56319){let i=e.charCodeAt(r+1);i>=56320&&i<=57343?(t+=e[r]+e[r+1],r++):t+="�"}else t+=i>=56320&&i<=57343?"�":e[r]}return t}function tv(e,t){if(!t)return e;let r=[];try{r=Object.keys(t)}catch{r=[]}for(let i of r){let r;try{r=t[i]}catch{r=ty}Object.defineProperty(e,i,{value:r,enumerable:!0,writable:!0,configurable:!0})}return e}Date.prototype.getTime,Date.prototype.toISOString,Object.prototype.propertyIsEnumerable;let tb=Object.prototype.propertyIsEnumerable;function tw(e,t){try{return tx(e,t,{ancestors:new WeakSet,remainingNodes:1e4},0)}catch{return[]}}function tx(e,t,r,i){let s=[];for(let n in e)if(tb.call(e,n)){if(!n){t?.debug("Dropping an attribute with an empty key");continue}if(s.length>=1e3||r.remainingNodes<=0){t?.debug("Attributes truncated: the value exceeds the OTLP encoder budget");break}try{let a=e[n];if(x(a)||v(a))continue;s.push({key:t_(n),value:function e(t,r,i,s){if(i.remainingNodes<=0)return{stringValue:tm};if(i.remainingNodes--,"[object Boolean]"===m.call(t))return{boolValue:t};if("bigint"==typeof t){let e,i;return e=t.toString(),t>=(i=BigInt("9223372036854775808"))||t<-i?(r?.debug(`Attribute ${e} is outside the int64 range; encoding it as a string`),{stringValue:e}):{intValue:e}}if("number"==typeof t){if(!Number.isFinite(t))return{stringValue:String(t)};if(Number.isInteger(t)){if(Number.isSafeInteger(t))return{intValue:String(t)};if("u"<typeof BigInt)return{stringValue:String(t)};let e=BigInt(t).toString();return t>=0x8000000000000000||t<-0x8000000000000000?(r?.debug(`Attribute ${e} is outside the int64 range; encoding it as a string`),{stringValue:e}):{intValue:e}}return{doubleValue:t}}if("string"==typeof t)return{stringValue:t_(t)};if("function"==typeof t)return{stringValue:"[Function]"};if("symbol"==typeof t)return{stringValue:String(t)};if("object"==typeof t&&null!==t){if(i.ancestors.has(t))return{stringValue:tg};if(s>=20)return{stringValue:tm};if(t instanceof Date){let e=Number.isFinite(t.getTime())?t.toISOString():String(t);return{stringValue:"string"==typeof e?t_(e):String(e)}}i.ancestors.add(t);try{try{let n=t.toJSON;if("function"==typeof n)return e(n.call(t),r,i,s+1)}catch{}if(y(t))return{arrayValue:{values:function(t,r,i,s){let n=[],a=Math.min(t.length,1e3),o=0;for(;o<a&&i.remainingNodes>0;o++)try{let a=o in t?t[o]:void 0;if(E(a))continue;n.push(e(a,r,i,s))}catch{n.push({stringValue:ty})}return t.length>o&&n.push({stringValue:tm}),n}(t,r,i,s+1)}};return{kvlistValue:{values:tx(t,r,i,s+1)}}}finally{i.ancestors.delete(t)}}return{stringValue:t_(String(t))}}(a,t,r,i)})}catch{s.push({key:t_(n),value:{stringValue:ty}})}}return s}function tE(e,t,r){return{...tv({},e.resourceAttributes),"service.name":e.serviceName||"unknown_service",...e.environment&&{"deployment.environment":e.environment},...e.serviceVersion&&{"service.version":e.serviceVersion},"telemetry.sdk.name":t,"telemetry.sdk.version":r}}let tS=["service.name","deployment.environment","service.version","telemetry.sdk.name","telemetry.sdk.version"];function tF(e,t){let r=tv({},e),i={};for(let e of tS)Object.prototype.hasOwnProperty.call(r,e)&&(i[e]=r[e],delete r[e]);return[...tw(r,t),...tw(i,t)]}let tP={darwin:"macOS",win32:"Windows",cygwin:"Windows",linux:"Linux",android:"Android",freebsd:"FreeBSD",openbsd:"OpenBSD",netbsd:"NetBSD",sunos:"SunOS",aix:"AIX",haiku:"Haiku","Mac OS X":"macOS"};class tI{constructor(e){this._onFire=e,this._firesAt=0}get pending(){return!!this._timer}arm(e){this.clear(),this._firesAt=Date.now()+e,this._timer=V(()=>{this._timer=void 0,this._onFire()},e)}armNoEarlierThan(e){this._timer&&Date.now()+e<=this._firesAt||this.arm(e)}clear(){this._timer&&(clearTimeout(this._timer),this._timer=void 0)}}function tA(){return .75+.25*Math.random()*2}function tC(e,t,r,i){let s=Math.min(Math.max(0,t-1),6),n=e*2**s;return Math.round((void 0===i?n:Math.min(n,Math.max(i,e)))*r)}let tk="0000000000000000",t$=tk+tk,tO=/^[0-9a-f]+$/;function tM(e){let t=function(e){let t="";for(let r=0;r<e.length;r++)t+=e[r].toString(16).padStart(2,"0");return t}(function(e){let t=new Uint8Array(e),r=globalThis.crypto;if(r&&"function"==typeof r.getRandomValues)try{return r.getRandomValues(t),t}catch{}for(let r=0;r<e;r++)t[r]=Math.floor(256*Math.random());return t}(e));return/[^0]/.test(t)?t:t.slice(0,-1)+"1"}function tT(e,t,r){return"string"==typeof e&&e.length===t&&e!==r&&tO.test(e)}let tR=/^([0-9a-f]{2})-([0-9a-f]{32})-([0-9a-f]{16})-([0-9a-f]{2})(-.*)?$/;function tj(e){let t=tD(e);return t&&{traceId:t.traceId,spanId:t.spanId,flags:1&parseInt(t.flags,16)?tL:tN}}function tD(e){if("string"!=typeof e)return;let t=tR.exec(e.trim());if(!t)return;let[,r,i,s,n,a]=t;if("ff"!==r&&("00"!==r||!a)&&tT(i,32,t$)&&tT(s,16,tk))return{version:r,traceId:i,spanId:s,flags:n}}function tB(e){return Array.isArray(e)&&1===e.length?e[0]:e}let tL="01",tN="00";function tq(e){if("string"!=typeof e)return;let t=e.trim();if(!t||/[^\x20-\x7e\t]/.test(t))return;let r=t.split(",");if(!(r.length>32)){for(let e of r)if(e.trim()&&!e.includes("="))return;return t.length<=512?t:function(e){let t=[...e],r=()=>t.reduce((e,t)=>e+t.length,0)+t.length-1;for(let e=t.length-1;e>=0&&r()>512;e--)t[e].length>128&&t.splice(e,1);for(;t.length&&r()>512;)t.pop();return t.length?t.join(","):void 0}(r)}}let tU=[0,5,10,25,50,75,100,250,500,750,1e3,2500,5e3,7500,1e4];function tV(e){return String(e)+"000000"}function tz(e,t,r,i){let s="";return i&&(s=Object.keys(i).sort().map(e=>`${JSON.stringify(e)}:${JSON.stringify(i[e])}`).join(",")),`${e}\0${t}\0${r??""}\0${s}`}class tH{constructor(e,t,r){this._instance=e,this._config=t,this._logger=r,this._series=new Map,this._flushTimer=new tI(()=>this.flush().catch(e=>{this._logger.error("Metrics flush failed:",e)})),this._flushPromise=null,this._seriesCapWarned=!1,this._typeByName=new Map,this._typeCollisionWarned=new Set,this._retryAfter=new ti,this._consecutiveFlushFailures=0,this._flushJitter=1,this._generation=0}count(e,t=1,r){this._capture({name:e,type:"count",value:t,unit:r?.unit,attributes:r?.attributes})}gauge(e,t,r){this._capture({name:e,type:"gauge",value:t,unit:r?.unit,attributes:r?.attributes})}histogram(e,t,r){this._capture({name:e,type:"histogram",value:t,unit:r?.unit,attributes:r?.attributes})}flush(){let e=this._flushPromise,t=(async()=>{e&&await e.catch(()=>{}),await this._doFlush()})().finally(()=>{this._flushPromise===t&&(this._flushPromise=null)});return this._flushPromise=t,t}drainWindow(){if(0===this._series.size)return null;let e=this._series;return this._series=new Map,this._seriesCapWarned=!1,this._typeByName=new Map,this._typeCollisionWarned=new Set,this._buildPayload(e)}reset(){this._generation++,this._retryAfter.reset(),this._consecutiveFlushFailures=0,this._flushJitter=1,this._flushTimer.clear(),this._series=new Map,this._flushPromise=null,this._seriesCapWarned=!1,this._typeByName=new Map,this._typeCollisionWarned=new Set}_capture(e){let t,r;if(this._instance.isDisabled||this._instance.optedOut)return;let i=this._runBeforeSend(e);if(null===i)return;if(!i.name||"string"!=typeof i.name)return void this._logger.warn("Dropping metric with empty name");if("number"!=typeof i.value||!Number.isFinite(i.value))return void this._logger.warn(`Dropping metric '${i.name}': value must be a finite number`);if("count"===i.type&&i.value<0)return void this._logger.warn(`Dropping count '${i.name}': counters are monotonic, value must be >= 0`);try{t=i.attributes?{...i.attributes}:void 0,r=tz(i.type,i.name,i.unit,t)}catch(e){this._logger.warn(`Dropping metric '${i.name}': attributes could not be serialized`,e);return}let s=this._series.get(r);if(!s){if(!this._admitNewSeries())return;s={name:i.name,type:i.type,unit:i.unit,attributes:t,windowStartMs:Date.now()},this._series.set(r,s)}let n=this._typeByName.get(i.name);void 0===n?this._typeByName.set(i.name,i.type):n===i.type||this._typeCollisionWarned.has(i.name)||(this._typeCollisionWarned.add(i.name),this._logger.warn(`Metric name '${i.name}' is already used as a ${n}; recording it as a ${i.type} too will blend both series in charts. Use a distinct name.`)),this._fold(s,i.value);let a=this._activeTraceContext();a&&(s.exemplar={...a,value:i.value,timeMs:Date.now()}),this._armFlushTimer()}_activeTraceContext(){try{let e=tj(this._instance.getActiveSpan?.()?.traceparent());if(e&&e.flags===tL)return{traceId:e.traceId,spanId:e.spanId}}catch{}}_admitNewSeries(){return this._series.size<this._config.maxSeriesPerFlush||(this._seriesCapWarned||(this._seriesCapWarned=!0,this._logger.warn(`Metric series cap reached (${this._config.maxSeriesPerFlush} per flush window); dropping new series until the next flush. Reduce attribute cardinality.`)),!1)}_fold(e,t){switch(e.type){case"count":e.total=(e.total??0)+t;break;case"gauge":e.last=t;break;case"histogram":{e.hist||(e.hist={count:0,sum:0,min:t,max:t,bucketCounts:Array(tU.length+1).fill(0)});let r=e.hist;r.count+=1,r.sum+=t,r.min=Math.min(r.min,t),r.max=Math.max(r.max,t),r.bucketCounts[function(e,t){for(let r=0;r<t.length;r++)if(e<=t[r])return r;return t.length}(t,tU)]+=1}}}_runBeforeSend(e){let t=this._config.beforeSend;if(!t)return e;let r=y(t)?t:[t],i=e;for(let e of r)try{let t=e(i);if(!t)return this._logger.info("Metric was rejected in beforeSend function"),null;i=t}catch(e){return this._logger.error("Error in beforeSend function for metric:",e),null}return i}_armFlushTimer(){this._flushTimer.pending||this._flushTimer.arm(this._nextFlushDelay())}_nextFlushDelay(){return Math.max(tC(this._config.flushIntervalMs,this._consecutiveFlushFailures,this._flushJitter,3e4),this._retryAfter.remainingMs())}async _doFlush(){if(this._flushTimer.clear(),0===this._series.size)return;let e=this._series;this._series=new Map,this._seriesCapWarned=!1,this._typeByName=new Map,this._typeCollisionWarned=new Set;let t=this._generation,r=await this._instance._sendMetricsBatch(this._buildPayload(e));if(t===this._generation)switch(this._retryAfter.record(r),"retry-later"===r.kind?(this._consecutiveFlushFailures++,this._flushJitter=tA()):(this._consecutiveFlushFailures=0,this._flushJitter=1),this._flushTimer.pending&&this._flushTimer.arm(this._nextFlushDelay()),r.kind){case"ok":return;case"retry-later":this._mergeWindowBack(e),this._flushTimer.armNoEarlierThan(this._nextFlushDelay());return;case"too-large":this._logger.warn("Metrics batch exceeded the server size limit and was dropped");return;case"fatal":this._logger.error("Failed to send metrics batch:",r.error);return}}_buildPayload(e){var t,r,i,s;return t=this._buildMetrics(e),r=tE(this._config,this._instance.getLibraryId(),this._instance.getLibraryVersion()),i=this._instance.getLibraryId(),s=this._instance.getLibraryVersion(),{resourceMetrics:[{resource:{attributes:tF(r)},scopeMetrics:[{scope:{name:i,version:s},metrics:t}]}]}}_buildMetrics(e){let t=tV(Date.now()),r=new Map;for(let s of e.values()){var i;let e=tz(s.type,s.name,s.unit,void 0),n=r.get(e);n||(n={name:s.name,...s.unit&&{unit:s.unit}},"count"===s.type?n.sum={aggregationTemporality:1,isMonotonic:!0,dataPoints:[]}:"gauge"===s.type?n.gauge={dataPoints:[]}:n.histogram={aggregationTemporality:1,dataPoints:[]},r.set(e,n));let a=tw(s.attributes??{},this._logger),o=tV(s.windowStartMs),l=(i=s.exemplar)?{exemplars:[{filteredAttributes:[],timeUnixNano:tV(i.timeMs),asDouble:i.value,traceId:i.traceId,spanId:i.spanId}]}:{};if("count"===s.type){let e={attributes:a,startTimeUnixNano:o,timeUnixNano:t,asDouble:s.total??0,...l};n.sum.dataPoints.push(e)}else if("gauge"===s.type){let e={attributes:a,timeUnixNano:t,asDouble:s.last??0,...l};n.gauge.dataPoints.push(e)}else if(s.hist){let e={attributes:a,startTimeUnixNano:o,timeUnixNano:t,count:s.hist.count,sum:s.hist.sum,min:s.hist.min,max:s.hist.max,bucketCounts:s.hist.bucketCounts,explicitBounds:tU,...l};n.histogram.dataPoints.push(e)}}return Array.from(r.values())}_mergeWindowBack(e){for(let[t,r]of e){let e=this._series.get(t);if(!e){this._admitNewSeries()&&this._series.set(t,r);continue}switch(e.windowStartMs=Math.min(e.windowStartMs,r.windowStartMs),e.exemplar=e.exemplar??r.exemplar,e.type){case"count":e.total=(e.total??0)+(r.total??0);break;case"gauge":break;case"histogram":if(r.hist)if(e.hist){e.hist.count+=r.hist.count,e.hist.sum+=r.hist.sum,e.hist.min=Math.min(e.hist.min,r.hist.min),e.hist.max=Math.max(e.hist.max,r.hist.max);for(let t=0;t<e.hist.bucketCounts.length;t++)e.hist.bucketCounts[t]+=r.hist.bucketCounts[t]}else e.hist=r.hist}}}}let tW="unknown";function tK(e,t,r,i){return"string"==typeof e&&e.trim()?e.length>r?e.slice(0,r):e:(i?.debug(`${t} must be a non-empty string; using "${tW}"`),tW)}function tG(e){if(null==e)return;let t=e;if(e instanceof Date)try{t=e.getTime()}catch{return}if("number"==typeof t&&Number.isFinite(t)&&!(t<0)&&!(t>0x8637bd05af6))return t}function tQ(e,t,r,i){let s=tG(e);return void 0===s?(void 0!==e&&i?.debug(`Span ${r} is out of range or not a valid time; using the derived time`),t):s}function tJ(){let e=globalThis.performance;return"function"==typeof e?.now?e.now():void 0}class tZ{constructor(e,t,r){for(let i of(this._onEnd=t,this._logger=r,this._events=[],this._ended=!1,this._userAttributeCount=0,this._userEventCount=0,this._droppedAttributes=0,this._droppedEvents=0,this._traceId=e.traceId,this._spanId=e.spanId,this._parentSpanId=e.parentSpanId,this._traceState=e.traceState,this._traceFlags=e.traceFlags??tL,this._parentIsRemote=e.parentIsRemote??!1,this._name=e.name,this._kind=e.kind,this._autoKeys=new Set(e.autoAttributeKeys),this._maxAttributes=e.maxAttributes,this._maxEvents=e.maxEvents,this._maxAttributesPerEvent=e.maxAttributesPerEvent,this._maxAttributeValueLength=e.maxAttributeValueLength,this._attributes=Object.create(null),Object.keys(e.attributes)))this._writeAttribute(i,e.attributes[i]);this._startMono=e.backdated?void 0:tJ(),this._startTime=e.clockAnchor&&void 0!==this._startMono?e.clockAnchor.wall+(this._startMono-e.clockAnchor.mono):e.startTime,void 0!==this._startMono&&(this._clockAnchor=e.clockAnchor??{wall:this._startTime,mono:this._startMono})}_now(){if(void 0!==this._startMono){let e=tJ();if(void 0!==e)return this._startTime+Math.max(0,e-this._startMono)}return Date.now()}_mutable(e){return!this._ended||(this._logger?.debug(`Ignoring ${e} on a span that has already ended`),!1)}_writeAttribute(e,t){if(E(t)){e in this._attributes&&!this._autoKeys.has(e)&&this._userAttributeCount--,delete this._attributes[e];return}if(!this._autoKeys.has(e)&&!(e in this._attributes)){if(this._userAttributeCount>=this._maxAttributes)return void this._droppedAttributes++;this._userAttributeCount++}this._attributes[e]=t6(t,this._maxAttributeValueLength)}setAttribute(e,t){return this._mutable("setAttribute")&&this._writeAttribute(e,t),this}setAttributes(e){if(this._mutable("setAttributes")){let t=tv({},e);for(let e of Object.keys(t))this._writeAttribute(e,t[e])}return this}addEvent(e,t,r){if(this._mutable("addEvent")){if(this._userEventCount>=this._maxEvents)return this._droppedEvents++,this;this._userEventCount++;let i=t&&t8(t,this._maxAttributesPerEvent,this._maxAttributeValueLength);this._events.push({name:tK(e,"Span event name",this._maxAttributeValueLength,this._logger),timestamp:tQ(r,this._now(),"event timestamp",this._logger),...i&&{attributes:i.attributes,...i.dropped&&{droppedAttributesCount:i.dropped}}})}return this}setStatus(e,t){if(this._mutable("setStatus")){if("ok"!==e&&"error"!==e)return this._logger?.debug(`Ignoring unknown span status "${String(e)}"; expected "ok" or "error"`),this;this._status={code:e,...t&&{message:t4(t,this._maxAttributeValueLength)}}}return this}get statusIsExplicitlyOk(){return this._status?.code==="ok"}recordException(e){if(!this._mutable("recordException"))return this;let{type:t,message:r,stack:i}=t7(e);return this.addEvent(tY,{"exception.type":t,"exception.message":r,...i&&{"exception.stacktrace":i}}),this.setStatus("error",r)}updateName(e){return this._mutable("updateName")&&(this._name=tK(e,"Span name",this._maxAttributeValueLength,this._logger)),this}traceparent(){return function(e,t,r=tL){return`00-${e}-${t}-${r}`}(this._traceId,this._spanId,this._traceFlags)}tracestate(){return this._traceState??null}childContext(){return{traceId:this._traceId,parentSpanId:this._spanId,traceState:this._traceState,traceFlags:this._traceFlags,clockAnchor:this._clockAnchor}}end(e){var t;if(this._ended)return void this._logger?.debug("Ignoring end() on a span that has already ended");this._ended=!0;let r=tQ(e,this._now(),"end time",this._logger);this._onEnd({traceId:this._traceId,spanId:this._spanId,...this._parentSpanId&&{parentSpanId:this._parentSpanId},...this._traceState&&{traceState:this._traceState},traceFlags:this._traceFlags,parentIsRemote:this._parentIsRemote,name:this._name,kind:this._kind,...this._status&&{status:this._status},attributes:{...this._attributes},events:this._events,startTime:this._startTime,endTime:r<(t=this._startTime)?t:r,...this._droppedAttributes&&{droppedAttributesCount:this._droppedAttributes},...this._droppedEvents&&{droppedEventsCount:this._droppedEvents}},this._autoKeys)}}let tY="exception";function tX(e){return"number"!=typeof e||!Number.isFinite(e)||e<=0?0:Math.min(Math.floor(e),0xffffffff)}class t0{setAttribute(){return this}setAttributes(){return this}addEvent(){return this}setStatus(){return this}recordException(){return this}updateName(){return this}traceparent(){return null}tracestate(){return null}end(){}}let t1=new t0;class t2 extends t0{constructor(e,t){super(),this._traceparent=e,this._tracestate=t}traceparent(){return this._traceparent}tracestate(){return this._tracestate??null}}function t3(e,t){var r;let i=tB(e?.parent)??t,s=tD(r="string"==typeof i||null==i?i:t5(i,"traceparent"))&&r.trim();return s?new t2(s,tq("string"==typeof i||null==i?e?.tracestate:t5(i,"tracestate"))):t1}function t5(e,t){try{let r=e[t];return"function"==typeof r?r.call(e):void 0}catch{return}}function t4(e,t){return e.length>t?e.slice(0,t):e}function t6(e,t){return function e(t,r,i,s){if(null===t||"object"!=typeof t)return E(t)||i.remainingNodes<=0?t:(i.remainingNodes--,"string"==typeof t?t4(t,r):t);if(i.ancestors.has(t))return tg;if(i.remainingNodes<=0||s>=20)return t;i.remainingNodes--,i.ancestors.add(t);try{if(t instanceof Date)return t;let n=function(e){try{let t=e.toJSON;if("function"==typeof t)return{selfDescribed:!0,value:t.call(e)}}catch{}return{selfDescribed:!1}}(t);if(n.selfDescribed)return E(n.value)?String(n.value):e(n.value,r,i,s+1);if(y(t)){let n=Math.min(t.length,1e3),a=[];for(let o=0;o<n;o++)try{a.push(e(t[o],r,i,s+1))}catch{a.push(ty)}return t.length>n&&(a.length=t.length),a}let a={},o=0;for(let n of Object.keys(t)){let l;if(o>=1e3)break;try{l=e(t[n],r,i,s+1)}catch{l=ty}n&&!E(l)&&o++,Object.defineProperty(a,n,{value:l,enumerable:!0,writable:!0,configurable:!0})}return a}catch{return t}finally{i.ancestors.delete(t)}}(e,t,{ancestors:new WeakSet,remainingNodes:1e4},0)}function t8(e,t,r){let i;try{i=Object.keys(e)}catch{return{attributes:{},dropped:0}}let s={},n=0,a=0;for(let o of i){let i;if(n>=t){a++;continue}try{i=t6(e[o],r)}catch{i=ty}E(i)||(n++,Object.defineProperty(s,o,{value:i,enumerable:!0,writable:!0,configurable:!0}))}return{attributes:s,dropped:a}}function t9(e,t,r){return t===t1?r(t):e.with(t,()=>r(t))}function t7(e){try{let t=function(e){try{let t=e.stack;return"string"==typeof t&&t?{stack:t}:{}}catch{return{}}}(e);if(I(e))return{type:e.name||"Error",message:e.message||"",...t};if("string"==typeof e)return{type:"string",message:e};if(e&&"object"==typeof e&&"string"==typeof e.message)return{type:"string"==typeof e.name?e.name:"Object",message:e.message,...t};return{type:typeof e,message:String(e)}}catch{return{type:typeof e,message:""}}}let re={internal:1,server:2,client:3,producer:4,consumer:5},rt={ok:1,error:2};function rr(e){if("string"==typeof e)return t_(e);try{return t_(String(e))}catch{return ty}}function ri(e){let t=Math.floor(e),r=Math.round((e-t)*1e6);return r>=1e6&&(t+=1,r=0),String(t)+String(r).padStart(6,"0")}function rs(){return tJ()??Date.now()}function rn(e){try{return e instanceof tZ}catch{return!1}}function ra(e,t){let r=tj(e);if(r)return{traceId:r.traceId,parentSpanId:r.spanId,traceState:tq(t),traceFlags:r.flags,isRemote:!0}}function ro(e,t,r){e[t]!==r&&(e[t]=r)}class rl{constructor(e,t,r,i,s,n){this._instance=e,this._config=t,this._logger=r,this._getContext=i,this._contextManager=s,this._onSpanQueued=n,this._queue=[],this._flushTimer=new tI(()=>this._flushInBackground()),this._flushPromise=null,this._droppedSinceWarning=0,this._lastDropWarningAt=0,this._dropReasons=new Set,this._consecutiveFlushFailures=0,this._flushJitter=1,this._retryAfter=new ti,this._headBatchFailures=0,this._headBatchSize=0,this._headBatchChargeableAt=0,this._generation=0,this._liveSpans=new Map,this._maxExportBatchSize=t.maxExportBatchSize}startSpan(e,t){var r,i;let s;if(this._instance.isDisabled||this._instance.optedOut)return t3(t,this._contextManager.active());let n=tB(t?.parent);if(n&&"string"!=typeof n&&!rn(n)){if(function(e){try{return"function"==typeof e.traceparent}catch{return!1}}(n))return this._logger.debug("Span parent is not a span from this SDK; returning an inert span"),t3(t,this._contextManager.active());this._logger.debug("Ignoring an unusable span parent")}let a=this._resolveParent(n,t);if(this._liveSpans.size>=this._config.maxLiveSpans&&this._evictAgedSpans(),this._liveSpans.size>=this._config.maxLiveSpans)return this._recordDrop(1,`the live-span limit (${this._config.maxLiveSpans}) was reached — spans are being started and never ended`),t3(t,this._contextManager.active());let o=Date.now(),l=(r=t?.startTime,i=this._logger,void 0===(s=tG(r))?(void 0!==r&&i?.debug("Span startTime is out of range or not a valid time; using the current time"),o):(o-s>864e5?i?.debug("Span startTime is more than 24 hours in the past; the server will clamp it to receive time and keep the original in $originalTimestamp"):s>o&&i?.debug("Span startTime is in the future; the span may export with a zero duration"),s)),u=tM(8);this._liveSpans.set(u,rs());let c=this._autoContextAttributes();return new tZ({traceId:a?.traceId??tM(16),spanId:u,parentSpanId:a?.parentSpanId,traceState:a?.traceState,traceFlags:a?.traceFlags,parentIsRemote:a?.isRemote,name:tK(e,"Span name",this._config.maxAttributeValueLength,this._logger),kind:t?.kind??"internal",attributes:tv({...c},t?.attributes),autoAttributeKeys:Object.keys(c),maxAttributes:this._config.maxAttributesPerSpan,maxEvents:this._config.maxEventsPerSpan,maxAttributesPerEvent:this._config.maxAttributesPerEvent,maxAttributeValueLength:this._config.maxAttributeValueLength,startTime:l,backdated:l!==o,clockAnchor:void 0===tG(t?.startTime)?a?.clockAnchor:void 0},(e,t)=>this._onSpanEnd(e,t),this._logger)}withSpan(e,t,r){let i=this.startSpan(e,"function"==typeof t?void 0:t);try{let e=t9(this._contextManager,i,"function"==typeof t?t:r);if(e&&"function"==typeof e.then)return e.then(e=>(i.end(),e),e=>{throw this._recordCallbackError(i,e),i.end(),e});return i.end(),e}catch(e){throw this._recordCallbackError(i,e),i.end(),e}}getActiveSpan(){return this._contextManager.active()??null}get throttled(){return this._retryAfter.isOpen()}async flush(){for(;;){if(!this._queue.length)return;let e=this._flushPromise;if(!await (e??this._startFlush()))return}}_startFlush(){this._flushTimer.clear();let e=this._generation,t=Promise.resolve().then(()=>e===this._generation?this._flushInner():0).finally(()=>{this._flushPromise===t&&(this._flushPromise=null),this._armFlushTimerIfQueuedNoEarlierThan()});return this._flushPromise=t,t}reset(){this._flushTimer.clear(),this._queue.length&&this._logger.critical(`Discarding ${this._queue.length} span(s) that were still queued when tracing was shut down. Raise the shutdown timeout or flush earlier if they matter.`),this._queue=[],this._liveSpans.clear(),this._flushPromise=null,this._generation++,this._maxExportBatchSize=this._config.maxExportBatchSize,this._droppedSinceWarning=0,this._dropReasons.clear(),this._lastDropWarningAt=0,this._consecutiveFlushFailures=0,this._flushJitter=1,this._retryAfter.reset(),this._resetHeadBatchBudget()}_resetHeadBatchBudget(){this._headBatchFailures=0,this._headBatchChargeableAt=0}_resolveParent(e,t){if("string"==typeof e){let r=ra(e,t?.tracestate);return r||this._logger.debug("Ignoring malformed traceparent; starting a new trace"),r}if(rn(e))return e.childContext();let r=this._contextManager.active();return rn(r)?r.childContext():r instanceof t2?ra(r.traceparent(),r.tracestate()??void 0):void 0}_autoContextAttributes(){let e;try{e=this._getContext()}catch(e){return this._logger.debug("Failed to read tracing context; span will carry no PostHog attributes",e),{}}let t={};return e.distinctId&&(t.posthogDistinctId=e.distinctId),e.sessionId&&(t.sessionId=e.sessionId),e.currentUrl&&(t["url.full"]=e.currentUrl),e.screenName&&(t["screen.name"]=e.screenName),e.appState&&(t["app.state"]=e.appState),t}_recordCallbackError(e,t){if(!(e instanceof tZ))return;let{type:r,message:i,stack:s}=t7(t);e.addEvent("exception",{"exception.type":r,"exception.message":i,...s&&{"exception.stacktrace":s}}),e.statusIsExplicitlyOk||e.setStatus("error",i)}_evictAgedSpans(){let e=rs()-this._config.maxSpanAgeMs,t=0;for(let[r,i]of this._liveSpans){if(i>e)break;this._liveSpans.delete(r),t++}t&&this._recordDrop(t,`they were still live after ${this._config.maxSpanAgeMs}ms`)}_onSpanEnd(e,t){if(!this._liveSpans.delete(e.spanId))return;if(this._instance.isDisabled||this._instance.optedOut)return void this._recordDrop(1,"the user has opted out");let r=this._runBeforeSpanSend(e,t);if(r){if(this._reportLimitDrops(r),this._queue.length>=this._config.maxQueueSize)return void this._recordDrop(1,`the queue is full (${this._config.maxQueueSize}) — raise the flush frequency or reduce span volume`);this._queue.push(r);try{this._onSpanQueued?.()}catch(e){this._logger.debug("Span queue notification failed",e)}!(this._queue.length>=this._maxExportBatchSize)||this._consecutiveFlushFailures||this._retryAfter.isOpen()?this._armFlushTimerIfQueued():this._flushInBackground()}}_reportLimitDrops(e){let t=e.droppedAttributesCount??0,r=e.droppedEventsCount??0,i=0;for(let t of e.events)i+=t.droppedAttributesCount??0;(t||r||i)&&this._logger.debug(`Span limits discarded data from "${e.name}": ${t} attributes, ${r} events, ${i} event attributes`)}_runBeforeSpanSend(e,t){if(!this._config.beforeSpanSend.length)return e;let r={traceId:e.traceId,spanId:e.spanId,parentSpanId:e.parentSpanId,traceState:e.traceState},i={startTime:e.startTime,endTime:e.endTime},s={attributes:e.droppedAttributesCount,events:e.droppedEventsCount},n=Object.keys(e.attributes),a={traceFlags:e.traceFlags,parentIsRemote:e.parentIsRemote},o=e.status&&{...e.status},l=e,u=e;try{var c,h,d;for(let e of this._config.beforeSpanSend){let t=e(l);if(!t)return this._recordDrop(1,"beforeSpanSend dropped it"),null;l=this._keepSpanIdentity(t,r)}if(!((c=u={traceId:r.traceId,spanId:r.spanId,parentSpanId:r.parentSpanId,traceState:r.traceState,name:l.name,kind:l.kind,status:l.status,attributes:l.attributes,events:l.events,startTime:l.startTime,endTime:l.endTime,traceFlags:a.traceFlags,parentIsRemote:a.parentIsRemote,droppedAttributesCount:s.attributes,droppedEventsCount:s.events}).attributes&&"object"==typeof c.attributes&&!Array.isArray(c.attributes)&&Array.isArray(c.events)&&void 0!==c.name&&void 0!==c.kind&&void 0!==c.startTime&&void 0!==c.endTime))return this._logger.debug("beforeSpanSend did not return a span record; dropping the span"),this._recordDrop(1,"beforeSpanSend returned an unusable record"),null;u.name=tK(u.name,"Span name",this._config.maxAttributeValueLength,this._logger),u.status&&"ok"!==u.status.code&&"error"!==u.status.code&&(this._logger.debug("beforeSpanSend set an unknown span status; keeping the original"),u.status=o),u.startTime=tG(u.startTime)??i.startTime,u.endTime=(h=tG(u.endTime)??i.endTime,d=u.startTime,h<d?d:h);let e=[];for(let t of u.events)try{e.push({...t,name:tK(t.name,"Span event name",this._config.maxAttributeValueLength,this._logger),timestamp:tQ(t.timestamp,u.startTime,"event timestamp",this._logger)})}catch{this._logger.debug("beforeSpanSend left an unreadable span event; dropping it")}return u.events=e,!function(e,t,r,i,s,n,a=[]){let o=0,l=0,u={};for(let i of function(e,t){if(!t.length)return Object.keys(e);let r=t.filter(t=>Object.prototype.propertyIsEnumerable.call(e,t)),i=new Set(r);return[...r,...Object.keys(e).filter(e=>!i.has(e))]}(e.attributes,a)){let s=e.attributes[i];if(!E(s)){if(!t.has(i)){if(o>=r){l++;continue}o++}Object.defineProperty(u,i,{value:t6(s,n),enumerable:!0,writable:!0,configurable:!0})}}e.attributes=u,l&&(e.droppedAttributesCount=tX(e.droppedAttributesCount)+l);let c=0,h=0,d=[];for(let t of e.events){if(c>=i){h++;continue}if(c++,t.attributes){let e=t8(t.attributes,s,n);t.attributes=e.attributes,e.dropped&&(t.droppedAttributesCount=tX(t.droppedAttributesCount)+e.dropped)}d.push(t)}e.events=d,h&&(e.droppedEventsCount=tX(e.droppedEventsCount)+h),e.status?.message&&(e.status={...e.status,message:t4(function(e){try{return"string"==typeof e?e:String(e)}catch{return ty}}(e.status.message),n)})}(u,t,this._config.maxAttributesPerSpan,this._config.maxEventsPerSpan,this._config.maxAttributesPerEvent,this._config.maxAttributeValueLength,n),u}catch(e){return this._logger.debug("beforeSpanSend failed; dropping the span rather than exporting it unscrubbed",e),this._recordDrop(1,"beforeSpanSend failed"),null}}_keepSpanIdentity(e,t){(e.traceId!==t.traceId||e.spanId!==t.spanId||e.parentSpanId!==t.parentSpanId)&&this._logger.debug("beforeSpanSend changed a span identity field; keeping the original ids");try{ro(e,"traceId",t.traceId),ro(e,"spanId",t.spanId),ro(e,"parentSpanId",t.parentSpanId),ro(e,"traceState",t.traceState)}catch{try{let r=Object.getOwnPropertyDescriptors(e);for(let e of["traceId","spanId","parentSpanId","traceState"])r[e]={value:t[e],enumerable:!0,writable:!0,configurable:!0};return Object.create(Object.getPrototypeOf(e),r)}catch{;}}return e}_recordDrop(e,t){this._droppedSinceWarning+=e,this._dropReasons.add(t),Date.now()-this._lastDropWarningAt>=this._config.flushIntervalMs&&this._warnAboutDrops()}_warnAboutDrops(){this._droppedSinceWarning&&(this._lastDropWarningAt=Date.now(),this._logger.warn(`Dropping ${this._droppedSinceWarning} span(s): ${[...this._dropReasons].join("; ")}`),this._droppedSinceWarning=0,this._dropReasons.clear())}_encodeBatch(e){let t=[];for(let r of e)try{t.push(function(e,t){var r;let i,s={traceId:e.traceId,spanId:e.spanId,name:rr(e.name),kind:(r=e.kind)&&Object.prototype.hasOwnProperty.call(re,r)?re[r]:re.internal,startTimeUnixNano:ri(e.startTime),endTimeUnixNano:ri(e.endTime),flags:(Number.isFinite(i=parseInt(e.traceFlags,16))?255&i:1)|256|512*!!e.parentIsRemote};e.parentSpanId&&(s.parentSpanId=e.parentSpanId),e.traceState&&(s.traceState=rr(e.traceState));let n=tw(e.attributes,t);n.length&&(s.attributes=n),e.events.length&&(s.events=e.events.map(e=>(function(e,t){let r={name:rr(e.name),timeUnixNano:ri(e.timestamp)};if(e.attributes){let i=tw(e.attributes,t);i.length&&(r.attributes=i)}let i=tX(e.droppedAttributesCount);return i&&(r.droppedAttributesCount=i),r})(e,t)));let a=tX(e.droppedAttributesCount);a&&(s.droppedAttributesCount=a);let o=tX(e.droppedEventsCount);return o&&(s.droppedEventsCount=o),e.status&&(s.status={code:rt[e.status.code],...e.status.message&&{message:rr(e.status.message)}}),s}(r,this._logger))}catch(e){this._logger.debug("Failed to encode a span; dropping it",e),this._recordDrop(1,"its attributes could not be encoded")}return t}_discardQueueIfConsentWithdrawn(){if(!this._instance.isDisabled&&!this._instance.optedOut)return 0;let e=this._queue.length;return this._queue=[],this._resetHeadBatchBudget(),this._recordDrop(e,"the user has opted out"),this._warnAboutDrops(),e}async _flushInner(){var e,t;if(!this._queue.length)return 0;let r=this._discardQueueIfConsentWithdrawn();if(r)return r;let i=function(e,t){for(let r of Object.keys(e))e[r]=t6(e[r],t);return e}((e=this._config,tE(e,this._instance.getLibraryId(),this._instance.getLibraryVersion())),this._config.maxAttributeValueLength),s=this._instance.getLibraryId(),n=this._instance.getLibraryVersion(),a=this._queue.length,o=0,l=1/0,u=this._generation;try{for(;a>0&&this._queue.length>0;){let e=this._discardQueueIfConsentWithdrawn();if(e)return o+e;let r=this._headBatchFailures>0?Math.min(this._maxExportBatchSize,this._headBatchSize):this._maxExportBatchSize,c=Math.max(1,Math.min(r,l,a,this._queue.length)),h=this._queue.slice(0,c),d=this._encodeBatch(h);if(!d.length){this._queue.splice(0,c),a-=c,o+=c,this._resetHeadBatchBudget();continue}let f=rs()>=this._headBatchChargeableAt&&!this._retryAfter.isOpen(),p=await this._instance._sendTracesBatch((t=this._logger,{resourceSpans:[{resource:{attributes:tF(i,t)},scopeSpans:[{scope:{name:s,version:n},spans:d}]}]}));if(u!==this._generation)break;if(this._retryAfter.record(p),"ok"===p.kind){this._consecutiveFlushFailures=0,this._flushJitter=1,this._resetHeadBatchBudget(),this._queue.splice(0,c),a-=c,o+=c,this._maxExportBatchSize<this._config.maxExportBatchSize&&this._maxExportBatchSize++;continue}if("too-large"===p.kind){if(1===c){this._queue.splice(0,1),a-=1,o+=1,this._recordDrop(1,"it is too large for the ingestion endpoint"),this._consecutiveFlushFailures=0,this._flushJitter=1,this._resetHeadBatchBudget();continue}let e=Math.max(1,Math.floor(c/2));p.measuredLocally?l=e:this._maxExportBatchSize=e,this._resetHeadBatchBudget(),this._logger.debug(`Batch too large; retrying the same spans in batches of ${e}`);continue}if("retry-later"===p.kind){if(this._consecutiveFlushFailures++,this._flushJitter=tA(),this._headBatchSize=c,f&&(this._headBatchFailures++,this._headBatchChargeableAt=rs()+this._nextFlushDelay()),this._headBatchFailures<8)return this._logger.debug("Span export failed; retrying on the next flush",p.error),o;if(this._queue.splice(0,c),a-=c,o+=c,this._consecutiveFlushFailures=0,this._flushJitter=1,this._resetHeadBatchBudget(),this._recordDrop(c,"the ingestion endpoint failed 8 times in a row"),this._retryAfter.isOpen())return o;continue}this._logger.debug("Dropping a span batch the ingestion endpoint rejected",p.error),this._queue.splice(0,c),a-=c,o+=c,this._consecutiveFlushFailures=0,this._flushJitter=1,this._resetHeadBatchBudget(),this._recordDrop(c,"the ingestion endpoint rejected the batch")}return o}finally{this._warnAboutDrops()}}_flushInBackground(){this._backgroundFlush||(this._backgroundFlush=this.flush().catch(e=>{this._logger.debug("Background span flush failed",e)}).finally(()=>{this._backgroundFlush=void 0,this._armFlushTimerIfQueuedNoEarlierThan()}))}_armFlushTimerIfQueued(){!this._flushTimer.pending&&this._queue.length&&this._flushTimer.arm(this._nextFlushDelay())}_armFlushTimerIfQueuedNoEarlierThan(){this._queue.length&&this._flushTimer.armNoEarlierThan(this._nextFlushDelay())}_nextFlushDelay(){return Math.max(tC(this._config.flushIntervalMs,this._consecutiveFlushFailures,this._flushJitter,3e4),this._retryAfter.remainingMs())}}var ru=e.i(2157),rc=e.i(12714),rh=e.i(50227),rd=e.i(1457);let rf=new ez.ReduceableCache(25),rp=new ez.ReduceableCache(20);async function rg(e,t=rc.open,r){let i,s={};try{i=process.cwd()}catch{}for(let t=e.length-1;t>=0;t--){var n,a;let r=e[t],o=r?.filename;!(!r||"string"!=typeof o||"number"!=typeof r.lineno||(n=o).startsWith("node:")||n.endsWith(".min.js")||n.endsWith(".min.cjs")||n.endsWith(".min.mjs")||n.startsWith("data:")||void 0!==(a=r).lineno&&a.lineno>1e4||void 0!==a.colno&&a.colno>1e3)&&((0,rh.isAbsolute)(o)||void 0!==i)&&(s[o]||(s[o]=[]),s[o].push(r.lineno))}let o=Object.keys(s);if(0==o.length)return e;let l=[];for(let e of o){let n=rv(e,i);if(void 0===n||rp.get(n))continue;let a=s[e];if(!a)continue;a.sort((e,t)=>e-t);let o=function(e){if(!e.length)return[];let t=0,r=e[0];if("number"!=typeof r)return[];let i=rb(r),s=[];for(;;){if(t===e.length-1){s.push(i);break}let r=e[t+1];if("number"!=typeof r)break;r<=i[1]?i[1]=r+7:(s.push(i),i=rb(r)),t++}return s}(a);if(o.every(e=>(function(e,t){let r=rf.get(e);if(void 0===r)return!1;for(let e=t[0];e<=t[1];e++)if(void 0===r[e])return!1;return!0})(n,e)))continue;let u=function(e,t,r){let i=e.get(t);return void 0===i?(e.set(t,r),r):i}(rf,n,{});l.push(ry(e,o,u,n,t,r))}return await Promise.all(l).catch(()=>{}),e&&e.length>0&&function(e,t,r){for(let i of e)if(i.filename&&void 0===i.context_line&&"number"==typeof i.lineno){let e=rv(i.filename,r),s=void 0===e?void 0:t.get(e);if(void 0===s)continue;!function(e,t,r){if(void 0===t.lineno||void 0===r)return;t.pre_context=[];for(let i=rw(e);i<e;i++){let e=r[i];if(void 0===e)return void r_(t);t.pre_context.push(e)}if(void 0===r[e])return r_(t);t.context_line=r[e];let i=function(e){return e+7}(e);t.post_context=[];for(let s=e+1;s<=i;s++){let e=r[s];if(void 0===e)break;t.post_context.push(e)}}(i.lineno,i,s)}}(e,rf,i),rf.reduce(),e}async function rm(e,t,r){let i,s=!1;try{i=await t(e,ru.constants.O_RDONLY|ru.constants.O_NONBLOCK);let n=await i.stat();if(!n.isFile())return;if(n.size>0xa00000)return void r?.debug(`Skipping source context for oversized file ${e}: ${n.size} bytes exceeds 10485760`);return s=!0,i}catch{return}finally{i&&!s&&await i.close().catch(()=>{})}}async function ry(e,t,r,i,s,n){let a=await rm(e,s,n);return void 0===a?void rp.set(i,1):new Promise(e=>{let s,n,o=!1;function l(t){o||(o=!0,t?.destroy(),a.close().then(e,e))}try{s=a.createReadStream({autoClose:!1,start:0,end:0x9fffff})}catch{rp.set(i,1),l();return}try{n=(0,rd.createInterface)({input:s})}catch{rp.set(i,1),l(s);return}let u=0,c=0,h=t[0];if(void 0===h)return void l(s);let d=h[0],f=h[1];function p(){rp.set(i,1),n.close(),n.removeAllListeners(),l(s)}s.on("error",p),n.on("error",p),n.on("close",()=>l(s)),n.on("line",e=>{if(!(++u<d)&&(r[u]=function(e,t){let r=e,i=r.length;if(i<=150)return r;t>i&&(t=i);let s=Math.max(t-60,0);s<5&&(s=0);let n=Math.min(s+140,i);return n>i-5&&(n=i),n===i&&(s=Math.max(n-140,0)),r=r.slice(s,n),s>0&&(r=`...${r}`),n<i&&(r+="..."),r}(e,0),u>=f)){if(c===t.length-1){n.close(),n.removeAllListeners();return}let e=t[++c];if(void 0===e){n.close(),n.removeAllListeners();return}d=e[0],f=e[1]}})})}function r_(e){delete e.pre_context,delete e.context_line,delete e.post_context}function rv(e,t){return(0,rh.isAbsolute)(e)?JSON.stringify([null,e]):void 0===t?void 0:JSON.stringify([t,e])}function rb(e){return[rw(e),e+7]}function rw(e){return Math.max(1,e-7)}class rx{active(){return this._active}with(e,t){let r=this._active;this._active=e;try{return t()}finally{this._active=r}}}let rE=["amazonbot","amazonproductbot","app.hypefactors.com","applebot","archive.org_bot","awariobot","backlinksextendedbot","baiduspider","bingbot","bingpreview","chrome-lighthouse","dataforseobot","deepscan","duckduckbot","facebookexternal","facebookcatalog","http://yandex.com/bots","hubspot","ia_archiver","leikibot","linkedinbot","meta-externalagent","mj12bot","msnbot","nessus","petalbot","pinterestbot","prerender","rogerbot","screaming frog","sebot-wa","sitebulb","slackbot","slurp","trendictionbot","turnitin","twitterbot","vercel-screenshot","vercelbot","yahoo! slurp","yandexbot","zoombot","bot.htm","bot.php","(bot;","bot/","crawler","ahrefsbot","ahrefssiteaudit","semrushbot","siteauditbot","splitsignalbot","gptbot","oai-searchbot","chatgpt-user","perplexitybot","better uptime bot","sentryuptimebot","uptimerobot","headlesschrome","cypress","google-hoteladsverifier","adsbot-google","apis-google","duplexweb-google","feedfetcher-google","google favicon","google web preview","google-read-aloud","googlebot","googleother","google-cloudvertexbot","googleweblight","mediapartners-google","storebot-google","google-inspectiontool","bytespider"],rS=new Map,rF=function(e,t=[]){if(!e)return!1;let r=function(e,t){let r="";for(let e=0;e<t.length;e++){let i=t[e];r+=i.length+":"+i}return e.length+":"+e+"|"+t.length+":"+r}(e,t),i=rS.get(r);if(void 0!==i)return i;let s=e.toLowerCase(),n=rE.concat(t).some(e=>-1!==s.indexOf(e.toLowerCase()));return rS.size>=256&&rS.clear(),rS.set(r,n),n};function rP(e,t){return"number"==typeof e&&Number.isInteger(e)&&e>=1?e:t}let rI=["service.name","service.version","deployment.environment"],rA={ERRORS_WHILE_COMPUTING:"errors_while_computing_flags",FLAG_MISSING:"flag_missing",LOCAL_EVALUATION_INCONCLUSIVE:"local_evaluation_inconclusive",QUOTA_LIMITED:"quota_limited",UNKNOWN_ERROR:"unknown_error"};e.s(["FeatureFlagError",0,rA],88096);class rC{constructor(e){this._host=e.host,this._distinctId=e.distinctId,this._groups=e.groups,this._disableGeoip=e.disableGeoip,this._flags=e.flags,this._unresolvedFlags=Object.freeze({...e.unresolvedFlags}),this._requestId=e.requestId,this._evaluatedAt=e.evaluatedAt,this._flagDefinitionsLoadedAt=e.flagDefinitionsLoadedAt,this._errorsWhileComputing=e.errorsWhileComputing??!1,this._quotaLimited=e.quotaLimited??!1,this._accessed=e.accessed??new Set,this._isSlice=e.isSlice??!1}isEnabled(e,t={}){let r=this._flags[e];return this._recordAccess(e),r?.enabled??t.defaultValue??!1}getFlag(e){let t=this._flags[e];if(this._recordAccess(e),t)return!!t.enabled&&(t.variant??!0)}getFlagPayload(e){return this._flags[e]?.payload}onlyAccessed(){let e={};for(let t of this._accessed){let r=this._flags[t];r&&(e[t]=r)}return this._cloneWith(e)}only(e){let t={},r=[];for(let i of e){let e=this._flags[i];e?t[i]=e:r.push(i)}return r.length>0&&this._host.logWarning(`FeatureFlagEvaluations.only() was called with flag keys that are not in the evaluation set and will be dropped: ${r.join(", ")}`),this._cloneWith(t)}get keys(){return Object.keys(this._flags)}get unresolvedFlags(){return this._unresolvedFlags}_getEventProperties(){let e={},t=[];for(let[r,i]of Object.entries(this._flags)){let s=!1!==i.enabled&&(i.variant??!0);e[`$feature/${r}`]=s,i.enabled&&t.push(r)}return t.length>0&&(t.sort(),e.$active_feature_flags=t),e}_cloneWith(e){return new rC({host:this._host,distinctId:this._distinctId,groups:this._groups,disableGeoip:this._disableGeoip,flags:e,requestId:this._requestId,evaluatedAt:this._evaluatedAt,flagDefinitionsLoadedAt:this._flagDefinitionsLoadedAt,errorsWhileComputing:this._errorsWhileComputing,quotaLimited:this._quotaLimited,accessed:new Set(this._accessed),isSlice:!0})}_recordAccess(e){if(this._accessed.add(e),""===this._distinctId||this._isSlice&&!(e in this._flags))return;let t=this._flags[e],r=void 0===t?void 0:!1!==t.enabled&&(t.variant??!0),i={$feature_flag:e,$feature_flag_response:r,$feature_flag_id:t?.id,$feature_flag_version:t?.version,$feature_flag_reason:t?.reason,locally_evaluated:t?.locallyEvaluated??!1,[`$feature/${e}`]:r,$feature_flag_request_id:this._requestId,$feature_flag_evaluated_at:t?.locallyEvaluated?Date.now():this._evaluatedAt};t?.hasExperiment!==void 0&&(i.$feature_flag_has_experiment=t.hasExperiment),t?.locallyEvaluated&&void 0!==this._flagDefinitionsLoadedAt&&(i.$feature_flag_definitions_loaded_at=this._flagDefinitionsLoadedAt);let s=[];this._errorsWhileComputing&&s.push(rA.ERRORS_WHILE_COMPUTING),this._quotaLimited&&s.push(rA.QUOTA_LIMITED),void 0===t&&s.push(Object.prototype.hasOwnProperty.call(this._unresolvedFlags,e)?rA.LOCAL_EVALUATION_INCONCLUSIVE:rA.FLAG_MISSING),s.length>0&&(i.$feature_flag_error=s.join(",")),this._host.captureFlagCalledEventIfNeeded({distinctId:this._distinctId,key:e,response:r,groups:this._groups,disableGeoip:this._disableGeoip,properties:i})}}let rk=["exact","is_not","icontains","not_icontains","starts_with","not_starts_with","ends_with","not_ends_with","regex","not_regex"];class r$ extends Error{constructor(e,t="unsupported_definition"){super(e),this.name=this.constructor.name,this.reason=t,Object.setPrototypeOf(this,r$.prototype)}}function rO(e){try{return e()}catch(e){if(e instanceof r$)throw new r$(e.message,"missing_context");throw e}}function rM(e){if("boolean"==typeof e)return!0;if("string"==typeof e){let t=e.toLowerCase();return"true"===t||"false"===t}if(!Array.isArray(e))return!1;for(let t=0;t<e.length;t++)if(!rM(t in e?e[t]:null))return!1;return!0}function rT(e){if("boolean"==typeof e)return e;if("string"==typeof e)return"true"===e.toLowerCase();if(!Array.isArray(e))return!1;for(let t=0;t<e.length;t++)if(!rT(t in e?e[t]:null))return!1;return!0}function rR(e){for(let t=0;t<e.length;t++){let r=e.charCodeAt(t);if(r>=55296&&r<=56319){let r=e.charCodeAt(t+1);if(t+1>=e.length||r<56320||r>57343)throw new r$("Cannot stringify an unpaired surrogate like the flags service");t++}else if(r>=56320&&r<=57343)throw new r$("Cannot stringify an unpaired surrogate like the flags service")}}function rj(e,t=new Set){if(null!==e&&"boolean"!=typeof e){if("string"==typeof e)return void rR(e);if("number"==typeof e){if(!Number.isFinite(e))throw new r$(`Cannot represent non-finite number ${e} like the flags service`);return}if(Array.isArray(e)){if(t.has(e))throw new r$("Cannot represent a circular array during local evaluation");t.add(e);try{for(let r=0;r<e.length;r++)r in e&&rj(e[r],t)}finally{t.delete(e)}return}if("object"==typeof e){let r=Object.getPrototypeOf(e);if(r!==Object.prototype&&null!==r)throw new r$("Cannot represent a non-JSON object like the flags service");if(t.has(e))throw new r$("Cannot represent a circular object during local evaluation");t.add(e);try{for(let r of Object.keys(e))rR(r),rj(e[r],t)}finally{t.delete(e)}return}throw new r$(`Cannot represent ${typeof e} like the flags service`)}}function rD(e,t){let r=0,i=0;for(;r<e.length&&i<t.length;){let s=e.charCodeAt(r),n=t.charCodeAt(i),a=s>=55296&&s<=56319,o=n>=55296&&n<=56319,l=a?e.charCodeAt(r+1):0,u=o?t.charCodeAt(i+1):0,c=a?(s-55296)*1024+l-56320+65536:s,h=o?(n-55296)*1024+u-56320+65536:n;if(c!==h)return c-h;r+=a?2:1,i+=o?2:1}return e.length-t.length}function rB(e){return"string"==typeof e?(rR(e),e):function e(t,r=new Set){if(null===t)return"null";if("string"==typeof t)return rR(t),JSON.stringify(t);if("boolean"==typeof t)return t?"true":"false";if("number"==typeof t){if(!Number.isFinite(t))throw new r$(`Cannot stringify non-finite number ${t} like the flags service`);if(Number.isInteger(t))throw new r$(`Cannot distinguish integer ${t} from an integral JSON float during local evaluation`);return String(t)}if(Array.isArray(t)){if(r.has(t))throw new r$("Cannot stringify a circular array during local evaluation");r.add(t);try{let i=[];for(let s=0;s<t.length;s++)i.push(s in t?e(t[s],r):"null");return`[${i.join(",")}]`}finally{r.delete(t)}}if("object"==typeof t){let i=Object.getPrototypeOf(t);if(i!==Object.prototype&&null!==i)throw new r$("Cannot stringify a non-JSON object like the flags service");if(r.has(t))throw new r$("Cannot stringify a circular object during local evaluation");r.add(t);try{let i=Object.keys(t);return i.forEach(rR),`{${i.sort(rD).map(i=>`${JSON.stringify(i)}:${e(t[i],r)}`).join(",")}}`}finally{r.delete(t)}}throw new r$(`Cannot stringify ${typeof t} like the flags service`)}(e)}let rL=/[\x20-\x2f:;=?@\x5b-\x60\x7b-\x7e]/;function rN(e){let t=new r$(e);return Object.defineProperty(t,Symbol.for("posthog.requiresServerRegexEvaluation"),{value:!0}),t}function rq(e){return String(e).replace(/[A-Z]/g,e=>e.toLowerCase())}function rU(e,t,r){if(!/^\d+$/.test(e)||"strict"===r&&e.length>1&&"0"===e[0])throw new r$(`Invalid semver: ${t}`);return parseInt(e,10)}function rV(e,t="strict"){let r=String(e).trim().replace(/^[vV]/,"").split("-")[0].split("+")[0];if(!r||r.startsWith("."))throw new r$(`Invalid semver: ${e}`);let i=r.split("."),s=r=>void 0===r||""===r?0:rU(r,e,t);return[s(i[0]),s(i[1]),s(i[2])]}function rz(e,t){for(let r=0;r<3;r++){if(e[r]<t[r])return -1;if(e[r]>t[r])return 1}return 0}function rH(e,t){let r=rV(e,t);return{lower:[r[0],r[1],r[2]],upper:[r[0],r[1]+1,0]}}function rW(e,t){let[r,i,s]=rV(e,t);return{lower:[r,i,s],upper:r>0?[r+1,0,0]:i>0?[0,i+1,0]:[0,0,s+1]}}function rK(e,t){let r=String(e).trim().replace(/^[vV]/,"").replace(/\.\*$/,"").replace(/\*$/,"");if(!r)throw new r$(`Invalid wildcard semver: ${e}`);let i=r.split("."),s=r=>{if("legacy-permissive"===t){let e=parseInt(r,10);if(!isNaN(e))return e}else try{return rU(r,e,t)}catch{}throw new r$(`Invalid wildcard semver: ${e}`)},n=s(i[0]);if(1===i.length)return{lower:[n,0,0],upper:[n+1,0,0]};let a=s(i[1]);return{lower:[n,a,0],upper:[n,a+1,0]}}function rG(e){if(e instanceof Date)return e;if("string"==typeof e||"number"==typeof e){let t=new Date(e);if(!isNaN(t.valueOf()))return t;throw new r$(`${e} is in an invalid date format`)}throw new r$(`The date provided ${e} must be a string, number, or date object`)}function rQ(e){if("boolean"==typeof e)throw new r$("Date operations cannot be performed on boolean values");return function(e){let t=e.match(/^-?(?<number>[0-9]+)(?<interval>[a-z])$/),r=new Date(new Date().toISOString());if(!t||!t.groups)return null;let i=parseInt(t.groups.number);if(i>=1e4)return null;let s=t.groups.interval;if("h"===s)r.setUTCHours(r.getUTCHours()-i);else if("d"===s)r.setUTCDate(r.getUTCDate()-i);else if("w"===s)r.setUTCDate(r.getUTCDate()-7*i);else if("m"===s)r.setUTCMonth(r.getUTCMonth()-i);else{if("y"!==s)return null;r.setUTCFullYear(r.getUTCFullYear()-i)}return r}(String(e))??rG(e)}function rJ(e,t={}){let r=e.value,i=t.semverParsingPolicy??"strict";switch(e.operator||"exact"){case"exact":case"is_not":for(let e of Array.isArray(r)?r:[r])rB(e);return;case"is_set":case"is_not_set":case"icontains":case"not_icontains":case"starts_with":case"not_starts_with":case"ends_with":case"not_ends_with":case"regex":case"not_regex":case"gt":case"gte":case"lt":case"lte":return;case"is_date_after":case"is_date_before":rQ(r);return;case"semver_eq":case"semver_neq":case"semver_gt":case"semver_gte":case"semver_lt":case"semver_lte":rV(String(r),i);return;case"semver_tilde":rH(String(r),i);return;case"semver_caret":rW(String(r),i);return;case"semver_wildcard":rK(String(r),i);return;default:throw new r$(`Unknown operator: ${e.operator}`)}}async function rZ(e){let t=globalThis.crypto?.subtle;if(!t)throw Error("SubtleCrypto API not available");return Array.from(new Uint8Array(await t.digest("SHA-1",new TextEncoder().encode(e)))).map(e=>e.toString(16).padStart(2,"0")).join("")}async function rY(e,t,r="",i="."){return parseInt((await rZ(`${e}${i}${t}${r}`)).slice(0,15),16)/0x1000000000000000}async function rX(e,t){if(null==e||null==e.id||null==e.exclusion_percentage)return;let r=Number(e.exclusion_percentage);if(!Number.isFinite(r))return;let i=Math.min(Math.max(r,0),100);if(!(100!==i&&await rY("holdout",t,"","-")>i/100))return`holdout-${e.id}`}function r0(e){let t=[],r=0;for(let i of e){let e=r+i.rollout_percentage/100;t.push({valueMin:r,valueMax:e,key:i.key}),r=e}return t}async function r1(e,t,r){let i=await rY(e,t,"variant");return r0(r).find(e=>i>=e.valueMin&&i<e.valueMax)?.key}function r2(e){return"client"===e||"server"===e?e:"all"}class r3 extends Error{constructor(e){super(),Error.captureStackTrace(this,this.constructor),this.name="ClientError",this.message=e,Object.setPrototypeOf(this,r3.prototype)}}class r5 extends Error{constructor(e){super(e),this.reason="unsupported_definition",this.name=r5.name,Error.captureStackTrace(this,r5),Object.setPrototypeOf(this,r5.prototype)}}let r4=["experience_continuity","unsupported_definition","unresolved_dependency","missing_context"];function r6(e,t){return void 0===e||r4.indexOf(t)<r4.indexOf(e)?t:e}function r8(e,t){return t instanceof r$&&Symbol.for("posthog.requiresServerRegexEvaluation")in t&&Object.defineProperty(e,Symbol.for("posthog.requiresServerRegexEvaluation"),{value:!0}),e}class r9{constructor({pollingInterval:e,personalApiKey:t,projectApiKey:r,timeout:i,host:s,customHeaders:n,...a}){this.debugMode=!1,this.shouldBeginExponentialBackoff=!1,this.backOffCount=0,this.pollerStopped=!1,this.filteredOutFlagKeys=new Set,this.warnedUnresolvableFlags=new Map,this.pollingInterval=e,this.personalApiKey=t,this.featureFlags=[],this.featureFlagsByKey={},this.groupTypeMapping={},this.cohorts={},this.loadedSuccessfullyOnce=!1,this.timeout=i,this.projectApiKey=r,this.host=s,this.poller=void 0,this.fetch=a.fetch||fetch,this.onError=a.onError,this.customHeaders=n,this.onLoad=a.onLoad,this.onMinimalFlagCalledEvents=a.onMinimalFlagCalledEvents,this.cacheProvider=a.cacheProvider,this.strictLocalEvaluation=a.strictLocalEvaluation??!1,this.evaluationContexts=a.evaluationContexts,this.loadFeatureFlags()}debug(e=!0){this.debugMode=e}logMsgIfDebug(e){this.debugMode&&e()}currentDefinitions(){return{featureFlagsByKey:this.featureFlagsByKey,groupTypeMapping:this.groupTypeMapping,cohorts:this.cohorts,filteredOutFlagKeys:this.filteredOutFlagKeys,propertyMatchingVersion:this.propertyMatchingVersion}}withEvaluationSnapshot(e){return e.definitions?e:{...e,evaluationCache:{},definitions:this.currentDefinitions()}}createEvaluationContext(e,t={},r={},i={},s={}){return{distinctId:e,groups:t,personProperties:r,groupProperties:i,evaluationCache:s}}async getFeatureFlag(e,t,r={},i={},s={}){let n,a;if(await this.loadFeatureFlags(),!this.loadedSuccessfullyOnce)return n;if(void 0!==(a=this.featureFlagsByKey[e])){let o=this.createEvaluationContext(t,r,i,s);try{n=(await this.computeFlagAndPayloadLocally(a,o)).value,this.logMsgIfDebug(()=>console.debug(`Successfully computed flag locally: ${e} -> ${n}`))}catch(t){t instanceof r5||t instanceof r$?this.logMsgIfDebug(()=>console.debug(`${t.name} when computing flag locally: ${e}: ${t.message}`)):t instanceof Error&&this.onError?.(Error(`Error computing flag locally: ${e}: ${t}`))}}return n}async getAllFlagsAndPayloads(e,t){await this.loadFeatureFlags();let r={},i={},s={},n=0==this.featureFlags.length,a=t?t.map(e=>this.featureFlagsByKey[e]).filter(Boolean):this.featureFlags,o=this.withEvaluationSnapshot({...e,definitions:void 0});return await Promise.all(a.map(async e=>{try{let{value:t,payload:s}=await this.computeFlagAndPayloadLocally(e,o,{skipLoadCheck:!0});r[e.key]=t,s&&(i[e.key]=s)}catch(t){t instanceof r5||t instanceof r$?(this.logMsgIfDebug(()=>console.debug(`${t.name} when computing flag locally: ${e.key}: ${t.message}`)),s[e.key]=t.reason):t instanceof Error&&this.onError?.(Error(`Error computing flag locally: ${e.key}: ${t}`)),n=!0}})),{response:r,payloads:i,unresolved:s,fallbackToFlags:n}}async computeFlagAndPayloadLocally(e,t,r={}){let i,{matchValue:s,skipLoadCheck:n=!1}=r;if(this.loadedSuccessfullyOnce&&(t=this.withEvaluationSnapshot(t)),n||await this.loadFeatureFlags(),!this.loadedSuccessfullyOnce)return{value:!1,payload:null};e=(t=this.withEvaluationSnapshot(t)).definitions.featureFlagsByKey[e.key]??e,i=void 0!==s?s:await this.computeFlagValueLocally(e,t);let a=function(e,t){if(!1===t||null==t||!e)return null;let r=e["boolean"==typeof t?t.toString():t]||null;return null==r?null:e5(r)}(e.filters?.payloads,i);return{value:i,payload:a}}async computeFlagValueLocally(e,t){let{distinctId:r,groups:i,personProperties:s,groupProperties:n}=t;if(!e.active)return!1;if(e.ensure_experience_continuity)throw new r$("Flag has experience continuity enabled","experience_continuity");let a=(e.filters||{}).aggregation_group_type_index;if(void 0!=a){let r=t.definitions.groupTypeMapping[String(a)];if(!r)throw this.logMsgIfDebug(()=>console.warn(`[FEATURE FLAGS] Unknown group type index ${a} for feature flag ${e.key}`)),new r$("Flag has unknown group type index");if(!(r in i))return this.logMsgIfDebug(()=>console.warn(`[FEATURE FLAGS] Can't compute group feature flag: ${e.key} without group names passed in`)),!1;"device_id"===e.bucketing_identifier&&(s?.$device_id===void 0||s?.$device_id===null||s?.$device_id==="")&&this.logMsgIfDebug(()=>console.warn(`[FEATURE FLAGS] Ignoring bucketing_identifier for group flag: ${e.key}`));let o=n[r];return await this.matchFeatureFlagProperties(e,i[r],o,t)}{let i=this.getBucketingValueForFlag(e,r,s);if(void 0===i)throw this.logMsgIfDebug(()=>console.warn(`[FEATURE FLAGS] Can't compute feature flag: ${e.key} without $device_id, falling back to server evaluation`)),new r$(`Can't compute feature flag: ${e.key} without $device_id`,r7(e,t.definitions)??"missing_context");return await this.matchFeatureFlagProperties(e,i,s,t)}}getBucketingValueForFlag(e,t,r){if(e.filters?.aggregation_group_type_index!=void 0)return t;if("device_id"===e.bucketing_identifier){let e=r?.$device_id;if(null==e||""===e)return;return e}return t}async evaluateFlagDependency(e,t,r){let{evaluationCache:i}=r,s=e.key;if(!r.definitions.featureFlagsByKey)throw new r$("Feature flags not available for dependency evaluation");if(!("dependency_chain"in e))throw new r$(`Flag dependency property for '${s}' is missing required 'dependency_chain' field`);let n=e.dependency_chain;if(!Array.isArray(n))throw new r$(`Flag dependency property for '${s}' has an invalid 'dependency_chain' (expected array, got ${typeof n})`);if(0===n.length)throw new r$(`Circular dependency detected for flag '${s}' (empty dependency chain)`);let a=n.find(e=>!(e in i)&&!r.definitions.featureFlagsByKey[e]&&!r.definitions.filteredOutFlagKeys.has(e));if(void 0!==a)throw new r$(`Missing flag dependency '${a}' for flag '${s}'`);for(let e of n){if(!(e in i)){let t=r.definitions.featureFlagsByKey[e];if(t)if(t.active)try{let s=await this.computeFlagValueLocally(t,r);i[e]=s}catch(t){throw r8(new r$(`Error evaluating flag dependency '${e}' for flag '${s}': ${t}`,"unresolved_dependency"),t)}else i[e]=!1;else i[e]=!1}if(null==i[e])throw new r$(`Dependency '${e}' could not be evaluated`,"unresolved_dependency")}let o=i[s];return this.flagEvaluatesToExpectedValue(e.value,o)}flagEvaluatesToExpectedValue(e,t){return"boolean"==typeof e?e===t||"string"==typeof t&&""!==t&&!0===e:"string"==typeof e&&t===e}async matchFeatureFlagProperties(e,t,r,i){let s,n,a;i=this.withEvaluationSnapshot(i);let o=e.filters||{},l=await rX(o.holdout,t);if(void 0!==l)return l;let u=o.groups||[],c=o.aggregation_group_type_index,h=o.early_exit??!1,{groups:d,groupProperties:f}=i,p=new Set;for(let l of u){let u=t;try{let t=void 0!==l.aggregation_group_type_index?l.aggregation_group_type_index:c,n=r;if(t!==c&&null!=t){let r=i.definitions.groupTypeMapping[String(t)];if(!r||!(r in d)){this.logMsgIfDebug(()=>console.debug(`[FEATURE FLAGS] Skipping group condition for flag '${e.key}': group type index ${t} not available`));continue}if(!(r in f)){s=r6(s,"missing_context");continue}n=f[r],u=d[r]}let p=await this.isConditionMatch(e,u,l,n,i);if("match"===p){let t=l.variant,r=o.multivariate?.variants||[];a=t&&r.some(e=>e.key===t)?t:await this.getMatchingVariant(e,u)||!0;break}if(h&&"out_of_rollout_bound"===p){if(s)break;return!1}}catch(t){if(t instanceof r5)throw t;if(t instanceof r$){if(s=r6(s,t.reason),Symbol.for("posthog.requiresServerRegexEvaluation")in t)if(n=t,h&&void 0!=l.rollout_percentage&&await rY(e.key,u)>l.rollout_percentage/100)p.add(!1);else{let t=o.multivariate?.variants||[],r=l.variant;p.add(r&&t.some(e=>e.key===r)?r:await this.getMatchingVariant(e,u)||!0)}}else throw t}}if(void 0!==a&&!(n&&[...p].some(e=>e!==a)))return a;if(s)throw r8(new r$("Can't determine if feature flag is enabled or not with given properties",s),n);return!1}async isConditionMatch(e,t,r,i,s){let n=(s=this.withEvaluationSnapshot(s)).definitions,a=r.rollout_percentage,o=e=>{this.logMsgIfDebug(()=>console.warn(e))};if((r.properties||[]).length>0){let t,l,u;for(let e of r.properties){let r=e.type,a=!1;try{if("cohort"===r){let t=await it(e,i,n.cohorts,this.debugMode,e=>this.evaluateFlagDependency(e,i,s),n.propertyMatchingVersion);a="not_in"===e.operator?!t:t}else if("flag"===r)a=await this.evaluateFlagDependency(e,i,s);else if(Object.prototype.hasOwnProperty.call(i,e.key))a=ie(e,i,o,n.propertyMatchingVersion);else{rJ(e),t=r6(t,"missing_context");continue}}catch(e){if(e instanceof r5){void 0===t&&(u??=e),t=r6(t,e.reason);continue}if(e instanceof r$){Symbol.for("posthog.requiresServerRegexEvaluation")in e&&(l=e),t=r6(t,e.reason);continue}throw e}if(!a)return"no_match"}if(u)throw u;if(t)throw r8(new r$(`Can't determine if a condition of flag ${e.key} matches`,t),l);if(void 0==a)return"match"}return void 0!=a&&await rY(e.key,t)>a/100?"out_of_rollout_bound":"match"}async getMatchingVariant(e,t){return r1(e.key,t,e.filters?.multivariate?.variants||[])}variantLookupTable(e){return r0(e.filters?.multivariate?.variants||[])}filterFlagsByEvaluationContexts(e){if(!this.evaluationContexts||0===this.evaluationContexts.length)return e;let t=new Set(this.evaluationContexts);return e.filter(e=>{let r=e.evaluation_contexts??e.evaluation_tags;return!r||0===r.length||r.some(e=>t.has(e))})}getEvaluationRuntimeForFlag(e){let t=this.featureFlagsByKey[e];return t?r2(t.evaluation_runtime):void 0}getFlagKeysByEvaluationRuntime(e){return this.featureFlags.filter(t=>{var r;return(r=r2(t.evaluation_runtime))===e||"all"===r||"all"===e}).map(e=>e.key)}updateFlagState(e){let t=this.filterFlagsByEvaluationContexts(e.flags),r=t.reduce((e,t)=>(e[t.key]=t,e),{}),i=new Set(t.map(e=>e.key)),s=new Set(e.flags.filter(e=>!i.has(e.key)).map(e=>e.key));this.featureFlags=t,this.featureFlagsByKey=r,this.filteredOutFlagKeys=s,this.groupTypeMapping=e.group_type_mapping??e.groupTypeMapping??{},this.cohorts=e.cohorts,this.propertyMatchingVersion=e.property_matching_version??e.propertyMatchingVersion,this.loadedSuccessfullyOnce=!0,this.onMinimalFlagCalledEvents?.((e.minimal_flag_called_events??e.minimalFlagCalledEvents)===!0)}warnAboutUnresolvableFlags(e){let t=[],r=[],i=new Map,s=this.currentDefinitions();for(let n of e){let e=r7(n,s);if(!e)continue;let a=JSON.stringify(n);i.set(n.key,a),this.warnedUnresolvableFlags.get(n.key)!==a&&("experience_continuity"===e?t.push(n.key):r.push(n.key))}if(this.warnedUnresolvableFlags=i,t.length>0){let e=this.strictLocalEvaluation?"With strictLocalEvaluation enabled these flags are left unresolved. To evaluate them locally, disable experience continuity on these flags in PostHog.":"Experience continuity is incompatible with local evaluation and will cause a server request on every flag evaluation, negating local evaluation cost savings. To avoid server requests and unexpected costs, either disable experience continuity on these flags in PostHog, use strictLocalEvaluation: true in client init, or pass onlyEvaluateLocally: true per flag call (flags that cannot be evaluated locally will return undefined).";console.warn(`[PostHog] You are using local evaluation but ${t.length} flag(s) have experience continuity enabled and cannot be resolved locally (reason: experience_continuity): ${t.join(", ")}. `+e)}if(r.length>0){let e=this.strictLocalEvaluation?"With strictLocalEvaluation enabled these flags are left unresolved when evaluation reaches that part.":"Evaluating these flags falls back to a server request when evaluation reaches that part.";console.warn(`[PostHog] You are using local evaluation but ${r.length} flag(s) use something local evaluation does not support, such as a static cohort, an unknown operator, or a missing or circular flag dependency (reason: unsupported_definition): ${r.join(", ")}. ${e} To evaluate them locally, change these flags in PostHog or upgrade posthog-node.`)}}async loadFromCache(e){if(!this.cacheProvider)return!1;try{let t=await this.cacheProvider.getFlagDefinitions();if(t)return this.updateFlagState(t),this.logMsgIfDebug(()=>console.debug(`[FEATURE FLAGS] ${e} (${t.flags.length} flags)`)),this.onLoad?.(this.featureFlags.length),this.warnAboutUnresolvableFlags(this.featureFlags),!0;return!1}catch(e){return this.onError?.(Error(`Failed to load from cache: ${e}`)),!1}}async loadFeatureFlags(e=!1){if(!this.loadedSuccessfullyOnce||e)return!e&&this.nextFetchAllowedAt&&Date.now()<this.nextFetchAllowedAt?void this.logMsgIfDebug(()=>console.debug("[FEATURE FLAGS] Skipping fetch, in backoff period")):(this.loadingPromise||(this.loadingPromise=this._loadFeatureFlags().catch(e=>this.logMsgIfDebug(()=>console.debug(`[FEATURE FLAGS] Failed to load feature flags: ${e}`))).finally(()=>{this.loadingPromise=void 0})),this.loadingPromise)}isLocalEvaluationReady(){return(this.loadedSuccessfullyOnce??!1)&&(this.featureFlags?.length??0)>0}getFlagDefinitionsLoadedAt(){return this.flagDefinitionsLoadedAt}getPollingInterval(){let e=this.pollingInterval??3e4;return this.shouldBeginExponentialBackoff?Math.min(6e4,e*2**this.backOffCount):e}beginBackoff(){this.shouldBeginExponentialBackoff=!0,this.backOffCount+=1,this.nextFetchAllowedAt=Date.now()+this.getPollingInterval()}clearBackoff(){this.shouldBeginExponentialBackoff=!1,this.backOffCount=0,this.nextFetchAllowedAt=void 0}async _loadFeatureFlags(){this.poller&&(clearTimeout(this.poller),this.poller=void 0);try{if(this.cacheProvider&&!this.personalApiKey)return void await this.loadFromCache("Loaded flags from cache (cache-only reader)");let e=!0;if(this.cacheProvider)try{e=await this.cacheProvider.shouldFetchFlagDefinitions()}catch(e){this.onError?.(Error(`Error in shouldFetchFlagDefinitions: ${e}`))}if(!e&&(await this.loadFromCache("Loaded flags from cache (skipped fetch)")||this.loadedSuccessfullyOnce))return;let t=await this._requestFeatureFlagDefinitions();if(!t)return;switch(t.status){case 304:this.logMsgIfDebug(()=>console.debug("[FEATURE FLAGS] Flags not modified (304), using cached data")),this.flagsEtag=t.headers?.get("ETag")??this.flagsEtag,this.loadedSuccessfullyOnce=!0,this.clearBackoff();return;case 401:throw this.beginBackoff(),new r3(`Your project key or secret key is invalid. Setting next polling interval to ${this.getPollingInterval()}ms. More information: https://posthog.com/docs/api#rate-limiting`);case 402:console.warn("[FEATURE FLAGS] Feature flags quota limit exceeded - unsetting all local flags. Learn more about billing limits at https://posthog.com/docs/billing/limits-alerts"),this.featureFlags=[],this.featureFlagsByKey={},this.filteredOutFlagKeys=new Set,this.groupTypeMapping={},this.cohorts={},this.propertyMatchingVersion=void 0,this.onMinimalFlagCalledEvents?.(!1);return;case 403:throw this.beginBackoff(),new r3(`Your secret key does not have permission to fetch feature flag definitions for local evaluation. Setting next polling interval to ${this.getPollingInterval()}ms. Are you sure you're using the correct secret and Project API key pair? More information: https://posthog.com/docs/api/overview`);case 429:throw this.beginBackoff(),new r3(`You are being rate limited. Setting next polling interval to ${this.getPollingInterval()}ms. More information: https://posthog.com/docs/api#rate-limiting`);case 200:{let r=await t.json()??{};if(!("flags"in r))return void this.onError?.(Error(`Invalid response when getting feature flags: ${JSON.stringify(r)}`));this.flagsEtag=t.headers?.get("ETag")??void 0;let i=r.group_type_mapping||{},s=!0===r.minimal_flag_called_events,n={flags:r.flags??[],group_type_mapping:i,cohorts:r.cohorts||{},minimal_flag_called_events:s,property_matching_version:r.property_matching_version,propertyMatchingVersion:r.property_matching_version,groupTypeMapping:i,minimalFlagCalledEvents:s};if(this.updateFlagState(n),this.flagDefinitionsLoadedAt=Date.now(),this.clearBackoff(),this.cacheProvider&&e)try{await this.cacheProvider.onFlagDefinitionsReceived(n)}catch(e){this.onError?.(Error(`Failed to store in cache: ${e}`))}this.onLoad?.(this.featureFlags.length),this.warnAboutUnresolvableFlags(this.featureFlags);break}default:return}}catch(e){e instanceof r3&&this.onError?.(e)}finally{this.pollerStopped||null===this.pollingInterval||(this.poller=setTimeout(()=>this.loadFeatureFlags(!0),this.getPollingInterval()))}}getPersonalApiKeyRequestOptions(e="GET",t){let r={...this.customHeaders,"Content-Type":"application/json",Authorization:`Bearer ${this.personalApiKey}`};return t&&(r["If-None-Match"]=t),{method:e,headers:r}}async _requestFeatureFlagDefinitions(){if(!this.personalApiKey)throw new r3("A secretKey or personalApiKey is required to fetch feature flag definitions from PostHog.");let e=`${this.host}/flags/definitions?token=${this.projectApiKey}&send_cohorts`,t=this.getPersonalApiKeyRequestOptions("GET",this.flagsEtag),r=null;if(this.timeout&&"number"==typeof this.timeout){let e=new AbortController;r=V(()=>{e.abort()},this.timeout),t.signal=e.signal}try{let i=this.fetch,s=await i(e,t);if(200!==s.status)return clearTimeout(r),s;return{status:s.status,headers:s.headers,body:s.body,text:async()=>{try{return await s.text()}finally{clearTimeout(r)}},json:async()=>{try{return await s.json()}finally{clearTimeout(r)}}}}catch(e){throw clearTimeout(r),e}}async stopPoller(e=3e4){if(this.pollerStopped=!0,clearTimeout(this.poller),this.poller=void 0,this.cacheProvider)try{let t=this.cacheProvider.shutdown();t instanceof Promise&&await z(t,e,()=>{throw Error(`Cache shutdown timeout after ${e}ms`)})}catch(e){this.onError?.(Error(`Error during cache shutdown: ${e}`))}}}function r7(e,t){if(!e.active)return;if(e.ensure_experience_continuity)return"experience_continuity";let r=e.filters||{},i=r.aggregation_group_type_index;return void 0==i||t.groupTypeMapping[String(i)]?(r.groups||[]).some(e=>(e.properties||[]).some(e=>(function e(t,r,i){if("flag"===t.type){let e=t.dependency_chain;return!Array.isArray(e)||0===e.length||e.some(e=>!r.featureFlagsByKey[e]&&!r.filteredOutFlagKeys.has(e))}if("cohort"!==t.type)try{return rJ(t),!1}catch(e){if(e instanceof r$)return!0;throw e}let s=String(t.value);return!(s in r.cohorts)||!i.has(s)&&(i.add(s),function t(r,i,s){return(r?.values??[]).some(r=>"values"in r?t(r,i,s):e(r,i,s))}(r.cohorts[s],r,i))})(e,t,new Set)))?"unsupported_definition":void 0:"unsupported_definition"}function ie(e,t,r,i){return function(e,t,r={}){try{return function(e,t,r){let i=e.key,s=e.value,n=e.operator||"exact",a=r.semverParsingPolicy??"strict";if(Object.prototype.hasOwnProperty.call(t,i)){if("is_not_set"===n)return!1;else if("is_set"===n)return!0}else throw new r$(`Property ${i} not found in propertyValues`,"missing_context");let o=t[i];if(void 0===o)throw r.warnFunction?.(`Property ${i} cannot have a value of undefined with the ${n} operator`),new r$(`Property ${i} is undefined in propertyValues`);if(null===o&&!rk.includes(n))return r.warnFunction?.(`Property ${i} cannot have a value of null with the ${n} operator`),!1;let l=(e,t)=>{if(2!==r.propertyMatchingVersion&&rM(e)||Array.isArray(e)&&0===e.length)return rO(()=>rj(t)),rT(e)===rT(t);if(2===r.propertyMatchingVersion&&"number"==typeof t&&rM(e))return rO(()=>rj(t)),!1;if(Array.isArray(e)){let r=rO(()=>rB(t)).toLowerCase();return e.some(e=>rB(e).toLowerCase()===r)}return rB(e).toLowerCase()===rO(()=>rB(t)).toLowerCase()},u=(e,t,r)=>{if("gt"===r)return e>t;if("gte"===r)return e>=t;if("lt"===r)return e<t;if("lte"===r)return e<=t;throw Error(`Invalid operator: ${r}`)},c=()=>rO(()=>rV(String(o),a)),h=()=>{let e=rV(String(s),a);return rz(c(),e)},d=({lower:e,upper:t})=>{let r=c();return rz(r,e)>=0&&0>rz(r,t)};switch(n){case"exact":return l(s,o);case"is_not":return!l(s,o);case"is_set":return!0;case"icontains":return rq(o).includes(rq(s));case"not_icontains":return!rq(o).includes(rq(s));case"starts_with":return rq(o).startsWith(rq(s));case"not_starts_with":return!rq(o).startsWith(rq(s));case"ends_with":return rq(o).endsWith(rq(s));case"not_ends_with":return!rq(o).endsWith(rq(s));case"regex":case"not_regex":{let e=function(e,t){let r;if(""===e)return!0;let i=function(e){let t=[],r=-1,i="";for(let s=0;s<e.length;s++){let n=e[s];if(n.charCodeAt(0)>127)return null;if("\\"===n){let t=e[++s];if(void 0===t)break;if("x"===t){if(!/^[\da-f]{2}$/i.test(e.slice(s+1,s+3)))return null;s+=2}else if(!"dDsSwWbBfnrtv".includes(t)&&!rL.test(t))return null;if(-1===r&&"bB".includes(t))return null;i="literal";continue}if("["===n){if(-1!==r)return null;r=s}else if("]"===n&&-1!==r){if(s===r+("^"===e[r+1]?2:1))return null;t.push(e.slice(r,s+1)),r=-1,i="literal";continue}else if(-1!==r){if(["&&","--","~~"].includes(e.slice(s,s+2)))return null;continue}else if("("===n&&"?"===e[s+1]){if(":"!==e[s+2])return null;s+=2}else if("{"===n){let t=/^\{(\d+)(?:,(\d*))?\}/.exec(e.slice(s));if(!t||["","|","("].includes(i)||t.slice(1).some(e=>Number(e)>0xffffffff))return null}else if("*+?}".includes(n)&&("+"===e[s+1]||"{"===e[s+1]))return null;if("*+?{".includes(n)&&["^","$","empty group"].includes(i))return null;i=")"===n&&["(","empty group"].includes(i)?"empty group":n}return t}(e);if(null===i)throw rN("Regex syntax requires server evaluation");try{r=new RegExp(e)}catch(e){if(e instanceof SyntaxError)return null;throw rN("Regex compilation requires server evaluation")}for(let e of i)try{RegExp(e,"u")}catch{throw rN("Regex character class syntax requires server evaluation")}for(let e=0;e<t.length;e++){let r=t[e];if(r.charCodeAt(0)>127||"\r"===r)throw rN("Regex matching for Unicode or carriage returns requires server evaluation")}try{return r.test(t)}catch{throw rN("Regex execution requires server evaluation")}}(String(s),String(o));if(null===e)return!1;return"regex"===n?e:!e}case"gt":case"gte":case"lt":case"lte":{let e="number"==typeof s?s:parseFloat(String(s)),t="number"==typeof o?o:null!=o?parseFloat(String(o)):0/0;if(Number.isFinite(e)&&Number.isFinite(t))return u(t,e,n);return u(String(o),String(s),n)}case"is_date_after":case"is_date_before":{let e=rQ(s),t=rO(()=>rG(o));return"is_date_before"===n?t<e:t>e}case"semver_eq":return 0===h();case"semver_neq":return 0!==h();case"semver_gt":return h()>0;case"semver_gte":return h()>=0;case"semver_lt":return 0>h();case"semver_lte":return 0>=h();case"semver_tilde":return d(rH(String(s),a));case"semver_caret":return d(rW(String(s),a));case"semver_wildcard":return d(rK(String(s),a));default:throw new r$(`Unknown operator: ${n}`)}}(e,t,r)}catch(t){throw t instanceof r$&&"missing_context"===t.reason&&rJ(e,r),t}}(e,t,{warnFunction:r,propertyMatchingVersion:i})}async function it(e,t,r,i=!1,s,n){let a=String(e.value);if(!(a in r))throw new r5(`cohort ${a} not found in local cohorts - likely a static cohort that requires server evaluation`);return ir(r[a],t,r,i,s,n)}async function ir(e,t,r,i=!1,s,n){let a,o;if(!e)return!0;let l=e.type,u=e.values;if(!u||0===u.length)return!0;if("values"in u[0]){for(let e of u)try{let a=await ir(e,t,r,i,s,n);if("AND"===l){if(!a)return!1}else if(a)return!0}catch(t){if(t instanceof r5)throw t;if(t instanceof r$)i&&console.debug(`Failed to compute property ${e} locally: ${t}`),a=r6(a,t.reason),Symbol.for("posthog.requiresServerRegexEvaluation")in t&&(o=t);else throw t}if(a)throw r8(new r$("Can't match cohort without a given cohort property value",a),o);return"AND"===l}for(let e of u)try{let a;if("cohort"===e.type)a=await it(e,t,r,i,s,n);else if("flag"===e.type){if(!s)throw new r$(`Flag dependency '${e.key||"unknown"}' cannot be evaluated without a flag dependency evaluator`);a=await s(e)}else a=ie(e,t,void 0,n);let o=e.negation||!1;if("AND"===l){if(!a&&!o||a&&o)return!1}else if(a&&!o||!a&&o)return!0}catch(t){if(t instanceof r5)throw t;if(t instanceof r$)i&&console.debug(`Failed to compute property ${e} locally: ${t}`),a=r6(a,t.reason),Symbol.for("posthog.requiresServerRegexEvaluation")in t&&(o=t);else throw t}if(a)throw r8(new r$("can't match cohort without a given cohort property value",a),o);return"AND"===l}let ii=["--unhandled-rejections","--unhandled_rejections"],is=new Set(["throw","strict","warn","warn-with-error-code","none"]),ia=[...globalThis.process?.execArgv??[]],io=globalThis.process?.env?.NODE_OPTIONS;function il(e){let t;for(let r=0;r<e.length;r++){let i=e[r],s=ii.find(e=>i===e||i.startsWith(`${e}=`));if(!s)continue;let n=i===s?e[++r]:i.slice(s.length+1);is.has(n)&&(t=n)}return t}let iu=function(e=ia,t=io){return il(e)??il(function(e){let t=[],r="",i=!1;for(let s=0;s<e.length;s++){let n=e[s];"\\"===n&&i&&s+1<e.length?r+=e[++s]:" "!==n||i?'"'===n?i=!i:r+=n:r&&(t.push(r),r="")}return r&&t.push(r),t}(t??""))??"throw"}();function ic(e,t,r){e(t,{mechanism:{type:"unhandledRejection"===r?"onunhandledrejection":"onuncaughtexception",handled:!1}})}function ih(e,t,r,i,s){if(t>r&&(i.warn("min cannot be greater than max."),t=r),S(e))if(e>r)return i.warn(" cannot be greater than max: "+r+". Using max value instead."),r;else return e<t?(i.warn(" cannot be less than min: "+t+". Using min value instead."),t):e;return i.warn(" must be a number. using max or fallback. max: "+r+", fallback: "+s),ih(s??r,t,r,i)}class id{constructor(e){this._buckets={},this._onBucketRateLimited=e._onBucketRateLimited,this._bucketSize=ih(e.bucketSize,0,100,e._logger),this._refillRate=ih(e.refillRate,0,this._bucketSize,e._logger),this._refillInterval=ih(e.refillInterval,0,864e5,e._logger)}_applyRefill(e,t){let r=Math.floor((t-e.lastAccess)/this._refillInterval);if(r>0){let t=r*this._refillRate;e.tokens=Math.min(e.tokens+t,this._bucketSize),e.lastAccess=e.lastAccess+r*this._refillInterval}}consumeRateLimit(e){let t=Date.now(),r=String(e),i=this._buckets[r];return i?this._applyRefill(i,t):(i={tokens:this._bucketSize,lastAccess:t},this._buckets[r]=i),0===i.tokens||(i.tokens--,0===i.tokens&&this._onBucketRateLimited?.(e),0===i.tokens)}stop(){this._buckets={}}}var ip=ez;let ig=class t{constructor(e,t,r){this.client=e,this._exceptionAutocaptureEnabled=t.enableExceptionAutocapture||!1,this._logger=r,this._rateLimiter=new id({...function(e={}){return{refillRate:e.exceptionRateLimiterRefillRate??e.__exceptionRateLimiterRefillRate??1,bucketSize:e.exceptionRateLimiterBucketSize??e.__exceptionRateLimiterBucketSize??10}}(t),refillInterval:1e4,_logger:this._logger}),this.startAutocaptureIfEnabled()}static isPreviouslyCapturedError(e){return _(e)&&"__posthog_previously_captured_error"in e&&!0===e.__posthog_previously_captured_error}static async buildEventMessage(e,t,r,i,s){let n={...s},a=e.buildFromUnknown(t,r);a.$exception_list=await e.modifyFrames(a.$exception_list);let o=ip.getInjectedReleaseId();return o&&(n.$release_id=o),{event:"$exception",distinctId:i,properties:{...a,...n},_originatedFromCaptureException:!0}}startAutocaptureIfEnabled(){this.isEnabled()&&(!function(t,r,i=iu){let s=globalThis.process;if(s){let n;if("strict"===i)return s.on("uncaughtExceptionMonitor",(e,r)=>ic(t,e,r));s.on("uncaughtException",(n=!1,Object.assign((i,s)=>{let a=e.g.process.listeners("uncaughtException").filter(e=>"domainUncaughtExceptionClear"!==e.name&&!0!==e._posthogErrorHandler).length;ic(t,i,s),n||0!==a||(n=!0,r(i))},{_posthogErrorHandler:!0})))}}(this.onException.bind(this),this.onFatalError.bind(this)),function(e,t=iu){let r=globalThis.process;r&&"throw"!==t&&"strict"!==t&&"warn-with-error-code"!==t&&r.on("unhandledRejection",t=>{e(t,{mechanism:{type:"onunhandledrejection",handled:!1}})})}(this.onException.bind(this)))}onException(e,r){this.client.addPendingPromise((async()=>{if(!t.isPreviouslyCapturedError(e)){let i=await t.buildEventMessage(this.client.getErrorPropertiesBuilder(),e,r),s=i.properties,n=s?.$exception_list[0]?.type??"Exception";return this._rateLimiter.consumeRateLimit(n)?void this._logger.info("Skipping exception capture because of client rate limiting.",{exception:n}):this.client._capturePreparedEvent(i,!1)}})())}async onFatalError(e){console.error(e),await this.client.shutdown(2e3),globalThis.process.exit(1)}isEnabled(){return!this.client.isDisabled&&this._exceptionAutocaptureEnabled}shutdown(){this._rateLimiter.stop()}},im=/^[0-9a-f]{32}$/i,iy=/^[0-9a-f]{16}$/i;async function i_(){try{let t=await (o??=e.A(37875)),r=t.trace.getActiveSpan()?.spanContext(),i=r?.traceId,s=r?.spanId;if("string"==typeof i&&"string"==typeof s&&im.test(i)&&iy.test(s)&&!/^0+$/.test(i)&&!/^0+$/.test(s))return{$trace_id:i.toLowerCase(),$span_id:s.toLowerCase()}}catch{}return{}}class iv{getProperty(e){return this._memoryStorage[e]}setProperty(e,t){this._memoryStorage[e]=null!==t?t:void 0}constructor(){this._memoryStorage={}}}let ib="analytics";class iw extends Error{constructor({requestId:e,drops:t,retryExhausted:r,cause:i}){super(iw.buildMessage(e,t,r,i)),this.name="CaptureV1Error",this.requestId=e,this.drops=t,this.retryExhausted=r,this.cause=i}static buildMessage(e,t,r,i){let s=`Capture V1 batch ${e} did not fully deliver: ${t.length} dropped, ${r.length} undelivered`;return i instanceof Error&&(s+=` (${i.message})`),s}}function ix(e){if("boolean"==typeof e)return e;if("number"==typeof e)return 0!==e;if("string"==typeof e){let t=e.trim().toLowerCase();if("true"===t||"1"===t)return!0;if("false"===t||"0"===t)return!1}}let iE=[{property:"$cookieless_mode",optionKey:"cookieless_mode",coerce:ix},{property:"$ignore_sent_at",optionKey:"disable_skew_correction",coerce:ix},{property:"$process_person_profile",optionKey:"process_person_profile",coerce:ix},{property:"$product_tour_id",optionKey:"product_tour_id",coerce:function(e){return"string"==typeof e?e:void 0}}],iS=[{property:"$session_id",field:"session_id"},{property:"$window_id",field:"window_id"}];function iF(e,t,r){void 0===r||t in e||(e[t]=r)}function iP(e){var t;let r={..."object"==typeof(t=e.properties)&&null!==t&&!Array.isArray(t)?e.properties:{}},i={};for(let{property:e,optionKey:t,coerce:s}of iE)if(e in r){let n=s(r[e]);void 0!==n&&(i[t]=n),delete r[e]}let s={};for(let{property:e,field:t}of iS)if(e in r){let i=r[e];"string"==typeof i&&(s[t]=i),delete r[e]}return delete r.$lib,delete r.$lib_version,iF(r,"$set",e.$set),iF(r,"$set_once",e.$set_once),{event:String(e.event??""),uuid:String(e.uuid??""),distinct_id:String(e.distinct_id??""),timestamp:function(e){if("string"==typeof e){let t=new Date(e);if(Number.isNaN(t.getTime()))return new Date().toISOString();let r=t.toISOString(),i=e.match(/\.(\d+)(?:Z|[+-]\d{2}:?\d{2})?$/i)?.[1];return i&&i.length>3?r.replace(/\.\d{3}Z$/,`.${i}Z`):r}if(e instanceof Date)return Number.isNaN(e.getTime())?new Date().toISOString():e.toISOString();let t=null==e?new Date:new Date(e);return Number.isNaN(t.getTime())?new Date().toISOString():t.toISOString()}(e.timestamp),...s,options:i,properties:r}}let iI=new Set([408,500,502,503,504]);class iA{constructor(e,t){this.config=e,this.maxBackoffMs=e.maxBackoffMs??3e4,this.fetchFn=t.fetch,this.onError=t.onError,this.now=t.now??Date.now,this.sleep=t.sleep??(e=>new Promise(t=>V(t,e))),this.generateRequestId=t.generateRequestId??eQ,this.compress=t.compress??te}async sendV1Batch(e){if(0===e.length)return;let t=this.generateRequestId(),r=new Date(this.now()).toISOString(),{batch:i}=function(e,{createdAt:t,historicalMigration:r}){let i={created_at:t,batch:e.map(iP)};return r&&(i.historical_migration=!0),i}(e,{createdAt:r,historicalMigration:this.config.historicalMigration}),s=`${this.config.host}/i/v1/analytics/events`,n=[],a=i,o=Math.max(1,this.config.maxAttempts);for(let e=1;e<=o;e++){let i,l,u=e===o,c=f({created_at:r,...this.config.historicalMigration?{historical_migration:!0}:{},batch:a});try{let{response:r,signal:o}=i=await this.sendOnce(s,c,e,t),{status:h}=r;if(h<200||h>=300)if(!u&&iI.has(h)){let t=this.parseRetryAfter(r);await i.waitFor(i.cancelBody()).catch(()=>{}),l=this.backoffDelay(e,t)}else{let e=await this.buildHttpError(r,h,i.waitFor);return this.surfaceBatchFailure(t,n,a,e)}else{let s;try{s=await i.waitFor(this.parseResponse(r))}catch(e){if(o.aborted)throw e;return this.surfaceBatchFailure(t,n,a,Error(`Capture V1 returned an unparseable ${h} response body`))}let c=this.classify(a,s,n);if(0===c.length)return this.surfacePartialDrops(t,n);if(u)return void this.onError(new iw({requestId:t,drops:n,retryExhausted:c.map(e=>e.uuid)}));a=c;let d=this.parseRetryAfter(r);l=this.backoffDelay(e,d)}}catch(r){if(i&&!i.signal.aborted)throw r;if(u)return this.surfaceBatchFailure(t,n,a,r);l=this.backoffDelay(e)}finally{i?.cleanup()}void 0!==l&&await this.sleep(l)}}async sendOnce(e,t,r,i){let s,n=this.buildHeaders(r,i),a=t;if(this.config.compressionEnabled){let e=await this.compress(t,this.config.isDebug);null!==e&&(a=e,n["Content-Encoding"]="gzip")}let o=new AbortController,l="waiting for response headers",u=new Promise((e,t)=>{s=V(()=>{let e=Error(`Capture V1 request timed out ${l} after ${this.config.requestTimeoutMs}ms`);e.name="AbortError",t(e),o.abort(e)},this.config.requestTimeoutMs)});try{let t,r=this.fetchFn(e,{method:"POST",headers:n,body:a,signal:o.signal}),i=!1;r.then(e=>{o.signal.aborted&&!i&&this.cancelBody(e)}).catch(()=>{});let c=await Promise.race([r,u]);i=!0,l="while reading the response body";let h=!1,d=()=>t??=this.cancelBody(c);return{response:c,signal:o.signal,waitFor:e=>Promise.race([e,u]),cancelBody:d,cleanup:()=>{!h&&(h=!0,clearTimeout(s),o.signal.aborted&&d())}}}catch(e){throw clearTimeout(s),e}}buildHeaders(e,t){let r=`${this.config.libraryId}/${this.config.libraryVersion}`,i={"Content-Type":"application/json",Authorization:`Bearer ${this.config.apiKey}`,"PostHog-Sdk-Info":r,"PostHog-Attempt":String(e),"PostHog-Request-Id":t,"PostHog-Request-Timestamp":new Date(this.now()).toISOString()};return this.config.userAgent&&(i["User-Agent"]=this.config.userAgent),i}classify(e,t,r){let i=t.results??{},s=[];for(let t of e){let e=i[t.uuid];e&&("drop"===e.result?r.push({uuid:t.uuid,details:e.details??void 0}):"retry"===e.result&&s.push(t))}return s}backoffDelay(e,t){let r=Math.min(this.config.initialRetryDelayMs*2**(e-1),this.maxBackoffMs);return void 0===t?r:Math.max(r,Math.min(t,this.maxBackoffMs))}parseRetryAfter(e){let t=e.headers?.get("Retry-After");if(!t)return;let r=t.trim();if(/^\d+$/.test(r)){let e=parseInt(r,10);return Number.isFinite(e)&&e>0?1e3*e:void 0}let i=Date.parse(r);if(Number.isNaN(i))return;let s=i-this.now();return s>0?s:void 0}async parseResponse(e){let t=JSON.parse(await e.text());if("object"!=typeof t||null===t||Array.isArray(t))throw Error("unexpected response shape");let r=t.results;if(void 0!==r&&("object"!=typeof r||null===r||Array.isArray(r)))throw Error("unexpected results shape");return{results:r??{}}}async buildHttpError(e,t,r){let i="";try{i=(await r(e.text())).slice(0,512)}catch{}let s=i?`: ${i}`:"";return Error(`Capture V1 request failed with HTTP ${t}${s}`)}surfaceBatchFailure(e,t,r,i){this.onError(new iw({requestId:e,drops:t,retryExhausted:r.map(e=>e.uuid),cause:i}))}surfacePartialDrops(e,t){t.length>0&&this.onError(new iw({requestId:e,drops:t,retryExhausted:[]}))}async cancelBody(e){try{await e.body?.cancel()}catch{}}}let iC="ai-capture",ik="/i/v0/ai/batch/",i$=new TextEncoder;function iO(e){return i$.encode(f(e)).length}let iM=new Set;function iT(e,t){iM.has(e)||(iM.add(e),console.warn(`[PostHog] ${t}`))}class iR extends tp{get distinctIdHasSentFlagCalls(){return Object.fromEntries(this._distinctIdHasSentFlagCalls)}set distinctIdHasSentFlagCalls(e){this._distinctIdHasSentFlagCalls=new Map(Object.entries(e??{}))}constructor(e,t={}){var r,i;let s,n="string"==typeof e?e.trim():"",a={...t,maxQueueSize:t.maxQueueSize??1e4,flushInterval:t.flushInterval??5e3,host:("string"==typeof(r=t.host)?r.trim():"")||"https://us.i.posthog.com",personalApiKey:("string"==typeof(i=t.secretKey??t.personalApiKey)?i.trim():"")||void 0};if(super(n,a),this._memoryStorage=new iv,this._aiCaptureRouteActive=!1,this._minimalFlagCalledEvents=!1,this.options=a,this.captureMode="v0"===(s="u">typeof process?process.env?.POSTHOG_CAPTURE_MODE:void 0)||"v1"===s?s:"v0",this.enableFullAiCapture=!0===a.enableFullAiCapture,this.privacyMode=!0===a.privacyMode,this.context=this.initializeContext(),this.options.featureFlagsPollingInterval="number"==typeof a.featureFlagsPollingInterval?Math.max(a.featureFlagsPollingInterval,100):null===a.featureFlagsPollingInterval?null:3e4,"number"==typeof a.waitUntilDebounceMs&&(this.options.waitUntilDebounceMs=Math.max(a.waitUntilDebounceMs,0)),"number"==typeof a.waitUntilMaxWaitMs&&(this.options.waitUntilMaxWaitMs=Math.max(a.waitUntilMaxWaitMs,0)),!this.disabled&&(a.personalApiKey||a.flagDefinitionCacheProvider)){if(a.personalApiKey?.includes("phc_"))throw Error('A project API key ("phc_...") was provided as secretKey or personalApiKey. Pass the project API key as the first constructor argument. For local evaluation, set secretKey (or the deprecated personalApiKey alias) to a server-only Project Secret API Key ("phs_...") or Personal API Key ("phx_...") with feature flag read access.');!1!==a.enableLocalEvaluation&&(this.featureFlagsPoller=new r9({pollingInterval:this.options.featureFlagsPollingInterval,personalApiKey:a.personalApiKey,projectApiKey:n,timeout:a.requestTimeout??1e4,host:this.host,fetch:a.fetch,onError:e=>{this._events.emit("error",e)},onLoad:e=>{this._events.emit("localEvaluationFlagsLoaded",e)},onMinimalFlagCalledEvents:e=>{this._minimalFlagCalledEvents=e},customHeaders:this.getCustomHeaders(),cacheProvider:a.flagDefinitionCacheProvider,strictLocalEvaluation:a.strictLocalEvaluation,evaluationContexts:a.evaluationContexts??a.evaluationEnvironments}))}this.errorTracking=new ig(this,a,this._logger),this._distinctIdHasSentFlagCalls=new Map,this.maxCacheSize=a.maxCacheSize||5e4}enqueue(e,t,r,i){super.enqueue(e,t,r,i),this.scheduleDebouncedFlush()}_flushEventsAndSpans(e=!1){let t=this.flushWithPendingPromises();return!this._traces||e&&this._traces.throttled?t:H([t,this._traces.flush().catch(()=>{})]).then(([e])=>{if("rejected"===e.status)throw e.reason})}flushAutomatic(){return this._flushKeepingRuntimeAlive(!0)}async flush(){return this._flushKeepingRuntimeAlive(!1)}_flushKeepingRuntimeAlive(e){let t=this._flushEventsAndSpans(e),r=this.options.waitUntil;if(r&&!this._waitUntilCycle)try{r(t.catch(()=>{}))}catch{}return t}scheduleDebouncedFlush(){let e=this.options.waitUntil;if(!e||this.disabled||this.optedOut)return;if(!this._waitUntilCycle){let t,r=new Promise(e=>{t=e});try{e(r)}catch{return}this._waitUntilCycle={resolve:t,startedAt:Date.now(),timer:void 0}}let t=Date.now()-this._waitUntilCycle.startedAt,r=this.options.waitUntilMaxWaitMs??500;if(void 0!==this._waitUntilCycle.timer&&clearTimeout(this._waitUntilCycle.timer),t>=r)return void this.resolveWaitUntilFlush();let i=this.options.waitUntilDebounceMs??50;this._waitUntilCycle.timer=V(()=>{this.resolveWaitUntilFlush()},i)}_consumeWaitUntilCycle(){let e=this._waitUntilCycle;return e&&(clearTimeout(e.timer),this._waitUntilCycle=void 0),e?.resolve}async resolveWaitUntilFlush(){let e=this._consumeWaitUntilCycle();try{await this._flushEventsAndSpans()}catch{}finally{e?.()}}getPersistedProperty(e){return this._memoryStorage.getProperty(e)}setPersistedProperty(e,t){return this._memoryStorage.setProperty(e,t)}fetch(e,t){return this.options.fetch?this.options.fetch(e,t):fetch(e,t)}getQueueRouteKey(e){var t;return"v1"===this.captureMode&&"string"==typeof(t=e).event&&t.event.startsWith("$ai_")?"ai":ib}persistedQueueKeyForRoute(e){return e===iC?h.AiCaptureQueue:"ai"===e?h.AiQueue:h.Queue}getActiveQueueRoutes(){let e="v1"===this.captureMode?[ib,"ai"]:[ib];return this._aiCaptureRouteActive&&e.push(iC),e}getBatchEndpointPath(e){return e===iC?ik:super.getBatchEndpointPath(e)}async sendBatch(e,t,r=ib){if(r===iC)return this.sendAiCaptureBatch(e,t);if("v1"!==this.captureMode||"ai"===r)return super.sendBatch(e,t,r);let i=e.filter(e=>void 0!==e);await this.getV1Sender().sendV1Batch(i)}async sendAiCaptureBatch(e,t){let{batches:r,dropped:i}=function(e,t=8388608,r=5242880){let i=[],s=[],n=[],a=0;for(let o of e){if(void 0===o)continue;let e=iO(o);if(e>t){s.push({event:"string"==typeof o.event?o.event:"unknown",bytes:e});continue}n.length>0&&a+e>r&&(i.push(n),n=[],a=0),n.push(o),a+=e}return n.length>0&&i.push(n),{batches:i,dropped:s}}(e);for(let{event:e,bytes:t}of i){let r=`Event ${e} (${t} bytes) exceeds the 8MiB limit for ${ik}, dropping.`;this._logger.error(r),this._events.emit("error",Error(r))}for(let e of r)await this.sendAiSubBatch(e,t)}async sendAiSubBatch(e,t){try{await super.sendBatch(e,t,iC)}catch(i){if(!tc(i))throw i;if(1===e.length){let[t]=e,r="string"==typeof t.event?t.event:"unknown",i=`Event ${r} (${iO(t)} bytes) was rejected with 413 by ${ik} on its own, dropping.`;this._logger.error(i),this._events.emit("error",Error(i));return}let r=Math.ceil(e.length/2);await this.sendAiSubBatch(e.slice(0,r),t),await this.sendAiSubBatch(e.slice(r),t)}}getV1Sender(){return this._v1Sender||(this._v1Sender=new iA({host:this.host,apiKey:this.apiKey,libraryId:this.getLibraryId(),libraryVersion:this.getLibraryVersion(),userAgent:this.getCustomUserAgent()||void 0,historicalMigration:this.historicalMigration,compressionEnabled:!this.disableCompression,requestTimeoutMs:this.requestTimeout,maxAttempts:(this.options.fetchRetryCount??3)+1,initialRetryDelayMs:this.options.fetchRetryDelay??3e3,isDebug:this.isDebug},{fetch:(e,t)=>this.fetch(e,t),onError:e=>this._events.emit("error",e),compress:e=>this.compressPayload(e)})),this._v1Sender}getLibraryVersion(){return"5.57.1"}get metrics(){var e;let t;return this._metrics||(this._metrics=new tH(this,(e=this.options.metrics,t=e?.resourceAttributes,{serviceName:t?.["service.name"]??e?.serviceName,serviceVersion:t?.["service.version"]??e?.serviceVersion,environment:t?.["deployment.environment"]??e?.environment,resourceAttributes:t,beforeSend:e?.beforeSend,flushIntervalMs:e?.flushIntervalMs??1e4,maxSeriesPerFlush:e?.maxSeriesPerFlush??1e3}),this._logger)),this._metrics}initializeSpanContextManager(){return new rx}hostResourceAttributes(){return{}}get _spanContextManager(){return this._spanContext||(this._spanContext=this.initializeSpanContextManager()),this._spanContext}get _tracesPipeline(){if(this.options.traces){var e,t,r;let i,s;return this._traces||(this._traces=new rl(this,(e=this.options.traces,t=this.hostResourceAttributes(),r=this._logger,i=tv({...t},function(e){if(!(!e||"object"!=typeof e||Array.isArray(e)))try{if(rI.every(t=>!(t in e)||"string"==typeof e[t]))return e;let t={...e};for(let e of rI)e in t&&"string"!=typeof t[e]&&delete t[e];return t}catch{return}}(e?.resourceAttributes)),s=rP(e?.maxExportBatchSize,512),{serviceName:i?.["service.name"]??e?.serviceName,serviceVersion:i?.["service.version"]??e?.serviceVersion,environment:i?.["deployment.environment"]??e?.environment,resourceAttributes:i,beforeSpanSend:function(e,t){if(!e)return[];let r=[e].flat().filter(e=>!!e),i=r.filter(e=>"function"==typeof e);return i.length!==r.length&&t?.critical(`beforeSpanSend: ignoring ${r.length-i.length} of ${r.length} entries that are not functions. Spans export without them, so whatever they were redacting is not redacted.`),i}(e?.beforeSpanSend,r),maxAttributesPerSpan:rP(e?.maxAttributesPerSpan,128),maxEventsPerSpan:rP(e?.maxEventsPerSpan,128),maxAttributesPerEvent:128,maxAttributeValueLength:rP(e?.maxAttributeValueLength,8192),flushIntervalMs:rP(e?.flushIntervalMs,5e3),maxExportBatchSize:s,maxQueueSize:Math.max(rP(e?.maxQueueSize,2048),s),maxLiveSpans:rP(e?.maxLiveSpans,1e4),maxSpanAgeMs:rP(e?.maxSpanAgeMs,36e5)}),this._logger,()=>this._tracingContext(),this._spanContextManager,()=>this.scheduleDebouncedFlush())),this._traces}}_tracingContext(){let e=this.context?.get();return{distinctId:e?.distinctId,sessionId:e?.sessionId}}startSpan(e,t){return this._tracesPipeline?.startSpan(e,t)??t3(t,this._spanContextManager.active())}withSpan(e,t,r){let i="function"==typeof t?void 0:t,s="function"==typeof t?t:r,n=this._tracesPipeline;return n?i?n.withSpan(e,i,s):n.withSpan(e,s):t9(this._spanContextManager,t3(i,this._spanContextManager.active()),s)}getActiveSpan(){return this._spanContextManager.active()??null}getCustomUserAgent(){return`${this.getLibraryId()}/${this.getLibraryVersion()}`}getEvaluationRuntime(){return"server"}getCommonEventProperties(){let e=super.getCommonEventProperties();return(this.options.isServer??!0)&&(e.$is_server=!0),e}enable(){return super.optIn()}disable(){return super.optOut()}debug(e=!0){super.debug(e),this.featureFlagsPoller?.debug(e)}_warnIfInvalidCapture(e,t,r){"string"==typeof e&&this._logger.warn(t),"$exception"!==e.event||e._originatedFromCaptureException||this._logger.warn(r)}_sendPreparedEvent(e,t,r,i,s){return this.addPendingPromise(this._prepareEventMessage(t,i).then(({distinctId:t,event:i,properties:n,options:a})=>{let o={timestamp:a.timestamp,disableGeoip:a.disableGeoip,uuid:a.uuid},l={distinctId:t,event:i,properties:{...n,...this.getCommonEventProperties()}};return r?this.sendImmediate(e,l,o,s):this.enqueue(e,l,o,s)}).catch(e=>{e&&console.error(e)}))}_capturePreparedEvent(e,t){return this._sendPreparedEvent("capture",e,t)}capture(e){this._warnIfInvalidCapture(e,"Called capture() with a string as the first argument when an object was expected.","Using `posthog.capture('$exception')` is unreliable because it does not attach required metadata. Use `posthog.captureException(error)` instead, which attaches required metadata automatically."),this._capturePreparedEvent(e,!1)}async captureImmediate(e){return this._warnIfInvalidCapture(e,"Called captureImmediate() with a string as the first argument when an object was expected.","Capturing a `$exception` event via `posthog.captureImmediate('$exception')` is unreliable because it does not attach required metadata. Use `posthog.captureExceptionImmediate(error)` instead, which attaches this metadata by default."),this._capturePreparedEvent(e,!0)}captureAi(e){if(this.disabled)return;let t=B(e.uuid,eQ);return this._sendPreparedAiEvent({...e,uuid:t},!1),t}async captureAiImmediate(e){if(this.disabled)return;let t=B(e.uuid,eQ);return await this._sendPreparedAiEvent({...e,uuid:t},!0),t}_sendPreparedAiEvent(e,t){return"string"!=typeof e?.event||e.event.startsWith("$ai_")||this._logger.debug(`captureAi called with non-AI event ${e.event}; routing it to the AI endpoint anyway.`),this._aiCaptureRouteActive=!0,this._sendPreparedEvent("capture",e,t,void 0,iC)}identify({distinctId:e,properties:t={},disableGeoip:r}){let{$set:i,$set_once:s,$anon_distinct_id:n,...a}=t;this._sendPreparedEvent("identify",{distinctId:e,event:"$identify",properties:{$set:i||a,$set_once:s||{},$anon_distinct_id:n??void 0},disableGeoip:r},!1,{includeContextProperties:!1})}async identifyImmediate({distinctId:e,properties:t={},disableGeoip:r}){let{$set:i,$set_once:s,$anon_distinct_id:n,...a}=t;await this._sendPreparedEvent("identify",{distinctId:e,event:"$identify",properties:{$set:i||a,$set_once:s||{},$anon_distinct_id:n??void 0},disableGeoip:r},!0,{includeContextProperties:!1})}setPersonProperties({distinctId:e,properties:t={},propertiesOnce:r={}}){if(0===Object.keys(t).length&&0===Object.keys(r).length)return;let i={};Object.keys(t).length>0&&(i.$set=t),Object.keys(r).length>0&&(i.$set_once=r),this.capture({distinctId:e,event:"$set",properties:i})}unsetPersonProperties({distinctId:e,properties:t}){let r=(Array.isArray(t)?t:[t]).filter(e=>"string"==typeof e&&e.trim().length>0);0!==r.length&&this.capture({distinctId:e,event:"$set",properties:{$unset:r}})}alias(e){this._sendPreparedEvent("alias",{distinctId:e.distinctId,event:"$create_alias",properties:{distinct_id:e.distinctId,alias:e.alias},disableGeoip:e.disableGeoip},!1,{includeContextProperties:!1})}async aliasImmediate(e){await this._sendPreparedEvent("alias",{distinctId:e.distinctId,event:"$create_alias",properties:{distinct_id:e.distinctId,alias:e.alias},disableGeoip:e.disableGeoip},!0,{includeContextProperties:!1})}isLocalEvaluationReady(){return this.featureFlagsPoller?.isLocalEvaluationReady()??!1}getFeatureFlagEvaluationRuntime(e){return this.featureFlagsPoller?.getEvaluationRuntimeForFlag(e)}getFeatureFlagKeysByEvaluationRuntime(e){return this.featureFlagsPoller?.getFlagKeysByEvaluationRuntime(e)??[]}async waitForLocalEvaluationReady(e=3e4){return!!this.isLocalEvaluationReady()||void 0!==this.featureFlagsPoller&&new Promise(t=>{let r=setTimeout(()=>{i(),t(!1)},e),i=this._events.on("localEvaluationFlagsLoaded",e=>{clearTimeout(r),i(),t(e>0)})})}_resolveDistinctId(e,t){return"string"==typeof e?{distinctId:e,options:t}:{distinctId:this.context?.get()?.distinctId,options:e}}async _getFeatureFlagResult(e,t,r={},i){let s,n,a,o,l,u,c,h;if(this.disabled)return void this._logger.warn("The client is disabled");let d=r.sendFeatureFlagEvents??!0;if(void 0!==this._flagOverrides&&e in this._flagOverrides){let t=this._flagOverrides[e];if(void 0===t)return;let r=this._payloadOverrides?.[e];return{key:e,enabled:!1!==t,variant:"string"==typeof t?t:void 0,payload:r}}let{groups:f,disableGeoip:p}=r,{onlyEvaluateLocally:g,personProperties:m,groupProperties:y}=r,_=this.addLocalPersonAndGroupProperties(t,f,m,y);m=_.allPersonProperties,y=_.allGroupProperties;let v=this.createFeatureFlagEvaluationContext(t,f,this.personPropertiesForLocalEvaluation(t,m),y);void 0==g&&(g=this.options.strictLocalEvaluation??!1);let b=!1;if(void 0!==this.featureFlagsPoller){await this.featureFlagsPoller?.loadFeatureFlags();let t=this.featureFlagsPoller?.featureFlagsByKey[e];if(t)try{let r=await this.featureFlagsPoller?.computeFlagAndPayloadLocally(t,v,{matchValue:i});if(r){b=!0;let i=r.value;l=t.id,c="Evaluated locally",h=t.has_experiment,s={key:e,enabled:!1!==i,variant:"string"==typeof i?i:void 0,payload:r.payload??void 0,reason:c,reasonCode:!1===t.active?"flag_disabled":void 0}}}catch(t){if(t instanceof r5||t instanceof r$)this._logger?.info(`${t.name} when computing flag locally: ${e}: ${t.message}`);else throw t}}if(!b&&!g){let t=await super.getFeatureFlagDetailsStateless(v.distinctId,v.groups,m,y,p,[e]);if(void 0===t)o=rA.UNKNOWN_ERROR;else{this._minimalFlagCalledEvents=!0===t.minimalFlagCalledEvents,n=t.requestId,a=t.evaluatedAt;let r=[];t.errorsWhileComputingFlags&&r.push(rA.ERRORS_WHILE_COMPUTING),t.quotaLimited?.includes("feature_flags")&&r.push(rA.QUOTA_LIMITED);let i=t.flags[e];if(void 0===i)r.push(rA.FLAG_MISSING);else{let t;if(l=i.metadata?.id,u=i.metadata?.version,c=i.reason?.description??i.reason?.code,h=i.metadata?.has_experiment,i.metadata?.payload!==void 0)try{t=JSON.parse(i.metadata.payload)}catch{t=i.metadata.payload}s={key:e,enabled:i.enabled,variant:i.variant??void 0,payload:t,reason:c,reasonCode:i.reason?.code}}r.length>0&&(o=r.join(","))}}if(d){let r=void 0===s?void 0:!1!==s.enabled&&(s.variant??!0),i={$feature_flag:e,$feature_flag_response:r,$feature_flag_id:l,$feature_flag_version:u,$feature_flag_reason:c,locally_evaluated:b,[`$feature/${e}`]:r,$feature_flag_request_id:n,$feature_flag_evaluated_at:b?Date.now():a};if(void 0!==h&&(i.$feature_flag_has_experiment=h),b&&this.featureFlagsPoller){let e=this.featureFlagsPoller.getFlagDefinitionsLoadedAt();void 0!==e&&(i.$feature_flag_definitions_loaded_at=e)}o&&(i.$feature_flag_error=o),this._captureFlagCalledEventIfNeeded({distinctId:t,key:e,response:r,groups:f,disableGeoip:p,properties:i})}return void 0!==s&&void 0!==this._payloadOverrides&&e in this._payloadOverrides&&(s={...s,payload:this._payloadOverrides[e]}),s}async getFeatureFlag(e,t,r){iT("getFeatureFlag","`getFeatureFlag` is deprecated and will be removed in a future major version. Use `posthog.evaluateFlags(distinctId, ...)` and call `flags.getFlag(key)` instead — this consolidates flag evaluation into a single `/flags` request per incoming request.");let i=await this._getFeatureFlagResult(e,t,{...r,sendFeatureFlagEvents:r?.sendFeatureFlagEvents??this.options.sendFeatureFlagEvent??!0});if(void 0!==i)return!1!==i.enabled&&(i.variant??!0)}async getFeatureFlagPayload(e,t,r,i){if(iT("getFeatureFlagPayload","`getFeatureFlagPayload` is deprecated and will be removed in a future major version. Use `posthog.evaluateFlags(distinctId, ...)` and call `flags.getFlagPayload(key)` instead — this consolidates flag evaluation into a single `/flags` request per incoming request."),void 0!==this._payloadOverrides&&e in this._payloadOverrides)return this._payloadOverrides[e];let s=await this._getFeatureFlagResult(e,t,{...i,sendFeatureFlagEvents:!1},r);if(void 0!==s)return s.payload??null}async getFeatureFlagResult(e,t,r){let{distinctId:i,options:s}=this._resolveDistinctId(t,r);return i?this._getFeatureFlagResult(e,i,{...s,sendFeatureFlagEvents:s?.sendFeatureFlagEvents??this.options.sendFeatureFlagEvent??!0}):void this._logger.warn("[PostHog] distinctId is required — pass it explicitly or use withContext()")}async getRemoteConfigPayload(e){if(this.disabled)return void this._logger.warn("The client is disabled");if(!this.options.personalApiKey)throw Error("Personal API key is required for remote config payload decryption");let t=await this._requestRemoteConfigPayload(e);if(!t)return;let r=await t.json();if("string"==typeof r)try{return JSON.parse(r)}catch(e){}return r}async isFeatureEnabled(e,t,r){iT("isFeatureEnabled","`isFeatureEnabled` is deprecated and will be removed in a future major version. Use `posthog.evaluateFlags(distinctId, ...)` and call `flags.isEnabled(key)` instead — this consolidates flag evaluation into a single `/flags` request per incoming request.");let i=await this._getFeatureFlagResult(e,t,{...r,sendFeatureFlagEvents:r?.sendFeatureFlagEvents??this.options.sendFeatureFlagEvent??!0});return void 0===i?void 0:!1!==i.enabled&&!!(i.variant??!0)}async getAllFlags(e,t){let{distinctId:r,options:i}=this._resolveDistinctId(e,t);return r?(await this.getAllFlagsAndPayloads(r,i)).featureFlags||{}:(this._logger.warn("[PostHog] distinctId is required to get feature flags — pass it explicitly or use withContext()"),{})}async getAllFlagsAndPayloads(e,t){let{distinctId:r,options:i}=this._resolveDistinctId(e,t);if(!r)return this._logger.warn("[PostHog] distinctId is required to get feature flags and payloads — pass it explicitly or use withContext()"),{featureFlags:{},featureFlagPayloads:{}};if(this.disabled)return this._logger.warn("The client is disabled"),{featureFlags:{},featureFlagPayloads:{}};let{groups:s,disableGeoip:n,flagKeys:a}=i||{},{onlyEvaluateLocally:o,personProperties:l,groupProperties:u}=i||{},c=this.addLocalPersonAndGroupProperties(r,s,l,u);l=c.allPersonProperties,u=c.allGroupProperties;let h=this.createFeatureFlagEvaluationContext(r,s,this.personPropertiesForLocalEvaluation(r,l),u);void 0==o&&(o=this.options.strictLocalEvaluation??!1);let d=await this.featureFlagsPoller?.getAllFlagsAndPayloads(h,a),f={},p={},g=!0;if(d&&(f=d.response,p=d.payloads,g=d.fallbackToFlags),g&&!o){let e=await super.getFeatureFlagsAndPayloadsStateless(h.distinctId,h.groups,l,u,n,a);f={...f,...e.flags||{}},p={...p,...e.payloads||{}}}return void 0!==this._flagOverrides&&(f={...f,...this._flagOverrides}),void 0!==this._payloadOverrides&&(p={...p,...this._payloadOverrides}),{featureFlags:f,featureFlagPayloads:p}}async evaluateFlags(e,t){let r,i,{distinctId:s,options:n}=this._resolveDistinctId(e,t);if(!s)return this._logger.warn("[PostHog] distinctId is required to evaluate feature flags — pass it explicitly or use withContext()"),new rC({host:this._getFeatureFlagEvaluationsHost(),distinctId:"",flags:{}});if(this.disabled)return this._logger.warn("The client is disabled"),new rC({host:this._getFeatureFlagEvaluationsHost(),distinctId:s,flags:{}});let{groups:a,disableGeoip:o}=n||{},l=n?.flagKeys??void 0;if(l?.length===0)return new rC({host:this._getFeatureFlagEvaluationsHost(),distinctId:s,groups:a,disableGeoip:o,flags:{}});let{onlyEvaluateLocally:u,personProperties:c,groupProperties:h}=n||{},d=this.addLocalPersonAndGroupProperties(s,a,c,h);c=d.allPersonProperties,h=d.allGroupProperties;let f=this.createFeatureFlagEvaluationContext(s,a,this.personPropertiesForLocalEvaluation(s,c),h);void 0==u&&(u=this.options.strictLocalEvaluation??!1);let p=l?new Set(l):void 0,g={},m=!1,y=!1,_=await this.featureFlagsPoller?.getAllFlagsAndPayloads(f,l),v=new Set;if(_)for(let[e,t]of Object.entries(_.response)){let r=this.featureFlagsPoller?.featureFlagsByKey[e];g[e]={key:e,enabled:!1!==t,variant:"string"==typeof t?t:void 0,payload:_.payloads[e],id:r?.id,version:void 0,reason:"Evaluated locally",locallyEvaluated:!0,hasExperiment:r?.has_experiment},v.add(e)}let b=void 0!==p&&Array.from(p).some(e=>this.featureFlagsPoller?.featureFlagsByKey[e]===void 0);if((!_||_.fallbackToFlags||b)&&!u){let e=await super.getFeatureFlagDetailsStateless(f.distinctId,f.groups,c,h,o,l);if(e)for(let[t,s]of(this._minimalFlagCalledEvents=!0===e.minimalFlagCalledEvents,r=e.requestId,i=e.evaluatedAt,m=!!e.errorsWhileComputingFlags,y=Array.isArray(e.quotaLimited)&&e.quotaLimited.includes("feature_flags"),Object.entries(e.flags))){let e;if(!v.has(t)){if(s.metadata?.payload!==void 0)try{e=JSON.parse(s.metadata.payload)}catch{e=s.metadata.payload}g[t]={key:t,enabled:s.enabled,variant:s.variant,payload:e,id:s.metadata?.id,version:s.metadata?.version,reason:s.reason?.description??s.reason?.code,locallyEvaluated:!1,hasExperiment:s.metadata?.has_experiment}}}}if(void 0!==this._flagOverrides)for(let[e,t]of Object.entries(this._flagOverrides)){if(void 0===t){delete g[e];continue}let r=g[e];g[e]={key:e,enabled:!1!==t,variant:"string"==typeof t?t:void 0,payload:r?.payload,id:r?.id,version:r?.version,reason:r?.reason,locallyEvaluated:r?.locallyEvaluated??!1,hasExperiment:r?.hasExperiment}}if(void 0!==this._payloadOverrides)for(let[e,t]of Object.entries(this._payloadOverrides)){let r=g[e];r&&(g[e]={...r,payload:t})}if(void 0!==p)for(let e of Object.keys(g))p.has(e)||delete g[e];let w={};for(let[e,t]of Object.entries(_?.unresolved??{}))Object.prototype.hasOwnProperty.call(g,e)||(w[e]=t);return new rC({host:this._getFeatureFlagEvaluationsHost(),distinctId:s,groups:a,disableGeoip:o,flags:g,unresolvedFlags:w,requestId:r,evaluatedAt:i,flagDefinitionsLoadedAt:this.featureFlagsPoller?.getFlagDefinitionsLoadedAt(),errorsWhileComputing:m,quotaLimited:y})}_shouldSendMinimalFlagCalledEvent(e,t){return"$feature_flag_called"===e&&this._minimalFlagCalledEvents&&!1===t.$feature_flag_has_experiment}_captureFlagCalledEventIfNeeded(e){let{distinctId:t,key:r,response:i,groups:s,disableGeoip:n,properties:a}=e,o=s&&Object.keys(s).length>0?`_${JSON.stringify(Object.entries(s).sort(([e],[t])=>e<t?-1:+(e>t)))}`:"",l=`${r}_${i}${o}`,u=this._distinctIdHasSentFlagCalls.get(t)??new Set;if(this._distinctIdHasSentFlagCalls.delete(t),this._distinctIdHasSentFlagCalls.set(t,u),!u.has(l)){for(u.add(l);this._distinctIdHasSentFlagCalls.size>Math.max(this.maxCacheSize,1);){let e=this._distinctIdHasSentFlagCalls.keys().next().value;if(void 0===e)break;this._distinctIdHasSentFlagCalls.delete(e)}this.capture({distinctId:t,event:"$feature_flag_called",properties:a,groups:s,disableGeoip:n})}}_getFeatureFlagEvaluationsHost(){return this._featureFlagEvaluationsHost||(this._featureFlagEvaluationsHost={captureFlagCalledEventIfNeeded:e=>this._captureFlagCalledEventIfNeeded(e),logWarning:e=>{!1!==this.options.featureFlagsLogWarnings&&console.warn(`[PostHog] ${e}`)}}),this._featureFlagEvaluationsHost}groupIdentify({groupType:e,groupKey:t,properties:r,distinctId:i,disableGeoip:s}){this._sendPreparedEvent("capture",{distinctId:i||`$${e}_${t}`,event:"$groupidentify",properties:{$group_type:e,$group_key:t,$group_set:r||{}},disableGeoip:s},!1,{includeContextProperties:!1})}async groupIdentifyImmediate({groupType:e,groupKey:t,properties:r,distinctId:i,disableGeoip:s}){await this._sendPreparedEvent("capture",{distinctId:i||`$${e}_${t}`,event:"$groupidentify",properties:{$group_type:e,$group_key:t,$group_set:r||{}},disableGeoip:s},!0,{includeContextProperties:!1})}async reloadFeatureFlags(){await this.featureFlagsPoller?.loadFeatureFlags(!0)}overrideFeatureFlags(e){let t=e=>Object.fromEntries(e.map(e=>[e,!0]));if(!1===e){this._flagOverrides=void 0,this._payloadOverrides=void 0;return}if(Array.isArray(e)){this._flagOverrides=t(e);return}if(this._isFeatureFlagOverrideOptions(e)){"flags"in e&&(!1===e.flags?this._flagOverrides=void 0:Array.isArray(e.flags)?this._flagOverrides=t(e.flags):void 0!==e.flags&&(this._flagOverrides={...e.flags})),"payloads"in e&&(!1===e.payloads?this._payloadOverrides=void 0:void 0!==e.payloads&&(this._payloadOverrides={...e.payloads}));return}this._flagOverrides={...e}}_isFeatureFlagOverrideOptions(e){if("object"!=typeof e||null===e||Array.isArray(e))return!1;if("flags"in e){let t=e.flags;if(!1===t||Array.isArray(t)||"object"==typeof t&&null!==t)return!0}if("payloads"in e){let t=e.payloads;if(!1===t||"object"==typeof t&&null!==t)return!0}return!1}withContext(e,t,r){return this.context?this.context.run(e,t,r):t()}getContext(){return this.context?.get()}enterContext(e,t){this.context?.enter(e,t)}async _shutdown(e){let t=Date.now()+(e??3e4),r=this._consumeWaitUntilCycle();await this.featureFlagsPoller?.stopPoller(e),this.errorTracking.shutdown(),this._metrics&&(await z(this._metrics.flush().catch(()=>{}),Math.max(0,t-Date.now())),this._metrics.reset()),this._traces&&(await z(this._traces.flush().catch(()=>{}),Math.max(0,t-Date.now())),this._traces.reset());try{return await super._shutdown(Math.max(0,t-Date.now()))}finally{this._distinctIdHasSentFlagCalls.clear(),r?.()}}async _requestRemoteConfigPayload(e){if(this.disabled||!this.apiKey||!this.options.personalApiKey)return;let t=`${this.host}/api/projects/@current/feature_flags/${e}/remote_config?token=${encodeURIComponent(this.apiKey)}`,r={method:"GET",headers:{...this.getCustomHeaders(),"Content-Type":"application/json",Authorization:`Bearer ${this.options.personalApiKey}`}},i=null;if(this.options.requestTimeout&&"number"==typeof this.options.requestTimeout){let e=new AbortController;i=V(()=>{e.abort()},this.options.requestTimeout),r.signal=e.signal}try{return await this.fetch(t,r)}catch(e){this._events.emit("error",e);return}finally{i&&clearTimeout(i)}}extractPropertiesFromEvent(e,t){if(!e)return{personProperties:{},groupProperties:{}};let r={},i={};for(let[s,n]of Object.entries(e))if(P(n,"Object")&&t&&s in t){let e={};for(let[t,r]of Object.entries(n))e[String(t)]=String(r);i[String(s)]=e}else r[String(s)]=String(n);return{personProperties:r,groupProperties:i}}async getFeatureFlagsForEvent(e,t,r,i){if(this.disabled||!this.apiKey)return void this._logger.warn("The client is disabled");let s=i?.personProperties||{},n=i?.groupProperties||{},a=i?.flagKeys;if(i?.onlyEvaluateLocally??this.options.strictLocalEvaluation)if(!((this.featureFlagsPoller?.featureFlags?.length||0)>0))return{};else{let i={};for(let[e,r]of Object.entries(t||{}))i[e]=String(r);return await this.getAllFlags(e,{groups:i,personProperties:s,groupProperties:n,disableGeoip:r,onlyEvaluateLocally:!0,flagKeys:a})}if((this.featureFlagsPoller?.featureFlags?.length||0)>0){let i={};for(let[e,r]of Object.entries(t||{}))i[e]=String(r);return await this.getAllFlags(e,{groups:i,personProperties:s,groupProperties:n,disableGeoip:r,onlyEvaluateLocally:!0,flagKeys:a})}return(await super.getFeatureFlagsStateless(e,t,s,n,r)).flags}addLocalPersonAndGroupProperties(e,t,r,i){let s={...r||{}},n={};if(t)for(let e of Object.keys(t))n[e]={$group_key:t[e],...i?.[e]||{}};return{allPersonProperties:s,allGroupProperties:n}}personPropertiesForLocalEvaluation(e,t){return{distinct_id:e,...t||{}}}createFeatureFlagEvaluationContext(e,t,r,i){return{distinctId:e,groups:t||{},personProperties:r||{},groupProperties:i||{},evaluationCache:{}}}captureException(e,t,r,i,s){if(!ig.isPreviouslyCapturedError(e)){let n=Error("PostHog syntheticException");this.addPendingPromise(ig.buildEventMessage(this.getErrorPropertiesBuilder(),e,{syntheticException:n},t,r).then(e=>this._capturePreparedEvent({...e,uuid:i,flags:s},!1)))}}async captureExceptionImmediate(e,t,r,i){if(!ig.isPreviouslyCapturedError(e)){let s=Error("PostHog syntheticException");return this.addPendingPromise(ig.buildEventMessage(this.getErrorPropertiesBuilder(),e,{syntheticException:s},t,r).then(e=>this.captureImmediate({...e,flags:i})))}}async prepareEventMessage(e){return this._prepareEventMessage(e)}async _prepareEventMessage(e,t={}){let{distinctId:r,event:i,properties:s,groups:n,flags:a,sendFeatureFlags:o,timestamp:l,disableGeoip:u,uuid:c}=e,h=this.context?.get(),d=t.includeContextProperties??!0,f=r||h?.distinctId,p=d?{...this.props,...h?.properties||{},...s||{}}:{...s||{}};"$exception"!==i||"$trace_id"in p||"$span_id"in p||Object.assign(p,await i_()),f||(f=eQ(),p.$process_person_profile=!1),d&&h?.sessionId&&!p.$session_id&&(p.$session_id=h.sessionId);let g=this._shouldSendMinimalFlagCalledEvent(i,p)?e6(p):p,m=this._runBeforeSend({distinctId:f,event:i,properties:g,groups:n,flags:a,sendFeatureFlags:o,timestamp:l,disableGeoip:u,uuid:c});if(!m)return Promise.reject(null);let y=await Promise.resolve().then(async()=>{if(a)return o&&console.warn("[PostHog] Both `flags` and `sendFeatureFlags` were passed to capture(); using `flags` and ignoring `sendFeatureFlags`."),a._getEventProperties();if(o){iT("sendFeatureFlags","`sendFeatureFlags` is deprecated and will be removed in a future major version. Pass a `flags` snapshot from `posthog.evaluateFlags(...)` instead — it avoids a second `/flags` request per capture and guarantees the event carries the exact flag values your code branched on.");var e=await this.getFeatureFlagsForEvent(m.distinctId,n,u,"object"==typeof o?o:void 0);if(!e)return{};let t={};for(let[r,i]of Object.entries(e))t[`$feature/${r}`]=i;let r=Object.keys(e).filter(t=>!1!==e[t]).sort();return r.length>0&&(t.$active_feature_flags=r),t}return{}}).catch(()=>({})).then(e=>{let t=m.groups||n;return{...e,...m.properties||{},...void 0!==t&&Object.keys(t).length>0?{$groups:t}:{}}});return"$pageview"===m.event&&this.options.__preview_capture_bot_pageviews&&"string"==typeof y.$raw_user_agent&&rF(y.$raw_user_agent,this.options.custom_blocked_useragents||[])&&(m.event="$bot_pageview",y.$browser_type="bot"),{distinctId:m.distinctId,event:m.event,properties:y,options:{timestamp:m.timestamp,disableGeoip:m.disableGeoip,uuid:m.uuid}}}_runBeforeSend(e){let t=this.options.before_send;if(!t)return e;let r=Array.isArray(t)?t:[t],i=e;for(let t of r)try{if(!(i=t(i)))return this._logger.info(`Event '${e.event}' was rejected in beforeSend function`),null;if(!i.properties||0===Object.keys(i.properties).length){let e=`Event '${i.event}' has no properties after beforeSend function, this is likely an error.`;this._logger.warn(e)}}catch(t){return this._logger.error(`Error in before_send function for event '${e.event}':`,t),null}return i}}var ij=e.i(78500);class iD{constructor(){this.storage=new ij.AsyncLocalStorage}get(){return this.storage.getStore()}run(e,t,r){return this.storage.run(this.resolve(e,r),t)}enter(e,t){this.storage.enterWith(this.resolve(e,t))}resolve(e,t){if(t?.fresh===!0)return e;let r=this.get()||{};return{distinctId:e.distinctId??r.distinctId,sessionId:e.sessionId??r.sessionId,properties:{...r.properties||{},...e.properties||{}}}}}class iB{active(){return this._storage.getStore()}with(e,t){return this._storage.run(e,t)}constructor(){this._storage=new ij.AsyncLocalStorage}}var iL=e.i(27028);let iN=(0,e.i(12057).promisify)(iL.gzip);async function iq(e,t=!0){try{let t=await iN(e);return new Uint8Array(t)}catch(e){return t&&console.error("Failed to gzip compress data",e),null}}var iU=e.i(60526),ip=ez;let iV="posthog-node";function iz(e,{organization:t,projectId:r,prefix:i,severityAllowList:s=["error"],sendExceptionsToPostHog:n=!0}={}){return a=>{if(!("*"===s||s.includes(a.level)))return a;a.tags||(a.tags={});let o=a.tags[iW.POSTHOG_ID_TAG];if(void 0===o)return a;let l=e.options.host??"https://us.i.posthog.com",u=new URL(`/project/${e.apiKey}/person/${o}`,l).toString();a.tags["PostHog Person URL"]=u;let c=a.exception?.values||[],h=c.map(e=>({...e,stacktrace:e.stacktrace?{...e.stacktrace,type:"raw",frames:(e.stacktrace.frames||[]).map(e=>({...e,platform:"node:javascript"}))}:void 0})),d={$exception_message:c[0]?.value||a.message,$exception_type:c[0]?.type,$exception_level:a.level,$exception_list:h,$sentry_event_id:a.event_id,$sentry_exception:a.exception,$sentry_exception_message:c[0]?.value||a.message,$sentry_exception_type:c[0]?.type,$sentry_tags:a.tags},f=ip.getInjectedReleaseId();return f&&(d.$release_id=f),t&&r&&(d.$sentry_url=(i||"https://sentry.io/organizations/")+t+"/issues/?project="+r+"&query="+a.event_id),n&&e.capture({event:"$exception",distinctId:o,properties:d}),a}}function iH(e,t){let r=iz(e,t);return{name:iV,processEvent:e=>r(e)}}class iW{static{this.POSTHOG_ID_TAG="posthog_distinct_id"}constructor(e,t,r,i,s){this.name=iV,this.name=iV,this.setupOnce=function(n,a){n(iz(e,{organization:t,projectId:a()?.getClient()?.getDsn()?.projectId,prefix:r,severityAllowList:i,sendExceptionsToPostHog:s??!0}))}}}e.s(["PostHogSentryIntegration",0,iW,"createEventProcessor",0,iz,"sentryIntegration",0,iH],92164);let iK=/[\x00-\x1f\x7f-\x9f]/g;function iG(e,t,r){null!=r&&""!==r&&(e[t]=r)}function iQ(e){return Array.isArray(e)?e[0]:e}function iJ(e){if(Array.isArray(e)){for(let t of e){let e=iJ(t);if(void 0!==e)return e}return}if("string"!=typeof e)return;let t=e.replace(iK,"").trim();if(t)return t.length>1e3?t.slice(0,1e3):t}function iZ(e,t){var r,i;let s,{sessionId:n,distinctId:a}=function(e){if(!e)return{};let t=iJ(e["x-posthog-session-id"]),r=iJ(e["x-posthog-distinct-id"]);return{...void 0!==t?{sessionId:t}:{},...void 0!==r?{distinctId:r}:{}}}(t.headers),o={},l=!0===e.options.disable_capture_url_hashes;return iG(o,"$current_url",(r=t.originalUrl||t.url,l?N(r):r)),iG(o,"$request_method",t.method),iG(o,"$request_path",(i=t.path,s=function(e){if(!e)return e;let t=e.indexOf("?"),r=e.indexOf("#");return -1===t||-1!==r&&r<t?e:`${e.slice(0,t)}${-1===r?"":e.slice(r)}`}(i),l?N(s):s)),iG(o,"$user_agent",iQ(t.headers["user-agent"])),iG(o,"$ip",function(e){let t=iQ(e.headers["x-forwarded-for"]);if(t){let e=t.split(",")[0].trim();if(e)return e}return e.socket?.remoteAddress}(t)),{...void 0!==n?{sessionId:n}:{},...void 0!==a?{distinctId:a}:{},properties:o}}function iY(e,t){var r;t.use((r=e,(e,t,i)=>{r.withContext(iZ(r,e),()=>i())}))}function iX(e,t){var r;t.use((r=e,(e,t,i,s)=>{if(ig.isPreviouslyCapturedError(e))return void s(e);let n=iZ(r,t),a=Error("Synthetic exception"),o={...void 0!==n.sessionId?{$session_id:n.sessionId}:{},...n.properties||{}};r.addPendingPromise(Promise.all([ig.buildEventMessage(r.getErrorPropertiesBuilder(),e,{mechanism:{type:"middleware",handled:!1},syntheticException:a},n.distinctId,o),i.headersSent||i.destroyed?Promise.resolve(i.headersSent?i.statusCode:void 0):new Promise(e=>{let t=t=>{clearTimeout(s),i.removeListener("finish",r),i.removeListener("close",r),e(t)},r=()=>t(i.headersSent?i.statusCode:void 0),s=setTimeout(()=>t(void 0),1e3);s.unref(),i.once("finish",r),i.once("close",r)})]).then(([e,t])=>(void 0!==t&&(e.properties={...e.properties,$response_status_code:t}),r._capturePreparedEvent(e,!1)))),s(e)}))}e.s(["setupExpressErrorHandler",0,iX,"setupExpressRequestContext",0,iY],88512),e.i(92164),e.i(88512),e.i(88096),e.s(["FeatureFlagError",0,d,"FeatureFlagEvaluations",0,rC,"PostHogSentryIntegration",0,iW,"cookieStateToProperties",0,e1,"cookieStoreFromHeader",0,eZ,"createEventProcessor",0,iz,"getPostHogCookieName",0,eY,"parsePostHogCookie",0,e2,"readPostHogCookie",0,e0,"sentryIntegration",0,iH,"serializePostHogCookie",0,eX,"setupExpressErrorHandler",0,iX,"setupExpressRequestContext",0,iY,"uuidv7",0,eQ],92349),e.i(92349),e.s(["FeatureFlagError",0,d,"FeatureFlagEvaluations",0,rC,"PostHog",0,class extends iR{getLibraryId(){return"posthog-node"}compressPayload(e){return iq(e,this.isDebug)}initializeContext(){return new iD}initializeSpanContextManager(){return new iB}hostResourceAttributes(){return function(){var e,t;let r,i,s;try{r=(0,iU.platform)(),i=(0,iU.release)()}catch{}return e=r,t=i,{...(s=function(e){if(e)return Object.prototype.hasOwnProperty.call(tP,e)?tP[e]:e}(e))?{"os.name":s}:{},...t?{"os.version":t}:{}}}()}createErrorPropertiesBuilder(){let e;return new ez.ErrorPropertiesBuilder([new ez.EventCoercer,new ez.ErrorCoercer,new ez.ObjectCoercer,new ez.StringCoercer,new ez.PrimitiveCoercer],ez.createStackParser("node:javascript",ez.nodeStackLineParser),[(e=function(e=process.argv[1]?(0,u.dirname)(process.argv[1]):process.cwd(),t="\\"===u.sep){let r=t?c(e):e;return e=>{if(!e)return;let i=t?c(e):e,{dir:s,base:n,ext:a}=u.posix.parse(i);(".js"===a||".mjs"===a||".cjs"===a)&&(n=n.slice(0,-1*a.length));let o=decodeURIComponent(n);s||(s=".");let l=s.lastIndexOf("/node_modules");if(l>-1)return`${s.slice(l+14).replace(/\//g,".")}:${o}`;if(s.startsWith(r)){let e=s.slice(r.length+1).replace(/\//g,".");return e?`${e}:${o}`:o}return o}}(),async t=>{for(let r of t)r.module=e(r.filename);return t}),e=>rg(e,void 0,this._logger),function(e=process.cwd()){u.sep;let t=e=>e,r=t(e);return async e=>{for(let i of e)!(!i.filename||i.filename.startsWith("node:")||i.filename.startsWith("data:"))&&(0,u.isAbsolute)(i.filename)&&(i.filename=t((0,u.relative)(r,t(i.filename))));return e}}()])}},"PostHogSentryIntegration",0,iW,"cookieStateToProperties",0,e1,"cookieStoreFromHeader",0,eZ,"createEventProcessor",0,iz,"getPostHogCookieName",0,eY,"parsePostHogCookie",0,e2,"readPostHogCookie",0,e0,"sentryIntegration",0,iH,"serializePostHogCookie",0,eX,"setupExpressErrorHandler",0,iX,"setupExpressRequestContext",0,iY,"uuidv7",0,eQ],39702)}];
3
3
 
4
4
  //# sourceMappingURL=node_modules_posthog-node_dist_entrypoints_index_node_mjs_01r25oigsgz07._.js.map